@tangle-network/agent-app 0.49.14 → 0.49.16
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.
|
@@ -6,17 +6,19 @@ export * from './engine';
|
|
|
6
6
|
* that person's own isolated sandbox. The developer's Tangle API key pays for
|
|
7
7
|
* every box, model turn and reply.
|
|
8
8
|
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* the
|
|
12
|
-
*
|
|
13
|
-
*
|
|
9
|
+
* The platform keeps each person's box and counts their turns: each person
|
|
10
|
+
* is one Sandbox instance (`sandbox.instances`), a fresh isolated box built
|
|
11
|
+
* from the published profile, and one member of a Hub allowance meter.
|
|
12
|
+
* Later messages resume the same box and conversation, so text and voice
|
|
13
|
+
* share one memory. A new profile starts a new session in the same box; a
|
|
14
|
+
* replaced box starts a new one. Either way the person's recent conversation
|
|
15
|
+
* carries over from the store.
|
|
14
16
|
*
|
|
15
17
|
* Every step is idempotent by the message's turn id: a retried delivery
|
|
16
|
-
* settles the same sandbox turn
|
|
17
|
-
* may retry any failure, and needs no dedupe table.
|
|
18
|
+
* settles the same sandbox turn, the same allowance admission and the same
|
|
19
|
+
* Hub send. So the caller may retry any failure, and needs no dedupe table.
|
|
18
20
|
*/
|
|
19
|
-
/** Durable key-value storage. A Cloudflare KV namespace satisfies it. */
|
|
21
|
+
/** Durable key-value storage for STOP state, the debug switch, call tokens and recent turns. A Cloudflare KV namespace satisfies it. */
|
|
20
22
|
export interface HostedAgentStore {
|
|
21
23
|
get(key: string): Promise<string | null>;
|
|
22
24
|
put(key: string, value: string, options?: {
|
|
@@ -49,11 +51,21 @@ export interface HostedAgentConfig {
|
|
|
49
51
|
/** Backend harness type, such as `opencode`; the runtime default when omitted. */
|
|
50
52
|
harness?: string;
|
|
51
53
|
store: HostedAgentStore;
|
|
52
|
-
/**
|
|
54
|
+
/**
|
|
55
|
+
* The Platform meter that counts this agent's turns (Hub
|
|
56
|
+
* `hub.allowances`). Each person is one member. Default `hosted-agent`.
|
|
57
|
+
*/
|
|
58
|
+
meter?: string;
|
|
59
|
+
/**
|
|
60
|
+
* Answers per person per UTC day before `allow` must decide. Default 20.
|
|
61
|
+
* Written to the meter's plan when the meter has none; a plan already set
|
|
62
|
+
* on the Platform wins.
|
|
63
|
+
*/
|
|
53
64
|
freeTurnsPerDay?: number;
|
|
54
65
|
/**
|
|
55
|
-
* Decide a new message
|
|
56
|
-
*
|
|
66
|
+
* Decide a new message past the free allowance when paying would lift the
|
|
67
|
+
* limit (the Platform's `paywall` decision), for example reply with a
|
|
68
|
+
* checkout link. Without it, or past the paid allowance, a person is told to
|
|
57
69
|
* come back tomorrow. Retries of an admitted message never reach this hook.
|
|
58
70
|
*/
|
|
59
71
|
allow?: (message: HostedMessage, usedToday: number) => Allowance | Promise<Allowance>;
|
|
@@ -99,7 +111,7 @@ export declare const DEFAULT_HOSTED_MODEL = "openai/gpt-5.6-luna";
|
|
|
99
111
|
/** What one turn reports about itself, for the owner's debug line. A figure
|
|
100
112
|
* the run did not report stays undefined and is left out of the line. */
|
|
101
113
|
export interface TurnTrace {
|
|
102
|
-
/**
|
|
114
|
+
/** Time the platform took to hand over the person's running box, such as `box 0.3s`. */
|
|
103
115
|
box?: string;
|
|
104
116
|
harness?: string;
|
|
105
117
|
model?: string;
|
|
@@ -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 {
|
|
4
|
+
import { InstanceRestartingError, Sandbox } from "@tangle-network/sandbox/core";
|
|
5
5
|
|
|
6
6
|
// src/hosted-agent/engine.ts
|
|
7
7
|
var MAX_MESSAGE_CHARS = 8e3;
|
|
@@ -201,9 +201,6 @@ var IMESSAGE_EVENT = "inkbox.imessage.received";
|
|
|
201
201
|
var IMESSAGE_REPLY = "inkbox.imessage.reply";
|
|
202
202
|
var STOP = /^(stop|stopall|unsubscribe|cancel|end|quit)$/i;
|
|
203
203
|
var START = /^(start|unstop|resume)$/i;
|
|
204
|
-
var TWO_DAYS = 2 * 86400;
|
|
205
|
-
var RESUMABLE = /* @__PURE__ */ new Set(["stopped", "expired"]);
|
|
206
|
-
var GONE = /* @__PURE__ */ new Set(["failed", "deleted"]);
|
|
207
204
|
var CARRY_CHARS = 6e3;
|
|
208
205
|
var CARRY_HEAD = "[Your conversation with this person so far. Your instructions may have changed since; follow the current ones.]";
|
|
209
206
|
var CARRY_NOW = "[Their new message:]";
|
|
@@ -279,45 +276,36 @@ function createHostedAgent(config) {
|
|
|
279
276
|
const policy = { ...DEFAULT_BOX_POLICY, ...config.box };
|
|
280
277
|
const wallCapMs = config.turnWallCapMs ?? 12e4;
|
|
281
278
|
const sandbox = new Sandbox({ apiKey: config.apiKey, baseUrl: config.sandboxUrl ?? "https://sandbox.tangle.tools", timeoutMs: 2e4 });
|
|
279
|
+
if (!("instances" in sandbox)) throw new HostedAgentError("sandbox_too_old", "hosted-agent needs @tangle-network/sandbox 0.50 or later.");
|
|
282
280
|
const hub = new HubClient({ baseUrl: config.hubUrl ?? "https://id.tangle.tools", apiKey: config.apiKey });
|
|
281
|
+
if (!("allowances" in hub)) throw new HostedAgentError("hub_sdk_too_old", "hosted-agent needs @tangle-network/hub-sdk 0.17 or later.");
|
|
283
282
|
const profile = conversationProfile(config.profile);
|
|
284
283
|
const backend = { ...config.harness ? { type: config.harness } : {}, profile };
|
|
285
284
|
const profileTag = sha256(JSON.stringify(profile)).then((hash) => hash.slice(0, 8));
|
|
286
|
-
async function
|
|
285
|
+
async function ensureBox(user, deadline) {
|
|
286
|
+
let box;
|
|
287
287
|
try {
|
|
288
|
-
await
|
|
289
|
-
|
|
288
|
+
({ box } = await sandbox.instances.ensure({
|
|
289
|
+
key: `hosted:${user}`,
|
|
290
|
+
profile: { version: await profileTag, backend },
|
|
291
|
+
// A box this kit made before the platform kept instances keeps its files.
|
|
292
|
+
adopt: await store.get(`box:${user}`) ?? void 0,
|
|
293
|
+
create: {
|
|
294
|
+
name: `hosted-${user.slice(0, 24)}`,
|
|
295
|
+
resources: { cpuCores: policy.cpuCores, memoryMB: policy.memoryMB, diskGB: policy.diskGB },
|
|
296
|
+
secrets: [],
|
|
297
|
+
sshEnabled: false,
|
|
298
|
+
egressPolicy: { mode: "strict", allowDomains: policy.allowDomains, includeImplicitDomains: false },
|
|
299
|
+
idleTimeoutSeconds: policy.idleTimeoutSeconds,
|
|
300
|
+
maxLifetimeSeconds: policy.maxLifetimeSeconds,
|
|
301
|
+
deleteAfterStoppedSeconds: policy.deleteAfterStoppedSeconds,
|
|
302
|
+
metadata: { hostedUser: user }
|
|
303
|
+
}
|
|
304
|
+
}));
|
|
290
305
|
} catch (error) {
|
|
291
|
-
if (error instanceof
|
|
306
|
+
if (error instanceof InstanceRestartingError) throw new TurnPending("box_restarting", true);
|
|
292
307
|
throw error;
|
|
293
308
|
}
|
|
294
|
-
}
|
|
295
|
-
async function ensureBox(user, deadline, trace) {
|
|
296
|
-
const key = `box:${user}`;
|
|
297
|
-
const known = await store.get(key);
|
|
298
|
-
let box = known ? await sandbox.get(known) : null;
|
|
299
|
-
if (trace) trace.box = !box || GONE.has(box.status) ? "new" : RESUMABLE.has(box.status) ? "resumed" : "warm";
|
|
300
|
-
if (box && RESUMABLE.has(box.status) && !await resumed(box)) {
|
|
301
|
-
box = null;
|
|
302
|
-
if (trace) trace.box = "new";
|
|
303
|
-
}
|
|
304
|
-
if (!box || GONE.has(box.status)) {
|
|
305
|
-
box = await sandbox.createIsolated({
|
|
306
|
-
name: `hosted-${user.slice(0, 24)}`,
|
|
307
|
-
idempotencyKey: known ? `hosted-${user}-after-${known}` : `hosted-${user}`,
|
|
308
|
-
resources: { cpuCores: policy.cpuCores, memoryMB: policy.memoryMB, diskGB: policy.diskGB },
|
|
309
|
-
backend,
|
|
310
|
-
secrets: [],
|
|
311
|
-
sshEnabled: false,
|
|
312
|
-
egressPolicy: { mode: "strict", allowDomains: policy.allowDomains, includeImplicitDomains: false },
|
|
313
|
-
idleTimeoutSeconds: policy.idleTimeoutSeconds,
|
|
314
|
-
maxLifetimeSeconds: policy.maxLifetimeSeconds,
|
|
315
|
-
deleteAfterStoppedSeconds: policy.deleteAfterStoppedSeconds,
|
|
316
|
-
metadata: { hostedUser: user }
|
|
317
|
-
});
|
|
318
|
-
await store.put(key, box.id);
|
|
319
|
-
}
|
|
320
|
-
if (RESUMABLE.has(box.status) && !await resumed(box)) throw new HostedAgentError("box_foreign", "A new box was made under another API key.");
|
|
321
309
|
if (box.status === "running") return box;
|
|
322
310
|
const timeoutMs = deadline - Date.now();
|
|
323
311
|
if (timeoutMs < 1e3) return null;
|
|
@@ -328,6 +316,20 @@ function createHostedAgent(config) {
|
|
|
328
316
|
throw error;
|
|
329
317
|
}
|
|
330
318
|
}
|
|
319
|
+
const meter = config.meter ?? "hosted-agent";
|
|
320
|
+
const owner = config.owner ? normalizeAddress(config.owner) : null;
|
|
321
|
+
let planned;
|
|
322
|
+
const ensurePlan = () => planned ??= (async () => {
|
|
323
|
+
if ((await hub.allowances.plan(meter)).configured) return;
|
|
324
|
+
await hub.allowances.setPlan(meter, {
|
|
325
|
+
free: { turnsPerDay: config.freeTurnsPerDay ?? 20, usdPerDay: null },
|
|
326
|
+
paid: null,
|
|
327
|
+
spendResourceType: null
|
|
328
|
+
});
|
|
329
|
+
})().catch((error) => {
|
|
330
|
+
planned = void 0;
|
|
331
|
+
throw error;
|
|
332
|
+
});
|
|
331
333
|
async function admit(message, user) {
|
|
332
334
|
const stopKey = `stop:${user}`;
|
|
333
335
|
if (message.channel !== "voice" && STOP.test(message.text.trim())) {
|
|
@@ -339,40 +341,36 @@ function createHostedAgent(config) {
|
|
|
339
341
|
return { reply: NOTICE.started };
|
|
340
342
|
}
|
|
341
343
|
if (await store.get(stopKey)) return "ignore";
|
|
342
|
-
|
|
343
|
-
const
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
344
|
+
await ensurePlan();
|
|
345
|
+
const allowance = await hub.allowances.admit(meter, {
|
|
346
|
+
member: user,
|
|
347
|
+
role: message.userId === owner ? "owner" : "member",
|
|
348
|
+
turnId: message.turnId,
|
|
349
|
+
channel: message.channel
|
|
350
|
+
});
|
|
351
|
+
if (allowance.decision === "admit") return "answer";
|
|
352
|
+
return allowance.decision === "paywall" && config.allow ? await config.allow(message, allowance.turns.used) : { reply: NOTICE.limit };
|
|
347
353
|
}
|
|
348
354
|
async function ask(message, options) {
|
|
349
355
|
const text = message.text.trim();
|
|
350
356
|
if (!text || text.length > 8e3 || !/^[\w-]{1,120}$/.test(message.turnId)) return { state: "declined" };
|
|
351
357
|
const user = (await sha256(message.userId)).slice(0, 32);
|
|
352
|
-
const admittedKey = `turn:${user}:${message.turnId}`;
|
|
353
358
|
const sessionId = `hosted-${user}-${await profileTag}`;
|
|
354
|
-
const trace = options.trace
|
|
359
|
+
const trace = options.trace;
|
|
355
360
|
const conversationKey = `convo:${user}`;
|
|
356
361
|
let declined;
|
|
357
362
|
let conversation, at = "";
|
|
358
363
|
const outcome = await runHostedTurn({ turnId: message.turnId, text }, {
|
|
364
|
+
// The allowance counts a turn id once per person and admits its retries
|
|
365
|
+
// again, so a model-supplied voice ticket cannot spend another person's turn.
|
|
359
366
|
async admit() {
|
|
360
|
-
if (await store.get(admittedKey)) return null;
|
|
361
367
|
const decision = await admit(message, user);
|
|
362
|
-
if (decision === "answer")
|
|
363
|
-
await store.put(admittedKey, "1", { expirationTtl: TWO_DAYS });
|
|
364
|
-
return null;
|
|
365
|
-
}
|
|
368
|
+
if (decision === "answer") return null;
|
|
366
369
|
declined = decision === "ignore" ? { state: "declined" } : { state: "declined", reply: decision.reply };
|
|
367
370
|
return { ok: false, reason: "refused", detail: "declined" };
|
|
368
371
|
},
|
|
369
372
|
async box() {
|
|
370
|
-
const box = await ensureBox(user, options.deadline
|
|
371
|
-
if (trace) {
|
|
372
|
-
const first = await store.get(traceKey);
|
|
373
|
-
if (first) trace.box = first;
|
|
374
|
-
else if (trace.box) await store.put(traceKey, trace.box, { expirationTtl: TWO_DAYS });
|
|
375
|
-
}
|
|
373
|
+
const box = await ensureBox(user, options.deadline);
|
|
376
374
|
if (!box) throw new TurnPending("box_starting", true);
|
|
377
375
|
return box;
|
|
378
376
|
},
|
|
@@ -400,6 +398,9 @@ ${asked}` : asked;
|
|
|
400
398
|
classify: (error) => error instanceof HostedAgentError ? { ok: false, reason: "unavailable", detail: error.code } : void 0,
|
|
401
399
|
observe: {
|
|
402
400
|
readCreatedSession: Boolean(trace),
|
|
401
|
+
span(step, ms) {
|
|
402
|
+
if (trace && step === "ensure") trace.box ??= `box ${seconds(ms)}`;
|
|
403
|
+
},
|
|
403
404
|
session(info) {
|
|
404
405
|
if (!trace) return;
|
|
405
406
|
trace.harness = info.harness ?? config.harness;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/hosted-agent/index.ts","../../src/hosted-agent/engine.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'\nimport { runHostedTurn, TurnPending } from './engine'\n\nexport * from './engine'\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 // A completed turn arrives as the run's own record (`tokenUsage`, `timing`,\n // `toolInvocations`) or as the platform's cached summary (`usage`, `costUsd`).\n // Both count every prompt token; the SDK's typed usage counts only the\n // uncached tail on the summary (3 of 1,214), so it is the fallback. The\n // summary's `durationMs` is not the run time, so that shape has none.\n const reported = (result.tokenUsage ?? result.usage ?? {}) 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(reported.inputTokens) ?? num(usage?.inputTokens)\n trace.outputTokens = num(reported.outputTokens) ?? num(usage?.outputTokens)\n trace.reasoningTokens = num(reported.reasoningTokens)\n if (result.usdKnown !== false) trace.costUsd = num(reported.cost) ?? num(result.costUsd) ?? num(result.totalCostUsd)\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 // 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 trace = options.trace, traceKey = `trace:${user}:${message.turnId}`\n const conversationKey = `convo:${user}`\n let declined: AskResult | undefined\n let conversation: Conversation | undefined, at = ''\n const outcome = await runHostedTurn({ turnId: message.turnId, text }, {\n async admit() {\n if (await store.get(admittedKey)) return null\n const decision = await admit(message, user)\n if (decision === 'answer') {\n await store.put(admittedKey, '1', { expirationTtl: TWO_DAYS })\n return null\n }\n declined = decision === 'ignore' ? { state: 'declined' } : { state: 'declined', reply: decision.reply }\n return { ok: false, reason: 'refused', detail: 'declined' }\n },\n async box() {\n const box = await ensureBox(user, options.deadline, trace)\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 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) throw new TurnPending('box_starting', true)\n return box\n },\n sessionId,\n backend: async () => backend,\n async prompt(box) {\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 at = `${box.id}/${sessionId}`\n const stored = await store.get(conversationKey)\n 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 return carried ? `${CARRY_HEAD}\\n${carried}\\n${CARRY_NOW}\\n${asked}` : asked\n },\n async answered(answer) {\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 },\n classify: error => error instanceof HostedAgentError ? { ok: false, reason: 'unavailable', detail: error.code } : undefined,\n observe: {\n readCreatedSession: Boolean(trace),\n session(info) {\n if (!trace) return\n trace.harness = info.harness ?? config.harness\n trace.model = info.model\n },\n drive(result) {\n if (trace && result.state === 'completed') noteResult(trace, result.result, result.usage)\n },\n failure(step, failure) {\n console.error(`[hosted-agent] turn=${message.turnId} step=${step} code=${failure.code} message=${JSON.stringify(failure.message)}`)\n },\n },\n }, { wallCapMs, timeoutMs: 8000, until: options.deadline })\n if (declined) return declined\n if (outcome.ok === true) return { state: 'answered', text: outcome.text }\n // A thrown failure is rethrown, so the caller's retry policy decides it.\n if (outcome.ok === 'pending') {\n if (outcome.cause !== undefined) throw outcome.cause\n return { state: 'pending' }\n }\n const code = outcome.detail ?? outcome.reason\n throw new HostedAgentError(code === 'agent_failed' ? 'turn_failed' : code, `The turn ended without an answer (${code}).`)\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","import type { BackendConfig, CreateSessionOptions } from '@tangle-network/sandbox'\nimport type { ConversationTurnOptions, ConversationTurnResult, PromptInputPart } from '@tangle-network/sandbox/core'\n\n/**\n * The one turn engine for a hosted agent, whatever hosts it. This kit's\n * `createHostedAgent` runs on it with a key-value store, and Agent Builder\n * runs on it with its D1 enrollments, per-user keys, spaces and product\n * ingest. A host supplies those as ports; the engine owns the order of the\n * steps and what each outcome and failure means.\n *\n * One call is one non-blocking pass for one message:\n *\n * validate -> admit once -> the person's box -> authorize -> session -> drive -> classify\n *\n * Every step is idempotent by the turn id: the sandbox's admission receipt\n * settles a repeated drive on the same turn, so a host may repeat a pass for\n * the same message any number of times and the agent runs it once.\n */\n\nexport type TurnRefusal = 'not_enrolled' | 'execution_not_ready' | 'refused' | 'unavailable'\nexport type TurnReply = { ok: true; text: string } | { ok: false; reason: TurnRefusal; detail?: string }\nexport type TurnStep = 'ensure' | 'drive' | 'turn'\n/**\n * Where an unfinished turn stands. `code` is the same on every repeat of the\n * same cause, so a host can tell a stuck turn from a slow one. A transient\n * cause (a lost response, a timeout, a busy platform, a box still starting)\n * is expected to clear by itself; any other repeats until it is fixed.\n */\nexport interface PendingDetail { step: TurnStep; code: string; transient: boolean }\n/** `cause` is what a port or the Sandbox threw, when a throw left the turn pending. */\nexport type TurnOutcome = TurnReply | { ok: 'pending'; detail: PendingDetail; cause?: unknown }\n\nexport const MAX_MESSAGE_CHARS = 8000\n/** Identical non-transient failures in a row after which a host fails a turn. */\nexport const MAX_REPEATED_FAILURES = 3\n/** Refusal detail when the host's `authorize` check fails. */\nexport const AUTHORITY_ENDED = 'authority_ended'\n\n/** The part of a Sandbox box one turn uses. `SandboxInstance` satisfies it. */\nexport interface TurnBox {\n readonly id: string\n driveConversationTurn(message: string | PromptInputPart[], options: ConversationTurnOptions): Promise<ConversationTurnResult>\n session(id: string): { status(): Promise<unknown> }\n createSession(options: CreateSessionOptions): Promise<unknown>\n}\n\n/** A port throws this to report a turn that is not ready yet, such as a box still starting. */\nexport class TurnPending extends Error {\n constructor(readonly code: string, readonly transient: boolean) {\n super(code)\n this.name = 'TurnPending'\n }\n}\n\n/** A thrown value as a stable code plus a secret-free message for a log line. */\nexport interface TurnFailure { name: string; code: string; status?: number; reason?: string; message: string }\n\n/** What a pass reports while it runs. Every hook is optional; none changes the outcome. */\nexport interface TurnObserver {\n /** Time one step of this pass took, whether it returned or threw. */\n span?(step: 'ensure' | 'session' | 'drive', ms: number): void\n /** The session the turn runs in, as the runtime reports it, or the backend it was created with. */\n session?(info: { harness?: string; model?: string; created: boolean }): void\n /**\n * Read a session this pass created once more, so `session` reports the\n * harness and model the runtime chose for it. It costs one request, so a\n * host asks for it only when it shows them (an owner's debug line, say).\n */\n readCreatedSession?: boolean\n /** Each drive result and the time it arrived. */\n drive?(result: ConversationTurnResult, at: number): void\n /** A failure that left the turn pending or refused. */\n failure?(step: TurnStep, failure: TurnFailure, boxId?: string): void | Promise<void>\n}\n\n/** Storage and policy a host supplies for one message. */\nexport interface HostedTurnPorts<Box extends TurnBox = TurnBox> {\n /**\n * Admit this turn once, before any compute. Return null to run it, or the\n * refusal. A turn admitted by an earlier pass must return null again, so a\n * retry never consumes allowance twice.\n */\n admit(): Promise<Extract<TurnReply, { ok: false }> | null>\n /** The person's running box: created, resumed or replaced as needed. Throw to report why not. */\n box(): Promise<Box>\n /** The host's own authority (a phone link, say), read after the box is ready and right before the drive. */\n authorize?(): Promise<boolean>\n /** The session this turn runs in. A session binds its backend when created, so a new persona needs a new id. */\n sessionId: string\n /** The backend a missing session is created with. Without it the runtime answers as its generic assistant. */\n backend(): Promise<BackendConfig>\n /** The message as the agent receives it: text, or text and images. */\n prompt(box: Box): Promise<string | PromptInputPart[]>\n /** Runs once the turn has a non-empty answer, before the pass returns it. */\n answered?(answer: string, box: Box): Promise<void>\n /** Map a thrown value to an outcome. Undefined leaves it to the engine's own classification. */\n classify?(error: unknown, step: 'ensure' | 'drive'): TurnOutcome | undefined\n observe?: TurnObserver\n}\n\nexport interface HostedTurnOptions {\n /** The run's wall-clock cap; the Sandbox cancels a turn that exceeds it. */\n wallCapMs: number\n /** How long one drive request may wait on a running turn. Default 8 s. */\n timeoutMs?: number\n /** False only reads a turn admitted earlier; it never admits or starts one. */\n allowDispatch?: boolean\n /** Keep driving a running turn until this time, instead of returning pending after one drive. */\n until?: number\n /** Wait between drives while `until` allows. Default 2 s. */\n pollMs?: number\n now?: () => number\n sleep?: (ms: number) => Promise<void>\n}\n\n/** Harness and model as the runtime reports them; the model it selected after normalization wins. */\nfunction sessionInfo(session: unknown): { harness?: string; model?: string } {\n const s = (typeof session === 'object' && session !== null ? session : {}) as\n { backend?: unknown; model?: unknown; effectiveBackend?: { model?: unknown } | null }\n const effective = s.effectiveBackend?.model\n const model = typeof effective === 'string' && effective ? effective : typeof s.model === 'string' && s.model ? s.model : undefined\n return { ...(typeof s.backend === 'string' && s.backend ? { harness: s.backend } : {}), ...(model ? { model } : {}) }\n}\n\nconst refusal = (reason: TurnRefusal, detail?: string): Extract<TurnReply, { ok: false }> => ({ ok: false, reason, ...(detail ? { detail } : {}) })\nconst RUNNING = new Set(['running', 'awaiting_input', 'not_admitted'])\nconst TRANSIENT_ERRORS = new Set(['NetworkError', 'TimeoutError', 'QuotaError', 'AbortError', 'EdgeNotReadyError'])\n/**\n * The 503 codes the Sandbox SDK itself classifies as refused before dispatch\n * and safe to retry. A 503 with any other code, such as\n * HUB_CREDENTIAL_REFRESH_FAILED, has not shown it will clear by itself.\n */\nconst TRANSIENT_503 = new Set(['MODEL_CREDENTIAL_SUPERSEDED', 'HUB_CREDENTIAL_REFRESH_UNAVAILABLE'])\n\n/** The code omits the message, which can carry ids or times that differ on every repeat of one cause. */\nexport function describeFailure(error: unknown): TurnFailure {\n const e = (typeof error === 'object' && error !== null ? error : {}) as Record<string, unknown>\n const name = typeof e.name === 'string' ? e.name : typeof error\n const status = typeof e.status === 'number' ? e.status : undefined\n const own = typeof e.code === 'string' ? e.code : typeof e.reason === 'string' ? e.reason : undefined\n const code = [name, own, status].filter(part => part !== undefined).join(':').replace(/[^\\w.:-]/g, '_').slice(0, 100)\n const message = String(typeof e.message === 'string' ? e.message : error)\n .replace(/sk-tan-[\\w-]+|eyJ[\\w-]+\\.[\\w-]+\\.[\\w-]*|Bearer\\s+\\S+/g, '<redacted>').slice(0, 400)\n return { name, code, ...(status !== undefined ? { status } : {}), ...(own !== undefined ? { reason: own } : {}), message }\n}\n\nexport function isTransientFailure(failure: Pick<TurnFailure, 'name' | 'status' | 'reason'>): boolean {\n return TRANSIENT_ERRORS.has(failure.name) || [408, 429, 502, 504].includes(failure.status ?? 0) ||\n (failure.status === 503 && (failure.reason === undefined || TRANSIENT_503.has(failure.reason)))\n}\n\n/**\n * The platform refuses a funded request once the paying key's budget is\n * spent. That refusal is decided, so retrying it would loop forever.\n */\nconst budgetExhausted = (error: unknown) => error instanceof Error && error.name === 'KeyBudgetExhaustedError'\n\n/** One non-blocking pass for one message. Safe to repeat with the same turn id. */\nexport async function runHostedTurn<Box extends TurnBox>(turn: { turnId: string; text: string }, ports: HostedTurnPorts<Box>,\n options: HostedTurnOptions): Promise<TurnOutcome> {\n const now = options.now ?? Date.now\n const sleep = options.sleep ?? ((ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms)))\n const observe = ports.observe ?? {}\n const allowDispatch = options.allowDispatch !== false\n const text = turn.text.trim()\n if (!text || text.length > MAX_MESSAGE_CHARS || !turn.turnId || turn.turnId.length > 200) return refusal('refused', 'invalid_message')\n const refused = await ports.admit()\n if (refused) return refused\n\n const timed = async <T>(step: 'ensure' | 'session' | 'drive', fn: () => Promise<T>): Promise<T> => {\n const start = now()\n try { return await fn() } finally { observe.span?.(step, now() - start) }\n }\n const failed = async (step: 'ensure' | 'drive', error: unknown, boxId?: string): Promise<TurnOutcome> => {\n const failure = describeFailure(error)\n await observe.failure?.(step, failure, boxId)\n const classified = ports.classify?.(error, step)\n if (classified) return classified\n if (error instanceof TurnPending) return { ok: 'pending', detail: { step, code: error.code, transient: error.transient } }\n if (budgetExhausted(error)) return refusal('refused', 'budget_exhausted')\n // An admission whose response was lost is retried with the same turn id;\n // the runtime's admission receipt prevents a second execution.\n return { ok: 'pending', detail: { step, code: failure.code, transient: isTransientFailure(failure) }, cause: error }\n }\n\n let box: Box\n try {\n box = await timed('ensure', () => ports.box())\n } catch (error) {\n return failed('ensure', error)\n }\n if (ports.authorize && !await ports.authorize()) return refusal('refused', AUTHORITY_ENDED)\n\n let result: ConversationTurnResult\n try {\n const prompt = await ports.prompt(box)\n const sessionId = ports.sessionId\n // The SDK would create a missing session with no profile, and the runtime\n // would then answer as its generic default assistant.\n if (allowDispatch) await timed('session', async () => {\n const session = await box.session(sessionId).status()\n if (session) {\n observe.session?.({ created: false, ...sessionInfo(session) })\n return\n }\n const backend = await ports.backend()\n await box.createSession({ sessionId, retention: 'workspace', backend })\n // A new session names its harness and model only once the runtime has created it.\n const created = observe.session && observe.readCreatedSession ? sessionInfo(await box.session(sessionId).status()) : {}\n observe.session?.({ created: true, ...(backend.type ? { harness: backend.type } : {}), ...created })\n })\n for (;;) {\n result = await timed('drive', () => box.driveConversationTurn(prompt, { sessionId, turnId: turn.turnId,\n wallCapMs: options.wallCapMs, timeoutMs: options.timeoutMs ?? 8000, allowDispatch }))\n observe.drive?.(result, now())\n const pollMs = options.pollMs ?? 2000\n if (!RUNNING.has(result.state) || options.until === undefined || now() + pollMs > options.until) break\n await sleep(pollMs)\n }\n } catch (error) {\n return failed('drive', error, box.id)\n }\n switch (result.state) {\n case 'completed': {\n const answer = result.text.trim()\n if (!answer) {\n await observe.failure?.('turn', describeFailure(new Error('The turn completed with no reply text')), box.id)\n return refusal('unavailable', 'empty_reply')\n }\n await ports.answered?.(answer, box)\n return { ok: true, text: answer }\n }\n case 'failed':\n await observe.failure?.('turn', describeFailure(Object.assign(new Error(result.error), { name: 'TurnFailed' })), box.id)\n return refusal('unavailable', 'agent_failed')\n // Interaction and plan approval are not exposed over messaging. The wall\n // cap cancels a turn that waits on one, which frees the session.\n // Sandbox 0.45 reported approval and question outcomes as `failed`.\n case 'awaiting_plan_decision': case 'blocked_on_approval': case 'awaiting_question': case 'awaiting_interaction':\n return refusal('refused', 'needs_decision')\n case 'running': case 'awaiting_input': case 'not_admitted':\n return { ok: 'pending', detail: { step: 'turn', code: result.state, transient: true } }\n }\n}\n\n/**\n * Repeat passes until the turn settles, for a caller that holds a connection\n * open (a voice question, say). A turn the runtime never finishes must not\n * hold the caller forever, so `deadline` bounds the wait; `signal` stops the\n * wait only, and the admitted turn keeps running.\n */\nexport async function settleHostedTurn(pass: () => Promise<TurnOutcome>, options: {\n deadline: number\n pollMs?: number\n signal?: AbortSignal\n now?: () => number\n sleep?: (ms: number, signal?: AbortSignal) => Promise<void>\n}): Promise<TurnReply> {\n const now = options.now ?? Date.now\n const sleep = options.sleep ?? ((ms: number, signal?: AbortSignal) => new Promise<void>((resolve, reject) => {\n const timer = setTimeout(resolve, ms)\n signal?.addEventListener('abort', () => { clearTimeout(timer); reject(signal.reason) }, { once: true })\n }))\n let last = '', repeats = 0\n for (;;) {\n if (options.signal?.aborted || now() > options.deadline) return refusal('unavailable', 'pending')\n const outcome = await pass()\n if (outcome.ok !== 'pending') return outcome\n repeats = outcome.detail.code === last ? repeats + 1 : 1\n last = outcome.detail.code\n if (!outcome.detail.transient && repeats >= MAX_REPEATED_FAILURES) return refusal('unavailable', `${outcome.detail.step}:${last}`)\n try { await sleep(options.pollMs ?? 1500, options.signal) } catch { return refusal('unavailable', 'pending') }\n }\n}\n\n/**\n * A space member who may chat only: no shell and no file writes in the shared\n * box. The profile's other settings are kept.\n */\nexport function chatOnlyBackend(backend: BackendConfig): BackendConfig {\n const profile = backend.profile ?? {}\n return { ...backend, profile: { ...profile,\n tools: { ...profile.tools, bash: false, edit: false, write: false },\n permissions: { ...profile.permissions, bash: 'deny', edit: 'deny' } } }\n}\n"],"mappings":";AAAA,SAAS,6BAA6B,iBAAwC;AAC9E,SAAS,qBAAqB,kCAAkC;AAEhE,SAAS,SAAS,oBAAoB;;;AC6B/B,IAAM,oBAAoB;AAE1B,IAAM,wBAAwB;AAE9B,IAAM,kBAAkB;AAWxB,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YAAqB,MAAuB,WAAoB;AAC9D,UAAM,IAAI;AADS;AAAuB;AAE1C,SAAK,OAAO;AAAA,EACd;AAAA,EAHqB;AAAA,EAAuB;AAI9C;AAgEA,SAAS,YAAY,SAAwD;AAC3E,QAAM,IAAK,OAAO,YAAY,YAAY,YAAY,OAAO,UAAU,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,UAChC,IAAI,EAAE,QAAQ,KAAK,OAAO,SAAS,SAAS,MAAM,MAAM,KAAK,GAAG,OAAO,GAAG,EAAE,UAAU,KAAK,IAAI,IAAI,SAAS,CAAC;AAAA,UAC7G,MAAM,QAAQ,EAAE,KAAK,OAAkB,EAAE,OAAO,UAAU,EAAE;AAAA,QAC9D,CAAC;AACD,YAAI,OAAO,UAAU,UAAW,QAAO,KAAK,EAAE,QAAQ,WAAW,QAAQ,GAAG,MAAM,IAAI,KAAK,GAAG,CAAC;AAC/F,YAAI,OAAO,UAAU,WAAY,QAAO,KAAK,EAAE,QAAQ,YAAY,QAAQ,OAAO,SAAS,kCAAkC,CAAC;AAC9H,eAAO,KAAK,EAAE,QAAQ,YAAY,QAAQ,OAAO,KAAK,CAAC;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":["sleep"]}
|
|
1
|
+
{"version":3,"sources":["../../src/hosted-agent/index.ts","../../src/hosted-agent/engine.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 { InstanceRestartingError, Sandbox } from '@tangle-network/sandbox/core'\nimport { runHostedTurn, TurnPending } from './engine'\n\nexport * from './engine'\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 * The platform keeps each person's box and counts their turns: each person\n * is one Sandbox instance (`sandbox.instances`), a fresh isolated box built\n * from the published profile, and one member of a Hub allowance meter.\n * Later messages resume the same box and conversation, so text and voice\n * share one memory. A new profile starts a new session in the same box; a\n * replaced box starts a new one. Either way the person's recent conversation\n * 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, the same allowance admission and the same\n * Hub send. So the caller may retry any failure, and needs no dedupe table.\n */\n\n/** Durable key-value storage for STOP state, the debug switch, call tokens and recent turns. 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 /**\n * The Platform meter that counts this agent's turns (Hub\n * `hub.allowances`). Each person is one member. Default `hosted-agent`.\n */\n meter?: string\n /**\n * Answers per person per UTC day before `allow` must decide. Default 20.\n * Written to the meter's plan when the meter has none; a plan already set\n * on the Platform wins.\n */\n freeTurnsPerDay?: number\n /**\n * Decide a new message past the free allowance when paying would lift the\n * limit (the Platform's `paywall` decision), for example reply with a\n * checkout link. Without it, or past the paid allowance, a person 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 /** Time the platform took to hand over the person's running box, such as `box 0.3s`. */\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\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 // A completed turn arrives as the run's own record (`tokenUsage`, `timing`,\n // `toolInvocations`) or as the platform's cached summary (`usage`, `costUsd`).\n // Both count every prompt token; the SDK's typed usage counts only the\n // uncached tail on the summary (3 of 1,214), so it is the fallback. The\n // summary's `durationMs` is not the run time, so that shape has none.\n const reported = (result.tokenUsage ?? result.usage ?? {}) 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(reported.inputTokens) ?? num(usage?.inputTokens)\n trace.outputTokens = num(reported.outputTokens) ?? num(usage?.outputTokens)\n trace.reasoningTokens = num(reported.reasoningTokens)\n if (result.usdKnown !== false) trace.costUsd = num(reported.cost) ?? num(result.costUsd) ?? num(result.totalCostUsd)\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 // The peer range admits older Sandbox minors for other subpaths; named instances arrived in 0.50.\n if (!('instances' in sandbox)) throw new HostedAgentError('sandbox_too_old', 'hosted-agent needs @tangle-network/sandbox 0.50 or later.')\n const hub = new HubClient({ baseUrl: config.hubUrl ?? 'https://id.tangle.tools', apiKey: config.apiKey })\n // The Hub SDK peer range admits older minors for apps that do not host agents; the allowance meter arrived in 0.17.\n if (!('allowances' in hub)) throw new HostedAgentError('hub_sdk_too_old', 'hosted-agent needs @tangle-network/hub-sdk 0.17 or later.')\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, kept by the platform. Null when the deadline passed while it starts. */\n async function ensureBox(user: string, deadline: number): Promise<SandboxInstance | null> {\n let box: SandboxInstance\n try {\n ({ box } = await sandbox.instances.ensure({\n key: `hosted:${user}`,\n profile: { version: await profileTag, backend },\n // A box this kit made before the platform kept instances keeps its files.\n adopt: await store.get(`box:${user}`) ?? undefined,\n create: {\n name: `hosted-${user.slice(0, 24)}`,\n resources: { cpuCores: policy.cpuCores, memoryMB: policy.memoryMB, diskGB: policy.diskGB },\n 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 }))\n } catch (error) {\n // The platform replaces a box that keeps failing to start; until then the turn waits.\n if (error instanceof InstanceRestartingError) throw new TurnPending('box_restarting', true)\n throw error\n }\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 const meter = config.meter ?? 'hosted-agent'\n const owner = config.owner ? normalizeAddress(config.owner) : null\n /** Give the meter the configured allowance once, unless it already has a plan. */\n let planned: Promise<void> | undefined\n const ensurePlan = () => planned ??= (async () => {\n if ((await hub.allowances.plan(meter)).configured) return\n await hub.allowances.setPlan(meter, { free: { turnsPerDay: config.freeTurnsPerDay ?? 20, usdPerDay: null }, paid: null,\n spendResourceType: null })\n })().catch(error => { planned = undefined; throw error })\n\n /** Admit a new message once: STOP/START, then the Platform's 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 await ensurePlan()\n // The Platform counts atomically and never counts one turn id twice.\n const allowance = await hub.allowances.admit(meter, { member: user, role: message.userId === owner ? 'owner' : 'member',\n turnId: message.turnId, channel: message.channel })\n if (allowance.decision === 'admit') return 'answer'\n // Past the paid allowance, nothing the person buys lifts today's limit.\n return allowance.decision === 'paywall' && config.allow ? await config.allow(message, allowance.turns.used) : { reply: NOTICE.limit }\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 // 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 trace = options.trace\n const conversationKey = `convo:${user}`\n let declined: AskResult | undefined\n let conversation: Conversation | undefined, at = ''\n const outcome = await runHostedTurn({ turnId: message.turnId, text }, {\n // The allowance counts a turn id once per person and admits its retries\n // again, so a model-supplied voice ticket cannot spend another person's turn.\n async admit() {\n const decision = await admit(message, user)\n if (decision === 'answer') return null\n declined = decision === 'ignore' ? { state: 'declined' } : { state: 'declined', reply: decision.reply }\n return { ok: false, reason: 'refused', detail: 'declined' }\n },\n async box() {\n const box = await ensureBox(user, options.deadline)\n if (!box) throw new TurnPending('box_starting', true)\n return box\n },\n sessionId,\n backend: async () => backend,\n async prompt(box) {\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 at = `${box.id}/${sessionId}`\n const stored = await store.get(conversationKey)\n 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 return carried ? `${CARRY_HEAD}\\n${carried}\\n${CARRY_NOW}\\n${asked}` : asked\n },\n async answered(answer) {\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 },\n classify: error => error instanceof HostedAgentError ? { ok: false, reason: 'unavailable', detail: error.code } : undefined,\n observe: {\n readCreatedSession: Boolean(trace),\n span(step, ms) {\n if (trace && step === 'ensure') trace.box ??= `box ${seconds(ms)}`\n },\n session(info) {\n if (!trace) return\n trace.harness = info.harness ?? config.harness\n trace.model = info.model\n },\n drive(result) {\n if (trace && result.state === 'completed') noteResult(trace, result.result, result.usage)\n },\n failure(step, failure) {\n console.error(`[hosted-agent] turn=${message.turnId} step=${step} code=${failure.code} message=${JSON.stringify(failure.message)}`)\n },\n },\n }, { wallCapMs, timeoutMs: 8000, until: options.deadline })\n if (declined) return declined\n if (outcome.ok === true) return { state: 'answered', text: outcome.text }\n // A thrown failure is rethrown, so the caller's retry policy decides it.\n if (outcome.ok === 'pending') {\n if (outcome.cause !== undefined) throw outcome.cause\n return { state: 'pending' }\n }\n const code = outcome.detail ?? outcome.reason\n throw new HostedAgentError(code === 'agent_failed' ? 'turn_failed' : code, `The turn ended without an answer (${code}).`)\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","import type { BackendConfig, CreateSessionOptions } from '@tangle-network/sandbox'\nimport type { ConversationTurnOptions, ConversationTurnResult, PromptInputPart } from '@tangle-network/sandbox/core'\n\n/**\n * The one turn engine for a hosted agent, whatever hosts it. This kit's\n * `createHostedAgent` runs on it with a key-value store, and Agent Builder\n * runs on it with its D1 enrollments, per-user keys, spaces and product\n * ingest. A host supplies those as ports; the engine owns the order of the\n * steps and what each outcome and failure means.\n *\n * One call is one non-blocking pass for one message:\n *\n * validate -> admit once -> the person's box -> authorize -> session -> drive -> classify\n *\n * Every step is idempotent by the turn id: the sandbox's admission receipt\n * settles a repeated drive on the same turn, so a host may repeat a pass for\n * the same message any number of times and the agent runs it once.\n */\n\nexport type TurnRefusal = 'not_enrolled' | 'execution_not_ready' | 'refused' | 'unavailable'\nexport type TurnReply = { ok: true; text: string } | { ok: false; reason: TurnRefusal; detail?: string }\nexport type TurnStep = 'ensure' | 'drive' | 'turn'\n/**\n * Where an unfinished turn stands. `code` is the same on every repeat of the\n * same cause, so a host can tell a stuck turn from a slow one. A transient\n * cause (a lost response, a timeout, a busy platform, a box still starting)\n * is expected to clear by itself; any other repeats until it is fixed.\n */\nexport interface PendingDetail { step: TurnStep; code: string; transient: boolean }\n/** `cause` is what a port or the Sandbox threw, when a throw left the turn pending. */\nexport type TurnOutcome = TurnReply | { ok: 'pending'; detail: PendingDetail; cause?: unknown }\n\nexport const MAX_MESSAGE_CHARS = 8000\n/** Identical non-transient failures in a row after which a host fails a turn. */\nexport const MAX_REPEATED_FAILURES = 3\n/** Refusal detail when the host's `authorize` check fails. */\nexport const AUTHORITY_ENDED = 'authority_ended'\n\n/** The part of a Sandbox box one turn uses. `SandboxInstance` satisfies it. */\nexport interface TurnBox {\n readonly id: string\n driveConversationTurn(message: string | PromptInputPart[], options: ConversationTurnOptions): Promise<ConversationTurnResult>\n session(id: string): { status(): Promise<unknown> }\n createSession(options: CreateSessionOptions): Promise<unknown>\n}\n\n/** A port throws this to report a turn that is not ready yet, such as a box still starting. */\nexport class TurnPending extends Error {\n constructor(readonly code: string, readonly transient: boolean) {\n super(code)\n this.name = 'TurnPending'\n }\n}\n\n/** A thrown value as a stable code plus a secret-free message for a log line. */\nexport interface TurnFailure { name: string; code: string; status?: number; reason?: string; message: string }\n\n/** What a pass reports while it runs. Every hook is optional; none changes the outcome. */\nexport interface TurnObserver {\n /** Time one step of this pass took, whether it returned or threw. */\n span?(step: 'ensure' | 'session' | 'drive', ms: number): void\n /** The session the turn runs in, as the runtime reports it, or the backend it was created with. */\n session?(info: { harness?: string; model?: string; created: boolean }): void\n /**\n * Read a session this pass created once more, so `session` reports the\n * harness and model the runtime chose for it. It costs one request, so a\n * host asks for it only when it shows them (an owner's debug line, say).\n */\n readCreatedSession?: boolean\n /** Each drive result and the time it arrived. */\n drive?(result: ConversationTurnResult, at: number): void\n /** A failure that left the turn pending or refused. */\n failure?(step: TurnStep, failure: TurnFailure, boxId?: string): void | Promise<void>\n}\n\n/** Storage and policy a host supplies for one message. */\nexport interface HostedTurnPorts<Box extends TurnBox = TurnBox> {\n /**\n * Admit this turn once, before any compute. Return null to run it, or the\n * refusal. A turn admitted by an earlier pass must return null again, so a\n * retry never consumes allowance twice.\n */\n admit(): Promise<Extract<TurnReply, { ok: false }> | null>\n /** The person's running box: created, resumed or replaced as needed. Throw to report why not. */\n box(): Promise<Box>\n /** The host's own authority (a phone link, say), read after the box is ready and right before the drive. */\n authorize?(): Promise<boolean>\n /** The session this turn runs in. A session binds its backend when created, so a new persona needs a new id. */\n sessionId: string\n /** The backend a missing session is created with. Without it the runtime answers as its generic assistant. */\n backend(): Promise<BackendConfig>\n /** The message as the agent receives it: text, or text and images. */\n prompt(box: Box): Promise<string | PromptInputPart[]>\n /** Runs once the turn has a non-empty answer, before the pass returns it. */\n answered?(answer: string, box: Box): Promise<void>\n /** Map a thrown value to an outcome. Undefined leaves it to the engine's own classification. */\n classify?(error: unknown, step: 'ensure' | 'drive'): TurnOutcome | undefined\n observe?: TurnObserver\n}\n\nexport interface HostedTurnOptions {\n /** The run's wall-clock cap; the Sandbox cancels a turn that exceeds it. */\n wallCapMs: number\n /** How long one drive request may wait on a running turn. Default 8 s. */\n timeoutMs?: number\n /** False only reads a turn admitted earlier; it never admits or starts one. */\n allowDispatch?: boolean\n /** Keep driving a running turn until this time, instead of returning pending after one drive. */\n until?: number\n /** Wait between drives while `until` allows. Default 2 s. */\n pollMs?: number\n now?: () => number\n sleep?: (ms: number) => Promise<void>\n}\n\n/** Harness and model as the runtime reports them; the model it selected after normalization wins. */\nfunction sessionInfo(session: unknown): { harness?: string; model?: string } {\n const s = (typeof session === 'object' && session !== null ? session : {}) as\n { backend?: unknown; model?: unknown; effectiveBackend?: { model?: unknown } | null }\n const effective = s.effectiveBackend?.model\n const model = typeof effective === 'string' && effective ? effective : typeof s.model === 'string' && s.model ? s.model : undefined\n return { ...(typeof s.backend === 'string' && s.backend ? { harness: s.backend } : {}), ...(model ? { model } : {}) }\n}\n\nconst refusal = (reason: TurnRefusal, detail?: string): Extract<TurnReply, { ok: false }> => ({ ok: false, reason, ...(detail ? { detail } : {}) })\nconst RUNNING = new Set(['running', 'awaiting_input', 'not_admitted'])\nconst TRANSIENT_ERRORS = new Set(['NetworkError', 'TimeoutError', 'QuotaError', 'AbortError', 'EdgeNotReadyError'])\n/**\n * The 503 codes the Sandbox SDK itself classifies as refused before dispatch\n * and safe to retry. A 503 with any other code, such as\n * HUB_CREDENTIAL_REFRESH_FAILED, has not shown it will clear by itself.\n */\nconst TRANSIENT_503 = new Set(['MODEL_CREDENTIAL_SUPERSEDED', 'HUB_CREDENTIAL_REFRESH_UNAVAILABLE'])\n\n/** The code omits the message, which can carry ids or times that differ on every repeat of one cause. */\nexport function describeFailure(error: unknown): TurnFailure {\n const e = (typeof error === 'object' && error !== null ? error : {}) as Record<string, unknown>\n const name = typeof e.name === 'string' ? e.name : typeof error\n const status = typeof e.status === 'number' ? e.status : undefined\n const own = typeof e.code === 'string' ? e.code : typeof e.reason === 'string' ? e.reason : undefined\n const code = [name, own, status].filter(part => part !== undefined).join(':').replace(/[^\\w.:-]/g, '_').slice(0, 100)\n const message = String(typeof e.message === 'string' ? e.message : error)\n .replace(/sk-tan-[\\w-]+|eyJ[\\w-]+\\.[\\w-]+\\.[\\w-]*|Bearer\\s+\\S+/g, '<redacted>').slice(0, 400)\n return { name, code, ...(status !== undefined ? { status } : {}), ...(own !== undefined ? { reason: own } : {}), message }\n}\n\nexport function isTransientFailure(failure: Pick<TurnFailure, 'name' | 'status' | 'reason'>): boolean {\n return TRANSIENT_ERRORS.has(failure.name) || [408, 429, 502, 504].includes(failure.status ?? 0) ||\n (failure.status === 503 && (failure.reason === undefined || TRANSIENT_503.has(failure.reason)))\n}\n\n/**\n * The platform refuses a funded request once the paying key's budget is\n * spent. That refusal is decided, so retrying it would loop forever.\n */\nconst budgetExhausted = (error: unknown) => error instanceof Error && error.name === 'KeyBudgetExhaustedError'\n\n/** One non-blocking pass for one message. Safe to repeat with the same turn id. */\nexport async function runHostedTurn<Box extends TurnBox>(turn: { turnId: string; text: string }, ports: HostedTurnPorts<Box>,\n options: HostedTurnOptions): Promise<TurnOutcome> {\n const now = options.now ?? Date.now\n const sleep = options.sleep ?? ((ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms)))\n const observe = ports.observe ?? {}\n const allowDispatch = options.allowDispatch !== false\n const text = turn.text.trim()\n if (!text || text.length > MAX_MESSAGE_CHARS || !turn.turnId || turn.turnId.length > 200) return refusal('refused', 'invalid_message')\n const refused = await ports.admit()\n if (refused) return refused\n\n const timed = async <T>(step: 'ensure' | 'session' | 'drive', fn: () => Promise<T>): Promise<T> => {\n const start = now()\n try { return await fn() } finally { observe.span?.(step, now() - start) }\n }\n const failed = async (step: 'ensure' | 'drive', error: unknown, boxId?: string): Promise<TurnOutcome> => {\n const failure = describeFailure(error)\n await observe.failure?.(step, failure, boxId)\n const classified = ports.classify?.(error, step)\n if (classified) return classified\n if (error instanceof TurnPending) return { ok: 'pending', detail: { step, code: error.code, transient: error.transient } }\n if (budgetExhausted(error)) return refusal('refused', 'budget_exhausted')\n // An admission whose response was lost is retried with the same turn id;\n // the runtime's admission receipt prevents a second execution.\n return { ok: 'pending', detail: { step, code: failure.code, transient: isTransientFailure(failure) }, cause: error }\n }\n\n let box: Box\n try {\n box = await timed('ensure', () => ports.box())\n } catch (error) {\n return failed('ensure', error)\n }\n if (ports.authorize && !await ports.authorize()) return refusal('refused', AUTHORITY_ENDED)\n\n let result: ConversationTurnResult\n try {\n const prompt = await ports.prompt(box)\n const sessionId = ports.sessionId\n // The SDK would create a missing session with no profile, and the runtime\n // would then answer as its generic default assistant.\n if (allowDispatch) await timed('session', async () => {\n const session = await box.session(sessionId).status()\n if (session) {\n observe.session?.({ created: false, ...sessionInfo(session) })\n return\n }\n const backend = await ports.backend()\n await box.createSession({ sessionId, retention: 'workspace', backend })\n // A new session names its harness and model only once the runtime has created it.\n const created = observe.session && observe.readCreatedSession ? sessionInfo(await box.session(sessionId).status()) : {}\n observe.session?.({ created: true, ...(backend.type ? { harness: backend.type } : {}), ...created })\n })\n for (;;) {\n result = await timed('drive', () => box.driveConversationTurn(prompt, { sessionId, turnId: turn.turnId,\n wallCapMs: options.wallCapMs, timeoutMs: options.timeoutMs ?? 8000, allowDispatch }))\n observe.drive?.(result, now())\n const pollMs = options.pollMs ?? 2000\n if (!RUNNING.has(result.state) || options.until === undefined || now() + pollMs > options.until) break\n await sleep(pollMs)\n }\n } catch (error) {\n return failed('drive', error, box.id)\n }\n switch (result.state) {\n case 'completed': {\n const answer = result.text.trim()\n if (!answer) {\n await observe.failure?.('turn', describeFailure(new Error('The turn completed with no reply text')), box.id)\n return refusal('unavailable', 'empty_reply')\n }\n await ports.answered?.(answer, box)\n return { ok: true, text: answer }\n }\n case 'failed':\n await observe.failure?.('turn', describeFailure(Object.assign(new Error(result.error), { name: 'TurnFailed' })), box.id)\n return refusal('unavailable', 'agent_failed')\n // Interaction and plan approval are not exposed over messaging. The wall\n // cap cancels a turn that waits on one, which frees the session.\n // Sandbox 0.45 reported approval and question outcomes as `failed`.\n case 'awaiting_plan_decision': case 'blocked_on_approval': case 'awaiting_question': case 'awaiting_interaction':\n return refusal('refused', 'needs_decision')\n case 'running': case 'awaiting_input': case 'not_admitted':\n return { ok: 'pending', detail: { step: 'turn', code: result.state, transient: true } }\n }\n}\n\n/**\n * Repeat passes until the turn settles, for a caller that holds a connection\n * open (a voice question, say). A turn the runtime never finishes must not\n * hold the caller forever, so `deadline` bounds the wait; `signal` stops the\n * wait only, and the admitted turn keeps running.\n */\nexport async function settleHostedTurn(pass: () => Promise<TurnOutcome>, options: {\n deadline: number\n pollMs?: number\n signal?: AbortSignal\n now?: () => number\n sleep?: (ms: number, signal?: AbortSignal) => Promise<void>\n}): Promise<TurnReply> {\n const now = options.now ?? Date.now\n const sleep = options.sleep ?? ((ms: number, signal?: AbortSignal) => new Promise<void>((resolve, reject) => {\n const timer = setTimeout(resolve, ms)\n signal?.addEventListener('abort', () => { clearTimeout(timer); reject(signal.reason) }, { once: true })\n }))\n let last = '', repeats = 0\n for (;;) {\n if (options.signal?.aborted || now() > options.deadline) return refusal('unavailable', 'pending')\n const outcome = await pass()\n if (outcome.ok !== 'pending') return outcome\n repeats = outcome.detail.code === last ? repeats + 1 : 1\n last = outcome.detail.code\n if (!outcome.detail.transient && repeats >= MAX_REPEATED_FAILURES) return refusal('unavailable', `${outcome.detail.step}:${last}`)\n try { await sleep(options.pollMs ?? 1500, options.signal) } catch { return refusal('unavailable', 'pending') }\n }\n}\n\n/**\n * A space member who may chat only: no shell and no file writes in the shared\n * box. The profile's other settings are kept.\n */\nexport function chatOnlyBackend(backend: BackendConfig): BackendConfig {\n const profile = backend.profile ?? {}\n return { ...backend, profile: { ...profile,\n tools: { ...profile.tools, bash: false, edit: false, write: false },\n permissions: { ...profile.permissions, bash: 'deny', edit: 'deny' } } }\n}\n"],"mappings":";AAAA,SAAS,6BAA6B,iBAAwC;AAC9E,SAAS,qBAAqB,kCAAkC;AAEhE,SAAS,yBAAyB,eAAe;;;AC6B1C,IAAM,oBAAoB;AAE1B,IAAM,wBAAwB;AAE9B,IAAM,kBAAkB;AAWxB,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YAAqB,MAAuB,WAAoB;AAC9D,UAAM,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WAAW,QAAQ,GAAG,MAAM,IAAI,KAAK,GAAG,CAAC;AAC/F,YAAI,OAAO,UAAU,WAAY,QAAO,KAAK,EAAE,QAAQ,YAAY,QAAQ,OAAO,SAAS,kCAAkC,CAAC;AAC9H,eAAO,KAAK,EAAE,QAAQ,YAAY,QAAQ,OAAO,KAAK,CAAC;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":["sleep"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/agent-app",
|
|
3
|
-
"version": "0.49.
|
|
3
|
+
"version": "0.49.16",
|
|
4
4
|
"packageManager": "pnpm@11.24.0",
|
|
5
5
|
"description": "Build agent applications with typed chat, tools, sandboxes, integrations, billing, and evaluation.",
|
|
6
6
|
"keywords": [
|
|
@@ -546,10 +546,10 @@
|
|
|
546
546
|
"@tangle-network/agent-interface": "2.12.0",
|
|
547
547
|
"@tangle-network/agent-knowledge": "17.1.2",
|
|
548
548
|
"@tangle-network/agent-profile-materialize": "0.20.1",
|
|
549
|
-
"@tangle-network/agent-runtime": "0.
|
|
549
|
+
"@tangle-network/agent-runtime": "0.262.0",
|
|
550
550
|
"@tangle-network/brand": "1.5.0",
|
|
551
|
-
"@tangle-network/hub-sdk": "0.
|
|
552
|
-
"@tangle-network/sandbox": "0.
|
|
551
|
+
"@tangle-network/hub-sdk": "0.17.0",
|
|
552
|
+
"@tangle-network/sandbox": "0.50.0",
|
|
553
553
|
"@tangle-network/sandbox-ui": "0.113.3",
|
|
554
554
|
"@tangle-network/ui": "11.9.0",
|
|
555
555
|
"@testing-library/dom": "^10.4.1",
|
|
@@ -607,10 +607,10 @@
|
|
|
607
607
|
"@tangle-network/agent-interface": "^2.11.0",
|
|
608
608
|
"@tangle-network/agent-knowledge": "^17.1.2",
|
|
609
609
|
"@tangle-network/agent-profile-materialize": ">=0.20.1 <0.21.0",
|
|
610
|
-
"@tangle-network/agent-runtime": ">=0.
|
|
610
|
+
"@tangle-network/agent-runtime": ">=0.262.0 <0.263.0",
|
|
611
611
|
"@tangle-network/brand": ">=1.5.0",
|
|
612
|
-
"@tangle-network/hub-sdk": ">=0.12.6 <0.
|
|
613
|
-
"@tangle-network/sandbox": ">=0.45.0 <0.48.0 || ^0.49.0",
|
|
612
|
+
"@tangle-network/hub-sdk": ">=0.12.6 <0.18.0",
|
|
613
|
+
"@tangle-network/sandbox": ">=0.45.0 <0.48.0 || ^0.49.0 || ^0.50.0",
|
|
614
614
|
"@tangle-network/sandbox-ui": ">=0.113.3 <0.114.0",
|
|
615
615
|
"@tangle-network/ui": ">=11.6.0 <12.0.0",
|
|
616
616
|
"@tiptap/core": ">=3.28.0 <4.0.0",
|