@tangle-network/agent-app 0.49.9 → 0.49.10
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.
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import type { BackendConfig, CreateSessionOptions } from '@tangle-network/sandbox';
|
|
2
|
+
import type { ConversationTurnOptions, ConversationTurnResult, PromptInputPart } from '@tangle-network/sandbox/core';
|
|
3
|
+
/**
|
|
4
|
+
* The one turn engine for a hosted agent, whatever hosts it. This kit's
|
|
5
|
+
* `createHostedAgent` runs on it with a key-value store, and Agent Builder
|
|
6
|
+
* runs on it with its D1 enrollments, per-user keys, spaces and product
|
|
7
|
+
* ingest. A host supplies those as ports; the engine owns the order of the
|
|
8
|
+
* steps and what each outcome and failure means.
|
|
9
|
+
*
|
|
10
|
+
* One call is one non-blocking pass for one message:
|
|
11
|
+
*
|
|
12
|
+
* validate -> admit once -> the person's box -> authorize -> session -> drive -> classify
|
|
13
|
+
*
|
|
14
|
+
* Every step is idempotent by the turn id: the sandbox's admission receipt
|
|
15
|
+
* settles a repeated drive on the same turn, so a host may repeat a pass for
|
|
16
|
+
* the same message any number of times and the agent runs it once.
|
|
17
|
+
*/
|
|
18
|
+
export type TurnRefusal = 'not_enrolled' | 'execution_not_ready' | 'refused' | 'unavailable';
|
|
19
|
+
export type TurnReply = {
|
|
20
|
+
ok: true;
|
|
21
|
+
text: string;
|
|
22
|
+
} | {
|
|
23
|
+
ok: false;
|
|
24
|
+
reason: TurnRefusal;
|
|
25
|
+
detail?: string;
|
|
26
|
+
};
|
|
27
|
+
export type TurnStep = 'ensure' | 'drive' | 'turn';
|
|
28
|
+
/**
|
|
29
|
+
* Where an unfinished turn stands. `code` is the same on every repeat of the
|
|
30
|
+
* same cause, so a host can tell a stuck turn from a slow one. A transient
|
|
31
|
+
* cause (a lost response, a timeout, a busy platform, a box still starting)
|
|
32
|
+
* is expected to clear by itself; any other repeats until it is fixed.
|
|
33
|
+
*/
|
|
34
|
+
export interface PendingDetail {
|
|
35
|
+
step: TurnStep;
|
|
36
|
+
code: string;
|
|
37
|
+
transient: boolean;
|
|
38
|
+
}
|
|
39
|
+
/** `cause` is what a port or the Sandbox threw, when a throw left the turn pending. */
|
|
40
|
+
export type TurnOutcome = TurnReply | {
|
|
41
|
+
ok: 'pending';
|
|
42
|
+
detail: PendingDetail;
|
|
43
|
+
cause?: unknown;
|
|
44
|
+
};
|
|
45
|
+
export declare const MAX_MESSAGE_CHARS = 8000;
|
|
46
|
+
/** Identical non-transient failures in a row after which a host fails a turn. */
|
|
47
|
+
export declare const MAX_REPEATED_FAILURES = 3;
|
|
48
|
+
/** Refusal detail when the host's `authorize` check fails. */
|
|
49
|
+
export declare const AUTHORITY_ENDED = "authority_ended";
|
|
50
|
+
/** The part of a Sandbox box one turn uses. `SandboxInstance` satisfies it. */
|
|
51
|
+
export interface TurnBox {
|
|
52
|
+
readonly id: string;
|
|
53
|
+
driveConversationTurn(message: string | PromptInputPart[], options: ConversationTurnOptions): Promise<ConversationTurnResult>;
|
|
54
|
+
session(id: string): {
|
|
55
|
+
status(): Promise<unknown>;
|
|
56
|
+
};
|
|
57
|
+
createSession(options: CreateSessionOptions): Promise<unknown>;
|
|
58
|
+
}
|
|
59
|
+
/** A port throws this to report a turn that is not ready yet, such as a box still starting. */
|
|
60
|
+
export declare class TurnPending extends Error {
|
|
61
|
+
readonly code: string;
|
|
62
|
+
readonly transient: boolean;
|
|
63
|
+
constructor(code: string, transient: boolean);
|
|
64
|
+
}
|
|
65
|
+
/** A thrown value as a stable code plus a secret-free message for a log line. */
|
|
66
|
+
export interface TurnFailure {
|
|
67
|
+
name: string;
|
|
68
|
+
code: string;
|
|
69
|
+
status?: number;
|
|
70
|
+
reason?: string;
|
|
71
|
+
message: string;
|
|
72
|
+
}
|
|
73
|
+
/** What a pass reports while it runs. Every hook is optional; none changes the outcome. */
|
|
74
|
+
export interface TurnObserver {
|
|
75
|
+
/** Time one step of this pass took, whether it returned or threw. */
|
|
76
|
+
span?(step: 'ensure' | 'session' | 'drive', ms: number): void;
|
|
77
|
+
/** The session the turn runs in, as the runtime reports it, or the backend it was created with. */
|
|
78
|
+
session?(info: {
|
|
79
|
+
harness?: string;
|
|
80
|
+
model?: string;
|
|
81
|
+
created: boolean;
|
|
82
|
+
}): void;
|
|
83
|
+
/**
|
|
84
|
+
* Read a session this pass created once more, so `session` reports the
|
|
85
|
+
* harness and model the runtime chose for it. It costs one request, so a
|
|
86
|
+
* host asks for it only when it shows them (an owner's debug line, say).
|
|
87
|
+
*/
|
|
88
|
+
readCreatedSession?: boolean;
|
|
89
|
+
/** Each drive result and the time it arrived. */
|
|
90
|
+
drive?(result: ConversationTurnResult, at: number): void;
|
|
91
|
+
/** A failure that left the turn pending or refused. */
|
|
92
|
+
failure?(step: TurnStep, failure: TurnFailure, boxId?: string): void | Promise<void>;
|
|
93
|
+
}
|
|
94
|
+
/** Storage and policy a host supplies for one message. */
|
|
95
|
+
export interface HostedTurnPorts<Box extends TurnBox = TurnBox> {
|
|
96
|
+
/**
|
|
97
|
+
* Admit this turn once, before any compute. Return null to run it, or the
|
|
98
|
+
* refusal. A turn admitted by an earlier pass must return null again, so a
|
|
99
|
+
* retry never consumes allowance twice.
|
|
100
|
+
*/
|
|
101
|
+
admit(): Promise<Extract<TurnReply, {
|
|
102
|
+
ok: false;
|
|
103
|
+
}> | null>;
|
|
104
|
+
/** The person's running box: created, resumed or replaced as needed. Throw to report why not. */
|
|
105
|
+
box(): Promise<Box>;
|
|
106
|
+
/** The host's own authority (a phone link, say), read after the box is ready and right before the drive. */
|
|
107
|
+
authorize?(): Promise<boolean>;
|
|
108
|
+
/** The session this turn runs in. A session binds its backend when created, so a new persona needs a new id. */
|
|
109
|
+
sessionId: string;
|
|
110
|
+
/** The backend a missing session is created with. Without it the runtime answers as its generic assistant. */
|
|
111
|
+
backend(): Promise<BackendConfig>;
|
|
112
|
+
/** The message as the agent receives it: text, or text and images. */
|
|
113
|
+
prompt(box: Box): Promise<string | PromptInputPart[]>;
|
|
114
|
+
/** Runs once the turn has a non-empty answer, before the pass returns it. */
|
|
115
|
+
answered?(answer: string, box: Box): Promise<void>;
|
|
116
|
+
/** Map a thrown value to an outcome. Undefined leaves it to the engine's own classification. */
|
|
117
|
+
classify?(error: unknown, step: 'ensure' | 'drive'): TurnOutcome | undefined;
|
|
118
|
+
observe?: TurnObserver;
|
|
119
|
+
}
|
|
120
|
+
export interface HostedTurnOptions {
|
|
121
|
+
/** The run's wall-clock cap; the Sandbox cancels a turn that exceeds it. */
|
|
122
|
+
wallCapMs: number;
|
|
123
|
+
/** How long one drive request may wait on a running turn. Default 8 s. */
|
|
124
|
+
timeoutMs?: number;
|
|
125
|
+
/** False only reads a turn admitted earlier; it never admits or starts one. */
|
|
126
|
+
allowDispatch?: boolean;
|
|
127
|
+
/** Keep driving a running turn until this time, instead of returning pending after one drive. */
|
|
128
|
+
until?: number;
|
|
129
|
+
/** Wait between drives while `until` allows. Default 2 s. */
|
|
130
|
+
pollMs?: number;
|
|
131
|
+
now?: () => number;
|
|
132
|
+
sleep?: (ms: number) => Promise<void>;
|
|
133
|
+
}
|
|
134
|
+
/** The code omits the message, which can carry ids or times that differ on every repeat of one cause. */
|
|
135
|
+
export declare function describeFailure(error: unknown): TurnFailure;
|
|
136
|
+
export declare function isTransientFailure(failure: Pick<TurnFailure, 'name' | 'status' | 'reason'>): boolean;
|
|
137
|
+
/** One non-blocking pass for one message. Safe to repeat with the same turn id. */
|
|
138
|
+
export declare function runHostedTurn<Box extends TurnBox>(turn: {
|
|
139
|
+
turnId: string;
|
|
140
|
+
text: string;
|
|
141
|
+
}, ports: HostedTurnPorts<Box>, options: HostedTurnOptions): Promise<TurnOutcome>;
|
|
142
|
+
/**
|
|
143
|
+
* Repeat passes until the turn settles, for a caller that holds a connection
|
|
144
|
+
* open (a voice question, say). A turn the runtime never finishes must not
|
|
145
|
+
* hold the caller forever, so `deadline` bounds the wait; `signal` stops the
|
|
146
|
+
* wait only, and the admitted turn keeps running.
|
|
147
|
+
*/
|
|
148
|
+
export declare function settleHostedTurn(pass: () => Promise<TurnOutcome>, options: {
|
|
149
|
+
deadline: number;
|
|
150
|
+
pollMs?: number;
|
|
151
|
+
signal?: AbortSignal;
|
|
152
|
+
now?: () => number;
|
|
153
|
+
sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
154
|
+
}): Promise<TurnReply>;
|
|
155
|
+
/**
|
|
156
|
+
* A space member who may chat only: no shell and no file writes in the shared
|
|
157
|
+
* box. The profile's other settings are kept.
|
|
158
|
+
*/
|
|
159
|
+
export declare function chatOnlyBackend(backend: BackendConfig): BackendConfig;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type HubProviderEvent } from '@tangle-network/hub-sdk';
|
|
2
2
|
import type { AgentProfile } from '@tangle-network/sandbox';
|
|
3
|
+
export * from './engine';
|
|
3
4
|
/**
|
|
4
5
|
* A hosted agent: a person texts or calls a line, and the agent answers from
|
|
5
6
|
* that person's own isolated sandbox. The developer's Tangle API key pays for
|
|
@@ -2,6 +2,165 @@
|
|
|
2
2
|
import { authenticateHubEventRequest, HubClient } from "@tangle-network/hub-sdk";
|
|
3
3
|
import { buildMessagingReply, normalizeConversationEvent } from "@tangle-network/agent-integrations/conversation-events";
|
|
4
4
|
import { Sandbox, SandboxError } from "@tangle-network/sandbox/core";
|
|
5
|
+
|
|
6
|
+
// src/hosted-agent/engine.ts
|
|
7
|
+
var MAX_MESSAGE_CHARS = 8e3;
|
|
8
|
+
var MAX_REPEATED_FAILURES = 3;
|
|
9
|
+
var AUTHORITY_ENDED = "authority_ended";
|
|
10
|
+
var TurnPending = class extends Error {
|
|
11
|
+
constructor(code, transient) {
|
|
12
|
+
super(code);
|
|
13
|
+
this.code = code;
|
|
14
|
+
this.transient = transient;
|
|
15
|
+
this.name = "TurnPending";
|
|
16
|
+
}
|
|
17
|
+
code;
|
|
18
|
+
transient;
|
|
19
|
+
};
|
|
20
|
+
function sessionInfo(session) {
|
|
21
|
+
const s = typeof session === "object" && session !== null ? session : {};
|
|
22
|
+
const effective = s.effectiveBackend?.model;
|
|
23
|
+
const model = typeof effective === "string" && effective ? effective : typeof s.model === "string" && s.model ? s.model : void 0;
|
|
24
|
+
return { ...typeof s.backend === "string" && s.backend ? { harness: s.backend } : {}, ...model ? { model } : {} };
|
|
25
|
+
}
|
|
26
|
+
var refusal = (reason, detail) => ({ ok: false, reason, ...detail ? { detail } : {} });
|
|
27
|
+
var RUNNING = /* @__PURE__ */ new Set(["running", "awaiting_input", "not_admitted"]);
|
|
28
|
+
var TRANSIENT_ERRORS = /* @__PURE__ */ new Set(["NetworkError", "TimeoutError", "QuotaError", "AbortError", "EdgeNotReadyError"]);
|
|
29
|
+
var TRANSIENT_503 = /* @__PURE__ */ new Set(["MODEL_CREDENTIAL_SUPERSEDED", "HUB_CREDENTIAL_REFRESH_UNAVAILABLE"]);
|
|
30
|
+
function describeFailure(error) {
|
|
31
|
+
const e = typeof error === "object" && error !== null ? error : {};
|
|
32
|
+
const name = typeof e.name === "string" ? e.name : typeof error;
|
|
33
|
+
const status = typeof e.status === "number" ? e.status : void 0;
|
|
34
|
+
const own = typeof e.code === "string" ? e.code : typeof e.reason === "string" ? e.reason : void 0;
|
|
35
|
+
const code = [name, own, status].filter((part) => part !== void 0).join(":").replace(/[^\w.:-]/g, "_").slice(0, 100);
|
|
36
|
+
const message = String(typeof e.message === "string" ? e.message : error).replace(/sk-tan-[\w-]+|eyJ[\w-]+\.[\w-]+\.[\w-]*|Bearer\s+\S+/g, "<redacted>").slice(0, 400);
|
|
37
|
+
return { name, code, ...status !== void 0 ? { status } : {}, ...own !== void 0 ? { reason: own } : {}, message };
|
|
38
|
+
}
|
|
39
|
+
function isTransientFailure(failure) {
|
|
40
|
+
return TRANSIENT_ERRORS.has(failure.name) || [408, 429, 502, 504].includes(failure.status ?? 0) || failure.status === 503 && (failure.reason === void 0 || TRANSIENT_503.has(failure.reason));
|
|
41
|
+
}
|
|
42
|
+
var budgetExhausted = (error) => error instanceof Error && error.name === "KeyBudgetExhaustedError";
|
|
43
|
+
async function runHostedTurn(turn, ports, options) {
|
|
44
|
+
const now = options.now ?? Date.now;
|
|
45
|
+
const sleep2 = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
46
|
+
const observe = ports.observe ?? {};
|
|
47
|
+
const allowDispatch = options.allowDispatch !== false;
|
|
48
|
+
const text = turn.text.trim();
|
|
49
|
+
if (!text || text.length > MAX_MESSAGE_CHARS || !turn.turnId || turn.turnId.length > 200) return refusal("refused", "invalid_message");
|
|
50
|
+
const refused = await ports.admit();
|
|
51
|
+
if (refused) return refused;
|
|
52
|
+
const timed = async (step, fn) => {
|
|
53
|
+
const start = now();
|
|
54
|
+
try {
|
|
55
|
+
return await fn();
|
|
56
|
+
} finally {
|
|
57
|
+
observe.span?.(step, now() - start);
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
const failed = async (step, error, boxId) => {
|
|
61
|
+
const failure = describeFailure(error);
|
|
62
|
+
await observe.failure?.(step, failure, boxId);
|
|
63
|
+
const classified = ports.classify?.(error, step);
|
|
64
|
+
if (classified) return classified;
|
|
65
|
+
if (error instanceof TurnPending) return { ok: "pending", detail: { step, code: error.code, transient: error.transient } };
|
|
66
|
+
if (budgetExhausted(error)) return refusal("refused", "budget_exhausted");
|
|
67
|
+
return { ok: "pending", detail: { step, code: failure.code, transient: isTransientFailure(failure) }, cause: error };
|
|
68
|
+
};
|
|
69
|
+
let box;
|
|
70
|
+
try {
|
|
71
|
+
box = await timed("ensure", () => ports.box());
|
|
72
|
+
} catch (error) {
|
|
73
|
+
return failed("ensure", error);
|
|
74
|
+
}
|
|
75
|
+
if (ports.authorize && !await ports.authorize()) return refusal("refused", AUTHORITY_ENDED);
|
|
76
|
+
let result;
|
|
77
|
+
try {
|
|
78
|
+
const prompt = await ports.prompt(box);
|
|
79
|
+
const sessionId = ports.sessionId;
|
|
80
|
+
if (allowDispatch) await timed("session", async () => {
|
|
81
|
+
const session = await box.session(sessionId).status();
|
|
82
|
+
if (session) {
|
|
83
|
+
observe.session?.({ created: false, ...sessionInfo(session) });
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
const backend = await ports.backend();
|
|
87
|
+
await box.createSession({ sessionId, retention: "workspace", backend });
|
|
88
|
+
const created = observe.session && observe.readCreatedSession ? sessionInfo(await box.session(sessionId).status()) : {};
|
|
89
|
+
observe.session?.({ created: true, ...backend.type ? { harness: backend.type } : {}, ...created });
|
|
90
|
+
});
|
|
91
|
+
for (; ; ) {
|
|
92
|
+
result = await timed("drive", () => box.driveConversationTurn(prompt, {
|
|
93
|
+
sessionId,
|
|
94
|
+
turnId: turn.turnId,
|
|
95
|
+
wallCapMs: options.wallCapMs,
|
|
96
|
+
timeoutMs: options.timeoutMs ?? 8e3,
|
|
97
|
+
allowDispatch
|
|
98
|
+
}));
|
|
99
|
+
observe.drive?.(result, now());
|
|
100
|
+
const pollMs = options.pollMs ?? 2e3;
|
|
101
|
+
if (!RUNNING.has(result.state) || options.until === void 0 || now() + pollMs > options.until) break;
|
|
102
|
+
await sleep2(pollMs);
|
|
103
|
+
}
|
|
104
|
+
} catch (error) {
|
|
105
|
+
return failed("drive", error, box.id);
|
|
106
|
+
}
|
|
107
|
+
switch (result.state) {
|
|
108
|
+
case "completed": {
|
|
109
|
+
const answer = result.text.trim();
|
|
110
|
+
if (!answer) {
|
|
111
|
+
await observe.failure?.("turn", describeFailure(new Error("The turn completed with no reply text")), box.id);
|
|
112
|
+
return refusal("unavailable", "empty_reply");
|
|
113
|
+
}
|
|
114
|
+
await ports.answered?.(answer, box);
|
|
115
|
+
return { ok: true, text: answer };
|
|
116
|
+
}
|
|
117
|
+
case "failed":
|
|
118
|
+
await observe.failure?.("turn", describeFailure(Object.assign(new Error(result.error), { name: "TurnFailed" })), box.id);
|
|
119
|
+
return refusal("unavailable", "agent_failed");
|
|
120
|
+
// Interaction and plan approval are not exposed over messaging. The wall
|
|
121
|
+
// cap cancels a turn that waits on one, which frees the session.
|
|
122
|
+
case "awaiting_plan_decision":
|
|
123
|
+
return refusal("refused", "needs_decision");
|
|
124
|
+
case "running":
|
|
125
|
+
case "awaiting_input":
|
|
126
|
+
case "not_admitted":
|
|
127
|
+
return { ok: "pending", detail: { step: "turn", code: result.state, transient: true } };
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
async function settleHostedTurn(pass, options) {
|
|
131
|
+
const now = options.now ?? Date.now;
|
|
132
|
+
const sleep2 = options.sleep ?? ((ms, signal) => new Promise((resolve, reject) => {
|
|
133
|
+
const timer = setTimeout(resolve, ms);
|
|
134
|
+
signal?.addEventListener("abort", () => {
|
|
135
|
+
clearTimeout(timer);
|
|
136
|
+
reject(signal.reason);
|
|
137
|
+
}, { once: true });
|
|
138
|
+
}));
|
|
139
|
+
let last = "", repeats = 0;
|
|
140
|
+
for (; ; ) {
|
|
141
|
+
if (options.signal?.aborted || now() > options.deadline) return refusal("unavailable", "pending");
|
|
142
|
+
const outcome = await pass();
|
|
143
|
+
if (outcome.ok !== "pending") return outcome;
|
|
144
|
+
repeats = outcome.detail.code === last ? repeats + 1 : 1;
|
|
145
|
+
last = outcome.detail.code;
|
|
146
|
+
if (!outcome.detail.transient && repeats >= MAX_REPEATED_FAILURES) return refusal("unavailable", `${outcome.detail.step}:${last}`);
|
|
147
|
+
try {
|
|
148
|
+
await sleep2(options.pollMs ?? 1500, options.signal);
|
|
149
|
+
} catch {
|
|
150
|
+
return refusal("unavailable", "pending");
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
function chatOnlyBackend(backend) {
|
|
155
|
+
const profile = backend.profile ?? {};
|
|
156
|
+
return { ...backend, profile: {
|
|
157
|
+
...profile,
|
|
158
|
+
tools: { ...profile.tools, bash: false, edit: false, write: false },
|
|
159
|
+
permissions: { ...profile.permissions, bash: "deny", edit: "deny" }
|
|
160
|
+
} };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// src/hosted-agent/index.ts
|
|
5
164
|
var DEFAULT_BOX_POLICY = {
|
|
6
165
|
cpuCores: 1,
|
|
7
166
|
memoryMB: 2048,
|
|
@@ -187,54 +346,77 @@ function createHostedAgent(config) {
|
|
|
187
346
|
if (!text || text.length > 8e3 || !/^[\w-]{1,120}$/.test(message.turnId)) return { state: "declined" };
|
|
188
347
|
const user = (await sha256(message.userId)).slice(0, 32);
|
|
189
348
|
const admittedKey = `turn:${user}:${message.turnId}`;
|
|
190
|
-
if (!await store.get(admittedKey)) {
|
|
191
|
-
const decision = await admit(message, user);
|
|
192
|
-
if (decision === "ignore") return { state: "declined" };
|
|
193
|
-
if (decision !== "answer") return { state: "declined", reply: decision.reply };
|
|
194
|
-
await store.put(admittedKey, "1", { expirationTtl: TWO_DAYS });
|
|
195
|
-
}
|
|
196
|
-
const trace = options.trace, traceKey = `trace:${user}:${message.turnId}`;
|
|
197
|
-
const box = await ensureBox(user, options.deadline, trace);
|
|
198
|
-
if (trace) {
|
|
199
|
-
const first = await store.get(traceKey);
|
|
200
|
-
if (first) trace.box = first;
|
|
201
|
-
else if (trace.box) await store.put(traceKey, trace.box, { expirationTtl: TWO_DAYS });
|
|
202
|
-
}
|
|
203
|
-
if (!box) return { state: "pending" };
|
|
204
349
|
const sessionId = `hosted-${user}-${await profileTag}`;
|
|
205
|
-
const
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
350
|
+
const trace = options.trace, traceKey = `trace:${user}:${message.turnId}`;
|
|
351
|
+
const conversationKey = `convo:${user}`;
|
|
352
|
+
let declined;
|
|
353
|
+
let conversation, at = "";
|
|
354
|
+
const outcome = await runHostedTurn({ turnId: message.turnId, text }, {
|
|
355
|
+
async admit() {
|
|
356
|
+
if (await store.get(admittedKey)) return null;
|
|
357
|
+
const decision = await admit(message, user);
|
|
358
|
+
if (decision === "answer") {
|
|
359
|
+
await store.put(admittedKey, "1", { expirationTtl: TWO_DAYS });
|
|
360
|
+
return null;
|
|
361
|
+
}
|
|
362
|
+
declined = decision === "ignore" ? { state: "declined" } : { state: "declined", reply: decision.reply };
|
|
363
|
+
return { ok: false, reason: "refused", detail: "declined" };
|
|
364
|
+
},
|
|
365
|
+
async box() {
|
|
366
|
+
const box = await ensureBox(user, options.deadline, trace);
|
|
367
|
+
if (trace) {
|
|
368
|
+
const first = await store.get(traceKey);
|
|
369
|
+
if (first) trace.box = first;
|
|
370
|
+
else if (trace.box) await store.put(traceKey, trace.box, { expirationTtl: TWO_DAYS });
|
|
371
|
+
}
|
|
372
|
+
if (!box) throw new TurnPending("box_starting", true);
|
|
373
|
+
return box;
|
|
374
|
+
},
|
|
375
|
+
sessionId,
|
|
376
|
+
backend: async () => backend,
|
|
377
|
+
async prompt(box) {
|
|
378
|
+
const asked = message.channel === "voice" ? `[Phone call. Answer in one to three short spoken sentences.]
|
|
212
379
|
${text}` : text;
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
380
|
+
at = `${box.id}/${sessionId}`;
|
|
381
|
+
const stored = await store.get(conversationKey);
|
|
382
|
+
conversation = stored ? JSON.parse(stored) : { at, turns: [] };
|
|
383
|
+
const carried = conversation.at === at ? "" : conversation.turns.map(([, them, you]) => `Them: ${them}
|
|
217
384
|
You: ${you}`).join("\n");
|
|
218
|
-
|
|
385
|
+
return carried ? `${CARRY_HEAD}
|
|
219
386
|
${carried}
|
|
220
387
|
${CARRY_NOW}
|
|
221
388
|
${asked}` : asked;
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
const answer = result.text.trim();
|
|
226
|
-
if (!answer) throw new HostedAgentError("empty_reply", "The turn completed with no reply text.");
|
|
227
|
-
if (trace) noteResult(trace, result.result, result.usage);
|
|
228
|
-
const turns = conversation.turns.filter(([id]) => id !== message.turnId);
|
|
389
|
+
},
|
|
390
|
+
async answered(answer) {
|
|
391
|
+
const turns = (conversation?.turns ?? []).filter(([id]) => id !== message.turnId);
|
|
229
392
|
turns.push([message.turnId, message.channel === "voice" ? `(on a call) ${text}` : text, answer]);
|
|
230
393
|
while (turns.length > 1 && JSON.stringify(turns).length > CARRY_CHARS) turns.shift();
|
|
231
394
|
await store.put(conversationKey, JSON.stringify({ at, turns }));
|
|
232
|
-
|
|
395
|
+
},
|
|
396
|
+
classify: (error) => error instanceof HostedAgentError ? { ok: false, reason: "unavailable", detail: error.code } : void 0,
|
|
397
|
+
observe: {
|
|
398
|
+
readCreatedSession: Boolean(trace),
|
|
399
|
+
session(info) {
|
|
400
|
+
if (!trace) return;
|
|
401
|
+
trace.harness = info.harness ?? config.harness;
|
|
402
|
+
trace.model = info.model;
|
|
403
|
+
},
|
|
404
|
+
drive(result) {
|
|
405
|
+
if (trace && result.state === "completed") noteResult(trace, result.result, result.usage);
|
|
406
|
+
},
|
|
407
|
+
failure(step, failure) {
|
|
408
|
+
console.error(`[hosted-agent] turn=${message.turnId} step=${step} code=${failure.code} message=${JSON.stringify(failure.message)}`);
|
|
409
|
+
}
|
|
233
410
|
}
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
411
|
+
}, { wallCapMs, timeoutMs: 8e3, until: options.deadline });
|
|
412
|
+
if (declined) return declined;
|
|
413
|
+
if (outcome.ok === true) return { state: "answered", text: outcome.text };
|
|
414
|
+
if (outcome.ok === "pending") {
|
|
415
|
+
if (outcome.cause !== void 0) throw outcome.cause;
|
|
416
|
+
return { state: "pending" };
|
|
237
417
|
}
|
|
418
|
+
const code = outcome.detail ?? outcome.reason;
|
|
419
|
+
throw new HostedAgentError(code === "agent_failed" ? "turn_failed" : code, `The turn ended without an answer (${code}).`);
|
|
238
420
|
}
|
|
239
421
|
return {
|
|
240
422
|
ask,
|
|
@@ -359,14 +541,23 @@ ${debugFooter(config.profile.name ?? "agent", turnId, trace, totalMs)}`;
|
|
|
359
541
|
};
|
|
360
542
|
}
|
|
361
543
|
export {
|
|
544
|
+
AUTHORITY_ENDED,
|
|
362
545
|
CONVERSATION_TOOLS_OFF,
|
|
363
546
|
DEFAULT_BOX_POLICY,
|
|
364
547
|
DEFAULT_HOSTED_MODEL,
|
|
365
548
|
HostedAgentError,
|
|
549
|
+
MAX_MESSAGE_CHARS,
|
|
550
|
+
MAX_REPEATED_FAILURES,
|
|
366
551
|
NOTICE,
|
|
552
|
+
TurnPending,
|
|
553
|
+
chatOnlyBackend,
|
|
367
554
|
createHostedAgent,
|
|
368
555
|
debugCommand,
|
|
369
556
|
debugFooter,
|
|
370
|
-
|
|
557
|
+
describeFailure,
|
|
558
|
+
isTransientFailure,
|
|
559
|
+
normalizeAddress,
|
|
560
|
+
runHostedTurn,
|
|
561
|
+
settleHostedTurn
|
|
371
562
|
};
|
|
372
563
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/hosted-agent/index.ts"],"sourcesContent":["import { authenticateHubEventRequest, HubClient, type HubProviderEvent } from '@tangle-network/hub-sdk'\nimport { buildMessagingReply, normalizeConversationEvent } from '@tangle-network/agent-integrations/conversation-events'\nimport type { AgentProfile, BackendConfig, SandboxInstance } from '@tangle-network/sandbox'\nimport { Sandbox, SandboxError } from '@tangle-network/sandbox/core'\n\n/**\n * A hosted agent: a person texts or calls a line, and the agent answers from\n * that person's own isolated sandbox. The developer's Tangle API key pays for\n * every box, model turn and reply.\n *\n * Each person gets one fresh isolated box built from the published profile,\n * never a copy of the developer's box. Later messages resume the same box and\n * the same conversation, so text and voice share one memory. A new profile\n * starts a new session, and a deleted box or a new API key starts a new box;\n * either way the person's recent conversation carries over from the store.\n *\n * Every step is idempotent by the message's turn id: a retried delivery\n * settles the same sandbox turn and replays the same Hub send. So the caller\n * may retry any failure, and needs no dedupe table.\n */\n\n/** Durable key-value storage. A Cloudflare KV namespace satisfies it. */\nexport interface HostedAgentStore {\n get(key: string): Promise<string | null>\n put(key: string, value: string, options?: { expirationTtl?: number }): Promise<void>\n}\n\nexport type HostedChannel = 'imessage' | 'voice'\n\nexport interface HostedMessage {\n /** The sender's address as the channel delivered it: E.164 for a phone. */\n userId: string\n channel: HostedChannel\n text: string\n /** Stable per logical message. Reusing it settles the same turn. */\n turnId: string\n}\n\n/** What the allowance hook decides for one new message. */\nexport type Allowance = 'answer' | 'ignore' | { reply: string }\n\nexport interface HostedAgentConfig {\n /** The developer's Tangle API key (Sandbox and Hub). */\n apiKey: string\n /**\n * The persona every person's box runs. A profile without `model.default`\n * runs {@link DEFAULT_HOSTED_MODEL}, and a profile without `tools` runs with\n * {@link CONVERSATION_TOOLS_OFF} turned off. Set `tools` to choose your own,\n * for example on a harness that cannot turn those tools off.\n */\n profile: AgentProfile\n /** Backend harness type, such as `opencode`; the runtime default when omitted. */\n harness?: string\n store: HostedAgentStore\n /** Answers per person per UTC day before `allow` must decide. Default 20. */\n freeTurnsPerDay?: number\n /**\n * Decide a new message after the free allowance is used, for example reply\n * with a checkout link. Without it, a person past the allowance is told to\n * come back tomorrow. Retries of an admitted message never reach this hook.\n */\n allow?: (message: HostedMessage, usedToday: number) => Allowance | Promise<Allowance>\n /**\n * The owner's own address (E.164 phone). Only this sender can text DEBUG ON\n * or DEBUG OFF; while on, each reply to them ends with one ⚙ line naming the\n * harness, model, box, time, tokens, cost and tools of that turn.\n */\n owner?: string\n /** Shared secret for the ph0ny call hook and `ask_workspace` webhook tool. */\n voiceSecret?: string\n /** How long one `ask_workspace` call may wait before it returns a ticket. Default 8 s. */\n voiceBudgetMs?: number\n box?: Partial<BoxPolicy>\n turnWallCapMs?: number\n sandboxUrl?: string\n hubUrl?: string\n}\n\nexport interface BoxPolicy {\n cpuCores: number\n memoryMB: number\n diskGB: number\n idleTimeoutSeconds: number\n maxLifetimeSeconds: number\n deleteAfterStoppedSeconds: number\n /** Egress allow-list. The default reaches the model router only. */\n allowDomains: string[]\n}\n\nexport const DEFAULT_BOX_POLICY: BoxPolicy = {\n cpuCores: 1, memoryMB: 2048, diskGB: 10,\n idleTimeoutSeconds: 600, maxLifetimeSeconds: 86_400, deleteAfterStoppedSeconds: 7 * 86_400,\n allowDomains: ['router.tangle.tools'],\n}\n\n/**\n * Harness tools a texting or calling assistant does not use. Their\n * descriptions present every turn as coding work: a shell, file search,\n * sub-agents, to-do lists, skills and web fetch. File read, write and edit\n * stay, so a persona can keep notes such as `memory.md`.\n */\nexport const CONVERSATION_TOOLS_OFF = ['bash', 'glob', 'grep', 'task', 'todowrite', 'webfetch', 'skill'] as const\n\n/**\n * The model for a profile without `model.default`. It gave the most useful\n * on-topic replies among four Router models on the same five texts and calls\n * (2026-09-23), within the latency of the others.\n */\nexport const DEFAULT_HOSTED_MODEL = 'openai/gpt-5.6-luna'\n\n/** The profile a person's box runs: the developer's profile over the conversation defaults. */\nfunction conversationProfile(profile: AgentProfile): AgentProfile {\n return {\n ...profile,\n model: { ...profile.model, default: profile.model?.default ?? DEFAULT_HOSTED_MODEL },\n // A profile that sets `tools` owns its tool set.\n ...(profile.tools ? {} : {\n tools: Object.fromEntries(CONVERSATION_TOOLS_OFF.map(tool => [tool, false])),\n // The sandbox's preview policy grants the shell unless its permission\n // is denied, so turning the tool off alone leaves the shell in place.\n permissions: { bash: 'deny' as const, ...profile.permissions },\n }),\n }\n}\n\n/** What one turn reports about itself, for the owner's debug line. A figure\n * the run did not report stays undefined and is left out of the line. */\nexport interface TurnTrace {\n /** Box before the turn: `warm`, `resumed` or `new`. */\n box?: string\n harness?: string\n model?: string\n /** Sandbox clock: the run's own start to finish. */\n runMs?: number\n inputTokens?: number\n outputTokens?: number\n reasoningTokens?: number\n costUsd?: number\n tools?: number\n}\n\nexport type AskResult =\n | { state: 'answered'; text: string }\n | { state: 'declined'; reply?: string }\n | { state: 'pending' }\n\n/** A Hub delivery that passed authentication, in a form a queue can carry. */\nexport interface HostedInbound {\n runId: string\n connectionId: string\n event: HubProviderEvent\n}\n\nexport const NOTICE = {\n debugOn: 'Debug on. Each reply now ends with a ⚙ line: agent, harness, model, box, time, tokens, cost, tools and turn. Text DEBUG OFF to stop.',\n debugOff: 'Debug off. Replies no longer carry the ⚙ line.',\n stopped: 'You are unsubscribed. Text START to talk again.',\n started: 'Welcome back. Text me anytime. Reply STOP to stop.',\n limit: 'You have used today\\'s free messages. Talk tomorrow!',\n unavailable: 'Sorry, I could not answer that just now. Please try again in a minute.',\n} as const\n\nconst IMESSAGE_EVENT = 'inkbox.imessage.received'\nconst IMESSAGE_REPLY = 'inkbox.imessage.reply'\nconst STOP = /^(stop|stopall|unsubscribe|cancel|end|quit)$/i\nconst START = /^(start|unstop|resume)$/i\nconst TWO_DAYS = 2 * 86_400\nconst RESUMABLE = new Set(['stopped', 'expired'])\nconst GONE = new Set(['failed', 'deleted'])\n/** How much of a person's recent conversation a new session inherits. */\nconst CARRY_CHARS = 6000\nconst CARRY_HEAD = '[Your conversation with this person so far. Your instructions may have changed since; follow the current ones.]'\nconst CARRY_NOW = '[Their new message:]'\n\n/** A person's recent turns, kept outside the box so a new session or box can continue them. */\ninterface Conversation {\n /** The box and session the turns last ran in. */\n at: string\n /** Oldest first: turn id, what they said, what the agent answered. */\n turns: Array<[string, string, string]>\n}\n\nconst encode = (text: string) => new TextEncoder().encode(text)\nconst hex = (bytes: ArrayBuffer) => Array.from(new Uint8Array(bytes), byte => byte.toString(16).padStart(2, '0')).join('')\nconst sha256 = async (value: string) => hex(await crypto.subtle.digest('SHA-256', encode(value)))\n/** Compares digests, so the time taken reveals nothing about the secret. */\nasync function equal(given: string | null | undefined, expected: string): Promise<boolean> {\n if (!given) return false\n const [a, b] = await Promise.all([sha256(given), sha256(expected)])\n let diff = 0\n for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)\n return diff === 0\n}\nconst CALL_TTL_MS = 2 * 3_600_000\n/** 43 url-safe characters from 32 random bytes. */\nconst randomToken = () => btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(32)))).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\nconst b64 = (text: string) => btoa(String.fromCharCode(...encode(text))).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\nconst unb64 = (text: string) => new TextDecoder().decode(Uint8Array.from(atob(text.replace(/-/g, '+').replace(/_/g, '/')), c => c.charCodeAt(0)))\nconst sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))\nconst json = (body: unknown, status = 200) => Response.json(body, { status })\nconst describe = (error: unknown) => (error instanceof Error ? `${error.name}: ${error.message}` : String(error))\n .replace(/sk-tan-[\\w-]+|Bearer\\s+\\S+/g, '<redacted>').slice(0, 400)\n\n/** One address per person: E.164 for anything phone-shaped, else lowercase. */\nexport function normalizeAddress(value: string): string | null {\n const trimmed = value.trim()\n if (trimmed.includes('@')) return trimmed.toLowerCase()\n const digits = trimmed.replace(/[^\\d]/g, '')\n if (digits.length < 8 || digits.length > 15) return null\n return `+${digits.length === 10 && !trimmed.startsWith('+') ? `1${digits}` : digits}`\n}\n\n/** `true` for DEBUG ON, `false` for DEBUG OFF, `null` for any other text. */\nexport function debugCommand(text: string): boolean | null {\n const match = /^debug\\s+(on|off)$/i.exec(text.trim())\n return match ? match[1]!.toLowerCase() === 'on' : null\n}\n\nconst num = (value: unknown) => typeof value === 'number' && Number.isFinite(value) ? value : undefined\nconst seconds = (ms: number) => ms < 10_000 ? `${(Math.max(0, ms) / 1000).toFixed(1)}s` : `${Math.round(ms / 1000)}s`\nconst count = (n: number) => n < 1000 ? String(n) : n < 10_000 ? `${(n / 1000).toFixed(1)}k` : `${Math.round(n / 1000)}k`\n\n/** The owner's ⚙ line. `totalMs` runs from the provider's receipt of the text to now. */\nexport function debugFooter(agent: string, turnId: string, trace: TurnTrace, totalMs?: number): string {\n const parts = [agent]\n if (trace.harness) parts.push(trace.harness)\n if (trace.model) parts.push(trace.model.split('/').at(-1)!)\n if (trace.box) parts.push(trace.box)\n if (totalMs !== undefined) parts.push(`${seconds(totalMs)}${trace.runMs !== undefined ? ` (run ${seconds(trace.runMs)})` : ''}`)\n else if (trace.runMs !== undefined) parts.push(`run ${seconds(trace.runMs)}`)\n if (trace.inputTokens !== undefined && trace.outputTokens !== undefined) {\n parts.push(`${count(trace.inputTokens)}→${count(trace.outputTokens)} tok${trace.reasoningTokens ? ` (${count(trace.reasoningTokens)} thinking)` : ''}`)\n }\n // Zero on a turn that used tokens means the harness had no price for the model.\n if (trace.costUsd !== undefined && (trace.costUsd > 0 || !trace.outputTokens)) {\n parts.push(trace.costUsd >= 0.01 ? `$${trace.costUsd.toFixed(3)}` : `$${trace.costUsd.toPrecision(2)}`)\n }\n if (trace.tools !== undefined) parts.push(`${trace.tools} tool${trace.tools === 1 ? '' : 's'}`)\n parts.push(turnId.slice(0, 8))\n return `⚙ ${parts.join(' · ')}`\n}\n\n/** Model, tokens, cost, tools and run time from a finished turn, as far as it reports them. */\nfunction noteResult(trace: TurnTrace, result: Record<string, unknown>, usage?: { inputTokens?: number; outputTokens?: number }) {\n // The SDK's typed usage carries counts only; the harness's own record also carries cost.\n const reported = (result.tokenUsage ?? {}) as Record<string, unknown>\n const timing = (result.timing ?? {}) as Record<string, unknown>\n const started = num(timing.startedAt), completed = num(timing.completedAt)\n if (started !== undefined && completed !== undefined) trace.runMs = completed - started\n trace.inputTokens = num(usage?.inputTokens) ?? num(reported.inputTokens)\n trace.outputTokens = num(usage?.outputTokens) ?? num(reported.outputTokens)\n trace.reasoningTokens = num(reported.reasoningTokens)\n if (result.usdKnown !== false) trace.costUsd = num(reported.cost)\n if (Array.isArray(result.toolInvocations)) trace.tools = result.toolInvocations.length\n}\n\nexport class HostedAgentError extends Error {\n constructor(readonly code: string, message: string) { super(message); this.name = 'HostedAgentError' }\n}\n\nexport function createHostedAgent(config: HostedAgentConfig) {\n const store = config.store\n const policy = { ...DEFAULT_BOX_POLICY, ...config.box }\n const wallCapMs = config.turnWallCapMs ?? 120_000\n const sandbox = new Sandbox({ apiKey: config.apiKey, baseUrl: config.sandboxUrl ?? 'https://sandbox.tangle.tools', timeoutMs: 20_000 })\n const hub = new HubClient({ baseUrl: config.hubUrl ?? 'https://id.tangle.tools', apiKey: config.apiKey })\n const profile = conversationProfile(config.profile)\n const backend: BackendConfig = { ...(config.harness ? { type: config.harness as BackendConfig['type'] } : {}), profile }\n const profileTag = sha256(JSON.stringify(profile)).then(hash => hash.slice(0, 8))\n\n /** Resume a stopped box. False when an earlier API key made it: the platform\n * resumes a box only under the key lineage that created it. */\n async function resumed(box: SandboxInstance): Promise<boolean> {\n try {\n await box.resume()\n return true\n } catch (error) {\n if (error instanceof SandboxError && error.code === 'SANDBOX_ATTRIBUTION_MISMATCH') return false\n throw error\n }\n }\n\n /** The person's running box: created on the first message, resumed later,\n * replaced when the platform deleted it. Null when the deadline passed. */\n async function ensureBox(user: string, deadline: number, trace?: TurnTrace): Promise<SandboxInstance | null> {\n const key = `box:${user}`\n const known = await store.get(key)\n let box = known ? await sandbox.get(known) : null\n if (trace) trace.box = !box || GONE.has(box.status) ? 'new' : RESUMABLE.has(box.status) ? 'resumed' : 'warm'\n if (box && RESUMABLE.has(box.status) && !await resumed(box)) {\n box = null\n if (trace) trace.box = 'new'\n }\n if (!box || GONE.has(box.status)) {\n // The key names the box it replaces, so concurrent first messages and\n // retries converge on one allocation instead of each creating a box.\n box = await sandbox.createIsolated({\n name: `hosted-${user.slice(0, 24)}`, idempotencyKey: known ? `hosted-${user}-after-${known}` : `hosted-${user}`,\n resources: { cpuCores: policy.cpuCores, memoryMB: policy.memoryMB, diskGB: policy.diskGB },\n backend, secrets: [], sshEnabled: false,\n egressPolicy: { mode: 'strict', allowDomains: policy.allowDomains, includeImplicitDomains: false },\n idleTimeoutSeconds: policy.idleTimeoutSeconds, maxLifetimeSeconds: policy.maxLifetimeSeconds,\n deleteAfterStoppedSeconds: policy.deleteAfterStoppedSeconds, metadata: { hostedUser: user },\n })\n await store.put(key, box.id)\n }\n if (RESUMABLE.has(box.status) && !await resumed(box)) throw new HostedAgentError('box_foreign', 'A new box was made under another API key.')\n if (box.status === 'running') return box\n const timeoutMs = deadline - Date.now()\n if (timeoutMs < 1000) return null\n try {\n return await sandbox.waitForRunning(box.id, { timeoutMs })\n } catch (error) {\n if (error instanceof Error && error.name === 'TimeoutError') return null\n throw error\n }\n }\n\n /** Admit a new message once: STOP/START, the free allowance, then `allow`. */\n async function admit(message: HostedMessage, user: string): Promise<Allowance> {\n const stopKey = `stop:${user}`\n if (message.channel !== 'voice' && STOP.test(message.text.trim())) { await store.put(stopKey, '1'); return { reply: NOTICE.stopped } }\n if (message.channel !== 'voice' && START.test(message.text.trim())) { await store.put(stopKey, ''); return { reply: NOTICE.started } }\n if (await store.get(stopKey)) return 'ignore'\n const dayKey = `turns:${user}:${new Date().toISOString().slice(0, 10)}`\n // KV has no atomic increment, so concurrent messages may overshoot the\n // allowance by a few; the sponsor key's budget is the hard ceiling.\n const used = Number(await store.get(dayKey) ?? 0)\n const decision = used < (config.freeTurnsPerDay ?? 20) ? 'answer'\n : config.allow ? await config.allow(message, used) : { reply: NOTICE.limit }\n if (decision === 'answer') await store.put(dayKey, String(used + 1), { expirationTtl: TWO_DAYS })\n return decision\n }\n\n /** Run one message in the person's box until it answers or `deadline`. */\n async function ask(message: HostedMessage, options: { deadline: number; trace?: TurnTrace }): Promise<AskResult> {\n const text = message.text.trim()\n if (!text || text.length > 8000 || !/^[\\w-]{1,120}$/.test(message.turnId)) return { state: 'declined' }\n const user = (await sha256(message.userId)).slice(0, 32)\n // Scoped to the person: a voice ticket is model-supplied, so a turn id\n // admitted for one person must not skip another person's allowance.\n const admittedKey = `turn:${user}:${message.turnId}`\n if (!await store.get(admittedKey)) {\n const decision = await admit(message, user)\n if (decision === 'ignore') return { state: 'declined' }\n if (decision !== 'answer') return { state: 'declined', reply: decision.reply }\n await store.put(admittedKey, '1', { expirationTtl: TWO_DAYS })\n }\n // A retried delivery finds the box it woke already warm, so the first\n // attempt's view of the box is kept for the turn.\n const trace = options.trace, traceKey = `trace:${user}:${message.turnId}`\n const box = await ensureBox(user, options.deadline, trace)\n if (trace) {\n const first = await store.get(traceKey)\n if (first) trace.box = first\n else if (trace.box) await store.put(traceKey, trace.box, { expirationTtl: TWO_DAYS })\n }\n if (!box) return { state: 'pending' }\n // A session binds its backend when created, and the runtime would give a\n // bare session its generic default assistant. A new profile starts a new\n // session, so the persona always matches the one in force.\n const sessionId = `hosted-${user}-${await profileTag}`\n const session = await box.session(sessionId).status()\n if (!session) await box.createSession({ sessionId, retention: 'workspace', backend })\n if (trace) {\n trace.harness = session?.backend ?? config.harness\n trace.model = session?.model\n }\n const asked = message.channel === 'voice' ? `[Phone call. Answer in one to three short spoken sentences.]\\n${text}` : text\n // The first turn in a new session or box inherits the person's recent\n // turns. A retry before that turn completes carries them again, so a\n // failed first attempt loses nothing.\n const conversationKey = `convo:${user}`, at = `${box.id}/${sessionId}`\n const stored = await store.get(conversationKey)\n const conversation: Conversation = stored ? JSON.parse(stored) as Conversation : { at, turns: [] }\n const carried = conversation.at === at ? '' : conversation.turns.map(([, them, you]) => `Them: ${them}\\nYou: ${you}`).join('\\n')\n const prompt = carried ? `${CARRY_HEAD}\\n${carried}\\n${CARRY_NOW}\\n${asked}` : asked\n for (;;) {\n const result = await box.driveConversationTurn(prompt, { sessionId, turnId: message.turnId, wallCapMs, timeoutMs: 8000 })\n if (result.state === 'completed') {\n const answer = result.text.trim()\n if (!answer) throw new HostedAgentError('empty_reply', 'The turn completed with no reply text.')\n if (trace) noteResult(trace, result.result, result.usage)\n // Concurrent turns may drop one another's entry; the box keeps the full record.\n const turns = conversation.turns.filter(([id]) => id !== message.turnId)\n turns.push([message.turnId, message.channel === 'voice' ? `(on a call) ${text}` : text, answer])\n while (turns.length > 1 && JSON.stringify(turns).length > CARRY_CHARS) turns.shift()\n await store.put(conversationKey, JSON.stringify({ at, turns } satisfies Conversation))\n return { state: 'answered', text: answer }\n }\n if (result.state === 'failed') throw new HostedAgentError('turn_failed', result.error)\n if (Date.now() + 2000 > options.deadline) return { state: 'pending' }\n await sleep(2000)\n }\n }\n\n return {\n ask,\n\n /**\n * One-time setup: route an Inkbox iMessage identity's messages, connected\n * to Hub under the developer's account, to `callbackUrl`, and allow the\n * one reply action on that connection. Safe to repeat.\n */\n async connect(input: { connectionId: string; identityId: string; callbackUrl: string; secret: string }) {\n const webhook = await hub.connections.inboundWebhook.get(input.connectionId)\n if (!webhook.configured) await hub.connections.inboundWebhook.create(input.connectionId, { identityId: input.identityId, imessage: true })\n await hub.permissions.set({ connectionId: input.connectionId, actionPath: IMESSAGE_REPLY, decision: 'allow' })\n const { subscription } = await hub.eventSubscriptions.create({\n clientReference: `hosted-agent:${input.connectionId}`, label: 'Hosted agent messages',\n source: { type: 'connection', connectionId: input.connectionId }, event: IMESSAGE_EVENT,\n callback: { url: input.callbackUrl, secret: input.secret },\n })\n return subscription\n },\n\n /** The Hub callback. Authenticates within Hub's 10 s budget and runs nothing. */\n async receive(request: Request, secret: string): Promise<{ response: Response; inbound?: HostedInbound }> {\n const authenticated = await authenticateHubEventRequest({ request, secret, maxBodyBytes: 64 * 1024 })\n if (!authenticated.ok) return { response: authenticated.response }\n const { runId, source, providerEvent } = authenticated.delivery\n const ack = new Response(null, { status: 204 })\n if (source.kind !== 'connection' || source.event !== IMESSAGE_EVENT || providerEvent.connectionId !== source.id) return { response: ack }\n return { response: ack, inbound: { runId, connectionId: source.id, event: providerEvent } }\n },\n\n /**\n * Answer one inbound message and send the reply through Hub. Returns\n * 'pending' while the turn still runs; call again with the same inbound.\n * On `lastAttempt`, a failure is answered with an apology instead of thrown.\n */\n async respond(inbound: HostedInbound, options: { lastAttempt?: boolean } = {}): Promise<'replied' | 'ignored' | 'pending'> {\n const normalized = normalizeConversationEvent(inbound.event)\n if (!normalized.ok) return 'ignored'\n const event = normalized.event\n const userId = normalizeAddress(event.sender.id ?? '')\n if (!userId || !event.text?.trim() || event.isGroup || event.historyOnly) return 'ignored'\n const turnId = `t-${(await sha256(inbound.runId)).slice(0, 40)}`\n // Only the configured owner toggles debug; anyone else's DEBUG ON is an ordinary message.\n const isOwner = Boolean(config.owner) && normalizeAddress(config.owner!) === userId\n const debugKey = `debug:${(await sha256(userId)).slice(0, 32)}`\n const toggle = isOwner ? debugCommand(event.text) : null\n const trace: TurnTrace | undefined = isOwner && toggle === null && await store.get(debugKey) ? {} : undefined\n let text: string\n try {\n if (toggle !== null) {\n await store.put(debugKey, toggle ? '1' : '')\n text = toggle ? NOTICE.debugOn : NOTICE.debugOff\n } else {\n const result = await ask({ userId, channel: 'imessage', text: event.text, turnId },\n { deadline: Date.now() + wallCapMs + 60_000, trace })\n if (result.state === 'pending') return 'pending'\n if (result.state === 'declined' && !result.reply) return 'ignored'\n text = result.state === 'answered' ? result.text : result.reply!\n if (trace && result.state === 'answered') {\n const totalMs = event.occurredAt !== null && event.occurredAt !== undefined ? Date.now() - event.occurredAt : undefined\n text = `${text.slice(0, 1300)}\\n\\n${debugFooter(config.profile.name ?? 'agent', turnId, trace, totalMs)}`\n }\n }\n } catch (error) {\n // A failed turn fails the same way on every retry; anything else may clear.\n if (!(error instanceof HostedAgentError) && !options.lastAttempt) throw error\n console.error(`[hosted-agent] turn=${turnId} ${describe(error)}`)\n text = NOTICE.unavailable\n }\n const plan = buildMessagingReply(inbound.event, text.slice(0, 1500), `reply-${turnId}`)\n if (!plan.ok) return 'ignored'\n // Hub replays the first result for a retry with this key and input.\n await hub.tools.invoke(plan.reply.action, plan.reply.input, { connectionId: inbound.connectionId, idempotencyKey: plan.reply.idempotencyKey })\n return 'replied'\n },\n\n /**\n * ph0ny's call hook. `admit` returns a call token bound to the caller's\n * number from the carrier's signed call record, never from the model.\n */\n async voiceHook(request: Request): Promise<Response> {\n const secret = config.voiceSecret\n if (!secret || !await equal(request.headers.get('authorization'), `Bearer ${secret}`)) return json({ error: 'unauthorized' }, 401)\n const body = await request.json().catch(() => null) as { event?: string; phone?: string } | null\n if (body?.event !== 'admit') return json({ ok: true })\n const phone = normalizeAddress(body.phone ?? '')\n if (!phone?.startsWith('+')) return json({ admit: false, say: 'Sorry, I can only take calls from a visible number.' })\n if (await store.get(`stop:${(await sha256(phone)).slice(0, 32)}`)) return json({ admit: false, say: 'You unsubscribed from this line.' })\n // ph0ny accepts only an opaque token matching ^[A-Za-z0-9_-]{16,128}$,\n // so the caller's number stays here and the token is its random key.\n const callToken = randomToken()\n await store.put(`vcall:${callToken}`, JSON.stringify({ phone, exp: Date.now() + CALL_TTL_MS }), { expirationTtl: CALL_TTL_MS / 1000 })\n return json({ admit: true, callToken })\n },\n\n /**\n * ph0ny's `ask_workspace` webhook tool, configured with `forwardCallToken`.\n * A slow turn returns a ticket; the voice agent asks again with it.\n */\n async voiceAsk(request: Request): Promise<Response> {\n const secret = config.voiceSecret\n if (!secret || !await equal(request.headers.get('authorization'), `Bearer ${secret}`)) return json({ error: 'unauthorized' }, 401)\n const token = request.headers.get('x-voice-call-token') ?? ''\n const admitted = /^[A-Za-z0-9_-]{16,128}$/.test(token) ? await store.get(`vcall:${token}`) : null\n if (!admitted) return json({ status: 'error', error: 'call_not_admitted' }, 403)\n const call = JSON.parse(admitted) as { phone: string; exp: number }\n if (call.exp < Date.now()) return json({ status: 'error', error: 'call_expired' }, 403)\n const body = await request.json().catch(() => null) as { utterance?: string; ticket?: string } | null\n // A ticket carries its own turn id and question, so a retry after a\n // slow first step still admits and settles exactly one turn.\n const [turnId, asked] = body?.ticket ? body.ticket.split('.') : [`v-${crypto.randomUUID()}`, b64(body?.utterance ?? '')]\n if (!turnId || !asked) return json({ status: 'error', error: 'missing_utterance' }, 400)\n try {\n // ph0ny drops the tool call at its own timeout, and resuming an idle\n // box can take longer than the budget. Answer 'pending' at the\n // budget regardless; every step is idempotent by turn id, so the\n // ticket call continues where this one stopped.\n const budgetMs = config.voiceBudgetMs ?? 8000\n const result = await Promise.race([\n ask({ userId: call.phone, channel: 'voice', text: unb64(asked), turnId }, { deadline: Date.now() + budgetMs }),\n sleep(budgetMs).then((): AskResult => ({ state: 'pending' })),\n ])\n if (result.state === 'pending') return json({ status: 'pending', ticket: `${turnId}.${asked}` })\n if (result.state === 'declined') return json({ status: 'complete', answer: result.reply ?? 'I cannot answer that right now.' })\n return json({ status: 'complete', answer: result.text })\n } catch (error) {\n console.error(`[hosted-agent] voice turn=${turnId} ${describe(error)}`)\n return json({ status: 'error', error: 'agent_unavailable' }, 502)\n }\n },\n }\n}\n\nexport type HostedAgent = ReturnType<typeof createHostedAgent>\n"],"mappings":";AAAA,SAAS,6BAA6B,iBAAwC;AAC9E,SAAS,qBAAqB,kCAAkC;AAEhE,SAAS,SAAS,oBAAoB;AAsF/B,IAAM,qBAAgC;AAAA,EAC3C,UAAU;AAAA,EAAG,UAAU;AAAA,EAAM,QAAQ;AAAA,EACrC,oBAAoB;AAAA,EAAK,oBAAoB;AAAA,EAAQ,2BAA2B,IAAI;AAAA,EACpF,cAAc,CAAC,qBAAqB;AACtC;AAQO,IAAM,yBAAyB,CAAC,QAAQ,QAAQ,QAAQ,QAAQ,aAAa,YAAY,OAAO;AAOhG,IAAM,uBAAuB;AAGpC,SAAS,oBAAoB,SAAqC;AAChE,SAAO;AAAA,IACL,GAAG;AAAA,IACH,OAAO,EAAE,GAAG,QAAQ,OAAO,SAAS,QAAQ,OAAO,WAAW,qBAAqB;AAAA;AAAA,IAEnF,GAAI,QAAQ,QAAQ,CAAC,IAAI;AAAA,MACvB,OAAO,OAAO,YAAY,uBAAuB,IAAI,UAAQ,CAAC,MAAM,KAAK,CAAC,CAAC;AAAA;AAAA;AAAA,MAG3E,aAAa,EAAE,MAAM,QAAiB,GAAG,QAAQ,YAAY;AAAA,IAC/D;AAAA,EACF;AACF;AA8BO,IAAM,SAAS;AAAA,EACpB,SAAS;AAAA,EACT,UAAU;AAAA,EACV,SAAS;AAAA,EACT,SAAS;AAAA,EACT,OAAO;AAAA,EACP,aAAa;AACf;AAEA,IAAM,iBAAiB;AACvB,IAAM,iBAAiB;AACvB,IAAM,OAAO;AACb,IAAM,QAAQ;AACd,IAAM,WAAW,IAAI;AACrB,IAAM,YAAY,oBAAI,IAAI,CAAC,WAAW,SA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AU,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":[]}
|
|
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 // The SDK's typed usage carries counts only; the harness's own record also carries cost.\n const reported = (result.tokenUsage ?? {}) as Record<string, unknown>\n const timing = (result.timing ?? {}) as Record<string, unknown>\n const started = num(timing.startedAt), completed = num(timing.completedAt)\n if (started !== undefined && completed !== undefined) trace.runMs = completed - started\n trace.inputTokens = num(usage?.inputTokens) ?? num(reported.inputTokens)\n trace.outputTokens = num(usage?.outputTokens) ?? num(reported.outputTokens)\n trace.reasoningTokens = num(reported.reasoningTokens)\n if (result.usdKnown !== false) trace.costUsd = num(reported.cost)\n if (Array.isArray(result.toolInvocations)) trace.tools = result.toolInvocations.length\n}\n\nexport class HostedAgentError extends Error {\n constructor(readonly code: string, message: string) { super(message); this.name = 'HostedAgentError' }\n}\n\nexport function createHostedAgent(config: HostedAgentConfig) {\n const store = config.store\n const policy = { ...DEFAULT_BOX_POLICY, ...config.box }\n const wallCapMs = config.turnWallCapMs ?? 120_000\n const sandbox = new Sandbox({ apiKey: config.apiKey, baseUrl: config.sandboxUrl ?? 'https://sandbox.tangle.tools', timeoutMs: 20_000 })\n const hub = new HubClient({ baseUrl: config.hubUrl ?? 'https://id.tangle.tools', apiKey: config.apiKey })\n const profile = conversationProfile(config.profile)\n const backend: BackendConfig = { ...(config.harness ? { type: config.harness as BackendConfig['type'] } : {}), profile }\n const profileTag = sha256(JSON.stringify(profile)).then(hash => hash.slice(0, 8))\n\n /** Resume a stopped box. False when an earlier API key made it: the platform\n * resumes a box only under the key lineage that created it. */\n async function resumed(box: SandboxInstance): Promise<boolean> {\n try {\n await box.resume()\n return true\n } catch (error) {\n if (error instanceof SandboxError && error.code === 'SANDBOX_ATTRIBUTION_MISMATCH') return false\n throw error\n }\n }\n\n /** The person's running box: created on the first message, resumed later,\n * replaced when the platform deleted it. Null when the deadline passed. */\n async function ensureBox(user: string, deadline: number, trace?: TurnTrace): Promise<SandboxInstance | null> {\n const key = `box:${user}`\n const known = await store.get(key)\n let box = known ? await sandbox.get(known) : null\n if (trace) trace.box = !box || GONE.has(box.status) ? 'new' : RESUMABLE.has(box.status) ? 'resumed' : 'warm'\n if (box && RESUMABLE.has(box.status) && !await resumed(box)) {\n box = null\n if (trace) trace.box = 'new'\n }\n if (!box || GONE.has(box.status)) {\n // The key names the box it replaces, so concurrent first messages and\n // retries converge on one allocation instead of each creating a box.\n box = await sandbox.createIsolated({\n name: `hosted-${user.slice(0, 24)}`, idempotencyKey: known ? `hosted-${user}-after-${known}` : `hosted-${user}`,\n resources: { cpuCores: policy.cpuCores, memoryMB: policy.memoryMB, diskGB: policy.diskGB },\n backend, secrets: [], sshEnabled: false,\n egressPolicy: { mode: 'strict', allowDomains: policy.allowDomains, includeImplicitDomains: false },\n idleTimeoutSeconds: policy.idleTimeoutSeconds, maxLifetimeSeconds: policy.maxLifetimeSeconds,\n deleteAfterStoppedSeconds: policy.deleteAfterStoppedSeconds, metadata: { hostedUser: user },\n })\n await store.put(key, box.id)\n }\n if (RESUMABLE.has(box.status) && !await resumed(box)) throw new HostedAgentError('box_foreign', 'A new box was made under another API key.')\n if (box.status === 'running') return box\n const timeoutMs = deadline - Date.now()\n if (timeoutMs < 1000) return null\n try {\n return await sandbox.waitForRunning(box.id, { timeoutMs })\n } catch (error) {\n if (error instanceof Error && error.name === 'TimeoutError') return null\n throw error\n }\n }\n\n /** Admit a new message once: STOP/START, the free allowance, then `allow`. */\n async function admit(message: HostedMessage, user: string): Promise<Allowance> {\n const stopKey = `stop:${user}`\n if (message.channel !== 'voice' && STOP.test(message.text.trim())) { await store.put(stopKey, '1'); return { reply: NOTICE.stopped } }\n if (message.channel !== 'voice' && START.test(message.text.trim())) { await store.put(stopKey, ''); return { reply: NOTICE.started } }\n if (await store.get(stopKey)) return 'ignore'\n const dayKey = `turns:${user}:${new Date().toISOString().slice(0, 10)}`\n // KV has no atomic increment, so concurrent messages may overshoot the\n // allowance by a few; the sponsor key's budget is the hard ceiling.\n const used = Number(await store.get(dayKey) ?? 0)\n const decision = used < (config.freeTurnsPerDay ?? 20) ? 'answer'\n : config.allow ? await config.allow(message, used) : { reply: NOTICE.limit }\n if (decision === 'answer') await store.put(dayKey, String(used + 1), { expirationTtl: TWO_DAYS })\n return decision\n }\n\n /** Run one message in the person's box until it answers or `deadline`. */\n async function ask(message: HostedMessage, options: { deadline: number; trace?: TurnTrace }): Promise<AskResult> {\n const text = message.text.trim()\n if (!text || text.length > 8000 || !/^[\\w-]{1,120}$/.test(message.turnId)) return { state: 'declined' }\n const user = (await sha256(message.userId)).slice(0, 32)\n // Scoped to the person: a voice ticket is model-supplied, so a turn id\n // admitted for one person must not skip another person's allowance.\n const admittedKey = `turn:${user}:${message.turnId}`\n // 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 case 'awaiting_plan_decision': 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,CAAC;AAExE,QAAM,YAAY,EAAE,kBAAkB;AACtC,QAAM,QAAQ,OAAO,cAAc,YAAY,YAAY,YAAY,OAAO,EAAE,UAAU,YAAY,EAAE,QAAQ,EAAE,QAAQ;AAC1H,SAAO,EAAE,GAAI,OAAO,EAAE,YAAY,YAAY,EAAE,UAAU,EAAE,SAAS,EAAE,QAAQ,IAAI,CAAC,GAAI,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC,EAAG;AACtH;AAEA,IAAM,UAAU,CAAC,QAAqB,YAAwD,EAAE,IAAI,OAAO,QAAQ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