@tangle-network/agent-app 0.60.131 → 0.60.133

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.
Files changed (58) hide show
  1. package/dist/app-auth/index.js +3 -3
  2. package/dist/assistant/index.js +10 -10
  3. package/dist/billing/index.js +1 -1
  4. package/dist/chat-react/index.js +2 -2
  5. package/dist/chat-routes/index.js +11 -11
  6. package/dist/chat-routes/turn-routes.d.ts +6 -2
  7. package/dist/chat-store/index.js +3 -3
  8. package/dist/{chunk-JZUSVGRJ.js → chunk-2GP6JOWE.js} +15 -2
  9. package/dist/chunk-2GP6JOWE.js.map +1 -0
  10. package/dist/chunk-4JUEOVQS.js +134 -0
  11. package/dist/chunk-4JUEOVQS.js.map +1 -0
  12. package/dist/{chunk-5S5ANZBS.js → chunk-HZGKPWVA.js} +6 -6
  13. package/dist/{chunk-NRG2YHGY.js → chunk-IMTU5LCF.js} +1 -1
  14. package/dist/{chunk-XPP653RG.js → chunk-JEM4BKR4.js} +10 -10
  15. package/dist/{chunk-JGLK5RDK.js → chunk-JIXM57JM.js} +28 -14
  16. package/dist/{chunk-JGLK5RDK.js.map → chunk-JIXM57JM.js.map} +1 -1
  17. package/dist/{chunk-4DEI6QC5.js → chunk-NNNAC3DV.js} +4 -4
  18. package/dist/{chunk-GU7OZFU7.js → chunk-VXWEJ7F2.js} +4 -4
  19. package/dist/{chunk-ZGUXI5SI.js → chunk-XNKLQG26.js} +5 -5
  20. package/dist/{chunk-LJDMPYGA.js → chunk-YJHE73TF.js} +8 -2
  21. package/dist/chunk-YJHE73TF.js.map +1 -0
  22. package/dist/design-canvas-react/index.js +4 -4
  23. package/dist/design-canvas-react/lazy.js +1 -1
  24. package/dist/journeys/index.js +11 -5
  25. package/dist/journeys/index.js.map +1 -1
  26. package/dist/journeys/send.d.ts +10 -0
  27. package/dist/platform/delegated-keys.d.ts +226 -0
  28. package/dist/platform/index.d.ts +1 -0
  29. package/dist/platform/index.js +315 -0
  30. package/dist/platform/index.js.map +1 -1
  31. package/dist/preset-cloudflare/index.js +1 -1
  32. package/dist/public-consultation/index.d.ts +1 -1
  33. package/dist/public-consultation/index.js +5 -5
  34. package/dist/rollout/cli.d.ts +25 -0
  35. package/dist/rollout/cli.js +121 -0
  36. package/dist/rollout/cli.js.map +1 -0
  37. package/dist/rollout/d1.d.ts +62 -0
  38. package/dist/rollout/d1.js +89 -0
  39. package/dist/rollout/d1.js.map +1 -0
  40. package/dist/rollout/index.d.ts +116 -0
  41. package/dist/rollout/index.js +19 -0
  42. package/dist/rollout/index.js.map +1 -0
  43. package/dist/sandbox/index.js +1 -1
  44. package/dist/sandbox/sandbox-exec-tool.d.ts +5 -3
  45. package/dist/sandbox/sandbox-run-tool.d.ts +12 -5
  46. package/dist/stream/index.js +2 -2
  47. package/dist/studio-react/index.js +2 -2
  48. package/dist/web-react/index.js +16 -16
  49. package/dist/workspace-react/index.js +5 -5
  50. package/package.json +12 -1
  51. package/dist/chunk-JZUSVGRJ.js.map +0 -1
  52. package/dist/chunk-LJDMPYGA.js.map +0 -1
  53. /package/dist/{chunk-5S5ANZBS.js.map → chunk-HZGKPWVA.js.map} +0 -0
  54. /package/dist/{chunk-NRG2YHGY.js.map → chunk-IMTU5LCF.js.map} +0 -0
  55. /package/dist/{chunk-XPP653RG.js.map → chunk-JEM4BKR4.js.map} +0 -0
  56. /package/dist/{chunk-4DEI6QC5.js.map → chunk-NNNAC3DV.js.map} +0 -0
  57. /package/dist/{chunk-GU7OZFU7.js.map → chunk-VXWEJ7F2.js.map} +0 -0
  58. /package/dist/{chunk-ZGUXI5SI.js.map → chunk-XNKLQG26.js.map} +0 -0
