-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtools.go
More file actions
272 lines (252 loc) · 9.81 KB
/
Copy pathtools.go
File metadata and controls
272 lines (252 loc) · 9.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
package telephony
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/Suren878/matrixclaw/internal/setup"
"github.com/Suren878/matrixclaw/internal/telephony/phone"
"github.com/Suren878/matrixclaw/internal/tools"
)
const CallToolID = "telephony_call"
const EndCallToolID = "telephony_end_call"
type setupLoader interface {
Load() (setup.Config, error)
}
type callTool struct {
setup setupLoader
http *http.Client
}
type endCallTool struct {
setup setupLoader
http *http.Client
}
type callInput struct {
To string `json:"to"`
Objective string `json:"objective,omitempty"`
InitialMessage string `json:"initial_message,omitempty"`
Profile string `json:"profile,omitempty"`
SystemInstruction string `json:"system_instruction,omitempty"`
}
type callResponse struct {
Call any `json:"call"`
}
type endCallInput struct {
CallID string `json:"call_id,omitempty"`
Reason string `json:"reason,omitempty"`
}
func NewCallTool(setupService setupLoader) tools.Executor {
return &callTool{
setup: setupService,
http: &http.Client{Timeout: 20 * time.Second},
}
}
func NewEndCallTool(setupService setupLoader) tools.Executor {
return &endCallTool{
setup: setupService,
http: &http.Client{Timeout: 10 * time.Second},
}
}
func (t *callTool) Spec() tools.Spec {
return tools.Spec{
ID: CallToolID,
Name: "Telephony Call",
Description: "Place a real outbound phone call through the configured MatrixClaw telephony gateway and delegate a concrete phone conversation objective. Use only when the user asks to call a phone number or explicitly delegates a phone conversation.",
Risk: tools.RiskApproval,
Effect: tools.EffectMutation,
ApprovalMode: tools.ApprovalOnRequest,
Namespace: "module.telephony",
Category: tools.CategoryAutomation,
Profiles: []tools.Profile{tools.ProfileAutomation, tools.ProfileCoding},
OutputKind: tools.OutputText,
InputJSONSchema: json.RawMessage(`{
"type": "object",
"properties": {
"to": {"type": "string", "description": "Destination phone number in international or provider format."},
"objective": {"type": "string", "description": "Short task for the phone conversation, for example book a table, ask opening hours, confirm an order, or leave a message."},
"system_instruction": {"type": "string", "description": "Optional detailed prompt for how the AI should behave on this call. If omitted, objective is used."},
"initial_message": {"type": "string", "description": "Optional first phrase the AI should say after the other side speaks first. Keep it brief and natural."},
"profile": {"type": "string", "description": "Optional telephony gateway profile, defaults to the configured profile."}
},
"required": ["to"],
"additionalProperties": false
}`),
}
}
func (t *callTool) Execute(ctx context.Context, call tools.Call) (tools.Result, error) {
var input callInput
if err := json.Unmarshal(call.Args, &input); err != nil {
return tools.Result{Content: "Invalid telephony_call arguments.", IsError: true, Status: tools.ResultStatusError}, nil
}
input.To = phone.Normalize(input.To)
input.Objective = strings.TrimSpace(input.Objective)
input.InitialMessage = strings.TrimSpace(input.InitialMessage)
input.Profile = strings.TrimSpace(input.Profile)
input.SystemInstruction = strings.TrimSpace(input.SystemInstruction)
if input.To == "" {
return tools.Result{Content: "Phone number is required.", IsError: true, Status: tools.ResultStatusError}, nil
}
if !call.Approved {
return tools.Result{
Content: "Approval required",
Approval: &tools.ApprovalRequest{
ToolID: CallToolID,
Action: "place_phone_call",
Path: input.To,
Description: approvalDescription(input),
Params: input,
},
}, nil
}
cfg, err := t.config()
if err != nil {
return tools.Result{Content: err.Error(), IsError: true, Status: tools.ResultStatusError}, nil
}
telephonyCfg := cfg.Modules.Telephony
requestBody := map[string]any{
"to": input.To,
"profile": firstNonEmpty(input.Profile, telephonyCfg.DefaultProfile),
"objective": input.Objective,
"system_instruction": input.SystemInstruction,
"initial_message": input.InitialMessage,
"external_key": firstNonEmpty(call.ExternalKey, input.To),
"session_id": call.SessionID,
"origin_client": call.Client,
"origin_external_key": call.ExternalKey,
"origin_session_id": call.SessionID,
"phone_prompt": telephonyCfg.PhonePrompt,
"assistant_name": cfg.Assistant.Name,
"assistant_custom_instructions": cfg.Assistant.CustomInstructions,
}
payload, err := json.Marshal(requestBody)
if err != nil {
return tools.Result{}, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(telephonyCfg.GatewayURL, "/")+"/v1/calls", bytes.NewReader(payload))
if err != nil {
return tools.Result{}, err
}
req.Header.Set("Content-Type", "application/json")
if strings.TrimSpace(telephonyCfg.GatewayToken) != "" {
req.Header.Set("Authorization", "Bearer "+strings.TrimSpace(telephonyCfg.GatewayToken))
}
res, err := t.http.Do(req)
if err != nil {
return tools.Result{Content: fmt.Sprintf("Telephony call failed: %s", err), IsError: true, Status: tools.ResultStatusError}, nil
}
defer func() { _ = res.Body.Close() }()
var response callResponse
_ = json.NewDecoder(res.Body).Decode(&response)
if res.StatusCode < 200 || res.StatusCode >= 300 {
return tools.Result{Content: fmt.Sprintf("Telephony gateway returned HTTP %d.", res.StatusCode), Metadata: response, IsError: true, Status: tools.ResultStatusError}, nil
}
return tools.Result{
Content: "Phone call started: " + input.To,
Metadata: response.Call,
Status: tools.ResultStatusSuccess,
}, nil
}
func (t *endCallTool) Spec() tools.Spec {
return tools.Spec{
ID: EndCallToolID,
Name: "Telephony End Call",
Description: "End the current active MatrixClaw telephony call after saying goodbye. Use only from an active phone conversation when the call objective is complete, impossible, refused, or repeatedly taken off-topic.",
Risk: tools.RiskSafe,
Effect: tools.EffectMutation,
ApprovalMode: tools.ApprovalNever,
Namespace: "module.telephony",
Category: tools.CategoryAutomation,
Profiles: []tools.Profile{tools.ProfileAutomation, tools.ProfileCoding},
OutputKind: tools.OutputText,
InputJSONSchema: json.RawMessage(`{
"type": "object",
"properties": {
"call_id": {"type": "string", "description": "Current MatrixClaw telephony call id. Use the call_id provided in the phone instructions."},
"reason": {"type": "string", "description": "Short internal reason for ending the call."}
},
"additionalProperties": false
}`),
}
}
func (t *endCallTool) Execute(ctx context.Context, call tools.Call) (tools.Result, error) {
var input endCallInput
if len(call.Args) > 0 {
_ = json.Unmarshal(call.Args, &input)
}
callID := strings.TrimSpace(input.CallID)
if callID == "" && strings.EqualFold(strings.TrimSpace(call.Client), "telephony") {
callID = strings.TrimSpace(call.ExternalKey)
}
if callID == "" {
return tools.Result{Content: "No active telephony call id was provided.", IsError: true, Status: tools.ResultStatusError}, nil
}
cfg, err := t.config()
if err != nil {
return tools.Result{Content: err.Error(), IsError: true, Status: tools.ResultStatusError}, nil
}
telephonyCfg := cfg.Modules.Telephony
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, strings.TrimRight(telephonyCfg.GatewayURL, "/")+"/v1/calls/"+url.PathEscape(callID), nil)
if err != nil {
return tools.Result{}, err
}
if strings.TrimSpace(telephonyCfg.GatewayToken) != "" {
req.Header.Set("Authorization", "Bearer "+strings.TrimSpace(telephonyCfg.GatewayToken))
}
res, err := t.http.Do(req)
if err != nil {
return tools.Result{Content: fmt.Sprintf("Telephony end call failed: %s", err), IsError: true, Status: tools.ResultStatusError}, nil
}
defer func() { _ = res.Body.Close() }()
if res.StatusCode < 200 || res.StatusCode >= 300 {
return tools.Result{Content: fmt.Sprintf("Telephony gateway returned HTTP %d while ending the call.", res.StatusCode), IsError: true, Status: tools.ResultStatusError}, nil
}
return tools.Result{Content: "Phone call ended.", Status: tools.ResultStatusSuccess}, nil
}
func (t *callTool) config() (setup.Config, error) {
if t == nil {
return setup.Config{}, fmt.Errorf("telephony setup is not configured")
}
return telephonyConfig(t.setup)
}
func (t *endCallTool) config() (setup.Config, error) {
if t == nil {
return setup.Config{}, fmt.Errorf("telephony setup is not configured")
}
return telephonyConfig(t.setup)
}
func telephonyConfig(setupService setupLoader) (setup.Config, error) {
if setupService == nil {
return setup.Config{}, fmt.Errorf("telephony setup is not configured")
}
cfg, err := setupService.Load()
if err != nil {
return setup.Config{}, err
}
module := setup.TelephonyModuleFromConfig(cfg.Modules)
if !module.Enabled {
return setup.Config{}, fmt.Errorf("telephony module is disabled")
}
if strings.TrimSpace(cfg.Modules.Telephony.GatewayURL) == "" {
return setup.Config{}, fmt.Errorf("telephony gateway URL is not configured")
}
return cfg, nil
}
func approvalDescription(input callInput) string {
objective := firstNonEmpty(input.Objective, input.InitialMessage)
if objective == "" {
return "Place a real outbound phone call to " + input.To + "."
}
return "Place a real outbound phone call to " + input.To + ": " + objective
}
func firstNonEmpty(values ...string) string {
for _, value := range values {
if trimmed := strings.TrimSpace(value); trimmed != "" {
return trimmed
}
}
return ""
}