-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask.ts
More file actions
218 lines (183 loc) Β· 5.69 KB
/
task.ts
File metadata and controls
218 lines (183 loc) Β· 5.69 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
import {
AuthStorage,
createAgentSession,
ModelRegistry,
SessionManager,
type AgentSession,
} from '@mariozechner/pi-coding-agent';
import { getModel } from '@mariozechner/pi-ai';
async function defaultCreateAgent(systemPrompt: string) {
const authStorage = AuthStorage.create();
const modelRegistry = new ModelRegistry(authStorage);
if (!process.env.ANTHROPIC_API_KEY) {
throw new Error('ANTHROPIC_API_KEY is not set');
}
const { session } = await createAgentSession({
model: getModel('anthropic', 'claude-sonnet-4-6'),
thinkingLevel: 'off',
tools: [],
sessionManager: SessionManager.inMemory(),
authStorage,
modelRegistry,
});
session.agent.state.systemPrompt = systemPrompt;
return session;
}
async function taskDrivenTurn(session: AgentSession, callerSpeech: string) {
const full = await new Promise<string>((resolve) => {
let text = '';
const unsubscribe = session.subscribe((event) => {
if (
event.type === 'message_update' &&
event.assistantMessageEvent?.type === 'text_delta'
) {
text += event.assistantMessageEvent.delta;
}
if (event.type === 'agent_end') {
unsubscribe();
resolve(text.trim());
}
});
const now = new Date();
const timestamp = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'short',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false,
}).format(now);
session.prompt(`[${timestamp}] Caller: ${callerSpeech}`);
});
if (!full) return { reply: '', taskComplete: false, conclusion: null };
const lines = full.split('\n');
const jsonLine = [...lines]
.reverse()
.find((line) => line.trim().startsWith('{'));
const reply = lines
.filter((l) => l.trim() !== jsonLine?.trim())
.join('\n')
.trim();
let taskComplete = false;
let conclusion: string | null = null;
try {
const status = JSON.parse(jsonLine ?? '{}') as {
done?: boolean;
conclusion?: string;
};
taskComplete = status.done === true;
conclusion = status.conclusion ?? null;
} catch {
// Malformed JSON β keep going
}
return { reply, taskComplete, conclusion };
}
async function generateConclusionFromSession(
session: AgentSession
): Promise<string> {
const summary = await new Promise<string>((resolve) => {
let text = '';
const unsubscribe = session.subscribe((event) => {
if (
event.type === 'message_update' &&
event.assistantMessageEvent?.type === 'text_delta'
) {
text += event.assistantMessageEvent.delta;
}
if (event.type === 'agent_end') {
unsubscribe();
resolve(text.trim());
}
});
session.prompt(
'The caller has ended the call, but you did not explicitly mark the task as done. Based on the entire conversation so far, write a concise one-sentence conclusion describing the outcome. Do not include any JSON, just plain text.'
);
});
return summary || 'Task was not completed.';
}
interface CallOptions {
/**
* The phone number to call in E.164 format.
*/
to: string;
/**
* The task to perform on the call.
* Example: "Make a reservation for a table for two."
*/
task: string;
/**
* Additional context for the call.
* Example: "You are a personal assistant for a person called John Doe."
*/
context: string;
/**
* A function to create an agent session for the call.
* Example: (task: string, context: string) => createAgentSession(task, context)
*/
createAgent?: (systemPrompt: string) => Promise<AgentSession>;
onStart?: (callId: string) => void;
onConnect?: () => void;
onSpeech?: (details: { role: 'caller' | 'agent'; text: string }) => void;
}
export async function callWithTask({
to,
task,
context,
createAgent = defaultCreateAgent,
onStart,
onSpeech,
onConnect,
}: CallOptions): Promise<{ conclusion: string; timedout: boolean }> {
let isHandlingTurn = false;
let timedout = false;
let lastConclusion: string | null = null;
const VoiceCall = (await import('./VoiceCall')).VoiceCall;
const call = await VoiceCall.create({ to });
await call.connect();
onStart?.(call.id!);
await call.waitForStatus('in-progress', { timeoutMs: 120_000 });
onConnect?.();
const systemPrompt = (await import('./systemPrompt')).systemPrompt;
const taskSession = await createAgent(systemPrompt(task, context));
const timeoutHandle = setTimeout(async () => {
console.error('\nCall timed out β hanging up.');
timedout = true;
await call.end();
process.exit(1);
}, 120 * 1000);
call.onSpeech(async (said) => {
if (isHandlingTurn) {
// Ignore caller speech while we're still handling the previous turn
// to avoid overlapping turns and "interrupt" style messiness.
return;
}
isHandlingTurn = true;
onSpeech?.({ role: 'caller', text: said });
const { reply, conclusion } = await taskDrivenTurn(taskSession, said);
if (!reply) return;
if (conclusion) lastConclusion = conclusion;
onSpeech?.({ role: 'agent', text: reply });
await call.speak(reply);
if (conclusion) {
clearTimeout(timeoutHandle);
taskSession.dispose();
await Bun.sleep(10000);
await call.end();
process.exit(0);
}
await Bun.sleep(1000);
isHandlingTurn = false;
});
return new Promise((resolve) => {
call.onEnd(async () => {
taskSession.dispose();
if (lastConclusion) {
resolve({ conclusion: lastConclusion, timedout });
} else {
const conclusionText = await generateConclusionFromSession(taskSession);
resolve({ conclusion: conclusionText, timedout });
}
});
});
}