@tangle-network/agent-app 0.49.7 → 0.49.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -7,8 +7,9 @@ import type { AgentProfile } from '@tangle-network/sandbox';
|
|
|
7
7
|
*
|
|
8
8
|
* Each person gets one fresh isolated box built from the published profile,
|
|
9
9
|
* never a copy of the developer's box. Later messages resume the same box and
|
|
10
|
-
* the same conversation, so text and voice share one memory. A
|
|
11
|
-
*
|
|
10
|
+
* the same conversation, so text and voice share one memory. A new profile
|
|
11
|
+
* starts a new session, and a deleted box or a new API key starts a new box;
|
|
12
|
+
* either way the person's recent conversation carries over from the store.
|
|
12
13
|
*
|
|
13
14
|
* Every step is idempotent by the message's turn id: a retried delivery
|
|
14
15
|
* settles the same sandbox turn and replays the same Hub send. So the caller
|
|
@@ -55,6 +56,12 @@ export interface HostedAgentConfig {
|
|
|
55
56
|
* come back tomorrow. Retries of an admitted message never reach this hook.
|
|
56
57
|
*/
|
|
57
58
|
allow?: (message: HostedMessage, usedToday: number) => Allowance | Promise<Allowance>;
|
|
59
|
+
/**
|
|
60
|
+
* The owner's own address (E.164 phone). Only this sender can text DEBUG ON
|
|
61
|
+
* or DEBUG OFF; while on, each reply to them ends with one ⚙ line naming the
|
|
62
|
+
* harness, model, box, time, tokens, cost and tools of that turn.
|
|
63
|
+
*/
|
|
64
|
+
owner?: string;
|
|
58
65
|
/** Shared secret for the ph0ny call hook and `ask_workspace` webhook tool. */
|
|
59
66
|
voiceSecret?: string;
|
|
60
67
|
/** How long one `ask_workspace` call may wait before it returns a ticket. Default 8 s. */
|
|
@@ -88,6 +95,21 @@ export declare const CONVERSATION_TOOLS_OFF: readonly ['bash', 'glob', 'grep', '
|
|
|
88
95
|
* (2026-09-23), within the latency of the others.
|
|
89
96
|
*/
|
|
90
97
|
export declare const DEFAULT_HOSTED_MODEL = "openai/gpt-5.6-luna";
|
|
98
|
+
/** What one turn reports about itself, for the owner's debug line. A figure
|
|
99
|
+
* the run did not report stays undefined and is left out of the line. */
|
|
100
|
+
export interface TurnTrace {
|
|
101
|
+
/** Box before the turn: `warm`, `resumed` or `new`. */
|
|
102
|
+
box?: string;
|
|
103
|
+
harness?: string;
|
|
104
|
+
model?: string;
|
|
105
|
+
/** Sandbox clock: the run's own start to finish. */
|
|
106
|
+
runMs?: number;
|
|
107
|
+
inputTokens?: number;
|
|
108
|
+
outputTokens?: number;
|
|
109
|
+
reasoningTokens?: number;
|
|
110
|
+
costUsd?: number;
|
|
111
|
+
tools?: number;
|
|
112
|
+
}
|
|
91
113
|
export type AskResult = {
|
|
92
114
|
state: 'answered';
|
|
93
115
|
text: string;
|
|
@@ -104,6 +126,8 @@ export interface HostedInbound {
|
|
|
104
126
|
event: HubProviderEvent;
|
|
105
127
|
}
|
|
106
128
|
export declare const NOTICE: {
|
|
129
|
+
readonly debugOn: 'Debug on. Each reply now ends with a ⚙ line: agent, harness, model, box, time, tokens, cost, tools and turn. Text DEBUG OFF to stop.';
|
|
130
|
+
readonly debugOff: 'Debug off. Replies no longer carry the ⚙ line.';
|
|
107
131
|
readonly stopped: 'You are unsubscribed. Text START to talk again.';
|
|
108
132
|
readonly started: 'Welcome back. Text me anytime. Reply STOP to stop.';
|
|
109
133
|
readonly limit: 'You have used today\'s free messages. Talk tomorrow!';
|
|
@@ -111,6 +135,10 @@ export declare const NOTICE: {
|
|
|
111
135
|
};
|
|
112
136
|
/** One address per person: E.164 for anything phone-shaped, else lowercase. */
|
|
113
137
|
export declare function normalizeAddress(value: string): string | null;
|
|
138
|
+
/** `true` for DEBUG ON, `false` for DEBUG OFF, `null` for any other text. */
|
|
139
|
+
export declare function debugCommand(text: string): boolean | null;
|
|
140
|
+
/** The owner's ⚙ line. `totalMs` runs from the provider's receipt of the text to now. */
|
|
141
|
+
export declare function debugFooter(agent: string, turnId: string, trace: TurnTrace, totalMs?: number): string;
|
|
114
142
|
export declare class HostedAgentError extends Error {
|
|
115
143
|
readonly code: string;
|
|
116
144
|
constructor(code: string, message: string);
|
|
@@ -118,6 +146,7 @@ export declare class HostedAgentError extends Error {
|
|
|
118
146
|
export declare function createHostedAgent(config: HostedAgentConfig): {
|
|
119
147
|
ask: (message: HostedMessage, options: {
|
|
120
148
|
deadline: number;
|
|
149
|
+
trace?: TurnTrace;
|
|
121
150
|
}) => Promise<AskResult>;
|
|
122
151
|
/**
|
|
123
152
|
* One-time setup: route an Inkbox iMessage identity's messages, connected
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// src/hosted-agent/index.ts
|
|
2
2
|
import { authenticateHubEventRequest, HubClient } from "@tangle-network/hub-sdk";
|
|
3
3
|
import { buildMessagingReply, normalizeConversationEvent } from "@tangle-network/agent-integrations/conversation-events";
|
|
4
|
-
import { Sandbox } from "@tangle-network/sandbox/core";
|
|
4
|
+
import { Sandbox, SandboxError } from "@tangle-network/sandbox/core";
|
|
5
5
|
var DEFAULT_BOX_POLICY = {
|
|
6
6
|
cpuCores: 1,
|
|
7
7
|
memoryMB: 2048,
|
|
@@ -27,6 +27,8 @@ function conversationProfile(profile) {
|
|
|
27
27
|
};
|
|
28
28
|
}
|
|
29
29
|
var NOTICE = {
|
|
30
|
+
debugOn: "Debug on. Each reply now ends with a \u2699 line: agent, harness, model, box, time, tokens, cost, tools and turn. Text DEBUG OFF to stop.",
|
|
31
|
+
debugOff: "Debug off. Replies no longer carry the \u2699 line.",
|
|
30
32
|
stopped: "You are unsubscribed. Text START to talk again.",
|
|
31
33
|
started: "Welcome back. Text me anytime. Reply STOP to stop.",
|
|
32
34
|
limit: "You have used today's free messages. Talk tomorrow!",
|
|
@@ -39,6 +41,9 @@ var START = /^(start|unstop|resume)$/i;
|
|
|
39
41
|
var TWO_DAYS = 2 * 86400;
|
|
40
42
|
var RESUMABLE = /* @__PURE__ */ new Set(["stopped", "expired"]);
|
|
41
43
|
var GONE = /* @__PURE__ */ new Set(["failed", "deleted"]);
|
|
44
|
+
var CARRY_CHARS = 6e3;
|
|
45
|
+
var CARRY_HEAD = "[Your conversation with this person so far. Your instructions may have changed since; follow the current ones.]";
|
|
46
|
+
var CARRY_NOW = "[Their new message:]";
|
|
42
47
|
var encode = (text) => new TextEncoder().encode(text);
|
|
43
48
|
var hex = (bytes) => Array.from(new Uint8Array(bytes), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
44
49
|
var sha256 = async (value) => hex(await crypto.subtle.digest("SHA-256", encode(value)));
|
|
@@ -63,6 +68,41 @@ function normalizeAddress(value) {
|
|
|
63
68
|
if (digits.length < 8 || digits.length > 15) return null;
|
|
64
69
|
return `+${digits.length === 10 && !trimmed.startsWith("+") ? `1${digits}` : digits}`;
|
|
65
70
|
}
|
|
71
|
+
function debugCommand(text) {
|
|
72
|
+
const match = /^debug\s+(on|off)$/i.exec(text.trim());
|
|
73
|
+
return match ? match[1].toLowerCase() === "on" : null;
|
|
74
|
+
}
|
|
75
|
+
var num = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
76
|
+
var seconds = (ms) => ms < 1e4 ? `${(Math.max(0, ms) / 1e3).toFixed(1)}s` : `${Math.round(ms / 1e3)}s`;
|
|
77
|
+
var count = (n) => n < 1e3 ? String(n) : n < 1e4 ? `${(n / 1e3).toFixed(1)}k` : `${Math.round(n / 1e3)}k`;
|
|
78
|
+
function debugFooter(agent, turnId, trace, totalMs) {
|
|
79
|
+
const parts = [agent];
|
|
80
|
+
if (trace.harness) parts.push(trace.harness);
|
|
81
|
+
if (trace.model) parts.push(trace.model.split("/").at(-1));
|
|
82
|
+
if (trace.box) parts.push(trace.box);
|
|
83
|
+
if (totalMs !== void 0) parts.push(`${seconds(totalMs)}${trace.runMs !== void 0 ? ` (run ${seconds(trace.runMs)})` : ""}`);
|
|
84
|
+
else if (trace.runMs !== void 0) parts.push(`run ${seconds(trace.runMs)}`);
|
|
85
|
+
if (trace.inputTokens !== void 0 && trace.outputTokens !== void 0) {
|
|
86
|
+
parts.push(`${count(trace.inputTokens)}\u2192${count(trace.outputTokens)} tok${trace.reasoningTokens ? ` (${count(trace.reasoningTokens)} thinking)` : ""}`);
|
|
87
|
+
}
|
|
88
|
+
if (trace.costUsd !== void 0 && (trace.costUsd > 0 || !trace.outputTokens)) {
|
|
89
|
+
parts.push(trace.costUsd >= 0.01 ? `$${trace.costUsd.toFixed(3)}` : `$${trace.costUsd.toPrecision(2)}`);
|
|
90
|
+
}
|
|
91
|
+
if (trace.tools !== void 0) parts.push(`${trace.tools} tool${trace.tools === 1 ? "" : "s"}`);
|
|
92
|
+
parts.push(turnId.slice(0, 8));
|
|
93
|
+
return `\u2699 ${parts.join(" \xB7 ")}`;
|
|
94
|
+
}
|
|
95
|
+
function noteResult(trace, result, usage) {
|
|
96
|
+
const reported = result.tokenUsage ?? {};
|
|
97
|
+
const timing = result.timing ?? {};
|
|
98
|
+
const started = num(timing.startedAt), completed = num(timing.completedAt);
|
|
99
|
+
if (started !== void 0 && completed !== void 0) trace.runMs = completed - started;
|
|
100
|
+
trace.inputTokens = num(usage?.inputTokens) ?? num(reported.inputTokens);
|
|
101
|
+
trace.outputTokens = num(usage?.outputTokens) ?? num(reported.outputTokens);
|
|
102
|
+
trace.reasoningTokens = num(reported.reasoningTokens);
|
|
103
|
+
if (result.usdKnown !== false) trace.costUsd = num(reported.cost);
|
|
104
|
+
if (Array.isArray(result.toolInvocations)) trace.tools = result.toolInvocations.length;
|
|
105
|
+
}
|
|
66
106
|
var HostedAgentError = class extends Error {
|
|
67
107
|
constructor(code, message) {
|
|
68
108
|
super(message);
|
|
@@ -80,10 +120,24 @@ function createHostedAgent(config) {
|
|
|
80
120
|
const profile = conversationProfile(config.profile);
|
|
81
121
|
const backend = { ...config.harness ? { type: config.harness } : {}, profile };
|
|
82
122
|
const profileTag = sha256(JSON.stringify(profile)).then((hash) => hash.slice(0, 8));
|
|
83
|
-
async function
|
|
123
|
+
async function resumed(box) {
|
|
124
|
+
try {
|
|
125
|
+
await box.resume();
|
|
126
|
+
return true;
|
|
127
|
+
} catch (error) {
|
|
128
|
+
if (error instanceof SandboxError && error.code === "SANDBOX_ATTRIBUTION_MISMATCH") return false;
|
|
129
|
+
throw error;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
async function ensureBox(user, deadline, trace) {
|
|
84
133
|
const key = `box:${user}`;
|
|
85
134
|
const known = await store.get(key);
|
|
86
135
|
let box = known ? await sandbox.get(known) : null;
|
|
136
|
+
if (trace) trace.box = !box || GONE.has(box.status) ? "new" : RESUMABLE.has(box.status) ? "resumed" : "warm";
|
|
137
|
+
if (box && RESUMABLE.has(box.status) && !await resumed(box)) {
|
|
138
|
+
box = null;
|
|
139
|
+
if (trace) trace.box = "new";
|
|
140
|
+
}
|
|
87
141
|
if (!box || GONE.has(box.status)) {
|
|
88
142
|
box = await sandbox.createIsolated({
|
|
89
143
|
name: `hosted-${user.slice(0, 24)}`,
|
|
@@ -100,7 +154,7 @@ function createHostedAgent(config) {
|
|
|
100
154
|
});
|
|
101
155
|
await store.put(key, box.id);
|
|
102
156
|
}
|
|
103
|
-
if (RESUMABLE.has(box.status)
|
|
157
|
+
if (RESUMABLE.has(box.status) && !await resumed(box)) throw new HostedAgentError("box_foreign", "A new box was made under another API key.");
|
|
104
158
|
if (box.status === "running") return box;
|
|
105
159
|
const timeoutMs = deadline - Date.now();
|
|
106
160
|
if (timeoutMs < 1e3) return null;
|
|
@@ -139,17 +193,42 @@ function createHostedAgent(config) {
|
|
|
139
193
|
if (decision !== "answer") return { state: "declined", reply: decision.reply };
|
|
140
194
|
await store.put(admittedKey, "1", { expirationTtl: TWO_DAYS });
|
|
141
195
|
}
|
|
142
|
-
const
|
|
196
|
+
const trace = options.trace, traceKey = `trace:${user}:${message.turnId}`;
|
|
197
|
+
const box = await ensureBox(user, options.deadline, trace);
|
|
198
|
+
if (trace) {
|
|
199
|
+
const first = await store.get(traceKey);
|
|
200
|
+
if (first) trace.box = first;
|
|
201
|
+
else if (trace.box) await store.put(traceKey, trace.box, { expirationTtl: TWO_DAYS });
|
|
202
|
+
}
|
|
143
203
|
if (!box) return { state: "pending" };
|
|
144
204
|
const sessionId = `hosted-${user}-${await profileTag}`;
|
|
145
|
-
|
|
146
|
-
|
|
205
|
+
const session = await box.session(sessionId).status();
|
|
206
|
+
if (!session) await box.createSession({ sessionId, retention: "workspace", backend });
|
|
207
|
+
if (trace) {
|
|
208
|
+
trace.harness = session?.backend ?? config.harness;
|
|
209
|
+
trace.model = session?.model;
|
|
210
|
+
}
|
|
211
|
+
const asked = message.channel === "voice" ? `[Phone call. Answer in one to three short spoken sentences.]
|
|
147
212
|
${text}` : text;
|
|
213
|
+
const conversationKey = `convo:${user}`, at = `${box.id}/${sessionId}`;
|
|
214
|
+
const stored = await store.get(conversationKey);
|
|
215
|
+
const conversation = stored ? JSON.parse(stored) : { at, turns: [] };
|
|
216
|
+
const carried = conversation.at === at ? "" : conversation.turns.map(([, them, you]) => `Them: ${them}
|
|
217
|
+
You: ${you}`).join("\n");
|
|
218
|
+
const prompt = carried ? `${CARRY_HEAD}
|
|
219
|
+
${carried}
|
|
220
|
+
${CARRY_NOW}
|
|
221
|
+
${asked}` : asked;
|
|
148
222
|
for (; ; ) {
|
|
149
223
|
const result = await box.driveConversationTurn(prompt, { sessionId, turnId: message.turnId, wallCapMs, timeoutMs: 8e3 });
|
|
150
224
|
if (result.state === "completed") {
|
|
151
225
|
const answer = result.text.trim();
|
|
152
226
|
if (!answer) throw new HostedAgentError("empty_reply", "The turn completed with no reply text.");
|
|
227
|
+
if (trace) noteResult(trace, result.result, result.usage);
|
|
228
|
+
const turns = conversation.turns.filter(([id]) => id !== message.turnId);
|
|
229
|
+
turns.push([message.turnId, message.channel === "voice" ? `(on a call) ${text}` : text, answer]);
|
|
230
|
+
while (turns.length > 1 && JSON.stringify(turns).length > CARRY_CHARS) turns.shift();
|
|
231
|
+
await store.put(conversationKey, JSON.stringify({ at, turns }));
|
|
153
232
|
return { state: "answered", text: answer };
|
|
154
233
|
}
|
|
155
234
|
if (result.state === "failed") throw new HostedAgentError("turn_failed", result.error);
|
|
@@ -198,15 +277,30 @@ ${text}` : text;
|
|
|
198
277
|
const userId = normalizeAddress(event.sender.id ?? "");
|
|
199
278
|
if (!userId || !event.text?.trim() || event.isGroup || event.historyOnly) return "ignored";
|
|
200
279
|
const turnId = `t-${(await sha256(inbound.runId)).slice(0, 40)}`;
|
|
280
|
+
const isOwner = Boolean(config.owner) && normalizeAddress(config.owner) === userId;
|
|
281
|
+
const debugKey = `debug:${(await sha256(userId)).slice(0, 32)}`;
|
|
282
|
+
const toggle = isOwner ? debugCommand(event.text) : null;
|
|
283
|
+
const trace = isOwner && toggle === null && await store.get(debugKey) ? {} : void 0;
|
|
201
284
|
let text;
|
|
202
285
|
try {
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
286
|
+
if (toggle !== null) {
|
|
287
|
+
await store.put(debugKey, toggle ? "1" : "");
|
|
288
|
+
text = toggle ? NOTICE.debugOn : NOTICE.debugOff;
|
|
289
|
+
} else {
|
|
290
|
+
const result = await ask(
|
|
291
|
+
{ userId, channel: "imessage", text: event.text, turnId },
|
|
292
|
+
{ deadline: Date.now() + wallCapMs + 6e4, trace }
|
|
293
|
+
);
|
|
294
|
+
if (result.state === "pending") return "pending";
|
|
295
|
+
if (result.state === "declined" && !result.reply) return "ignored";
|
|
296
|
+
text = result.state === "answered" ? result.text : result.reply;
|
|
297
|
+
if (trace && result.state === "answered") {
|
|
298
|
+
const totalMs = event.occurredAt !== null && event.occurredAt !== void 0 ? Date.now() - event.occurredAt : void 0;
|
|
299
|
+
text = `${text.slice(0, 1300)}
|
|
300
|
+
|
|
301
|
+
${debugFooter(config.profile.name ?? "agent", turnId, trace, totalMs)}`;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
210
304
|
} catch (error) {
|
|
211
305
|
if (!(error instanceof HostedAgentError) && !options.lastAttempt) throw error;
|
|
212
306
|
console.error(`[hosted-agent] turn=${turnId} ${describe(error)}`);
|
|
@@ -271,6 +365,8 @@ export {
|
|
|
271
365
|
HostedAgentError,
|
|
272
366
|
NOTICE,
|
|
273
367
|
createHostedAgent,
|
|
368
|
+
debugCommand,
|
|
369
|
+
debugFooter,
|
|
274
370
|
normalizeAddress
|
|
275
371
|
};
|
|
276
372
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/hosted-agent/index.ts"],"sourcesContent":["import { authenticateHubEventRequest, HubClient, type HubProviderEvent } from '@tangle-network/hub-sdk'\nimport { buildMessagingReply, normalizeConversationEvent } from '@tangle-network/agent-integrations/conversation-events'\nimport type { AgentProfile, BackendConfig, SandboxInstance } from '@tangle-network/sandbox'\nimport { Sandbox } from '@tangle-network/sandbox/core'\n\n/**\n * A hosted agent: a person texts or calls a line, and the agent answers from\n * that person's own isolated sandbox. The developer's Tangle API key pays for\n * every box, model turn and reply.\n *\n * Each person gets one fresh isolated box built from the published profile,\n * never a copy of the developer's box. Later messages resume the same box and\n * the same conversation, so text and voice share one memory. A box the\n * platform deleted is replaced by a fresh one instead of blocking the person.\n *\n * Every step is idempotent by the message's turn id: a retried delivery\n * settles the same sandbox turn and replays the same Hub send. So the caller\n * may retry any failure, and needs no dedupe table.\n */\n\n/** Durable key-value storage. A Cloudflare KV namespace satisfies it. */\nexport interface HostedAgentStore {\n get(key: string): Promise<string | null>\n put(key: string, value: string, options?: { expirationTtl?: number }): Promise<void>\n}\n\nexport type HostedChannel = 'imessage' | 'voice'\n\nexport interface HostedMessage {\n /** The sender's address as the channel delivered it: E.164 for a phone. */\n userId: string\n channel: HostedChannel\n text: string\n /** Stable per logical message. Reusing it settles the same turn. */\n turnId: string\n}\n\n/** What the allowance hook decides for one new message. */\nexport type Allowance = 'answer' | 'ignore' | { reply: string }\n\nexport interface HostedAgentConfig {\n /** The developer's Tangle API key (Sandbox and Hub). */\n apiKey: string\n /**\n * The persona every person's box runs. A profile without `model.default`\n * runs {@link DEFAULT_HOSTED_MODEL}, and a profile without `tools` runs with\n * {@link CONVERSATION_TOOLS_OFF} turned off. Set `tools` to choose your own,\n * for example on a harness that cannot turn those tools off.\n */\n profile: AgentProfile\n /** Backend harness type, such as `opencode`; the runtime default when omitted. */\n harness?: string\n store: HostedAgentStore\n /** Answers per person per UTC day before `allow` must decide. Default 20. */\n freeTurnsPerDay?: number\n /**\n * Decide a new message after the free allowance is used, for example reply\n * with a checkout link. Without it, a person past the allowance is told to\n * come back tomorrow. Retries of an admitted message never reach this hook.\n */\n allow?: (message: HostedMessage, usedToday: number) => Allowance | Promise<Allowance>\n /** Shared secret for the ph0ny call hook and `ask_workspace` webhook tool. */\n voiceSecret?: string\n /** How long one `ask_workspace` call may wait before it returns a ticket. Default 8 s. */\n voiceBudgetMs?: number\n box?: Partial<BoxPolicy>\n turnWallCapMs?: number\n sandboxUrl?: string\n hubUrl?: string\n}\n\nexport interface BoxPolicy {\n cpuCores: number\n memoryMB: number\n diskGB: number\n idleTimeoutSeconds: number\n maxLifetimeSeconds: number\n deleteAfterStoppedSeconds: number\n /** Egress allow-list. The default reaches the model router only. */\n allowDomains: string[]\n}\n\nexport const DEFAULT_BOX_POLICY: BoxPolicy = {\n cpuCores: 1, memoryMB: 2048, diskGB: 10,\n idleTimeoutSeconds: 600, maxLifetimeSeconds: 86_400, deleteAfterStoppedSeconds: 7 * 86_400,\n allowDomains: ['router.tangle.tools'],\n}\n\n/**\n * Harness tools a texting or calling assistant does not use. Their\n * descriptions present every turn as coding work: a shell, file search,\n * sub-agents, to-do lists, skills and web fetch. File read, write and edit\n * stay, so a persona can keep notes such as `memory.md`.\n */\nexport const CONVERSATION_TOOLS_OFF = ['bash', 'glob', 'grep', 'task', 'todowrite', 'webfetch', 'skill'] as const\n\n/**\n * The model for a profile without `model.default`. It gave the most useful\n * on-topic replies among four Router models on the same five texts and calls\n * (2026-09-23), within the latency of the others.\n */\nexport const DEFAULT_HOSTED_MODEL = 'openai/gpt-5.6-luna'\n\n/** The profile a person's box runs: the developer's profile over the conversation defaults. */\nfunction conversationProfile(profile: AgentProfile): AgentProfile {\n return {\n ...profile,\n model: { ...profile.model, default: profile.model?.default ?? DEFAULT_HOSTED_MODEL },\n // A profile that sets `tools` owns its tool set.\n ...(profile.tools ? {} : {\n tools: Object.fromEntries(CONVERSATION_TOOLS_OFF.map(tool => [tool, false])),\n // The sandbox's preview policy grants the shell unless its permission\n // is denied, so turning the tool off alone leaves the shell in place.\n permissions: { bash: 'deny' as const, ...profile.permissions },\n }),\n }\n}\n\nexport type AskResult =\n | { state: 'answered'; text: string }\n | { state: 'declined'; reply?: string }\n | { state: 'pending' }\n\n/** A Hub delivery that passed authentication, in a form a queue can carry. */\nexport interface HostedInbound {\n runId: string\n connectionId: string\n event: HubProviderEvent\n}\n\nexport const NOTICE = {\n stopped: 'You are unsubscribed. Text START to talk again.',\n started: 'Welcome back. Text me anytime. Reply STOP to stop.',\n limit: 'You have used today\\'s free messages. Talk tomorrow!',\n unavailable: 'Sorry, I could not answer that just now. Please try again in a minute.',\n} as const\n\nconst IMESSAGE_EVENT = 'inkbox.imessage.received'\nconst IMESSAGE_REPLY = 'inkbox.imessage.reply'\nconst STOP = /^(stop|stopall|unsubscribe|cancel|end|quit)$/i\nconst START = /^(start|unstop|resume)$/i\nconst TWO_DAYS = 2 * 86_400\nconst RESUMABLE = new Set(['stopped', 'expired'])\nconst GONE = new Set(['failed', 'deleted'])\n\nconst encode = (text: string) => new TextEncoder().encode(text)\nconst hex = (bytes: ArrayBuffer) => Array.from(new Uint8Array(bytes), byte => byte.toString(16).padStart(2, '0')).join('')\nconst sha256 = async (value: string) => hex(await crypto.subtle.digest('SHA-256', encode(value)))\n/** Compares digests, so the time taken reveals nothing about the secret. */\nasync function equal(given: string | null | undefined, expected: string): Promise<boolean> {\n if (!given) return false\n const [a, b] = await Promise.all([sha256(given), sha256(expected)])\n let diff = 0\n for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n return diff === 0\n}\nconst CALL_TTL_MS = 2 * 3_600_000\n/** 43 url-safe characters from 32 random bytes. */\nconst randomToken = () => btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32)))).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\nconst b64 = (text: string) => btoa(String.fromCharCode(...encode(text))).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\nconst unb64 = (text: string) => new TextDecoder().decode(Uint8Array.from(atob(text.replace(/-/g, '+').replace(/_/g, '/')), c => c.charCodeAt(0)))\nconst sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))\nconst json = (body: unknown, status = 200) => Response.json(body, { status })\nconst describe = (error: unknown) => (error instanceof Error ? `${error.name}: ${error.message}` : String(error))\n .replace(/sk-tan-[\\w-]+|Bearer\\s+\\S+/g, '<redacted>').slice(0, 400)\n\n/** One address per person: E.164 for anything phone-shaped, else lowercase. */\nexport function normalizeAddress(value: string): string | null {\n const trimmed = value.trim()\n if (trimmed.includes('@')) return trimmed.toLowerCase()\n const digits = trimmed.replace(/[^\\d]/g, '')\n if (digits.length < 8 || digits.length > 15) return null\n return `+${digits.length === 10 && !trimmed.startsWith('+') ? `1${digits}` : digits}`\n}\n\nexport class HostedAgentError extends Error {\n constructor(readonly code: string, message: string) { super(message); this.name = 'HostedAgentError' }\n}\n\nexport function createHostedAgent(config: HostedAgentConfig) {\n const store = config.store\n const policy = { ...DEFAULT_BOX_POLICY, ...config.box }\n const wallCapMs = config.turnWallCapMs ?? 120_000\n const sandbox = new Sandbox({ apiKey: config.apiKey, baseUrl: config.sandboxUrl ?? 'https://sandbox.tangle.tools', timeoutMs: 20_000 })\n const hub = new HubClient({ baseUrl: config.hubUrl ?? 'https://id.tangle.tools', apiKey: config.apiKey })\n const profile = conversationProfile(config.profile)\n const backend: BackendConfig = { ...(config.harness ? { type: config.harness as BackendConfig['type'] } : {}), profile }\n const profileTag = sha256(JSON.stringify(profile)).then(hash => hash.slice(0, 8))\n\n /** The person's running box: created on the first message, resumed later,\n * replaced when the platform deleted it. Null when the deadline passed. */\n async function ensureBox(user: string, deadline: number): Promise<SandboxInstance | null> {\n const key = `box:${user}`\n const known = await store.get(key)\n let box = known ? await sandbox.get(known) : null\n if (!box || GONE.has(box.status)) {\n // The key names the box it replaces, so concurrent first messages and\n // retries converge on one allocation instead of each creating a box.\n box = await sandbox.createIsolated({\n name: `hosted-${user.slice(0, 24)}`, idempotencyKey: known ? `hosted-${user}-after-${known}` : `hosted-${user}`,\n resources: { cpuCores: policy.cpuCores, memoryMB: policy.memoryMB, diskGB: policy.diskGB },\n backend, secrets: [], sshEnabled: false,\n egressPolicy: { mode: 'strict', allowDomains: policy.allowDomains, includeImplicitDomains: false },\n idleTimeoutSeconds: policy.idleTimeoutSeconds, maxLifetimeSeconds: policy.maxLifetimeSeconds,\n deleteAfterStoppedSeconds: policy.deleteAfterStoppedSeconds, metadata: { hostedUser: user },\n })\n await store.put(key, box.id)\n }\n if (RESUMABLE.has(box.status)) await box.resume()\n if (box.status === 'running') return box\n const timeoutMs = deadline - Date.now()\n if (timeoutMs < 1000) return null\n try {\n return await sandbox.waitForRunning(box.id, { timeoutMs })\n } catch (error) {\n if (error instanceof Error && error.name === 'TimeoutError') return null\n throw error\n }\n }\n\n /** Admit a new message once: STOP/START, the free allowance, then `allow`. */\n async function admit(message: HostedMessage, user: string): Promise<Allowance> {\n const stopKey = `stop:${user}`\n if (message.channel !== 'voice' && STOP.test(message.text.trim())) { await store.put(stopKey, '1'); return { reply: NOTICE.stopped } }\n if (message.channel !== 'voice' && START.test(message.text.trim())) { await store.put(stopKey, ''); return { reply: NOTICE.started } }\n if (await store.get(stopKey)) return 'ignore'\n const dayKey = `turns:${user}:${new Date().toISOString().slice(0, 10)}`\n // KV has no atomic increment, so concurrent messages may overshoot the\n // allowance by a few; the sponsor key's budget is the hard ceiling.\n const used = Number(await store.get(dayKey) ?? 0)\n const decision = used < (config.freeTurnsPerDay ?? 20) ? 'answer'\n : config.allow ? await config.allow(message, used) : { reply: NOTICE.limit }\n if (decision === 'answer') await store.put(dayKey, String(used + 1), { expirationTtl: TWO_DAYS })\n return decision\n }\n\n /** Run one message in the person's box until it answers or `deadline`. */\n async function ask(message: HostedMessage, options: { deadline: number }): Promise<AskResult> {\n const text = message.text.trim()\n if (!text || text.length > 8000 || !/^[\\w-]{1,120}$/.test(message.turnId)) return { state: 'declined' }\n const user = (await sha256(message.userId)).slice(0, 32)\n // Scoped to the person: a voice ticket is model-supplied, so a turn id\n // admitted for one person must not skip another person's allowance.\n const admittedKey = `turn:${user}:${message.turnId}`\n if (!await store.get(admittedKey)) {\n const decision = await admit(message, user)\n if (decision === 'ignore') return { state: 'declined' }\n if (decision !== 'answer') return { state: 'declined', reply: decision.reply }\n await store.put(admittedKey, '1', { expirationTtl: TWO_DAYS })\n }\n const box = await ensureBox(user, options.deadline)\n if (!box) return { state: 'pending' }\n // A session binds its backend when created, and the runtime would give a\n // bare session its generic default assistant. A new profile starts a new\n // conversation, so the persona always matches the one in force.\n const sessionId = `hosted-${user}-${await profileTag}`\n if (!await box.session(sessionId).status()) await box.createSession({ sessionId, retention: 'workspace', backend })\n const prompt = message.channel === 'voice' ? `[Phone call. Answer in one to three short spoken sentences.]\\n${text}` : text\n for (;;) {\n const result = await box.driveConversationTurn(prompt, { sessionId, turnId: message.turnId, wallCapMs, timeoutMs: 8000 })\n if (result.state === 'completed') {\n const answer = result.text.trim()\n if (!answer) throw new HostedAgentError('empty_reply', 'The turn completed with no reply text.')\n return { state: 'answered', text: answer }\n }\n if (result.state === 'failed') throw new HostedAgentError('turn_failed', result.error)\n if (Date.now() + 2000 > options.deadline) return { state: 'pending' }\n await sleep(2000)\n }\n }\n\n return {\n ask,\n\n /**\n * One-time setup: route an Inkbox iMessage identity's messages, connected\n * to Hub under the developer's account, to `callbackUrl`, and allow the\n * one reply action on that connection. Safe to repeat.\n */\n async connect(input: { connectionId: string; identityId: string; callbackUrl: string; secret: string }) {\n const webhook = await hub.connections.inboundWebhook.get(input.connectionId)\n if (!webhook.configured) await hub.connections.inboundWebhook.create(input.connectionId, { identityId: input.identityId, imessage: true })\n await hub.permissions.set({ connectionId: input.connectionId, actionPath: IMESSAGE_REPLY, decision: 'allow' })\n const { subscription } = await hub.eventSubscriptions.create({\n clientReference: `hosted-agent:${input.connectionId}`, label: 'Hosted agent messages',\n source: { type: 'connection', connectionId: input.connectionId }, event: IMESSAGE_EVENT,\n callback: { url: input.callbackUrl, secret: input.secret },\n })\n return subscription\n },\n\n /** The Hub callback. Authenticates within Hub's 10 s budget and runs nothing. */\n async receive(request: Request, secret: string): Promise<{ response: Response; inbound?: HostedInbound }> {\n const authenticated = await authenticateHubEventRequest({ request, secret, maxBodyBytes: 64 * 1024 })\n if (!authenticated.ok) return { response: authenticated.response }\n const { runId, source, providerEvent } = authenticated.delivery\n const ack = new Response(null, { status: 204 })\n if (source.kind !== 'connection' || source.event !== IMESSAGE_EVENT || providerEvent.connectionId !== source.id) return { response: ack }\n return { response: ack, inbound: { runId, connectionId: source.id, event: providerEvent } }\n },\n\n /**\n * Answer one inbound message and send the reply through Hub. Returns\n * 'pending' while the turn still runs; call again with the same inbound.\n * On `lastAttempt`, a failure is answered with an apology instead of thrown.\n */\n async respond(inbound: HostedInbound, options: { lastAttempt?: boolean } = {}): Promise<'replied' | 'ignored' | 'pending'> {\n const normalized = normalizeConversationEvent(inbound.event)\n if (!normalized.ok) return 'ignored'\n const event = normalized.event\n const userId = normalizeAddress(event.sender.id ?? '')\n if (!userId || !event.text?.trim() || event.isGroup || event.historyOnly) return 'ignored'\n const turnId = `t-${(await sha256(inbound.runId)).slice(0, 40)}`\n let text: string\n try {\n const result = await ask({ userId, channel: 'imessage', text: event.text, turnId },\n { deadline: Date.now() + wallCapMs + 60_000 })\n if (result.state === 'pending') return 'pending'\n if (result.state === 'declined' && !result.reply) return 'ignored'\n text = result.state === 'answered' ? result.text : result.reply!\n } catch (error) {\n // A failed turn fails the same way on every retry; anything else may clear.\n if (!(error instanceof HostedAgentError) && !options.lastAttempt) throw error\n console.error(`[hosted-agent] turn=${turnId} ${describe(error)}`)\n text = NOTICE.unavailable\n }\n const plan = buildMessagingReply(inbound.event, text.slice(0, 1500), `reply-${turnId}`)\n if (!plan.ok) return 'ignored'\n // Hub replays the first result for a retry with this key and input.\n await hub.tools.invoke(plan.reply.action, plan.reply.input, { connectionId: inbound.connectionId, idempotencyKey: plan.reply.idempotencyKey })\n return 'replied'\n },\n\n /**\n * ph0ny's call hook. `admit` returns a call token bound to the caller's\n * number from the carrier's signed call record, never from the model.\n */\n async voiceHook(request: Request): Promise<Response> {\n const secret = config.voiceSecret\n if (!secret || !await equal(request.headers.get('authorization'), `Bearer ${secret}`)) return json({ error: 'unauthorized' }, 401)\n const body = await request.json().catch(() => null) as { event?: string; phone?: string } | null\n if (body?.event !== 'admit') return json({ ok: true })\n const phone = normalizeAddress(body.phone ?? '')\n if (!phone?.startsWith('+')) return json({ admit: false, say: 'Sorry, I can only take calls from a visible number.' })\n if (await store.get(`stop:${(await sha256(phone)).slice(0, 32)}`)) return json({ admit: false, say: 'You unsubscribed from this line.' })\n // ph0ny accepts only an opaque token matching ^[A-Za-z0-9_-]{16,128}$,\n // so the caller's number stays here and the token is its random key.\n const callToken = randomToken()\n await store.put(`vcall:${callToken}`, JSON.stringify({ phone, exp: Date.now() + CALL_TTL_MS }), { expirationTtl: CALL_TTL_MS / 1000 })\n return json({ admit: true, callToken })\n },\n\n /**\n * ph0ny's `ask_workspace` webhook tool, configured with `forwardCallToken`.\n * A slow turn returns a ticket; the voice agent asks again with it.\n */\n async voiceAsk(request: Request): Promise<Response> {\n const secret = config.voiceSecret\n if (!secret || !await equal(request.headers.get('authorization'), `Bearer ${secret}`)) return json({ error: 'unauthorized' }, 401)\n const token = request.headers.get('x-voice-call-token') ?? ''\n const admitted = /^[A-Za-z0-9_-]{16,128}$/.test(token) ? await store.get(`vcall:${token}`) : null\n if (!admitted) return json({ status: 'error', error: 'call_not_admitted' }, 403)\n const call = JSON.parse(admitted) as { phone: string; exp: number }\n if (call.exp < Date.now()) return json({ status: 'error', error: 'call_expired' }, 403)\n const body = await request.json().catch(() => null) as { utterance?: string; ticket?: string } | null\n // A ticket carries its own turn id and question, so a retry after a\n // slow first step still admits and settles exactly one turn.\n const [turnId, asked] = body?.ticket ? body.ticket.split('.') : [`v-${crypto.randomUUID()}`, b64(body?.utterance ?? '')]\n if (!turnId || !asked) return json({ status: 'error', error: 'missing_utterance' }, 400)\n try {\n // ph0ny drops the tool call at its own timeout, and resuming an idle\n // box can take longer than the budget. Answer 'pending' at the\n // budget regardless; every step is idempotent by turn id, so the\n // ticket call continues where this one stopped.\n const budgetMs = config.voiceBudgetMs ?? 8000\n const result = await Promise.race([\n ask({ userId: call.phone, channel: 'voice', text: unb64(asked), turnId }, { deadline: Date.now() + budgetMs }),\n sleep(budgetMs).then((): AskResult => ({ state: 'pending' })),\n ])\n if (result.state === 'pending') return json({ status: 'pending', ticket: `${turnId}.${asked}` })\n if (result.state === 'declined') return json({ status: 'complete', answer: result.reply ?? 'I cannot answer that right now.' })\n return json({ status: 'complete', answer: result.text })\n } catch (error) {\n console.error(`[hosted-agent] voice turn=${turnId} ${describe(error)}`)\n return json({ status: 'error', error: 'agent_unavailable' }, 502)\n }\n },\n }\n}\n\nexport type HostedAgent = ReturnType<typeof createHostedAgent>\n"],"mappings":";AAAA,SAAS,6BAA6B,iBAAwC;AAC9E,SAAS,qBAAqB,kCAAkC;AAEhE,SAAS,eAAe;AA+EjB,IAAM,qBAAgC;AAAA,EAC3C,UAAU;AAAA,EAAG,UAAU;AAAA,EAAM,QAAQ;AAAA,EACrC,oBAAoB;AAAA,EAAK,oBAAoB;AAAA,EAAQ,2BAA2B,IAAI;AAAA,EACpF,cAAc,CAAC,qBAAqB;AACtC;AAQO,IAAM,yBAAyB,CAAC,QAAQ,QAAQ,QAAQ,QAAQ,aAAa,YAAY,OAAO;AAOhG,IAAM,uBAAuB;AAGpC,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AC;AAAA,MACzD,SAAS,OAAO;AACd,gBAAQ,MAAM,6BAA6B,MAAM,IAAI,SAAS,KAAK,CAAC,EAAE;AACtE,eAAO,KAAK,EAAE,QAAQ,SAAS,OAAO,oBAAoB,GAAG,GAAG;AAAA,MAClE;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/hosted-agent/index.ts"],"sourcesContent":["import { authenticateHubEventRequest, HubClient, type HubProviderEvent } from '@tangle-network/hub-sdk'\nimport { buildMessagingReply, normalizeConversationEvent } from '@tangle-network/agent-integrations/conversation-events'\nimport type { AgentProfile, BackendConfig, SandboxInstance } from '@tangle-network/sandbox'\nimport { Sandbox, SandboxError } from '@tangle-network/sandbox/core'\n\n/**\n * A hosted agent: a person texts or calls a line, and the agent answers from\n * that person's own isolated sandbox. The developer's Tangle API key pays for\n * every box, model turn and reply.\n *\n * Each person gets one fresh isolated box built from the published profile,\n * never a copy of the developer's box. Later messages resume the same box and\n * the same conversation, so text and voice share one memory. A new profile\n * starts a new session, and a deleted box or a new API key starts a new box;\n * either way the person's recent conversation carries over from the store.\n *\n * Every step is idempotent by the message's turn id: a retried delivery\n * settles the same sandbox turn and replays the same Hub send. So the caller\n * may retry any failure, and needs no dedupe table.\n */\n\n/** Durable key-value storage. A Cloudflare KV namespace satisfies it. */\nexport interface HostedAgentStore {\n get(key: string): Promise<string | null>\n put(key: string, value: string, options?: { expirationTtl?: number }): Promise<void>\n}\n\nexport type HostedChannel = 'imessage' | 'voice'\n\nexport interface HostedMessage {\n /** The sender's address as the channel delivered it: E.164 for a phone. */\n userId: string\n channel: HostedChannel\n text: string\n /** Stable per logical message. Reusing it settles the same turn. */\n turnId: string\n}\n\n/** What the allowance hook decides for one new message. */\nexport type Allowance = 'answer' | 'ignore' | { reply: string }\n\nexport interface HostedAgentConfig {\n /** The developer's Tangle API key (Sandbox and Hub). */\n apiKey: string\n /**\n * The persona every person's box runs. A profile without `model.default`\n * runs {@link DEFAULT_HOSTED_MODEL}, and a profile without `tools` runs with\n * {@link CONVERSATION_TOOLS_OFF} turned off. Set `tools` to choose your own,\n * for example on a harness that cannot turn those tools off.\n */\n profile: AgentProfile\n /** Backend harness type, such as `opencode`; the runtime default when omitted. */\n harness?: string\n store: HostedAgentStore\n /** Answers per person per UTC day before `allow` must decide. Default 20. */\n freeTurnsPerDay?: number\n /**\n * Decide a new message after the free allowance is used, for example reply\n * with a checkout link. Without it, a person past the allowance is told to\n * come back tomorrow. Retries of an admitted message never reach this hook.\n */\n allow?: (message: HostedMessage, usedToday: number) => Allowance | Promise<Allowance>\n /**\n * The owner's own address (E.164 phone). Only this sender can text DEBUG ON\n * or DEBUG OFF; while on, each reply to them ends with one ⚙ line naming the\n * harness, model, box, time, tokens, cost and tools of that turn.\n */\n owner?: string\n /** Shared secret for the ph0ny call hook and `ask_workspace` webhook tool. */\n voiceSecret?: string\n /** How long one `ask_workspace` call may wait before it returns a ticket. Default 8 s. */\n voiceBudgetMs?: number\n box?: Partial<BoxPolicy>\n turnWallCapMs?: number\n sandboxUrl?: string\n hubUrl?: string\n}\n\nexport interface BoxPolicy {\n cpuCores: number\n memoryMB: number\n diskGB: number\n idleTimeoutSeconds: number\n maxLifetimeSeconds: number\n deleteAfterStoppedSeconds: number\n /** Egress allow-list. The default reaches the model router only. */\n allowDomains: string[]\n}\n\nexport const DEFAULT_BOX_POLICY: BoxPolicy = {\n cpuCores: 1, memoryMB: 2048, diskGB: 10,\n idleTimeoutSeconds: 600, maxLifetimeSeconds: 86_400, deleteAfterStoppedSeconds: 7 * 86_400,\n allowDomains: ['router.tangle.tools'],\n}\n\n/**\n * Harness tools a texting or calling assistant does not use. Their\n * descriptions present every turn as coding work: a shell, file search,\n * sub-agents, to-do lists, skills and web fetch. File read, write and edit\n * stay, so a persona can keep notes such as `memory.md`.\n */\nexport const CONVERSATION_TOOLS_OFF = ['bash', 'glob', 'grep', 'task', 'todowrite', 'webfetch', 'skill'] as const\n\n/**\n * The model for a profile without `model.default`. It gave the most useful\n * on-topic replies among four Router models on the same five texts and calls\n * (2026-09-23), within the latency of the others.\n */\nexport const DEFAULT_HOSTED_MODEL = 'openai/gpt-5.6-luna'\n\n/** The profile a person's box runs: the developer's profile over the conversation defaults. */\nfunction conversationProfile(profile: AgentProfile): AgentProfile {\n return {\n ...profile,\n model: { ...profile.model, default: profile.model?.default ?? DEFAULT_HOSTED_MODEL },\n // A profile that sets `tools` owns its tool set.\n ...(profile.tools ? {} : {\n tools: Object.fromEntries(CONVERSATION_TOOLS_OFF.map(tool => [tool, false])),\n // The sandbox's preview policy grants the shell unless its permission\n // is denied, so turning the tool off alone leaves the shell in place.\n permissions: { bash: 'deny' as const, ...profile.permissions },\n }),\n }\n}\n\n/** What one turn reports about itself, for the owner's debug line. A figure\n * the run did not report stays undefined and is left out of the line. */\nexport interface TurnTrace {\n /** Box before the turn: `warm`, `resumed` or `new`. */\n box?: string\n harness?: string\n model?: string\n /** Sandbox clock: the run's own start to finish. */\n runMs?: number\n inputTokens?: number\n outputTokens?: number\n reasoningTokens?: number\n costUsd?: number\n tools?: number\n}\n\nexport type AskResult =\n | { state: 'answered'; text: string }\n | { state: 'declined'; reply?: string }\n | { state: 'pending' }\n\n/** A Hub delivery that passed authentication, in a form a queue can carry. */\nexport interface HostedInbound {\n runId: string\n connectionId: string\n event: HubProviderEvent\n}\n\nexport const NOTICE = {\n debugOn: 'Debug on. Each reply now ends with a ⚙ line: agent, harness, model, box, time, tokens, cost, tools and turn. Text DEBUG OFF to stop.',\n debugOff: 'Debug off. Replies no longer carry the ⚙ line.',\n stopped: 'You are unsubscribed. Text START to talk again.',\n started: 'Welcome back. Text me anytime. Reply STOP to stop.',\n limit: 'You have used today\\'s free messages. Talk tomorrow!',\n unavailable: 'Sorry, I could not answer that just now. Please try again in a minute.',\n} as const\n\nconst IMESSAGE_EVENT = 'inkbox.imessage.received'\nconst IMESSAGE_REPLY = 'inkbox.imessage.reply'\nconst STOP = /^(stop|stopall|unsubscribe|cancel|end|quit)$/i\nconst START = /^(start|unstop|resume)$/i\nconst TWO_DAYS = 2 * 86_400\nconst RESUMABLE = new Set(['stopped', 'expired'])\nconst GONE = new Set(['failed', 'deleted'])\n/** How much of a person's recent conversation a new session inherits. */\nconst CARRY_CHARS = 6000\nconst CARRY_HEAD = '[Your conversation with this person so far. Your instructions may have changed since; follow the current ones.]'\nconst CARRY_NOW = '[Their new message:]'\n\n/** A person's recent turns, kept outside the box so a new session or box can continue them. */\ninterface Conversation {\n /** The box and session the turns last ran in. */\n at: string\n /** Oldest first: turn id, what they said, what the agent answered. */\n turns: Array<[string, string, string]>\n}\n\nconst encode = (text: string) => new TextEncoder().encode(text)\nconst hex = (bytes: ArrayBuffer) => Array.from(new Uint8Array(bytes), byte => byte.toString(16).padStart(2, '0')).join('')\nconst sha256 = async (value: string) => hex(await crypto.subtle.digest('SHA-256', encode(value)))\n/** Compares digests, so the time taken reveals nothing about the secret. */\nasync function equal(given: string | null | undefined, expected: string): Promise<boolean> {\n if (!given) return false\n const [a, b] = await Promise.all([sha256(given), sha256(expected)])\n let diff = 0\n for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n return diff === 0\n}\nconst CALL_TTL_MS = 2 * 3_600_000\n/** 43 url-safe characters from 32 random bytes. */\nconst randomToken = () => btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32)))).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\nconst b64 = (text: string) => btoa(String.fromCharCode(...encode(text))).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\nconst unb64 = (text: string) => new TextDecoder().decode(Uint8Array.from(atob(text.replace(/-/g, '+').replace(/_/g, '/')), c => c.charCodeAt(0)))\nconst sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))\nconst json = (body: unknown, status = 200) => Response.json(body, { status })\nconst describe = (error: unknown) => (error instanceof Error ? `${error.name}: ${error.message}` : String(error))\n .replace(/sk-tan-[\\w-]+|Bearer\\s+\\S+/g, '<redacted>').slice(0, 400)\n\n/** One address per person: E.164 for anything phone-shaped, else lowercase. */\nexport function normalizeAddress(value: string): string | null {\n const trimmed = value.trim()\n if (trimmed.includes('@')) return trimmed.toLowerCase()\n const digits = trimmed.replace(/[^\\d]/g, '')\n if (digits.length < 8 || digits.length > 15) return null\n return `+${digits.length === 10 && !trimmed.startsWith('+') ? `1${digits}` : digits}`\n}\n\n/** `true` for DEBUG ON, `false` for DEBUG OFF, `null` for any other text. */\nexport function debugCommand(text: string): boolean | null {\n const match = /^debug\\s+(on|off)$/i.exec(text.trim())\n return match ? match[1]!.toLowerCase() === 'on' : null\n}\n\nconst num = (value: unknown) => typeof value === 'number' && Number.isFinite(value) ? value : undefined\nconst seconds = (ms: number) => ms < 10_000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : `${Math.round(ms / 1000)}s`\nconst count = (n: number) => n < 1000 ? String(n) : n < 10_000 ? `${(n / 1000).toFixed(1)}k` : `${Math.round(n / 1000)}k`\n\n/** The owner's ⚙ line. `totalMs` runs from the provider's receipt of the text to now. */\nexport function debugFooter(agent: string, turnId: string, trace: TurnTrace, totalMs?: number): string {\n const parts = [agent]\n if (trace.harness) parts.push(trace.harness)\n if (trace.model) parts.push(trace.model.split('/').at(-1)!)\n if (trace.box) parts.push(trace.box)\n if (totalMs !== undefined) parts.push(`${seconds(totalMs)}${trace.runMs !== undefined ? ` (run ${seconds(trace.runMs)})` : ''}`)\n else if (trace.runMs !== undefined) parts.push(`run ${seconds(trace.runMs)}`)\n if (trace.inputTokens !== undefined && trace.outputTokens !== undefined) {\n parts.push(`${count(trace.inputTokens)}→${count(trace.outputTokens)} tok${trace.reasoningTokens ? ` (${count(trace.reasoningTokens)} thinking)` : ''}`)\n }\n // Zero on a turn that used tokens means the harness had no price for the model.\n if (trace.costUsd !== undefined && (trace.costUsd > 0 || !trace.outputTokens)) {\n parts.push(trace.costUsd >= 0.01 ? `$${trace.costUsd.toFixed(3)}` : `$${trace.costUsd.toPrecision(2)}`)\n }\n if (trace.tools !== undefined) parts.push(`${trace.tools} tool${trace.tools === 1 ? '' : 's'}`)\n parts.push(turnId.slice(0, 8))\n return `⚙ ${parts.join(' · ')}`\n}\n\n/** Model, tokens, cost, tools and run time from a finished turn, as far as it reports them. */\nfunction noteResult(trace: TurnTrace, result: Record<string, unknown>, usage?: { inputTokens?: number; outputTokens?: number }) {\n // The SDK's typed usage carries counts only; the harness's own record also carries cost.\n const reported = (result.tokenUsage ?? {}) as Record<string, unknown>\n const timing = (result.timing ?? {}) as Record<string, unknown>\n const started = num(timing.startedAt), completed = num(timing.completedAt)\n if (started !== undefined && completed !== undefined) trace.runMs = completed - started\n trace.inputTokens = num(usage?.inputTokens) ?? num(reported.inputTokens)\n trace.outputTokens = num(usage?.outputTokens) ?? num(reported.outputTokens)\n trace.reasoningTokens = num(reported.reasoningTokens)\n if (result.usdKnown !== false) trace.costUsd = num(reported.cost)\n if (Array.isArray(result.toolInvocations)) trace.tools = result.toolInvocations.length\n}\n\nexport class HostedAgentError extends Error {\n constructor(readonly code: string, message: string) { super(message); this.name = 'HostedAgentError' }\n}\n\nexport function createHostedAgent(config: HostedAgentConfig) {\n const store = config.store\n const policy = { ...DEFAULT_BOX_POLICY, ...config.box }\n const wallCapMs = config.turnWallCapMs ?? 120_000\n const sandbox = new Sandbox({ apiKey: config.apiKey, baseUrl: config.sandboxUrl ?? 'https://sandbox.tangle.tools', timeoutMs: 20_000 })\n const hub = new HubClient({ baseUrl: config.hubUrl ?? 'https://id.tangle.tools', apiKey: config.apiKey })\n const profile = conversationProfile(config.profile)\n const backend: BackendConfig = { ...(config.harness ? { type: config.harness as BackendConfig['type'] } : {}), profile }\n const profileTag = sha256(JSON.stringify(profile)).then(hash => hash.slice(0, 8))\n\n /** Resume a stopped box. False when an earlier API key made it: the platform\n * resumes a box only under the key lineage that created it. */\n async function resumed(box: SandboxInstance): Promise<boolean> {\n try {\n await box.resume()\n return true\n } catch (error) {\n if (error instanceof SandboxError && error.code === 'SANDBOX_ATTRIBUTION_MISMATCH') return false\n throw error\n }\n }\n\n /** The person's running box: created on the first message, resumed later,\n * replaced when the platform deleted it. Null when the deadline passed. */\n async function ensureBox(user: string, deadline: number, trace?: TurnTrace): Promise<SandboxInstance | null> {\n const key = `box:${user}`\n const known = await store.get(key)\n let box = known ? await sandbox.get(known) : null\n if (trace) trace.box = !box || GONE.has(box.status) ? 'new' : RESUMABLE.has(box.status) ? 'resumed' : 'warm'\n if (box && RESUMABLE.has(box.status) && !await resumed(box)) {\n box = null\n if (trace) trace.box = 'new'\n }\n if (!box || GONE.has(box.status)) {\n // The key names the box it replaces, so concurrent first messages and\n // retries converge on one allocation instead of each creating a box.\n box = await sandbox.createIsolated({\n name: `hosted-${user.slice(0, 24)}`, idempotencyKey: known ? `hosted-${user}-after-${known}` : `hosted-${user}`,\n resources: { cpuCores: policy.cpuCores, memoryMB: policy.memoryMB, diskGB: policy.diskGB },\n backend, secrets: [], sshEnabled: false,\n egressPolicy: { mode: 'strict', allowDomains: policy.allowDomains, includeImplicitDomains: false },\n idleTimeoutSeconds: policy.idleTimeoutSeconds, maxLifetimeSeconds: policy.maxLifetimeSeconds,\n deleteAfterStoppedSeconds: policy.deleteAfterStoppedSeconds, metadata: { hostedUser: user },\n })\n await store.put(key, box.id)\n }\n if (RESUMABLE.has(box.status) && !await resumed(box)) throw new HostedAgentError('box_foreign', 'A new box was made under another API key.')\n if (box.status === 'running') return box\n const timeoutMs = deadline - Date.now()\n if (timeoutMs < 1000) return null\n try {\n return await sandbox.waitForRunning(box.id, { timeoutMs })\n } catch (error) {\n if (error instanceof Error && error.name === 'TimeoutError') return null\n throw error\n }\n }\n\n /** Admit a new message once: STOP/START, the free allowance, then `allow`. */\n async function admit(message: HostedMessage, user: string): Promise<Allowance> {\n const stopKey = `stop:${user}`\n if (message.channel !== 'voice' && STOP.test(message.text.trim())) { await store.put(stopKey, '1'); return { reply: NOTICE.stopped } }\n if (message.channel !== 'voice' && START.test(message.text.trim())) { await store.put(stopKey, ''); return { reply: NOTICE.started } }\n if (await store.get(stopKey)) return 'ignore'\n const dayKey = `turns:${user}:${new Date().toISOString().slice(0, 10)}`\n // KV has no atomic increment, so concurrent messages may overshoot the\n // allowance by a few; the sponsor key's budget is the hard ceiling.\n const used = Number(await store.get(dayKey) ?? 0)\n const decision = used < (config.freeTurnsPerDay ?? 20) ? 'answer'\n : config.allow ? await config.allow(message, used) : { reply: NOTICE.limit }\n if (decision === 'answer') await store.put(dayKey, String(used + 1), { expirationTtl: TWO_DAYS })\n return decision\n }\n\n /** Run one message in the person's box until it answers or `deadline`. */\n async function ask(message: HostedMessage, options: { deadline: number; trace?: TurnTrace }): Promise<AskResult> {\n const text = message.text.trim()\n if (!text || text.length > 8000 || !/^[\\w-]{1,120}$/.test(message.turnId)) return { state: 'declined' }\n const user = (await sha256(message.userId)).slice(0, 32)\n // Scoped to the person: a voice ticket is model-supplied, so a turn id\n // admitted for one person must not skip another person's allowance.\n const admittedKey = `turn:${user}:${message.turnId}`\n if (!await store.get(admittedKey)) {\n const decision = await admit(message, user)\n if (decision === 'ignore') return { state: 'declined' }\n if (decision !== 'answer') return { state: 'declined', reply: decision.reply }\n await store.put(admittedKey, '1', { expirationTtl: TWO_DAYS })\n }\n // A retried delivery finds the box it woke already warm, so the first\n // attempt's view of the box is kept for the turn.\n const trace = options.trace, traceKey = `trace:${user}:${message.turnId}`\n const box = await ensureBox(user, options.deadline, trace)\n if (trace) {\n const first = await store.get(traceKey)\n if (first) trace.box = first\n else if (trace.box) await store.put(traceKey, trace.box, { expirationTtl: TWO_DAYS })\n }\n if (!box) return { state: 'pending' }\n // A session binds its backend when created, and the runtime would give a\n // bare session its generic default assistant. A new profile starts a new\n // session, so the persona always matches the one in force.\n const sessionId = `hosted-${user}-${await profileTag}`\n const session = await box.session(sessionId).status()\n if (!session) await box.createSession({ sessionId, retention: 'workspace', backend })\n if (trace) {\n trace.harness = session?.backend ?? config.harness\n trace.model = session?.model\n }\n const asked = message.channel === 'voice' ? `[Phone call. Answer in one to three short spoken sentences.]\\n${text}` : text\n // The first turn in a new session or box inherits the person's recent\n // turns. A retry before that turn completes carries them again, so a\n // failed first attempt loses nothing.\n const conversationKey = `convo:${user}`, at = `${box.id}/${sessionId}`\n const stored = await store.get(conversationKey)\n const conversation: Conversation = stored ? JSON.parse(stored) as Conversation : { at, turns: [] }\n const carried = conversation.at === at ? '' : conversation.turns.map(([, them, you]) => `Them: ${them}\\nYou: ${you}`).join('\\n')\n const prompt = carried ? `${CARRY_HEAD}\\n${carried}\\n${CARRY_NOW}\\n${asked}` : asked\n for (;;) {\n const result = await box.driveConversationTurn(prompt, { sessionId, turnId: message.turnId, wallCapMs, timeoutMs: 8000 })\n if (result.state === 'completed') {\n const answer = result.text.trim()\n if (!answer) throw new HostedAgentError('empty_reply', 'The turn completed with no reply text.')\n if (trace) noteResult(trace, result.result, result.usage)\n // Concurrent turns may drop one another's entry; the box keeps the full record.\n const turns = conversation.turns.filter(([id]) => id !== message.turnId)\n turns.push([message.turnId, message.channel === 'voice' ? `(on a call) ${text}` : text, answer])\n while (turns.length > 1 && JSON.stringify(turns).length > CARRY_CHARS) turns.shift()\n await store.put(conversationKey, JSON.stringify({ at, turns } satisfies Conversation))\n return { state: 'answered', text: answer }\n }\n if (result.state === 'failed') throw new HostedAgentError('turn_failed', result.error)\n if (Date.now() + 2000 > options.deadline) return { state: 'pending' }\n await sleep(2000)\n }\n }\n\n return {\n ask,\n\n /**\n * One-time setup: route an Inkbox iMessage identity's messages, connected\n * to Hub under the developer's account, to `callbackUrl`, and allow the\n * one reply action on that connection. Safe to repeat.\n */\n async connect(input: { connectionId: string; identityId: string; callbackUrl: string; secret: string }) {\n const webhook = await hub.connections.inboundWebhook.get(input.connectionId)\n if (!webhook.configured) await hub.connections.inboundWebhook.create(input.connectionId, { identityId: input.identityId, imessage: true })\n await hub.permissions.set({ connectionId: input.connectionId, actionPath: IMESSAGE_REPLY, decision: 'allow' })\n const { subscription } = await hub.eventSubscriptions.create({\n clientReference: `hosted-agent:${input.connectionId}`, label: 'Hosted agent messages',\n source: { type: 'connection', connectionId: input.connectionId }, event: IMESSAGE_EVENT,\n callback: { url: input.callbackUrl, secret: input.secret },\n })\n return subscription\n },\n\n /** The Hub callback. Authenticates within Hub's 10 s budget and runs nothing. */\n async receive(request: Request, secret: string): Promise<{ response: Response; inbound?: HostedInbound }> {\n const authenticated = await authenticateHubEventRequest({ request, secret, maxBodyBytes: 64 * 1024 })\n if (!authenticated.ok) return { response: authenticated.response }\n const { runId, source, providerEvent } = authenticated.delivery\n const ack = new Response(null, { status: 204 })\n if (source.kind !== 'connection' || source.event !== IMESSAGE_EVENT || providerEvent.connectionId !== source.id) return { response: ack }\n return { response: ack, inbound: { runId, connectionId: source.id, event: providerEvent } }\n },\n\n /**\n * Answer one inbound message and send the reply through Hub. Returns\n * 'pending' while the turn still runs; call again with the same inbound.\n * On `lastAttempt`, a failure is answered with an apology instead of thrown.\n */\n async respond(inbound: HostedInbound, options: { lastAttempt?: boolean } = {}): Promise<'replied' | 'ignored' | 'pending'> {\n const normalized = normalizeConversationEvent(inbound.event)\n if (!normalized.ok) return 'ignored'\n const event = normalized.event\n const userId = normalizeAddress(event.sender.id ?? '')\n if (!userId || !event.text?.trim() || event.isGroup || event.historyOnly) return 'ignored'\n const turnId = `t-${(await sha256(inbound.runId)).slice(0, 40)}`\n // Only the configured owner toggles debug; anyone else's DEBUG ON is an ordinary message.\n const isOwner = Boolean(config.owner) && normalizeAddress(config.owner!) === userId\n const debugKey = `debug:${(await sha256(userId)).slice(0, 32)}`\n const toggle = isOwner ? debugCommand(event.text) : null\n const trace: TurnTrace | undefined = isOwner && toggle === null && await store.get(debugKey) ? {} : undefined\n let text: string\n try {\n if (toggle !== null) {\n await store.put(debugKey, toggle ? '1' : '')\n text = toggle ? NOTICE.debugOn : NOTICE.debugOff\n } else {\n const result = await ask({ userId, channel: 'imessage', text: event.text, turnId },\n { deadline: Date.now() + wallCapMs + 60_000, trace })\n if (result.state === 'pending') return 'pending'\n if (result.state === 'declined' && !result.reply) return 'ignored'\n text = result.state === 'answered' ? result.text : result.reply!\n if (trace && result.state === 'answered') {\n const totalMs = event.occurredAt !== null && event.occurredAt !== undefined ? Date.now() - event.occurredAt : undefined\n text = `${text.slice(0, 1300)}\\n\\n${debugFooter(config.profile.name ?? 'agent', turnId, trace, totalMs)}`\n }\n }\n } catch (error) {\n // A failed turn fails the same way on every retry; anything else may clear.\n if (!(error instanceof HostedAgentError) && !options.lastAttempt) throw error\n console.error(`[hosted-agent] turn=${turnId} ${describe(error)}`)\n text = NOTICE.unavailable\n }\n const plan = buildMessagingReply(inbound.event, text.slice(0, 1500), `reply-${turnId}`)\n if (!plan.ok) return 'ignored'\n // Hub replays the first result for a retry with this key and input.\n await hub.tools.invoke(plan.reply.action, plan.reply.input, { connectionId: inbound.connectionId, idempotencyKey: plan.reply.idempotencyKey })\n return 'replied'\n },\n\n /**\n * ph0ny's call hook. `admit` returns a call token bound to the caller's\n * number from the carrier's signed call record, never from the model.\n */\n async voiceHook(request: Request): Promise<Response> {\n const secret = config.voiceSecret\n if (!secret || !await equal(request.headers.get('authorization'), `Bearer ${secret}`)) return json({ error: 'unauthorized' }, 401)\n const body = await request.json().catch(() => null) as { event?: string; phone?: string } | null\n if (body?.event !== 'admit') return json({ ok: true })\n const phone = normalizeAddress(body.phone ?? '')\n if (!phone?.startsWith('+')) return json({ admit: false, say: 'Sorry, I can only take calls from a visible number.' })\n if (await store.get(`stop:${(await sha256(phone)).slice(0, 32)}`)) return json({ admit: false, say: 'You unsubscribed from this line.' })\n // ph0ny accepts only an opaque token matching ^[A-Za-z0-9_-]{16,128}$,\n // so the caller's number stays here and the token is its random key.\n const callToken = randomToken()\n await store.put(`vcall:${callToken}`, JSON.stringify({ phone, exp: Date.now() + CALL_TTL_MS }), { expirationTtl: CALL_TTL_MS / 1000 })\n return json({ admit: true, callToken })\n },\n\n /**\n * ph0ny's `ask_workspace` webhook tool, configured with `forwardCallToken`.\n * A slow turn returns a ticket; the voice agent asks again with it.\n */\n async voiceAsk(request: Request): Promise<Response> {\n const secret = config.voiceSecret\n if (!secret || !await equal(request.headers.get('authorization'), `Bearer ${secret}`)) return json({ error: 'unauthorized' }, 401)\n const token = request.headers.get('x-voice-call-token') ?? ''\n const admitted = /^[A-Za-z0-9_-]{16,128}$/.test(token) ? await store.get(`vcall:${token}`) : null\n if (!admitted) return json({ status: 'error', error: 'call_not_admitted' }, 403)\n const call = JSON.parse(admitted) as { phone: string; exp: number }\n if (call.exp < Date.now()) return json({ status: 'error', error: 'call_expired' }, 403)\n const body = await request.json().catch(() => null) as { utterance?: string; ticket?: string } | null\n // A ticket carries its own turn id and question, so a retry after a\n // slow first step still admits and settles exactly one turn.\n const [turnId, asked] = body?.ticket ? body.ticket.split('.') : [`v-${crypto.randomUUID()}`, b64(body?.utterance ?? '')]\n if (!turnId || !asked) return json({ status: 'error', error: 'missing_utterance' }, 400)\n try {\n // ph0ny drops the tool call at its own timeout, and resuming an idle\n // box can take longer than the budget. Answer 'pending' at the\n // budget regardless; every step is idempotent by turn id, so the\n // ticket call continues where this one stopped.\n const budgetMs = config.voiceBudgetMs ?? 8000\n const result = await Promise.race([\n ask({ userId: call.phone, channel: 'voice', text: unb64(asked), turnId }, { deadline: Date.now() + budgetMs }),\n sleep(budgetMs).then((): AskResult => ({ state: 'pending' })),\n ])\n if (result.state === 'pending') return json({ status: 'pending', ticket: `${turnId}.${asked}` })\n if (result.state === 'declined') return json({ status: 'complete', answer: result.reply ?? 'I cannot answer that right now.' })\n return json({ status: 'complete', answer: result.text })\n } catch (error) {\n console.error(`[hosted-agent] voice turn=${turnId} ${describe(error)}`)\n return json({ status: 'error', error: 'agent_unavailable' }, 502)\n }\n },\n }\n}\n\nexport type HostedAgent = ReturnType<typeof createHostedAgent>\n"],"mappings":";AAAA,SAAS,6BAA6B,iBAAwC;AAC9E,SAAS,qBAAqB,kCAAkC;AAEhE,SAAS,SAA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