@@ -0,0 +1,121 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ decideRollout
4
+ } from "../chunk-4JUEOVQS.js";
5
+ import {
6
+ invokedAsScript
7
+ } from "../chunk-C3CAYGGQ.js";
8
+
9
+ // src/rollout/cli.ts
10
+ import { execFileSync } from "child_process";
11
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "fs";
12
+ import { dirname, join, resolve } from "path";
13
+ import { pathToFileURL } from "url";
14
+ var CONFIG_NAMES = ["rollout.config.mjs", "rollout.config.js"];
15
+ function parseArgs(argv) {
16
+ const args = { appDir: process.cwd(), base: "origin/main", record: ".rollout/decisions.jsonl" };
17
+ for (let index = 0; index < argv.length; index += 1) {
18
+ const arg = argv[index];
19
+ const value = () => {
20
+ const next = argv[++index];
21
+ if (next === void 0) throw new Error(`${arg} needs a value`);
22
+ return next;
23
+ };
24
+ if (arg === "--config") args.config = value();
25
+ else if (arg === "--base") args.base = value();
26
+ else if (arg === "--from") args.from = value();
27
+ else if (arg === "--to") args.to = value();
28
+ else if (arg === "--plan") args.plan = value();
29
+ else if (arg === "--record") args.record = value();
30
+ else if (arg.startsWith("--")) throw new Error(`unknown option ${arg}`);
31
+ else args.appDir = resolve(arg);
32
+ }
33
+ return args;
34
+ }
35
+ function readWranglerVar(source, name) {
36
+ let inVars = false;
37
+ for (const line of source.split("\n")) {
38
+ const header = line.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);
39
+ if (header) {
40
+ inVars = header[1].trim() === "vars";
41
+ continue;
42
+ }
43
+ if (!inVars) continue;
44
+ const entry = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*"((?:[^"\\]|\\.)*)"/);
45
+ if (entry && entry[1] === name) return JSON.parse(`"${entry[2]}"`);
46
+ }
47
+ return null;
48
+ }
49
+ async function loadConfig(appDir, explicit) {
50
+ const file = explicit ? resolve(appDir, explicit) : CONFIG_NAMES.map((name) => join(appDir, name)).find((path) => existsSync(path));
51
+ if (!file || !existsSync(file)) throw new Error(`no ${CONFIG_NAMES[0]} in ${appDir}`);
52
+ const config = (await import(pathToFileURL(file).href)).default;
53
+ if (!Array.isArray(config?.plans) || typeof config.measure !== "function") {
54
+ throw new Error(`${file} must export { plans, measure }`);
55
+ }
56
+ return config;
57
+ }
58
+ function wranglerAt(appDir, file, ref) {
59
+ try {
60
+ return execFileSync("git", ["show", `${ref}:${file}`], { cwd: appDir, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
61
+ } catch {
62
+ throw new Error(`cannot read ${file} at ${ref}; fetch it or pass --from`);
63
+ }
64
+ }
65
+ async function runRolloutCheck(args) {
66
+ const config = await loadConfig(args.appDir, args.config);
67
+ const file = config.wrangler ?? "wrangler.toml";
68
+ const plans = args.plan ? config.plans.filter((plan) => plan.name === args.plan) : config.plans;
69
+ if (!plans.length) throw new Error(args.plan ? `no plan named ${args.plan}` : "the config declares no plans");
70
+ if (plans.length > 1 && (args.from !== void 0 || args.to !== void 0)) throw new Error("--from and --to need --plan");
71
+ const head = readFileSync(join(args.appDir, file), "utf8");
72
+ const base = args.from === void 0 ? wranglerAt(args.appDir, file, args.base) : null;
73
+ const decisions = [];
74
+ for (const plan of plans) {
75
+ const fromValue = args.from ?? readWranglerVar(base, plan.variable) ?? "";
76
+ const toValue = args.to ?? readWranglerVar(head, plan.variable) ?? "";
77
+ const decision = await decideRollout({ plan, fromValue, toValue, measure: (stage) => config.measure({ plan, stage }) });
78
+ decisions.push(decision);
79
+ const ledger = resolve(args.appDir, args.record);
80
+ mkdirSync(dirname(ledger), { recursive: true });
81
+ appendFileSync(ledger, `${JSON.stringify(decision)}
82
+ `);
83
+ await config.record?.(decision);
84
+ }
85
+ return decisions;
86
+ }
87
+ function describe(decision) {
88
+ const move = `${decision.from.stage ?? decision.from.value ?? "(empty)"} -> ${decision.to.stage ?? decision.to.value}`;
89
+ if (decision.decision === "allowed") {
90
+ return `rollout ${decision.rollout}: allowed ${move}${decision.widens ? "" : " (not a widening)"}`;
91
+ }
92
+ return `rollout ${decision.rollout}: REFUSED ${move}
93
+ ${decision.reasons.map((reason) => ` - ${reason}`).join("\n")}`;
94
+ }
95
+ async function main() {
96
+ let args;
97
+ try {
98
+ args = parseArgs(process.argv.slice(2));
99
+ } catch (error) {
100
+ console.error(error instanceof Error ? error.message : String(error));
101
+ return 2;
102
+ }
103
+ try {
104
+ const decisions = await runRolloutCheck(args);
105
+ for (const decision of decisions) console.log(describe(decision));
106
+ return decisions.some((decision) => decision.decision === "refused") ? 1 : 0;
107
+ } catch (error) {
108
+ console.error(`agent-app-rollout-check: ${error instanceof Error ? error.message : String(error)}`);
109
+ return 2;
110
+ }
111
+ }
112
+ if (invokedAsScript(import.meta.url, process.argv[1])) {
113
+ main().then((code) => {
114
+ process.exitCode = code;
115
+ });
116
+ }
117
+ export {
118
+ readWranglerVar,
119
+ runRolloutCheck
120
+ };
121
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/rollout/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * `agent-app-rollout-check` — refuse a deploy that widens a staged rollout\n * before the stage it leaves met its kill lines.\n *\n * Runs in the app's repo, in the step that ships (ship.sh verify, or the PR\n * check). Add `rollout.config.mjs` at the root:\n *\n * export default {\n * plans: [{\n * name: 'hospitality-routed-chat',\n * variable: 'HOSPITALITY_ROUTED_BUSINESS_IDS',\n * stages: [\n * { name: 'qa', value: 'ws-a,ws-b', minSamples: 30,\n * kill: { first_words_p50_ms: { max: 2500 }, failure_rate: { max: 0 } } },\n * { name: 'all', value: '*', minSamples: 200,\n * kill: { first_words_p50_ms: { max: 1500 }, failure_rate: { max: 0.01 } } },\n * ],\n * }],\n * // The product's own instrument: production numbers for the stage being left.\n * async measure({ plan, stage }) { return { stage: stage.name, samples, metrics: { … }, source } },\n * // Optional: keep the decision somewhere durable as well as the JSONL ledger.\n * async record(decision) {},\n * }\n *\n * The new value is read from the `[vars]` of wrangler.toml; the current one\n * from the same file at `--base` (default `origin/main`), or given with\n * `--from`. `--to` overrides the new value.\n *\n * Usage: agent-app-rollout-check [appDir] [--config <file>] [--base <git ref>]\n * [--from <value>] [--to <value>] [--plan <name>] [--record <jsonl>]\n * Exits 0 when every plan's change is allowed, 1 when one is refused, 2 on a usage error.\n */\nimport { execFileSync } from 'node:child_process'\nimport { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs'\nimport { dirname, join, resolve } from 'node:path'\nimport { pathToFileURL } from 'node:url'\nimport { invokedAsScript } from '../signoff/invoked-as-script.js'\nimport { decideRollout, type RolloutDecision, type RolloutPlan, type RolloutStage, type StageMeasurement } from './index.js'\n\nexport interface RolloutConfig {\n plans: RolloutPlan[]\n measure(input: { plan: RolloutPlan; stage: RolloutStage }): Promise<StageMeasurement | null>\n record?(decision: RolloutDecision): Promise<void> | void\n /** Default `wrangler.toml`. */\n wrangler?: string\n}\n\ninterface CliArgs {\n appDir: string\n config?: string\n base: string\n from?: string\n to?: string\n plan?: string\n record: string\n}\n\nconst CONFIG_NAMES = ['rollout.config.mjs', 'rollout.config.js']\n\nfunction parseArgs(argv: readonly string[]): CliArgs {\n const args: CliArgs = { appDir: process.cwd(), base: 'origin/main', record: '.rollout/decisions.jsonl' }\n for (let index = 0; index < argv.length; index += 1) {\n const arg = argv[index]!\n const value = () => {\n const next = argv[++index]\n if (next === undefined) throw new Error(`${arg} needs a value`)\n return next\n }\n if (arg === '--config') args.config = value()\n else if (arg === '--base') args.base = value()\n else if (arg === '--from') args.from = value()\n else if (arg === '--to') args.to = value()\n else if (arg === '--plan') args.plan = value()\n else if (arg === '--record') args.record = value()\n else if (arg.startsWith('--')) throw new Error(`unknown option ${arg}`)\n else args.appDir = resolve(arg)\n }\n return args\n}\n\n/** A top-level `[vars]` string value from wrangler.toml source; environments are not read. */\nexport function readWranglerVar(source: string, name: string): string | null {\n let inVars = false\n for (const line of source.split('\\n')) {\n const header = line.match(/^\\s*\\[([^\\]]+)\\]\\s*(?:#.*)?$/)\n if (header) {\n inVars = header[1]!.trim() === 'vars'\n continue\n }\n if (!inVars) continue\n const entry = line.match(/^\\s*([A-Za-z_][A-Za-z0-9_]*)\\s*=\\s*\"((?:[^\"\\\\]|\\\\.)*)\"/)\n if (entry && entry[1] === name) return JSON.parse(`\"${entry[2]}\"`) as string\n }\n return null\n}\n\nasync function loadConfig(appDir: string, explicit?: string): Promise<RolloutConfig> {\n const file = explicit ? resolve(appDir, explicit) : CONFIG_NAMES.map(name => join(appDir, name)).find(path => existsSync(path))\n if (!file || !existsSync(file)) throw new Error(`no ${CONFIG_NAMES[0]} in ${appDir}`)\n const config = ((await import(pathToFileURL(file).href)) as { default: RolloutConfig }).default\n if (!Array.isArray(config?.plans) || typeof config.measure !== 'function') {\n throw new Error(`${file} must export { plans, measure }`)\n }\n return config\n}\n\nfunction wranglerAt(appDir: string, file: string, ref: string): string {\n try {\n return execFileSync('git', ['show', `${ref}:${file}`], { cwd: appDir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })\n } catch {\n throw new Error(`cannot read ${file} at ${ref}; fetch it or pass --from`)\n }\n}\n\nexport async function runRolloutCheck(args: CliArgs): Promise<RolloutDecision[]> {\n const config = await loadConfig(args.appDir, args.config)\n const file = config.wrangler ?? 'wrangler.toml'\n const plans = args.plan ? config.plans.filter(plan => plan.name === args.plan) : config.plans\n if (!plans.length) throw new Error(args.plan ? `no plan named ${args.plan}` : 'the config declares no plans')\n if (plans.length > 1 && (args.from !== undefined || args.to !== undefined)) throw new Error('--from and --to need --plan')\n const head = readFileSync(join(args.appDir, file), 'utf8')\n const base = args.from === undefined ? wranglerAt(args.appDir, file, args.base) : null\n const decisions: RolloutDecision[] = []\n for (const plan of plans) {\n const fromValue = args.from ?? readWranglerVar(base!, plan.variable) ?? ''\n const toValue = args.to ?? readWranglerVar(head, plan.variable) ?? ''\n const decision = await decideRollout({ plan, fromValue, toValue, measure: stage => config.measure({ plan, stage }) })\n decisions.push(decision)\n const ledger = resolve(args.appDir, args.record)\n mkdirSync(dirname(ledger), { recursive: true })\n appendFileSync(ledger, `${JSON.stringify(decision)}\\n`)\n await config.record?.(decision)\n }\n return decisions\n}\n\nfunction describe(decision: RolloutDecision): string {\n const move = `${decision.from.stage ?? decision.from.value ?? '(empty)'} -> ${decision.to.stage ?? decision.to.value}`\n if (decision.decision === 'allowed') {\n return `rollout ${decision.rollout}: allowed ${move}${decision.widens ? '' : ' (not a widening)'}`\n }\n return `rollout ${decision.rollout}: REFUSED ${move}\\n${decision.reasons.map(reason => ` - ${reason}`).join('\\n')}`\n}\n\nasync function main(): Promise<number> {\n let args: CliArgs\n try {\n args = parseArgs(process.argv.slice(2))\n } catch (error) {\n console.error(error instanceof Error ? error.message : String(error))\n return 2\n }\n try {\n const decisions = await runRolloutCheck(args)\n for (const decision of decisions) console.log(describe(decision))\n return decisions.some(decision => decision.decision === 'refused') ? 1 : 0\n } catch (error) {\n console.error(`agent-app-rollout-check: ${error instanceof Error ? error.message : String(error)}`)\n return 2\n }\n}\n\nif (invokedAsScript(import.meta.url, process.argv[1])) {\n main().then(code => { process.exitCode = code })\n}\n"],"mappings":";;;;;;;;;AAiCA,SAAS,oBAAoB;AAC7B,SAAS,gBAAgB,YAAY,WAAW,oBAAoB;AACpE,SAAS,SAAS,MAAM,eAAe;AACvC,SAAS,qBAAqB;AAsB9B,IAAM,eAAe,CAAC,sBAAsB,mBAAmB;AAE/D,SAAS,UAAU,MAAkC;AACnD,QAAM,OAAgB,EAAE,QAAQ,QAAQ,IAAI,GAAG,MAAM,eAAe,QAAQ,2BAA2B;AACvG,WAAS,QAAQ,GAAG,QAAQ,KAAK,QAAQ,SAAS,GAAG;AACnD,UAAM,MAAM,KAAK,KAAK;AACtB,UAAM,QAAQ,MAAM;AAClB,YAAM,OAAO,KAAK,EAAE,KAAK;AACzB,UAAI,SAAS,OAAW,OAAM,IAAI,MAAM,GAAG,GAAG,gBAAgB;AAC9D,aAAO;AAAA,IACT;AACA,QAAI,QAAQ,WAAY,MAAK,SAAS,MAAM;AAAA,aACnC,QAAQ,SAAU,MAAK,OAAO,MAAM;AAAA,aACpC,QAAQ,SAAU,MAAK,OAAO,MAAM;AAAA,aACpC,QAAQ,OAAQ,MAAK,KAAK,MAAM;AAAA,aAChC,QAAQ,SAAU,MAAK,OAAO,MAAM;AAAA,aACpC,QAAQ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GAAG,SAAS,KAAK,SAAS,SAAS,KAAK,SAAS,SAAS,OAAO,SAAS,GAAG,SAAS,SAAS,GAAG,KAAK;AACpH,MAAI,SAAS,aAAa,WAAW;AACnC,WAAO,WAAW,SAAS,OAAO,aAAa,IAAI,GAAG,SAAS,SAAS,KAAK,mBAAmB;AAAA,EAClG;AACA,SAAO,WAAW,SAAS,OAAO,aAAa,IAAI;AAAA,EAAK,SAAS,QAAQ,IAAI,YAAU,OAAO,MAAM,EAAE,EAAE,KAAK,IAAI,CAAC;AACpH;AAEA,eAAe,OAAwB;AACrC,MAAI;AACJ,MAAI;AACF,WAAO,UAAU,QAAQ,KAAK,MAAM,CAAC,CAAC;AAAA,EACxC,SAAS,OAAO;AACd,YAAQ,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AACpE,WAAO;AAAA,EACT;AACA,MAAI;AACF,UAAM,YAAY,MAAM,gBAAgB,IAAI;AAC5C,eAAW,YAAY,UAAW,SAAQ,IAAI,SAAS,QAAQ,CAAC;AAChE,WAAO,UAAU,KAAK,cAAY,SAAS,aAAa,SAAS,IAAI,IAAI;AAAA,EAC3E,SAAS,OAAO;AACd,YAAQ,MAAM,4BAA4B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC,EAAE;AAClG,WAAO;AAAA,EACT;AACF;AAEA,IAAI,gBAAgB,YAAY,KAAK,QAAQ,KAAK,CAAC,CAAC,GAAG;AACrD,OAAK,EAAE,KAAK,UAAQ;AAAE,YAAQ,WAAW;AAAA,EAAK,CAAC;AACjD;","names":[]}
@@ -0,0 +1,62 @@
1
+ /**
2
+ * The measurement a rollout guard reads: one row per turn with its lane, its
3
+ * first visible word and whether it failed, and the stage numbers computed
4
+ * from those rows.
5
+ *
6
+ * Record from the chat route's lifecycle (`onTurnComplete` / `onTurnError`
7
+ * carry `firstTextMs` and `durationMs`), then serve `measureStage` behind an
8
+ * operator endpoint that the deploy's `rollout.config.mjs` calls. A stage is
9
+ * measured on the turns of the workspaces it admits, in the lane being rolled
10
+ * out, since the time it went live.
11
+ */
12
+ import { type RolloutStage, type StageMeasurement } from './index';
13
+ /** Minimal D1 surface (Cloudflare's `D1Database` satisfies it). */
14
+ export interface D1LikeForRollout {
15
+ prepare(sql: string): {
16
+ bind(...values: unknown[]): {
17
+ run(): Promise<unknown>;
18
+ all<T = Record<string, unknown>>(): Promise<{
19
+ results?: T[];
20
+ }>;
21
+ };
22
+ };
23
+ }
24
+ export declare const ROLLOUT_TURN_TIMING_SCHEMA_SQL = "\nCREATE TABLE IF NOT EXISTS rollout_turn_timing (\n turn_id TEXT PRIMARY KEY,\n rollout TEXT NOT NULL,\n workspace_id TEXT NOT NULL,\n lane TEXT NOT NULL,\n first_text_ms INTEGER,\n settled_ms INTEGER NOT NULL,\n failed INTEGER NOT NULL CHECK (failed IN (0, 1)),\n failure_code TEXT,\n at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS rollout_turn_timing_by_lane ON rollout_turn_timing (rollout, lane, at);\n";
25
+ export interface TurnTimingRow {
26
+ turnId: string;
27
+ /** The plan this turn counts toward, e.g. `hospitality-routed-chat`. */
28
+ rollout: string;
29
+ workspaceId: string;
30
+ /** The lane that served the turn, e.g. `routed` or `sandbox`. Only the rolled-out lane is measured. */
31
+ lane: string;
32
+ /** From the lifecycle's `firstTextMs`; absent when no word streamed. */
33
+ firstTextMs?: number;
34
+ settledMs: number;
35
+ failed: boolean;
36
+ failureCode?: string;
37
+ /** Epoch ms; defaults to now. */
38
+ at?: number;
39
+ }
40
+ /** Stage metrics from turn rows: first-words and settled percentiles in ms, and the failure rate. */
41
+ export declare function stageMetrics(rows: ReadonlyArray<Pick<TurnTimingRow, 'firstTextMs' | 'settledMs' | 'failed'>>): {
42
+ first_words_p50_ms: number | null;
43
+ first_words_p90_ms: number | null;
44
+ settled_p50_ms: number | null;
45
+ settled_p90_ms: number | null;
46
+ failure_rate: number | null;
47
+ };
48
+ export declare function createD1TurnTimingStore(options: {
49
+ db: D1LikeForRollout;
50
+ now?: () => number;
51
+ }): {
52
+ /** Record one settled turn. Idempotent on `turnId`. Never throws: telemetry must not fail a turn. */
53
+ record(row: TurnTimingRow): Promise<void>;
54
+ /** The stage's numbers: its admitted workspaces' turns in `lane` since `since` (epoch ms). A row carries no
55
+ * workspace creation time, so a workspace admitted only by a `new-since:` entry is not counted. */
56
+ measureStage(input: {
57
+ rollout: string;
58
+ stage: RolloutStage;
59
+ lane: string;
60
+ since: number;
61
+ }): Promise<StageMeasurement>;
62
+ };
@@ -0,0 +1,89 @@
1
+ import {
2
+ rolloutAdmits
3
+ } from "../chunk-4JUEOVQS.js";
4
+
5
+ // src/rollout/d1.ts
6
+ var ROLLOUT_TURN_TIMING_SCHEMA_SQL = `
7
+ CREATE TABLE IF NOT EXISTS rollout_turn_timing (
8
+ turn_id TEXT PRIMARY KEY,
9
+ rollout TEXT NOT NULL,
10
+ workspace_id TEXT NOT NULL,
11
+ lane TEXT NOT NULL,
12
+ first_text_ms INTEGER,
13
+ settled_ms INTEGER NOT NULL,
14
+ failed INTEGER NOT NULL CHECK (failed IN (0, 1)),
15
+ failure_code TEXT,
16
+ at INTEGER NOT NULL
17
+ );
18
+ CREATE INDEX IF NOT EXISTS rollout_turn_timing_by_lane ON rollout_turn_timing (rollout, lane, at);
19
+ `;
20
+ var MEASURE_ROW_LIMIT = 2e4;
21
+ function percentile(sorted, p) {
22
+ if (!sorted.length) return null;
23
+ return sorted[Math.min(sorted.length - 1, Math.ceil(p / 100 * sorted.length) - 1)];
24
+ }
25
+ function stageMetrics(rows) {
26
+ const firstWords = rows.flatMap((row) => row.firstTextMs === void 0 || row.firstTextMs === null ? [] : [row.firstTextMs]).sort((a, b) => a - b);
27
+ const settled = rows.filter((row) => !row.failed).map((row) => row.settledMs).sort((a, b) => a - b);
28
+ return {
29
+ first_words_p50_ms: percentile(firstWords, 50),
30
+ first_words_p90_ms: percentile(firstWords, 90),
31
+ settled_p50_ms: percentile(settled, 50),
32
+ settled_p90_ms: percentile(settled, 90),
33
+ // A turn that streamed no word failed the user whatever its envelope said.
34
+ failure_rate: rows.length ? rows.filter((row) => row.failed || row.firstTextMs === void 0 || row.firstTextMs === null).length / rows.length : null
35
+ };
36
+ }
37
+ function createD1TurnTimingStore(options) {
38
+ const now = options.now ?? Date.now;
39
+ return {
40
+ /** Record one settled turn. Idempotent on `turnId`. Never throws: telemetry must not fail a turn. */
41
+ async record(row) {
42
+ try {
43
+ await options.db.prepare(
44
+ `INSERT OR IGNORE INTO rollout_turn_timing
45
+ (turn_id, rollout, workspace_id, lane, first_text_ms, settled_ms, failed, failure_code, at)
46
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
47
+ ).bind(
48
+ row.turnId,
49
+ row.rollout,
50
+ row.workspaceId,
51
+ row.lane,
52
+ row.firstTextMs === void 0 ? null : Math.round(row.firstTextMs),
53
+ Math.round(row.settledMs),
54
+ row.failed ? 1 : 0,
55
+ row.failureCode ?? null,
56
+ row.at ?? now()
57
+ ).run();
58
+ } catch (error) {
59
+ console.error(JSON.stringify({
60
+ event: "rollout_turn_timing_record_failed",
61
+ turnId: row.turnId,
62
+ error: error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200)
63
+ }));
64
+ }
65
+ },
66
+ /** The stage's numbers: its admitted workspaces' turns in `lane` since `since` (epoch ms). A row carries no
67
+ * workspace creation time, so a workspace admitted only by a `new-since:` entry is not counted. */
68
+ async measureStage(input) {
69
+ const { results = [] } = await options.db.prepare(
70
+ `SELECT workspace_id, first_text_ms, settled_ms, failed FROM rollout_turn_timing
71
+ WHERE rollout = ? AND lane = ? AND at >= ? ORDER BY at DESC LIMIT ?`
72
+ ).bind(input.rollout, input.lane, input.since, MEASURE_ROW_LIMIT).all();
73
+ const rows = results.filter((row) => rolloutAdmits(input.stage.value, { id: row.workspace_id })).map((row) => ({ firstTextMs: row.first_text_ms ?? void 0, settledMs: row.settled_ms, failed: row.failed === 1 }));
74
+ return {
75
+ stage: input.stage.name,
76
+ samples: rows.length,
77
+ metrics: stageMetrics(rows),
78
+ source: `rollout_turn_timing lane=${input.lane}`,
79
+ window: { from: new Date(input.since).toISOString(), to: new Date(now()).toISOString() }
80
+ };
81
+ }
82
+ };
83
+ }
84
+ export {
85
+ ROLLOUT_TURN_TIMING_SCHEMA_SQL,
86
+ createD1TurnTimingStore,
87
+ stageMetrics
88
+ };
89
+ //# sourceMappingURL=d1.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/rollout/d1.ts"],"sourcesContent":["/**\n * The measurement a rollout guard reads: one row per turn with its lane, its\n * first visible word and whether it failed, and the stage numbers computed\n * from those rows.\n *\n * Record from the chat route's lifecycle (`onTurnComplete` / `onTurnError`\n * carry `firstTextMs` and `durationMs`), then serve `measureStage` behind an\n * operator endpoint that the deploy's `rollout.config.mjs` calls. A stage is\n * measured on the turns of the workspaces it admits, in the lane being rolled\n * out, since the time it went live.\n */\nimport { rolloutAdmits, type RolloutStage, type StageMeasurement } from './index'\n\n/** Minimal D1 surface (Cloudflare's `D1Database` satisfies it). */\nexport interface D1LikeForRollout {\n prepare(sql: string): {\n bind(...values: unknown[]): {\n run(): Promise<unknown>\n all<T = Record<string, unknown>>(): Promise<{ results?: T[] }>\n }\n }\n}\n\nexport const ROLLOUT_TURN_TIMING_SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS rollout_turn_timing (\n turn_id TEXT PRIMARY KEY,\n rollout TEXT NOT NULL,\n workspace_id TEXT NOT NULL,\n lane TEXT NOT NULL,\n first_text_ms INTEGER,\n settled_ms INTEGER NOT NULL,\n failed INTEGER NOT NULL CHECK (failed IN (0, 1)),\n failure_code TEXT,\n at INTEGER NOT NULL\n);\nCREATE INDEX IF NOT EXISTS rollout_turn_timing_by_lane ON rollout_turn_timing (rollout, lane, at);\n`\n\nexport interface TurnTimingRow {\n turnId: string\n /** The plan this turn counts toward, e.g. `hospitality-routed-chat`. */\n rollout: string\n workspaceId: string\n /** The lane that served the turn, e.g. `routed` or `sandbox`. Only the rolled-out lane is measured. */\n lane: string\n /** From the lifecycle's `firstTextMs`; absent when no word streamed. */\n firstTextMs?: number\n settledMs: number\n failed: boolean\n failureCode?: string\n /** Epoch ms; defaults to now. */\n at?: number\n}\n\n/** Rows read for one measurement; a stage needing more than this would be measured on its newest rows. */\nconst MEASURE_ROW_LIMIT = 20_000\n\nfunction percentile(sorted: readonly number[], p: number): number | null {\n if (!sorted.length) return null\n return sorted[Math.min(sorted.length - 1, Math.ceil((p / 100) * sorted.length) - 1)]!\n}\n\n/** Stage metrics from turn rows: first-words and settled percentiles in ms, and the failure rate. */\nexport function stageMetrics(rows: ReadonlyArray<Pick<TurnTimingRow, 'firstTextMs' | 'settledMs' | 'failed'>>) {\n const firstWords = rows.flatMap(row => row.firstTextMs === undefined || row.firstTextMs === null ? [] : [row.firstTextMs]).sort((a, b) => a - b)\n const settled = rows.filter(row => !row.failed).map(row => row.settledMs).sort((a, b) => a - b)\n return {\n first_words_p50_ms: percentile(firstWords, 50),\n first_words_p90_ms: percentile(firstWords, 90),\n settled_p50_ms: percentile(settled, 50),\n settled_p90_ms: percentile(settled, 90),\n // A turn that streamed no word failed the user whatever its envelope said.\n failure_rate: rows.length ? rows.filter(row => row.failed || row.firstTextMs === undefined || row.firstTextMs === null).length / rows.length : null,\n }\n}\n\nexport function createD1TurnTimingStore(options: { db: D1LikeForRollout; now?: () => number }) {\n const now = options.now ?? Date.now\n return {\n /** Record one settled turn. Idempotent on `turnId`. Never throws: telemetry must not fail a turn. */\n async record(row: TurnTimingRow): Promise<void> {\n try {\n await options.db.prepare(\n `INSERT OR IGNORE INTO rollout_turn_timing\n (turn_id, rollout, workspace_id, lane, first_text_ms, settled_ms, failed, failure_code, at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,\n ).bind(row.turnId, row.rollout, row.workspaceId, row.lane,\n row.firstTextMs === undefined ? null : Math.round(row.firstTextMs), Math.round(row.settledMs),\n row.failed ? 1 : 0, row.failureCode ?? null, row.at ?? now()).run()\n } catch (error) {\n console.error(JSON.stringify({ event: 'rollout_turn_timing_record_failed', turnId: row.turnId,\n error: error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200) }))\n }\n },\n\n /** The stage's numbers: its admitted workspaces' turns in `lane` since `since` (epoch ms). A row carries no\n * workspace creation time, so a workspace admitted only by a `new-since:` entry is not counted. */\n async measureStage(input: { rollout: string; stage: RolloutStage; lane: string; since: number }): Promise<StageMeasurement> {\n const { results = [] } = await options.db.prepare(\n `SELECT workspace_id, first_text_ms, settled_ms, failed FROM rollout_turn_timing\n WHERE rollout = ? AND lane = ? AND at >= ? ORDER BY at DESC LIMIT ?`,\n ).bind(input.rollout, input.lane, input.since, MEASURE_ROW_LIMIT).all<{\n workspace_id: string; first_text_ms: number | null; settled_ms: number; failed: number\n }>()\n const rows = results\n .filter(row => rolloutAdmits(input.stage.value, { id: row.workspace_id }))\n .map(row => ({ firstTextMs: row.first_text_ms ?? undefined, settledMs: row.settled_ms, failed: row.failed === 1 }))\n return {\n stage: input.stage.name,\n samples: rows.length,\n metrics: stageMetrics(rows),\n source: `rollout_turn_timing lane=${input.lane}`,\n window: { from: new Date(input.since).toISOString(), to: new Date(now()).toISOString() },\n }\n },\n }\n}\n"],"mappings":";;;;;AAuBO,IAAM,iCAAiC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAgC9C,IAAM,oBAAoB;AAE1B,SAAS,WAAW,QAA2B,GAA0B;AACvE,MAAI,CAAC,OAAO,OAAQ,QAAO;AAC3B,SAAO,OAAO,KAAK,IAAI,OAAO,SAAS,GAAG,KAAK,KAAM,IAAI,MAAO,OAAO,MAAM,IAAI,CAAC,CAAC;AACrF;AAGO,SAAS,aAAa,MAAkF;AAC7G,QAAM,aAAa,KAAK,QAAQ,SAAO,IAAI,gBAAgB,UAAa,IAAI,gBAAgB,OAAO,CAAC,IAAI,CAAC,IAAI,WAAW,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AA;AAAA,IAIA,MAAM,aAAa,OAAyG;AAC1H,YAAM,EAAE,UAAU,CAAC,EAAE,IAAI,MAAM,QAAQ,GAAG;AAAA,QACxC;AAAA;AAAA,MAEF,EAAE,KAAK,MAAM,SAAS,MAAM,MAAM,MAAM,OAAO,iBAAiB,EAAE,IAE/D;AACH,YAAM,OAAO,QACV,OAAO,SAAO,cAAc,MAAM,MAAM,OAAO,EAAE,IAAI,IAAI,aAAa,CAAC,CAAC,EACxE,IAAI,UAAQ,EAAE,aAAa,IAAI,iBAAiB,QAAW,WAAW,IAAI,YAAY,QAAQ,IAAI,WAAW,EAAE,EAAE;AACpH,aAAO;AAAA,QACL,OAAO,MAAM,MAAM;AAAA,QACnB,SAAS,KAAK;AAAA,QACd,SAAS,aAAa,IAAI;AAAA,QAC1B,QAAQ,4BAA4B,MAAM,IAAI;AAAA,QAC9C,QAAQ,EAAE,MAAM,IAAI,KAAK,MAAM,KAAK,EAAE,YAAY,GAAG,IAAI,IAAI,KAAK,IAAI,CAAC,EAAE,YAAY,EAAE;AAAA,MACzF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Rollout guard: a staged rollout widens only when the stage it leaves met
3
+ * that stage's kill lines on measured production numbers.
4
+ *
5
+ * WHY. Hospitality's routed lane widened from two QA workspaces to `*` at a
6
+ * first-words p50 of 3.54 s, past kill lines of 2.5 s and 3.0 s
7
+ * (hospitality-agent #382, 2026-10-11). The numbers existed; nothing read them
8
+ * before the list changed. This module is the one place that reads them.
9
+ *
10
+ * THE LIST. A rollout is one comma-separated value, usually a deploy variable
11
+ * such as `HOSPITALITY_ROUTED_BUSINESS_IDS`: workspace ids, `*` for every
12
+ * workspace, `!<id>` to keep one out whatever else matches, and
13
+ * `new-since:<ISO time>` for workspaces created at or after that time.
14
+ * {@link rolloutAdmits} is the reference reading of that grammar.
15
+ *
16
+ * THE RULE ({@link decideRollout}).
17
+ * - A change that admits no workspace the current value did not (a narrowing,
18
+ * a rollback, the same stage) is always allowed: a guard that can block a
19
+ * rollback is worse than none.
20
+ * - A widening must land on a declared stage, the next one after the current
21
+ * value's stage, never past it.
22
+ * - The stage being left must have at least `minSamples` measured turns and
23
+ * every kill line met. A metric that was not measured fails its line.
24
+ * - A refusal names each reason (`first_words_p50_ms 3540 over kill line 2500`).
25
+ *
26
+ * Every decision, allowed or refused, is returned as one record the caller
27
+ * persists (the CLI appends it to a JSONL ledger and hands it to the
28
+ * config's `record`).
29
+ */
30
+ /** A kill line: the measured value must stay at or under `max` and at or over `min`. */
31
+ export interface RolloutKillLine {
32
+ max?: number;
33
+ min?: number;
34
+ }
35
+ export interface RolloutStage {
36
+ /** Short name used in refusals and records, e.g. `qa`, `all-but-recenter`. */
37
+ name: string;
38
+ /** The exact list value that defines this stage. */
39
+ value: string;
40
+ /** Turns the stage must have served, measured, before the rollout may leave it. */
41
+ minSamples: number;
42
+ /** Metric name → line. Metric names are the product's, e.g. `first_words_p50_ms`, `failure_rate`. */
43
+ kill: Record<string, RolloutKillLine>;
44
+ }
45
+ export interface RolloutPlan {
46
+ /** e.g. `hospitality-routed-chat`. */
47
+ name: string;
48
+ /** The deploy variable that carries the list, e.g. `HOSPITALITY_ROUTED_BUSINESS_IDS`. */
49
+ variable: string;
50
+ /** In widening order. */
51
+ stages: RolloutStage[];
52
+ }
53
+ /** Production numbers for one stage, from the product's own instrument. */
54
+ export interface StageMeasurement {
55
+ stage: string;
56
+ samples: number;
57
+ metrics: Record<string, number | null | undefined>;
58
+ /** Where the numbers came from (ledger, query, soak), for the record. */
59
+ source?: string;
60
+ window?: {
61
+ from: string;
62
+ to: string;
63
+ };
64
+ }
65
+ export interface RolloutDecision {
66
+ rollout: string;
67
+ variable: string;
68
+ from: {
69
+ value: string;
70
+ stage: string | null;
71
+ };
72
+ to: {
73
+ value: string;
74
+ stage: string | null;
75
+ };
76
+ widens: boolean;
77
+ decision: 'allowed' | 'refused';
78
+ /** Empty when allowed; each refusal reason otherwise. */
79
+ reasons: string[];
80
+ measured: StageMeasurement | null;
81
+ at: string;
82
+ }
83
+ export interface ParsedRolloutList {
84
+ all: boolean;
85
+ ids: ReadonlySet<string>;
86
+ excluded: ReadonlySet<string>;
87
+ /** Epoch ms of each `new-since:` entry. */
88
+ newSince: readonly number[];
89
+ }
90
+ export declare function parseRolloutList(value: string | null | undefined): ParsedRolloutList;
91
+ /** Whether a list admits one workspace. `createdAt` (epoch ms) is needed only for `new-since:` entries. */
92
+ export declare function rolloutAdmits(value: string | ParsedRolloutList, workspace: {
93
+ id: string;
94
+ createdAt?: number;
95
+ }): boolean;
96
+ /**
97
+ * Whether `to` may admit a workspace `from` does not. Conservative: a change it
98
+ * cannot prove narrower counts as a widening.
99
+ */
100
+ export declare function rolloutWidens(fromValue: string, toValue: string): boolean;
101
+ /** Canonical form for matching a value to a stage: entries trimmed and sorted. */
102
+ export declare function normalizeRolloutValue(value: string): string;
103
+ /** Each kill line the measurement misses, as a reason. Empty when every line holds. */
104
+ export declare function killLineBreaches(stage: RolloutStage, measured: StageMeasurement | null): string[];
105
+ export declare function validateRolloutPlan(plan: RolloutPlan): void;
106
+ /**
107
+ * Decide one change of the list. `measure` is called only for a widening, and
108
+ * only for the stage being left.
109
+ */
110
+ export declare function decideRollout(input: {
111
+ plan: RolloutPlan;
112
+ fromValue: string;
113
+ toValue: string;
114
+ measure(stage: RolloutStage): Promise<StageMeasurement | null>;
115
+ now?: () => Date;
116
+ }): Promise<RolloutDecision>;
@@ -0,0 +1,19 @@
1
+ import {
2
+ decideRollout,
3
+ killLineBreaches,
4
+ normalizeRolloutValue,
5
+ parseRolloutList,
6
+ rolloutAdmits,
7
+ rolloutWidens,
8
+ validateRolloutPlan
9
+ } from "../chunk-4JUEOVQS.js";
10
+ export {
11
+ decideRollout,
12
+ killLineBreaches,
13
+ normalizeRolloutValue,
14
+ parseRolloutList,
15
+ rolloutAdmits,
16
+ rolloutWidens,
17
+ validateRolloutPlan
18
+ };
19
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -96,7 +96,7 @@ import {
96
96
  warmBinOf,
97
97
  warmWeekdayOf,
98
98
  writeProfileFilesToBox
99
- } from "../chunk-JGLK5RDK.js";
99
+ } from "../chunk-JIXM57JM.js";
100
100
  import {
101
101
  EGRESS_PROXY_RECOVERY_PHASE,
102
102
  EGRESS_PROXY_RECOVERY_REQUIRED,
@@ -19,7 +19,7 @@
19
19
  * copy the session's documents in). `allow` is the product's command policy.
20
20
  */
21
21
  import type { SandboxInstance } from '@tangle-network/sandbox';
22
- import { SandboxRunError } from './sandbox-run-tool';
22
+ import { SandboxRunError, type SandboxToolContext } from './sandbox-run-tool';
23
23
  export interface SandboxExecToolOptions {
24
24
  /** The box commands run in. The product provisions, binds and bills it. A throw is
25
25
  * `sandbox_unavailable`, unless it is a `SandboxRunError`, which is kept as it is. */
@@ -31,7 +31,9 @@ export interface SandboxExecToolOptions {
31
31
  env?: Record<string, string>;
32
32
  /** Cap for one command, box start and prepare included. Default 2 minutes. */
33
33
  timeoutMs?: number;
34
- /** Characters of stdout and of stderr returned to the model, each. Default 20 000 (the tail is kept). */
34
+ /** Characters of stdout and of stderr returned to the model, each; the tail is kept. Default 4 000, so
35
+ * one result stays inside `runRouterTurn`'s default 12 000-character tool-result limit, which keeps the
36
+ * head and would otherwise cut the tail, where errors are. Raise both together. */
35
37
  maxOutputChars?: number;
36
38
  /** The product's command policy: a string refuses the command with that reason. */
37
39
  allow?(command: string): string | null;
@@ -62,7 +64,7 @@ export interface SandboxExecTool {
62
64
  name: string;
63
65
  description: string;
64
66
  inputSchema: Record<string, unknown>;
65
- run(args: Record<string, unknown>): Promise<SandboxExecResult>;
67
+ run(args: Record<string, unknown>, context?: SandboxToolContext): Promise<SandboxExecResult>;
66
68
  }
67
69
  export declare const SANDBOX_EXEC_DESCRIPTION: string;
68
70
  export declare function createSandboxExecTool(options: SandboxExecToolOptions): SandboxExecTool;
@@ -27,6 +27,16 @@ export declare class SandboxRunError extends Error {
27
27
  cause?: unknown;
28
28
  });
29
29
  }
30
+ /** The engine's per-call tool context (`RouterTurnToolContext`), kept structural so this module does not import the engine. */
31
+ export interface SandboxToolContext {
32
+ emit(kind: string, data?: unknown): void;
33
+ }
34
+ export interface SandboxTaskOptions {
35
+ signal: AbortSignal;
36
+ timeoutMs: number;
37
+ /** Streams a typed side event from the box run (a progress step, a file written) as the turn's `tool_event`. */
38
+ emit(kind: string, data?: unknown): void;
39
+ }
30
40
  export interface SandboxRunToolOptions {
31
41
  /** The box this call runs in. The product provisions, binds and bills it; this module never
32
42
  * creates one. A throw is reported to the model as `sandbox_unavailable`, unless it is a
@@ -34,10 +44,7 @@ export interface SandboxRunToolOptions {
34
44
  box(signal: AbortSignal): Promise<SandboxInstance>;
35
45
  /** Runs the task on the box and returns the box agent's final answer: {@link sandboxPromptRunner}
36
46
  * for the shell's own prompt path, or the product's runner (skill placement, app-tool MCP, a spend tap). */
37
- runTask(box: SandboxInstance, task: string, options: {
38
- signal: AbortSignal;
39
- timeoutMs: number;
40
- }): Promise<string>;
47
+ runTask(box: SandboxInstance, task: string, options: SandboxTaskOptions): Promise<string>;
41
48
  /** Wall-clock cap for one call, box start included. Default 5 minutes. */
42
49
  timeoutMs?: number;
43
50
  /** Cancels a call in flight, for example the turn's own signal. */
@@ -59,7 +66,7 @@ export interface SandboxRunTool {
59
66
  name: string;
60
67
  description: string;
61
68
  inputSchema: Record<string, unknown>;
62
- run(args: Record<string, unknown>): Promise<{
69
+ run(args: Record<string, unknown>, context?: SandboxToolContext): Promise<{
63
70
  answer: string;
64
71
  ms: number;
65
72
  }>;
@@ -50,9 +50,9 @@ import {
50
50
  terminalizeDanglingAssistantToolUpdates,
51
51
  terminalizeDanglingToolPart,
52
52
  terminalizeDanglingToolParts
53
- } from "../chunk-ZGUXI5SI.js";
54
- import "../chunk-6VQCFJWP.js";
53
+ } from "../chunk-XNKLQG26.js";
55
54
  import "../chunk-LQYIBL3G.js";
55
+ import "../chunk-6VQCFJWP.js";
56
56
  export {
57
57
  DEFAULT_RUNNING_TURN_LEASE_MS,
58
58
  DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS,
@@ -39,8 +39,9 @@ import {
39
39
  } from "../chunk-6PRQ45QE.js";
40
40
  import {
41
41
  useInfiniteScroll
42
- } from "../chunk-5S5ANZBS.js";
42
+ } from "../chunk-HZGKPWVA.js";
43
43
  import "../chunk-NTSZGBHZ.js";
44
+ import "../chunk-SJWIZT7B.js";
44
45
  import {
45
46
  CheckGlyph,
46
47
  ChevronDown,
@@ -51,7 +52,6 @@ import {
51
52
  PopoverSurface,
52
53
  usePopover
53
54
  } from "../chunk-GE7Y7ODP.js";
54
- import "../chunk-SJWIZT7B.js";
55
55
  import {
56
56
  ProviderLogo
57
57
  } from "../chunk-MLG6XKPV.js";
@@ -138,18 +138,27 @@ import {
138
138
  withoutRecordGridCreated,
139
139
  withoutRecordGridRemoved,
140
140
  withoutRecordGridUpdate
141
- } from "../chunk-XPP653RG.js";
141
+ } from "../chunk-JEM4BKR4.js";
142
142
  import {
143
143
  SessionHistoryPanel,
144
144
  formatSessionTimestamp,
145
145
  useInfiniteScroll,
146
146
  useSessionActions,
147
147
  useSessionHistory
148
- } from "../chunk-5S5ANZBS.js";
148
+ } from "../chunk-HZGKPWVA.js";
149
149
  import {
150
150
  MENTION_PILL_CLASS
151
151
  } from "../chunk-3HUFJ5LO.js";
152
152
  import "../chunk-FBVLEGEG.js";
153
+ import {
154
+ WorkspaceInitial,
155
+ WorkspaceSwitcher
156
+ } from "../chunk-GHOXLL2T.js";
157
+ import "../chunk-NTSZGBHZ.js";
158
+ import {
159
+ tabTerminalConnectionId,
160
+ useSandboxTerminalConnection
161
+ } from "../chunk-E4AY62T2.js";
153
162
  import {
154
163
  AGENT_PROFILE_EDITOR_SECTIONS,
155
164
  AgentProfileEditor,
@@ -183,8 +192,9 @@ import {
183
192
  preloadWhenIdle,
184
193
  useComposerAttachments,
185
194
  useDictation
186
- } from "../chunk-4DEI6QC5.js";
195
+ } from "../chunk-NNNAC3DV.js";
187
196
  import "../chunk-L7MB2LLM.js";
197
+ import "../chunk-SJWIZT7B.js";
188
198
  import {
189
199
  AgentSessionControls,
190
200
  AgentSettingsPopover,
@@ -195,11 +205,6 @@ import {
195
205
  isAcceptedFileType,
196
206
  renamePastedImages
197
207
  } from "../chunk-T6BAHD5S.js";
198
- import {
199
- WorkspaceInitial,
200
- WorkspaceSwitcher
201
- } from "../chunk-GHOXLL2T.js";
202
- import "../chunk-NTSZGBHZ.js";
203
208
  import "../chunk-WTHMHOU2.js";
204
209
  import {
205
210
  DEFAULT_EFFORT_LEVELS,
@@ -219,11 +224,6 @@ import {
219
224
  usePending,
220
225
  usePopover
221
226
  } from "../chunk-GE7Y7ODP.js";
222
- import {
223
- tabTerminalConnectionId,
224
- useSandboxTerminalConnection
225
- } from "../chunk-E4AY62T2.js";
226
- import "../chunk-SJWIZT7B.js";
227
227
  import {
228
228
  ProviderLogo
229
229
  } from "../chunk-MLG6XKPV.js";
@@ -243,7 +243,7 @@ import {
243
243
  isChatAttachmentPart,
244
244
  mentionInputToPart,
245
245
  mentionPartsFromMessageParts
246
- } from "../chunk-GU7OZFU7.js";
246
+ } from "../chunk-VXWEJ7F2.js";
247
247
  import "../chunk-ZVEEWGDK.js";
248
248
  import {
249
249
  DISPATCH_MAX_MEDIA_PARTS,
@@ -271,7 +271,8 @@ import {
271
271
  import "../chunk-TXD5HXLE.js";
272
272
  import {
273
273
  attachmentPartKey
274
- } from "../chunk-ZGUXI5SI.js";
274
+ } from "../chunk-XNKLQG26.js";
275
+ import "../chunk-LQYIBL3G.js";
275
276
  import {
276
277
  INTERACTION_CANCEL_EVENT,
277
278
  INTERACTION_EVENT,
@@ -297,7 +298,6 @@ import {
297
298
  questionInteractionContentSignature,
298
299
  stampInteractionAnswers
299
300
  } from "../chunk-6VQCFJWP.js";
300
- import "../chunk-LQYIBL3G.js";
301
301
  export {
302
302
  AGENT_PROFILE_EDITOR_SECTIONS,
303
303
  ATTACHMENT_ACCEPT,