@tangle-network/agent-app 0.60.114 → 0.60.116

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 (84) hide show
  1. package/dist/VaultPane-OWOPGPXP.js +7 -0
  2. package/dist/assistant/index.js +8 -8
  3. package/dist/chat-react/index.js +2 -2
  4. package/dist/chat-routes/index.js +2 -2
  5. package/dist/{chunk-Y4WLCFDZ.js → chunk-2FLSODOX.js} +6 -6
  6. package/dist/chunk-BTEVD7HG.js +198 -0
  7. package/dist/chunk-BTEVD7HG.js.map +1 -0
  8. package/dist/chunk-FVI2MHUL.js +1152 -0
  9. package/dist/chunk-FVI2MHUL.js.map +1 -0
  10. package/dist/{chunk-RQSYR4AV.js → chunk-GHUQ5HXU.js} +4 -4
  11. package/dist/{chunk-Q7M3GVLL.js → chunk-JCSHTJT6.js} +36 -2
  12. package/dist/chunk-JCSHTJT6.js.map +1 -0
  13. package/dist/{chunk-OGDEUCNW.js → chunk-JGLK5RDK.js} +176 -1
  14. package/dist/chunk-JGLK5RDK.js.map +1 -0
  15. package/dist/{chunk-AB63T2LM.js → chunk-KBJZMR4E.js} +8 -1
  16. package/dist/chunk-KBJZMR4E.js.map +1 -0
  17. package/dist/{chunk-RQSNTJTW.js → chunk-MO7PDQRZ.js} +526 -187
  18. package/dist/chunk-MO7PDQRZ.js.map +1 -0
  19. package/dist/{chunk-MEUNTJL5.js → chunk-N3CYCSKK.js} +6 -1
  20. package/dist/chunk-N3CYCSKK.js.map +1 -0
  21. package/dist/{chunk-56GPDCOJ.js → chunk-TSGWACTC.js} +5 -5
  22. package/dist/eval/index.d.ts +2 -0
  23. package/dist/eval/index.js +64 -0
  24. package/dist/eval/index.js.map +1 -1
  25. package/dist/eval/parity.d.ts +74 -0
  26. package/dist/journeys/cli.d.ts +2 -0
  27. package/dist/journeys/cli.js +165 -0
  28. package/dist/journeys/cli.js.map +1 -0
  29. package/dist/journeys/config.d.ts +96 -0
  30. package/dist/journeys/index.d.ts +18 -0
  31. package/dist/journeys/index.js +731 -0
  32. package/dist/journeys/index.js.map +1 -0
  33. package/dist/journeys/journey.d.ts +173 -0
  34. package/dist/journeys/page-reading.d.ts +42 -0
  35. package/dist/journeys/report.d.ts +51 -0
  36. package/dist/journeys/score.d.ts +115 -0
  37. package/dist/journeys/scrub.d.ts +21 -0
  38. package/dist/journeys/send.d.ts +46 -0
  39. package/dist/journeys/session.d.ts +27 -0
  40. package/dist/journeys/trace-zip.d.ts +28 -0
  41. package/dist/journeys/video.d.ts +53 -0
  42. package/dist/public-consultation/index.d.ts +1 -1
  43. package/dist/runtime/index.js +9 -3
  44. package/dist/runtime/index.js.map +1 -1
  45. package/dist/runtime/router-turn.d.ts +8 -1
  46. package/dist/runtime/router-turn.js +9 -3
  47. package/dist/runtime/turn-knowledge.d.ts +50 -0
  48. package/dist/sandbox/index.d.ts +2 -0
  49. package/dist/sandbox/index.js +13 -1
  50. package/dist/sandbox/sandbox-exec-tool.d.ts +68 -0
  51. package/dist/sandbox/sandbox-run-tool.d.ts +70 -0
  52. package/dist/studio-react/index.js +2 -2
  53. package/dist/teams/index.js +10 -6
  54. package/dist/teams/invitations-api.js +6 -3
  55. package/dist/teams/invitations-api.js.map +1 -1
  56. package/dist/teams/invitations.d.ts +4 -0
  57. package/dist/teams/members-api.js +2 -1
  58. package/dist/teams-react/components/InviteForm.d.ts +20 -0
  59. package/dist/teams-react/contracts.d.ts +2 -0
  60. package/dist/teams-react/index.js +196 -217
  61. package/dist/teams-react/index.js.map +1 -1
  62. package/dist/vault/VaultContentResults.d.ts +29 -0
  63. package/dist/vault/VaultHistoryPanel.d.ts +20 -0
  64. package/dist/vault/VaultPane.d.ts +3 -1
  65. package/dist/vault/contracts.d.ts +38 -0
  66. package/dist/vault/index.js +1 -1
  67. package/dist/vault/lazy.js +1 -1
  68. package/dist/web-react/index.js +22 -22
  69. package/dist/workspace-export/index.js +4 -193
  70. package/dist/workspace-export/index.js.map +1 -1
  71. package/dist/workspace-react/index.js +9 -7
  72. package/dist/workspace-react/index.js.map +1 -1
  73. package/dist/workspace-react/workspace-list.d.ts +7 -1
  74. package/package.json +8 -2
  75. package/dist/VaultPane-JUSNGOV7.js +0 -7
  76. package/dist/chunk-AB63T2LM.js.map +0 -1
  77. package/dist/chunk-MEUNTJL5.js.map +0 -1
  78. package/dist/chunk-OGDEUCNW.js.map +0 -1
  79. package/dist/chunk-Q7M3GVLL.js.map +0 -1
  80. package/dist/chunk-RQSNTJTW.js.map +0 -1
  81. /package/dist/{VaultPane-JUSNGOV7.js.map → VaultPane-OWOPGPXP.js.map} +0 -0
  82. /package/dist/{chunk-Y4WLCFDZ.js.map → chunk-2FLSODOX.js.map} +0 -0
  83. /package/dist/{chunk-RQSYR4AV.js.map → chunk-GHUQ5HXU.js.map} +0 -0
  84. /package/dist/{chunk-56GPDCOJ.js.map → chunk-TSGWACTC.js.map} +0 -0
@@ -0,0 +1,28 @@
1
+ interface ZipEntryInfo {
2
+ readonly name: string;
3
+ readonly method: number;
4
+ readonly crc32: number;
5
+ readonly compressedSize: number;
6
+ readonly uncompressedSize: number;
7
+ readonly localOffset: number;
8
+ readonly dosTime: number;
9
+ readonly dosDate: number;
10
+ }
11
+ /** Every entry in the central directory, sizes and offsets resolved through zip64 extras. */
12
+ export declare function readCentralDirectory(fd: number): ZipEntryInfo[];
13
+ /** One entry's stored bytes, still compressed. */
14
+ export declare function readRaw(fd: number, entry: ZipEntryInfo): Buffer;
15
+ /** One entry's content. */
16
+ export declare function inflateEntry(entry: ZipEntryInfo, raw: Buffer): Buffer;
17
+ interface ZipWriter {
18
+ /** Add an entry from its content (deflated here). */
19
+ add(name: string, content: Buffer, from?: Pick<ZipEntryInfo, 'dosTime' | 'dosDate'>): void;
20
+ /** Add an entry exactly as another archive stored it. */
21
+ copy(entry: ZipEntryInfo, raw: Buffer): void;
22
+ close(): void;
23
+ }
24
+ /** Write a zip to `path`, entries in the order added. `forceZip64` exercises the large-archive records in tests. */
25
+ export declare function createZipWriter(path: string, opts?: {
26
+ forceZip64?: boolean;
27
+ }): ZipWriter;
28
+ export {};
@@ -0,0 +1,53 @@
1
+ export interface Chapter {
2
+ /** Epoch ms. */
3
+ at: number;
4
+ caption: string;
5
+ /** Context label, or null for every context. */
6
+ label: string | null;
7
+ kind: 'step' | 'wait';
8
+ /** Epoch ms a wait ended. */
9
+ until?: number;
10
+ }
11
+ export interface Cue {
12
+ start: number;
13
+ end: number;
14
+ text: string;
15
+ }
16
+ export interface HighlightSegment {
17
+ /** Source range, seconds. */
18
+ a: number;
19
+ b: number;
20
+ /** Speed-up factor. */
21
+ k: number;
22
+ text: string;
23
+ }
24
+ export declare const MAX_HIGHLIGHTS_S = 178;
25
+ export declare function probeSeconds(file: string): number;
26
+ /** Chapters on the video's own clock; each caption holds until the next. */
27
+ export declare function chapterCues(chapters: readonly Chapter[], t0: number, duration: number): Cue[];
28
+ /**
29
+ * The highlights cut: which source ranges, at what speed, under which caption.
30
+ * A wait longer than 6 s plays in about 5 s; an idle stretch longer than 15 s
31
+ * plays in about 10 s; then everything scales to fit {@link MAX_HIGHLIGHTS_S}.
32
+ */
33
+ export declare function highlightPlan(chapters: readonly Chapter[], t0: number, duration: number): HighlightSegment[];
34
+ interface PostProcessInput {
35
+ webm: string;
36
+ /** Raw working folder on the host; keeps the webm and chapters for a rebuild. */
37
+ workDir: string;
38
+ videoDir: string;
39
+ label: string;
40
+ /** Epoch ms the recorded page was created. */
41
+ t0: number;
42
+ wallSeconds: number;
43
+ chapters: readonly Chapter[];
44
+ speedup2x: boolean;
45
+ }
46
+ export declare function postProcessVideo(o: PostProcessInput): string[];
47
+ /** Re-render from a raw folder after editing `<label>.chapters.json` by hand. */
48
+ export declare function rebuildVideo(rawLabelDir: string, videoDir: string, label: string, speedup2x: boolean): string[];
49
+ /** Seconds at which to grab frames: one per caption (1.5 s in), at most `max`, evenly spread. */
50
+ export declare function frameTimes(srt: string | null, times: readonly number[], max?: number): number[];
51
+ /** PNG frames of a video, named by label and timestamp, into `outDir`. */
52
+ export declare function extractFrames(video: string, srtFile: string | null, outDir: string, times: readonly number[], max?: number): string[];
53
+ export {};
@@ -121,9 +121,9 @@ export declare function createPublicConsultation(options: PublicConsultationOpti
121
121
  executionBudget?: ChatTurnExecutionLimits;
122
122
  maxOutputTokens?: number;
123
123
  }) => Promise<{
124
+ start?: undefined;
124
125
  status: 'unsupported';
125
126
  reason: string;
126
- start?: undefined;
127
127
  } | {
128
128
  reason?: undefined;
129
129
  status: 'prepared';
@@ -3,14 +3,17 @@ import {
3
3
  createRouterProtectedModelPort
4
4
  } from "../chunk-RN2N75EI.js";
5
5
  import {
6
+ budgetTurnKnowledge,
6
7
  composeRouterTurnPrompt,
7
8
  createOpenAICompatStreamTurn,
8
9
  routerFunctionName,
9
10
  runRouterTurn,
10
11
  runToolLoop,
11
12
  streamToolLoop,
12
- toLoopEvents
13
- } from "../chunk-Q7M3GVLL.js";
13
+ toLoopEvents,
14
+ turnKnowledgeInstructions,
15
+ workspaceKnowledgeForTurn
16
+ } from "../chunk-JCSHTJT6.js";
14
17
  import {
15
18
  DEFAULT_TANGLE_BILLING_ENFORCEMENT_ENV_VAR,
16
19
  DEFAULT_TANGLE_ROUTER_BASE_URL,
@@ -153,6 +156,7 @@ export {
153
156
  ProtectedModelSettlementError,
154
157
  TangleExecutionKeyError,
155
158
  __resetCatalogCache,
159
+ budgetTurnKnowledge,
156
160
  buildCatalog,
157
161
  catalogModelForId,
158
162
  composeRouterTurnPrompt,
@@ -181,6 +185,8 @@ export {
181
185
  streamToolLoop as streamAppToolLoop,
182
186
  tangleExecutionKeyHttpError,
183
187
  toLoopEvents,
184
- trimOrNull
188
+ trimOrNull,
189
+ turnKnowledgeInstructions,
190
+ workspaceKnowledgeForTurn
185
191
  };
186
192
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/runtime/certified-delivery.ts","../../src/runtime/surface-profile.ts"],"sourcesContent":["/**\n * Application profile composition using Runtime's certified-guidance source.\n *\n * The shell adapts the prompt source to the application's resolved profile;\n * Runtime owns pulling, cache lifetime, concurrent refresh and retained guidance.\n * Only prompt-compatible guidance is folded here. Tool definitions, execution\n * permissions, MCP servers and files are not installed from certified material.\n * The complete profile remains available through `current()` for inspection and\n * the product's separately authorized materialization path.\n */\nimport {\n createCertifiedPromptSource,\n type CertifiedProfile,\n type CertifiedPromptSourceOptions,\n} from '@tangle-network/agent-runtime/intelligence'\nimport type { ResolvedAgentProfile } from './agent'\n\n/** Pull coordinates, refresh cadence and timeout owned by the shared source. */\nexport type CertifiedDeliveryConfig = CertifiedPromptSourceOptions\n\n/** Adapt certified prompt guidance without granting execution authority. */\nexport interface CertifiedDelivery {\n /** Refresh on the source's cadence and compose the current prompt guidance.\n * Other resolved profile fields pass through unchanged. */\n composeProfile(base: ResolvedAgentProfile): Promise<ResolvedAgentProfile>\n /** Force a pull now, coalescing with an in-flight pull. Best-effort; not a\n * post-activation revision barrier or a permission-revocation protocol. */\n refresh(): Promise<void>\n /** Last successfully pulled profile, or null before a successful pull. */\n current(): CertifiedProfile | null\n}\n\nexport function createCertifiedDelivery(config: CertifiedDeliveryConfig): CertifiedDelivery {\n const source = createCertifiedPromptSource(config)\n return {\n async composeProfile(base) {\n return { ...base, systemPrompt: await source.compose(base.systemPrompt) }\n },\n refresh: () => source.refresh({ force: true }),\n current: source.current,\n }\n}\n","/**\n * Surface-scoped profile overlay — the seam letting any product page (a\n * sequence editor, a brief composer, a dataset view) add MCP servers, a prompt\n * addendum, and permission tightening to the workspace agent profile for turns\n * initiated FROM that surface, without the chat orchestrator knowing any\n * surface's specifics. The orchestrator resolves `(kind, ctx)` through a\n * registry the REQUEST HANDLER constructs per request (construction is a Map\n * build — cheap) and merges the result into the base profile it was about to\n * send to the sandbox. Per-request construction is the trust mechanism, not an\n * optimization target: each `build()` closes over server-trusted request state\n * (env bindings, secrets, the AUTHENTICATED user/workspace), which on Workers\n * exists only per request — a startup-built registry would force identity\n * through the untrusted client `ctx`.\n *\n * SECURITY INVARIANT: the surface `kind` and the ids inside `ctx` arrive on\n * the client request and are pure ROUTING data — never trusted content, never\n * identity. Identity comes from the closure (see above). The registered\n * `build()` runs server-side only: it validates the routing ids against the\n * product's access control, then mints its own URLs from server configuration\n * (`buildHttpMcpServer` in ../tools). A client can therefore never inject an\n * arbitrary MCP url, header, or credential into the agent profile: the\n * overlay's `mcp` values are typed as {@link SurfaceMcpServer} (= the\n * server-built `AppToolMcpServer` entry shape), and only build() constructs\n * them.\n *\n * The credential itself never appears in the overlay. Since the tagged-config\n * contract (`agent-interface` 0.38.0) the `Authorization` header is a\n * `secret-ref` naming a box-environment variable, which the sandbox resolves\n * privately; `build()` supplies that key NAME from server configuration and the\n * product writes the value through `SandboxRuntimeConfig.env` at creation or\n * refreshes it through `SandboxRuntimeConfig.runtimeEnv` before retained-box\n * bootstrap. The value remains workspace-scoped because every member and turn\n * shares the box; runtime renewal does not create a per-user secret channel.\n */\n\nimport type { AppToolMcpServer } from '../tools/mcp'\n\n/** Sandbox permission posture values, ranked deny > ask > allow for merging. */\nexport type SurfacePermissionValue = 'allow' | 'ask' | 'deny'\n\n/** The only MCP entry shape an overlay may carry: the server-built bridge\n * entry from ../tools/mcp (transport, url, headers, and capability token all\n * assembled server-side). The alias exists so overlay authors reach for the\n * builders in ../tools rather than hand-rolling `{ url: ctx.url }` shapes\n * that would let request data become a dialable endpoint. */\nexport type SurfaceMcpServer = AppToolMcpServer\n\n/** What one surface contributes to the agent profile for a single turn. */\nexport interface SurfaceOverlay {\n /** MCP servers to mount for this turn, keyed by tool-routing name. Names\n * must not collide with the base profile's — see {@link mergeSurfaceOverlay}. */\n mcp?: Record<string, SurfaceMcpServer>\n /** Appended to the base system-prompt addendum with a blank-line separator. */\n promptAddendum?: string\n /** Per-key posture the surface wants for its turns. Merging is monotone\n * fail-closed: the stricter of base/overlay wins, so a surface can tighten\n * the workspace posture but never relax it. */\n permissions?: Record<string, SurfacePermissionValue>\n}\n\n/**\n * One registered surface kind. `TCtx` is the shape build() expects — a CLAIM\n * about the client payload, not a guarantee: the registry hands build() the\n * request's `ctx` unvalidated, so build() must treat every field as an\n * untrusted id (resolve it through access control that throws on a bad or\n * foreign id) before minting anything from it.\n */\nexport interface SurfaceKindDefinition<TCtx> {\n kind: string\n build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>\n}\n\n/** The variance-erased form a registry accepts (`build` is contravariant in\n * `TCtx`, so every concrete definition is assignable to this). */\nexport type AnySurfaceKind = SurfaceKindDefinition<never>\n\n/**\n * Declare one surface kind. The `kind` string is the client-visible routing\n * key (e.g. `'sequences'`); `build` is the server-side factory that turns a\n * validated ctx into the overlay for one turn.\n */\nexport function defineSurfaceKind<TCtx>(opts: {\n kind: string\n build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>\n}): SurfaceKindDefinition<TCtx> {\n if (typeof opts.kind !== 'string' || opts.kind.length === 0 || /\\s/.test(opts.kind)) {\n throw new Error(`surface kind must be a non-empty string without whitespace (got ${JSON.stringify(opts.kind)})`)\n }\n if (typeof opts.build !== 'function') {\n throw new Error(`surface kind '${opts.kind}' requires a build function`)\n }\n return { kind: opts.kind, build: opts.build }\n}\n\n/** Resolve and build the overlay for a given surface kind within a turn context */\nexport interface SurfaceRegistry {\n /** Build the overlay for one turn. Throws on an unknown kind — an unknown\n * surface is a routing bug (client and server registries drifted), and\n * silently returning an empty overlay would strip the surface's tools from\n * the turn with no signal anywhere. Build errors propagate unwrapped. */\n resolve(kind: string, ctx: unknown): Promise<SurfaceOverlay>\n}\n\n/**\n * Assemble the product's surface registry from its registered kinds. Duplicate\n * kinds throw at construction: two builders behind one routing key would make\n * the mounted toolset depend on registration order.\n */\nexport function createSurfaceRegistry(kinds: readonly AnySurfaceKind[]): SurfaceRegistry {\n const byKind = new Map<string, AnySurfaceKind>()\n for (const definition of kinds) {\n if (byKind.has(definition.kind)) {\n throw new Error(`duplicate surface kind '${definition.kind}' — each kind must be registered exactly once`)\n }\n byKind.set(definition.kind, definition)\n }\n\n return {\n async resolve(kind, ctx) {\n const definition = byKind.get(kind)\n if (!definition) {\n const known = [...byKind.keys()].join(', ') || '(none)'\n throw new Error(\n `unknown surface kind '${kind}' — registered kinds: ${known}. ` +\n 'An unknown surface is a routing bug: register the kind via defineSurfaceKind before clients can reference it.',\n )\n }\n // The trust boundary where static ctx typing ends: the request payload is\n // handed to build() as-is, and build() validates it (see SurfaceKindDefinition).\n const overlay = await definition.build(ctx as never)\n assertSurfaceOverlay(overlay, `surface kind '${kind}'`)\n return overlay\n },\n }\n}\n\n/** Base-profile slice the merge reads/writes. Real callers pass their full\n * profile object; every field outside this slice passes through untouched. */\nexport interface SurfaceMergeBase {\n mcp?: Record<string, unknown>\n systemPromptAddendum?: string\n permissions?: Record<string, SurfacePermissionValue>\n}\n\nconst PERMISSION_SEVERITY: Record<SurfacePermissionValue, number> = { allow: 0, ask: 1, deny: 2 }\n\n/**\n * Merge one surface overlay into a base profile, returning a new object\n * (the base is never mutated; untouched nested records are shared by\n * reference).\n *\n * - `mcp`: overlay servers are added under their own names. A name already\n * present on the base THROWS — a collision is two servers claiming one\n * routing name, and renaming either silently would corrupt tool routing for\n * whichever caller expected the original binding.\n * - `systemPromptAddendum`: the overlay's `promptAddendum` appends after a\n * blank-line separator (no separator when the base has no addendum).\n * - `permissions`: per key the STRICTER value wins (deny > ask > allow). A\n * surface can tighten the base posture for its turns; a base 'deny' survives\n * any overlay.\n */\nexport function mergeSurfaceOverlay<TBase extends SurfaceMergeBase>(\n base: TBase,\n overlay: SurfaceOverlay,\n): TBase & SurfaceMergeBase {\n assertSurfaceOverlay(overlay, 'surface overlay')\n const merged: SurfaceMergeBase = { ...base }\n\n if (overlay.mcp && Object.keys(overlay.mcp).length > 0) {\n const baseMcp = base.mcp ?? {}\n const collisions = Object.keys(overlay.mcp).filter((name) => name in baseMcp)\n if (collisions.length > 0) {\n throw new Error(\n `surface overlay MCP name collision: ${collisions.map((n) => `'${n}'`).join(', ')} already exist on the base profile. ` +\n 'Two servers cannot claim one name — give the surface server a distinct name.',\n )\n }\n merged.mcp = { ...baseMcp, ...overlay.mcp }\n }\n\n if (overlay.promptAddendum !== undefined) {\n merged.systemPromptAddendum = base.systemPromptAddendum\n ? `${base.systemPromptAddendum}\\n\\n${overlay.promptAddendum}`\n : overlay.promptAddendum\n }\n\n if (overlay.permissions && Object.keys(overlay.permissions).length > 0) {\n const permissions: Record<string, SurfacePermissionValue> = { ...(base.permissions ?? {}) }\n for (const [key, value] of Object.entries(overlay.permissions)) {\n const existing = permissions[key]\n permissions[key] =\n existing === undefined || PERMISSION_SEVERITY[value] > PERMISSION_SEVERITY[existing] ? value : existing\n }\n merged.permissions = permissions\n }\n\n // merged began as a shallow copy of base; only the three slice fields were\n // replaced, so the intersection type is the true shape.\n return merged as TBase & SurfaceMergeBase\n}\n\n/** Reject overlays a build() (or hand-rolled caller) malformed, with the exact\n * field named: a relative MCP url, a blank addendum, or an off-vocabulary\n * permission would otherwise surface only as an opaque sandbox failure. */\nfunction assertSurfaceOverlay(overlay: SurfaceOverlay, label: string): void {\n if (overlay.promptAddendum !== undefined) {\n if (typeof overlay.promptAddendum !== 'string' || overlay.promptAddendum.trim().length === 0) {\n throw new Error(`${label}: promptAddendum must be a non-blank string when provided`)\n }\n }\n if (overlay.mcp !== undefined) {\n for (const [name, server] of Object.entries(overlay.mcp)) {\n if (name.trim().length === 0) throw new Error(`${label}: MCP server names must be non-empty`)\n if (server.transport !== 'http') {\n throw new Error(`${label}: MCP server '${name}' must use transport 'http' (got ${JSON.stringify((server as { transport?: unknown }).transport)})`)\n }\n let parsed: URL\n try {\n parsed = new URL(server.url)\n } catch {\n throw new Error(`${label}: MCP server '${name}' url must be an absolute URL (got ${JSON.stringify(server.url)})`)\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error(`${label}: MCP server '${name}' url must be http(s) (got ${JSON.stringify(server.url)})`)\n }\n }\n }\n if (overlay.permissions !== undefined) {\n for (const [key, value] of Object.entries(overlay.permissions)) {\n if (!(value in PERMISSION_SEVERITY)) {\n throw new Error(`${label}: permission '${key}' must be 'allow' | 'ask' | 'deny' (got ${JSON.stringify(value)})`)\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA;AAAA,EACE;AAAA,OAGK;AAkBA,SAAS,wBAAwB,QAAoD;AAC1F,QAAM,SAAS,4BAA4B,MAAM;AACjD,SAAO;AAAA,IACL,MAAM,eAAe,MAAM;AACzB,aAAO,EAAE,GAAG,MAAM,cAAc,MAAM,OAAO,QAAQ,KAAK,YAAY,EAAE;AAAA,IAC1E;AAAA,IACA,SAAS,MAAM,OAAO,QAAQ,EAAE,OAAO,KAAK,CAAC;AAAA,IAC7C,SAAS,OAAO;AAAA,EAClB;AACF;;;ACwCO,SAAS,kBAAwB,MAGR;AAC9B,MAAI,OAAO,KAAK,SAAS,YAAY,KAAK,KAAK,WAAW,KAAK,KAAK,KAAK,KAAK,IAAI,GAAG;AACnF,UAAM,IAAI,MAAM,mEAAmE,KAAK,UAAU,KAAK,IAAI,CAAC,GAAG;AAAA,EACjH;AACA,MAAI,OAAO,KAAK,UAAU,YAAY;AACpC,UAAM,IAAI,MAAM,iBAAiB,KAAK,IAAI,6BAA6B;AAAA,EACzE;AACA,SAAO,EAAE,MAAM,KAAK,MAAM,OAAO,KAAK,MAAM;AAC9C;AAgBO,SAAS,sBAAsB,OAAmD;AACvF,QAAM,SAAS,oBAAI,IAA4B;AAC/C,aAAW,cAAc,OAAO;AAC9B,QAAI,OAAO,IAAI,WAAW,IAAI,GAAG;AAC/B,YAAM,IAAI,MAAM,2BAA2B,WAAW,IAAI,oDAA+C;AAAA,IAC3G;AACA,WAAO,IAAI,WAAW,MAAM,UAAU;AAAA,EACxC;AAEA,SAAO;AAAA,IACL,MAAM,QAAQ,MAAM,KAAK;AACvB,YAAM,aAAa,OAAO,IAAI,IAAI;AAClC,UAAI,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AG,2CAA2C,KAAK,UAAU,KAAK,CAAC,GAAG;AAAA,MACjH;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/runtime/certified-delivery.ts","../../src/runtime/surface-profile.ts"],"sourcesContent":["/**\n * Application profile composition using Runtime's certified-guidance source.\n *\n * The shell adapts the prompt source to the application's resolved profile;\n * Runtime owns pulling, cache lifetime, concurrent refresh and retained guidance.\n * Only prompt-compatible guidance is folded here. Tool definitions, execution\n * permissions, MCP servers and files are not installed from certified material.\n * The complete profile remains available through `current()` for inspection and\n * the product's separately authorized materialization path.\n */\nimport {\n createCertifiedPromptSource,\n type CertifiedProfile,\n type CertifiedPromptSourceOptions,\n} from '@tangle-network/agent-runtime/intelligence'\nimport type { ResolvedAgentProfile } from './agent'\n\n/** Pull coordinates, refresh cadence and timeout owned by the shared source. */\nexport type CertifiedDeliveryConfig = CertifiedPromptSourceOptions\n\n/** Adapt certified prompt guidance without granting execution authority. */\nexport interface CertifiedDelivery {\n /** Refresh on the source's cadence and compose the current prompt guidance.\n * Other resolved profile fields pass through unchanged. */\n composeProfile(base: ResolvedAgentProfile): Promise<ResolvedAgentProfile>\n /** Force a pull now, coalescing with an in-flight pull. Best-effort; not a\n * post-activation revision barrier or a permission-revocation protocol. */\n refresh(): Promise<void>\n /** Last successfully pulled profile, or null before a successful pull. */\n current(): CertifiedProfile | null\n}\n\nexport function createCertifiedDelivery(config: CertifiedDeliveryConfig): CertifiedDelivery {\n const source = createCertifiedPromptSource(config)\n return {\n async composeProfile(base) {\n return { ...base, systemPrompt: await source.compose(base.systemPrompt) }\n },\n refresh: () => source.refresh({ force: true }),\n current: source.current,\n }\n}\n","/**\n * Surface-scoped profile overlay — the seam letting any product page (a\n * sequence editor, a brief composer, a dataset view) add MCP servers, a prompt\n * addendum, and permission tightening to the workspace agent profile for turns\n * initiated FROM that surface, without the chat orchestrator knowing any\n * surface's specifics. The orchestrator resolves `(kind, ctx)` through a\n * registry the REQUEST HANDLER constructs per request (construction is a Map\n * build — cheap) and merges the result into the base profile it was about to\n * send to the sandbox. Per-request construction is the trust mechanism, not an\n * optimization target: each `build()` closes over server-trusted request state\n * (env bindings, secrets, the AUTHENTICATED user/workspace), which on Workers\n * exists only per request — a startup-built registry would force identity\n * through the untrusted client `ctx`.\n *\n * SECURITY INVARIANT: the surface `kind` and the ids inside `ctx` arrive on\n * the client request and are pure ROUTING data — never trusted content, never\n * identity. Identity comes from the closure (see above). The registered\n * `build()` runs server-side only: it validates the routing ids against the\n * product's access control, then mints its own URLs from server configuration\n * (`buildHttpMcpServer` in ../tools). A client can therefore never inject an\n * arbitrary MCP url, header, or credential into the agent profile: the\n * overlay's `mcp` values are typed as {@link SurfaceMcpServer} (= the\n * server-built `AppToolMcpServer` entry shape), and only build() constructs\n * them.\n *\n * The credential itself never appears in the overlay. Since the tagged-config\n * contract (`agent-interface` 0.38.0) the `Authorization` header is a\n * `secret-ref` naming a box-environment variable, which the sandbox resolves\n * privately; `build()` supplies that key NAME from server configuration and the\n * product writes the value through `SandboxRuntimeConfig.env` at creation or\n * refreshes it through `SandboxRuntimeConfig.runtimeEnv` before retained-box\n * bootstrap. The value remains workspace-scoped because every member and turn\n * shares the box; runtime renewal does not create a per-user secret channel.\n */\n\nimport type { AppToolMcpServer } from '../tools/mcp'\n\n/** Sandbox permission posture values, ranked deny > ask > allow for merging. */\nexport type SurfacePermissionValue = 'allow' | 'ask' | 'deny'\n\n/** The only MCP entry shape an overlay may carry: the server-built bridge\n * entry from ../tools/mcp (transport, url, headers, and capability token all\n * assembled server-side). The alias exists so overlay authors reach for the\n * builders in ../tools rather than hand-rolling `{ url: ctx.url }` shapes\n * that would let request data become a dialable endpoint. */\nexport type SurfaceMcpServer = AppToolMcpServer\n\n/** What one surface contributes to the agent profile for a single turn. */\nexport interface SurfaceOverlay {\n /** MCP servers to mount for this turn, keyed by tool-routing name. Names\n * must not collide with the base profile's — see {@link mergeSurfaceOverlay}. */\n mcp?: Record<string, SurfaceMcpServer>\n /** Appended to the base system-prompt addendum with a blank-line separator. */\n promptAddendum?: string\n /** Per-key posture the surface wants for its turns. Merging is monotone\n * fail-closed: the stricter of base/overlay wins, so a surface can tighten\n * the workspace posture but never relax it. */\n permissions?: Record<string, SurfacePermissionValue>\n}\n\n/**\n * One registered surface kind. `TCtx` is the shape build() expects — a CLAIM\n * about the client payload, not a guarantee: the registry hands build() the\n * request's `ctx` unvalidated, so build() must treat every field as an\n * untrusted id (resolve it through access control that throws on a bad or\n * foreign id) before minting anything from it.\n */\nexport interface SurfaceKindDefinition<TCtx> {\n kind: string\n build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>\n}\n\n/** The variance-erased form a registry accepts (`build` is contravariant in\n * `TCtx`, so every concrete definition is assignable to this). */\nexport type AnySurfaceKind = SurfaceKindDefinition<never>\n\n/**\n * Declare one surface kind. The `kind` string is the client-visible routing\n * key (e.g. `'sequences'`); `build` is the server-side factory that turns a\n * validated ctx into the overlay for one turn.\n */\nexport function defineSurfaceKind<TCtx>(opts: {\n kind: string\n build: (ctx: TCtx) => SurfaceOverlay | Promise<SurfaceOverlay>\n}): SurfaceKindDefinition<TCtx> {\n if (typeof opts.kind !== 'string' || opts.kind.length === 0 || /\\s/.test(opts.kind)) {\n throw new Error(`surface kind must be a non-empty string without whitespace (got ${JSON.stringify(opts.kind)})`)\n }\n if (typeof opts.build !== 'function') {\n throw new Error(`surface kind '${opts.kind}' requires a build function`)\n }\n return { kind: opts.kind, build: opts.build }\n}\n\n/** Resolve and build the overlay for a given surface kind within a turn context */\nexport interface SurfaceRegistry {\n /** Build the overlay for one turn. Throws on an unknown kind — an unknown\n * surface is a routing bug (client and server registries drifted), and\n * silently returning an empty overlay would strip the surface's tools from\n * the turn with no signal anywhere. Build errors propagate unwrapped. */\n resolve(kind: string, ctx: unknown): Promise<SurfaceOverlay>\n}\n\n/**\n * Assemble the product's surface registry from its registered kinds. Duplicate\n * kinds throw at construction: two builders behind one routing key would make\n * the mounted toolset depend on registration order.\n */\nexport function createSurfaceRegistry(kinds: readonly AnySurfaceKind[]): SurfaceRegistry {\n const byKind = new Map<string, AnySurfaceKind>()\n for (const definition of kinds) {\n if (byKind.has(definition.kind)) {\n throw new Error(`duplicate surface kind '${definition.kind}' — each kind must be registered exactly once`)\n }\n byKind.set(definition.kind, definition)\n }\n\n return {\n async resolve(kind, ctx) {\n const definition = byKind.get(kind)\n if (!definition) {\n const known = [...byKind.keys()].join(', ') || '(none)'\n throw new Error(\n `unknown surface kind '${kind}' — registered kinds: ${known}. ` +\n 'An unknown surface is a routing bug: register the kind via defineSurfaceKind before clients can reference it.',\n )\n }\n // The trust boundary where static ctx typing ends: the request payload is\n // handed to build() as-is, and build() validates it (see SurfaceKindDefinition).\n const overlay = await definition.build(ctx as never)\n assertSurfaceOverlay(overlay, `surface kind '${kind}'`)\n return overlay\n },\n }\n}\n\n/** Base-profile slice the merge reads/writes. Real callers pass their full\n * profile object; every field outside this slice passes through untouched. */\nexport interface SurfaceMergeBase {\n mcp?: Record<string, unknown>\n systemPromptAddendum?: string\n permissions?: Record<string, SurfacePermissionValue>\n}\n\nconst PERMISSION_SEVERITY: Record<SurfacePermissionValue, number> = { allow: 0, ask: 1, deny: 2 }\n\n/**\n * Merge one surface overlay into a base profile, returning a new object\n * (the base is never mutated; untouched nested records are shared by\n * reference).\n *\n * - `mcp`: overlay servers are added under their own names. A name already\n * present on the base THROWS — a collision is two servers claiming one\n * routing name, and renaming either silently would corrupt tool routing for\n * whichever caller expected the original binding.\n * - `systemPromptAddendum`: the overlay's `promptAddendum` appends after a\n * blank-line separator (no separator when the base has no addendum).\n * - `permissions`: per key the STRICTER value wins (deny > ask > allow). A\n * surface can tighten the base posture for its turns; a base 'deny' survives\n * any overlay.\n */\nexport function mergeSurfaceOverlay<TBase extends SurfaceMergeBase>(\n base: TBase,\n overlay: SurfaceOverlay,\n): TBase & SurfaceMergeBase {\n assertSurfaceOverlay(overlay, 'surface overlay')\n const merged: SurfaceMergeBase = { ...base }\n\n if (overlay.mcp && Object.keys(overlay.mcp).length > 0) {\n const baseMcp = base.mcp ?? {}\n const collisions = Object.keys(overlay.mcp).filter((name) => name in baseMcp)\n if (collisions.length > 0) {\n throw new Error(\n `surface overlay MCP name collision: ${collisions.map((n) => `'${n}'`).join(', ')} already exist on the base profile. ` +\n 'Two servers cannot claim one name — give the surface server a distinct name.',\n )\n }\n merged.mcp = { ...baseMcp, ...overlay.mcp }\n }\n\n if (overlay.promptAddendum !== undefined) {\n merged.systemPromptAddendum = base.systemPromptAddendum\n ? `${base.systemPromptAddendum}\\n\\n${overlay.promptAddendum}`\n : overlay.promptAddendum\n }\n\n if (overlay.permissions && Object.keys(overlay.permissions).length > 0) {\n const permissions: Record<string, SurfacePermissionValue> = { ...(base.permissions ?? {}) }\n for (const [key, value] of Object.entries(overlay.permissions)) {\n const existing = permissions[key]\n permissions[key] =\n existing === undefined || PERMISSION_SEVERITY[value] > PERMISSION_SEVERITY[existing] ? value : existing\n }\n merged.permissions = permissions\n }\n\n // merged began as a shallow copy of base; only the three slice fields were\n // replaced, so the intersection type is the true shape.\n return merged as TBase & SurfaceMergeBase\n}\n\n/** Reject overlays a build() (or hand-rolled caller) malformed, with the exact\n * field named: a relative MCP url, a blank addendum, or an off-vocabulary\n * permission would otherwise surface only as an opaque sandbox failure. */\nfunction assertSurfaceOverlay(overlay: SurfaceOverlay, label: string): void {\n if (overlay.promptAddendum !== undefined) {\n if (typeof overlay.promptAddendum !== 'string' || overlay.promptAddendum.trim().length === 0) {\n throw new Error(`${label}: promptAddendum must be a non-blank string when provided`)\n }\n }\n if (overlay.mcp !== undefined) {\n for (const [name, server] of Object.entries(overlay.mcp)) {\n if (name.trim().length === 0) throw new Error(`${label}: MCP server names must be non-empty`)\n if (server.transport !== 'http') {\n throw new Error(`${label}: MCP server '${name}' must use transport 'http' (got ${JSON.stringify((server as { transport?: unknown }).transport)})`)\n }\n let parsed: URL\n try {\n parsed = new URL(server.url)\n } catch {\n throw new Error(`${label}: MCP server '${name}' url must be an absolute URL (got ${JSON.stringify(server.url)})`)\n }\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {\n throw new Error(`${label}: MCP server '${name}' url must be http(s) (got ${JSON.stringify(server.url)})`)\n }\n }\n }\n if (overlay.permissions !== undefined) {\n for (const [key, value] of Object.entries(overlay.permissions)) {\n if (!(value in PERMISSION_SEVERITY)) {\n throw new Error(`${label}: permission '${key}' must be 'allow' | 'ask' | 'deny' (got ${JSON.stringify(value)})`)\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA;AAAA,EACE;AAAA,OAGK;AAkBA,SAAS,wBAAwB,QAAoD;AAC1F,QAAM,SAAS,4BAA4B,MAAM;AACjD,SAAO;AAAA,IACL,MAAM,eAAe,MAAM;AACzB,aAAO,EAAE,GAAG,MAAM,cAAc,MAAM,OAAO,QAAQ,KAAK,YAAY,EAAE;AAAA,IAC1E;AAAA,IACA,SAAS,MAAM,OAAO,QAAQ,EAAE,OAAO,KAAK,CAAC;AAAA,IAC7C,SAAS,OAAO;AAAA,EAClB;AACF;;;ACwCO,SAAS,kBAAwB,MAGR;AAC9B,MAAI,OAAO,KAAK,SAAS,YAAY,KAAK,KAAK,WAAW,KAAK,KAAK,KAAK,KAAK,IAAI,GAAG;AACnF,UAAM,IAAI,MAAM,mEAAmE,KAAK,UAAU,KAAK,IAAI,CAAC,GAAG;AAAA,EACjH;AACA,MAAI,OAAO,KAAK,UAAU,YAAY;AACpC,UAAM,IAAI,MAAM,iBAAiB,KAAK,IAAI,6BAA6B;AAAA,EACzE;AACA,SAAO,EAAE,MAAM,KAAK,MAAM,OAAO,KAAK,MAAM;AAC9C;AAgBO,SAAS,sBAAsB,OAAmD;AACvF,QAAM,SAAS,oBAAI,IAA4B;AAC/C,aAAW,cAAc,OAAO;AAC9B,QAAI,OAAO,IAAI,WAAW,IAAI,GAAG;AAC/B,YAAM,IAAI,MAAM,2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F;AACA,MAAI,QAAQ,gBAAgB,QAAW;AACrC,eAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,QAAQ,WAAW,GAAG;AAC9D,UAAI,EAAE,SAAS,sBAAsB;AACnC,cAAM,IAAI,MAAM,GAAG,KAAK,iBAAiB,GAAG,2CAA2C,KAAK,UAAU,KAAK,CAAC,GAAG;AAAA,MACjH;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -15,6 +15,8 @@
15
15
  * automatic repeat is one model call that failed before any word or tool.
16
16
  */
17
17
  import { type LoopMessage } from './loop';
18
+ import { type TurnKnowledgeFile } from './turn-knowledge';
19
+ export { budgetTurnKnowledge, turnKnowledgeInstructions, workspaceKnowledgeForTurn, type TurnKnowledgeBudget, type TurnKnowledgeFile } from './turn-knowledge';
18
20
  /** A tool the turn may call. Structurally an `McpToolDefinition` whose env is already bound. */
19
21
  export interface RouterTurnTool {
20
22
  name: string;
@@ -120,7 +122,7 @@ export interface RouterTurnOptions {
120
122
  export declare function routerFunctionName(name: string): string;
121
123
  /**
122
124
  * The lean system prompt for a Router turn: the profile's system prompt and
123
- * instructions, then caller context, with tool names rewritten to the function
125
+ * instructions, the turn's knowledge files, then caller context, with tool names rewritten to the function
124
126
  * names the model actually calls.
125
127
  */
126
128
  export declare function composeRouterTurnPrompt(profile: {
@@ -131,5 +133,10 @@ export declare function composeRouterTurnPrompt(profile: {
131
133
  }, options?: {
132
134
  context?: readonly string[];
133
135
  toolNames?: readonly string[];
136
+ /** Knowledge files every turn carries; see {@link turnKnowledgeInstructions}. */
137
+ knowledge?: {
138
+ files: readonly TurnKnowledgeFile[];
139
+ readTool?: string;
140
+ };
134
141
  }): string;
135
142
  export declare function runRouterTurn(options: RouterTurnOptions): Promise<RouterTurnOutcome>;
@@ -1,13 +1,19 @@
1
1
  import {
2
+ budgetTurnKnowledge,
2
3
  composeRouterTurnPrompt,
3
4
  routerFunctionName,
4
- runRouterTurn
5
- } from "../chunk-Q7M3GVLL.js";
5
+ runRouterTurn,
6
+ turnKnowledgeInstructions,
7
+ workspaceKnowledgeForTurn
8
+ } from "../chunk-JCSHTJT6.js";
6
9
  import "../chunk-D6UJEOZQ.js";
7
10
  import "../chunk-7YA4QNTU.js";
8
11
  export {
12
+ budgetTurnKnowledge,
9
13
  composeRouterTurnPrompt,
10
14
  routerFunctionName,
11
- runRouterTurn
15
+ runRouterTurn,
16
+ turnKnowledgeInstructions,
17
+ workspaceKnowledgeForTurn
12
18
  };
13
19
  //# sourceMappingURL=router-turn.js.map
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Knowledge in every turn: the index of an app's knowledge files, the full
3
+ * text of the small ones, and the rule that keeps answers on them.
4
+ *
5
+ * Measured on Hospitality production (2026-10-11): a Router turn that had to
6
+ * discover files through list/read tools answered 17/17 correctly but needed
7
+ * 3 tool calls (first words 12-17 s), and a turn that skipped the tools
8
+ * answered from model defaults ("checkout 11:00" when the file said 12 pm).
9
+ * Putting the text in the prompt removes both failure modes.
10
+ */
11
+ /** The fields read from an agent-runtime workspace-store entry; structural so older runtimes still type-check. */
12
+ interface KnowledgeEntry {
13
+ path: string;
14
+ kind: string;
15
+ content?: string;
16
+ bytes?: {
17
+ size: number;
18
+ };
19
+ }
20
+ /** One knowledge file a turn carries; `text` is null when it is too large or not readable here. */
21
+ export interface TurnKnowledgeFile {
22
+ path: string;
23
+ size: number;
24
+ text: string | null;
25
+ }
26
+ export interface TurnKnowledgeBudget {
27
+ /** Files at most this many bytes have their text included. Default 8 000. */
28
+ fileBytes?: number;
29
+ /** Total text bytes across files. Default 16 000. */
30
+ textBytes?: number;
31
+ /** Most files listed. Default 60. */
32
+ maxFiles?: number;
33
+ }
34
+ /** Apply the byte budget in path order: small files keep their text until the total is spent. */
35
+ export declare function budgetTurnKnowledge(files: readonly TurnKnowledgeFile[], budget?: TurnKnowledgeBudget): TurnKnowledgeFile[];
36
+ /**
37
+ * The prompt lines for a turn's knowledge. `readTool` names the tool that
38
+ * opens a listed file whose text is not shown; without one, such a file is
39
+ * listed by name only.
40
+ */
41
+ export declare function turnKnowledgeInstructions(files: readonly TurnKnowledgeFile[], options?: {
42
+ readTool?: string;
43
+ }): string[];
44
+ /** A workspace store's knowledge files (kind `file` under `prefix`) as turn knowledge, within the budget. */
45
+ export declare function workspaceKnowledgeForTurn(store: {
46
+ list(workspaceId: string, prefix: string): Promise<readonly KnowledgeEntry[]>;
47
+ }, workspaceId: string, options?: TurnKnowledgeBudget & {
48
+ prefix?: string;
49
+ }): Promise<TurnKnowledgeFile[]>;
50
+ export {};
@@ -874,6 +874,8 @@ export declare function detectInteractiveQuestion(event: unknown): string | null
874
874
  export * from './workspace-sandbox-manager';
875
875
  export * from './terminal-connection';
876
876
  export * from './prewarm';
877
+ export * from './sandbox-run-tool';
878
+ export * from './sandbox-exec-tool';
877
879
  export * from './prewarm-claim-d1';
878
880
  export * from './prewarm-route';
879
881
  export * from './foreground-single-flight';
@@ -12,11 +12,14 @@ import {
12
12
  PROVISION_PAYLOAD_MAX_BYTES,
13
13
  PYPI_EGRESS_DOMAINS,
14
14
  SANDBOX_DISPATCH_TRANSIENT_DEADLINE_MS,
15
+ SANDBOX_EXEC_DESCRIPTION,
16
+ SANDBOX_RUN_DESCRIPTION,
15
17
  SandboxEgressPolicyMismatchError,
16
18
  SandboxFilesystemNotReadyError,
17
19
  SandboxModelResolutionError,
18
20
  SandboxProvisioningFailedElsewhereError,
19
21
  SandboxRecoveryFailedError,
22
+ SandboxRunError,
20
23
  SandboxRuntimeAuthRefreshError,
21
24
  WARM_LEASE_DECLINED_UNTIL_DDL,
22
25
  WARM_LEASE_PENDING_DDL,
@@ -40,7 +43,9 @@ import {
40
43
  createD1PrewarmClaimStore,
41
44
  createD1WarmLeaseStore,
42
45
  createEscalationSpeculator,
46
+ createSandboxExecTool,
43
47
  createSandboxPrewarmer,
48
+ createSandboxRunTool,
44
49
  createSandboxTerminalConnectionRoute,
45
50
  createWarmLeases,
46
51
  createWorkspacePrewarmRoute,
@@ -74,6 +79,7 @@ import {
74
79
  runSandboxPrompt,
75
80
  runSandboxToolPathSetup,
76
81
  sandboxPrewarmClaimKey,
82
+ sandboxPromptRunner,
77
83
  sandboxToolBinDir,
78
84
  sandboxToolPath,
79
85
  sandboxToolRootDir,
@@ -90,7 +96,7 @@ import {
90
96
  warmBinOf,
91
97
  warmWeekdayOf,
92
98
  writeProfileFilesToBox
93
- } from "../chunk-OGDEUCNW.js";
99
+ } from "../chunk-JGLK5RDK.js";
94
100
  import {
95
101
  EGRESS_PROXY_RECOVERY_PHASE,
96
102
  EGRESS_PROXY_RECOVERY_REQUIRED,
@@ -156,12 +162,15 @@ export {
156
162
  PYPI_EGRESS_DOMAINS,
157
163
  SANDBOX_BACKING_CONTAINER_MISSING_CODE,
158
164
  SANDBOX_DISPATCH_TRANSIENT_DEADLINE_MS,
165
+ SANDBOX_EXEC_DESCRIPTION,
166
+ SANDBOX_RUN_DESCRIPTION,
159
167
  SANDBOX_TRANSIENT_DEADLINE_MS,
160
168
  SandboxEgressPolicyMismatchError,
161
169
  SandboxFilesystemNotReadyError,
162
170
  SandboxModelResolutionError,
163
171
  SandboxProvisioningFailedElsewhereError,
164
172
  SandboxRecoveryFailedError,
173
+ SandboxRunError,
165
174
  SandboxRuntimeAuthRefreshError,
166
175
  SandboxTransientDeadlineError,
167
176
  WARM_LEASE_DECLINED_UNTIL_DDL,
@@ -195,7 +204,9 @@ export {
195
204
  createD1PrewarmClaimStore,
196
205
  createD1WarmLeaseStore,
197
206
  createEscalationSpeculator,
207
+ createSandboxExecTool,
198
208
  createSandboxPrewarmer,
209
+ createSandboxRunTool,
199
210
  createSandboxTerminalConnectionRoute,
200
211
  createWarmLeases,
201
212
  createWorkspacePrewarmRoute,
@@ -244,6 +255,7 @@ export {
244
255
  runSandboxPrompt,
245
256
  runSandboxToolPathSetup,
246
257
  sandboxPrewarmClaimKey,
258
+ sandboxPromptRunner,
247
259
  sandboxToolBinDir,
248
260
  sandboxToolPath,
249
261
  sandboxToolRootDir,
@@ -0,0 +1,68 @@
1
+ /**
2
+ * `createSandboxExecTool`: the `sandbox_exec` tool a Router turn calls to run
3
+ * one command in the product's box — a toolkit script, a converter, a check —
4
+ * and read its exit code and output. Unlike `sandbox_run` it starts no box
5
+ * agent: the Router model stays in charge and the box only executes.
6
+ *
7
+ * WHY. Tax's Router default lost its Python form toolkit because the lane had
8
+ * no way to reach a box: 685 tool calls, 0 form fills (2026-10). A toolkit
9
+ * the product mounts in the box is reachable from the Router lane only
10
+ * through a command tool.
11
+ *
12
+ * NEVER SILENT. A box that cannot start or be prepared, and a command that
13
+ * cannot run or outruns its cap, come back as a typed `SandboxRunError`
14
+ * (`sandbox_unavailable`, `sandbox_failed`) the model must report. A command
15
+ * that runs and exits non-zero is a result, not a failure: the model reads
16
+ * its exit code and stderr and can correct itself.
17
+ *
18
+ * `prepare` runs once per tool, before the first command (install a runtime,
19
+ * copy the session's documents in). `allow` is the product's command policy.
20
+ */
21
+ import type { SandboxInstance } from '@tangle-network/sandbox';
22
+ import { SandboxRunError } from './sandbox-run-tool';
23
+ export interface SandboxExecToolOptions {
24
+ /** The box commands run in. The product provisions, binds and bills it. A throw is
25
+ * `sandbox_unavailable`, unless it is a `SandboxRunError`, which is kept as it is. */
26
+ box(signal: AbortSignal): Promise<SandboxInstance>;
27
+ /** Once per tool, before the first command: install a runtime, sync files in. */
28
+ prepare?(box: SandboxInstance, signal: AbortSignal): Promise<void>;
29
+ /** Default working directory. */
30
+ cwd?: string;
31
+ env?: Record<string, string>;
32
+ /** Cap for one command, box start and prepare included. Default 2 minutes. */
33
+ timeoutMs?: number;
34
+ /** Characters of stdout and of stderr returned to the model, each. Default 20 000 (the tail is kept). */
35
+ maxOutputChars?: number;
36
+ /** The product's command policy: a string refuses the command with that reason. */
37
+ allow?(command: string): string | null;
38
+ /** After each command, the files the product wants the model to know about (e.g. its output folder). */
39
+ listFiles?(box: SandboxInstance, signal: AbortSignal): Promise<string[]>;
40
+ signal?: AbortSignal;
41
+ /** The box's warm lease, so a call is recorded as a turn on it. */
42
+ warm?: {
43
+ leases: {
44
+ turn(key: string): Promise<unknown>;
45
+ };
46
+ key: string;
47
+ };
48
+ onFailure?(error: SandboxRunError): void;
49
+ name?: string;
50
+ description?: string;
51
+ }
52
+ export interface SandboxExecResult {
53
+ exitCode: number;
54
+ stdout: string;
55
+ stderr: string;
56
+ /** True when stdout or stderr was cut to `maxOutputChars`. */
57
+ truncated: boolean;
58
+ ms: number;
59
+ files?: string[];
60
+ }
61
+ export interface SandboxExecTool {
62
+ name: string;
63
+ description: string;
64
+ inputSchema: Record<string, unknown>;
65
+ run(args: Record<string, unknown>): Promise<SandboxExecResult>;
66
+ }
67
+ export declare const SANDBOX_EXEC_DESCRIPTION: string;
68
+ export declare function createSandboxExecTool(options: SandboxExecToolOptions): SandboxExecTool;
@@ -0,0 +1,70 @@
1
+ /**
2
+ * `createSandboxRunTool`: the `sandbox_run` tool a Router turn calls when the
3
+ * work needs a computer — run code, read a PDF or a sheet, fill a form with a
4
+ * Python toolkit. The conversational turn stays on the Router engine
5
+ * (`./router-turn`); only this call enters the box, and its final answer comes
6
+ * back to the model as the tool result.
7
+ *
8
+ * NEVER SILENT. A box that cannot start, a run that fails and a run that ends
9
+ * with no answer each come back as a typed failure (`sandbox_unavailable`,
10
+ * `sandbox_failed`, `sandbox_empty`) that the model reads and must report. A
11
+ * product that leaves this tool out when it cannot place a box drops the
12
+ * capability without the model or the user knowing; mount the tool and let it
13
+ * fail instead.
14
+ *
15
+ * WARM LEASES. When the product passes `warm`, the call counts as a turn on the
16
+ * box's lease (`leases.turn(key)`), so an `escalation-likely` warm from
17
+ * `createEscalationSpeculator` is recorded as used. The default name is the
18
+ * one the speculator listens for (`DEFAULT_ESCALATION_TOOLS`).
19
+ */
20
+ import type { SandboxInstance } from '@tangle-network/sandbox';
21
+ import { type SandboxRuntimeConfig, type StreamSandboxPromptOptions } from './index';
22
+ export type SandboxRunFailureCode = 'sandbox_unavailable' | 'sandbox_failed' | 'sandbox_empty' | 'invalid_arguments';
23
+ /** A typed `sandbox_run` failure. `code` and `message` are what the model reads. */
24
+ export declare class SandboxRunError extends Error {
25
+ readonly code: SandboxRunFailureCode;
26
+ constructor(code: SandboxRunFailureCode, message: string, options?: {
27
+ cause?: unknown;
28
+ });
29
+ }
30
+ export interface SandboxRunToolOptions {
31
+ /** The box this call runs in. The product provisions, binds and bills it; this module never
32
+ * creates one. A throw is reported to the model as `sandbox_unavailable`, unless it is a
33
+ * `SandboxRunError`, whose own code and message are kept (an unpaid account, for example). */
34
+ box(signal: AbortSignal): Promise<SandboxInstance>;
35
+ /** Runs the task on the box and returns the box agent's final answer: {@link sandboxPromptRunner}
36
+ * 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>;
41
+ /** Wall-clock cap for one call, box start included. Default 5 minutes. */
42
+ timeoutMs?: number;
43
+ /** Cancels a call in flight, for example the turn's own signal. */
44
+ signal?: AbortSignal;
45
+ /** The box's warm lease, so the call is recorded as a turn on it. */
46
+ warm?: {
47
+ leases: {
48
+ turn(key: string): Promise<unknown>;
49
+ };
50
+ key: string;
51
+ };
52
+ /** Every failure with its cause, for the product's logs. The model only reads the typed message. */
53
+ onFailure?(error: SandboxRunError): void;
54
+ name?: string;
55
+ description?: string;
56
+ }
57
+ /** The tool shape `runRouterTurn` takes (`RouterTurnTool`), kept structural so this module does not import the engine. */
58
+ export interface SandboxRunTool {
59
+ name: string;
60
+ description: string;
61
+ inputSchema: Record<string, unknown>;
62
+ run(args: Record<string, unknown>): Promise<{
63
+ answer: string;
64
+ ms: number;
65
+ }>;
66
+ }
67
+ export declare const SANDBOX_RUN_DESCRIPTION: string;
68
+ /** The default `runTask`: the shell's own `runSandboxPrompt`, unattended (questions refused). */
69
+ export declare function sandboxPromptRunner(shell: SandboxRuntimeConfig, prompt?: Omit<StreamSandboxPromptOptions, 'signal' | 'history'>): SandboxRunToolOptions['runTask'];
70
+ export declare function createSandboxRunTool(options: SandboxRunToolOptions): SandboxRunTool;
@@ -39,9 +39,8 @@ import {
39
39
  } from "../chunk-PT7H37YH.js";
40
40
  import {
41
41
  useInfiniteScroll
42
- } from "../chunk-Y4WLCFDZ.js";
42
+ } from "../chunk-2FLSODOX.js";
43
43
  import "../chunk-XEURJVS5.js";
44
- import "../chunk-SJWIZT7B.js";
45
44
  import {
46
45
  CheckGlyph,
47
46
  ChevronDown,
@@ -51,6 +50,7 @@ import {
51
50
  PopoverSurface,
52
51
  usePopover
53
52
  } from "../chunk-HG4OONJA.js";
53
+ import "../chunk-SJWIZT7B.js";
54
54
  import {
55
55
  ProviderLogo
56
56
  } from "../chunk-MLG6XKPV.js";
@@ -1,16 +1,18 @@
1
1
  import {
2
+ generateInviteToken,
3
+ isInviteTokenShape,
4
+ validateInviteToken
5
+ } from "../chunk-DJ4VJIH5.js";
6
+ import {
7
+ INVITATION_EMAIL_HINT,
2
8
  INVITATION_EXPIRY_DAYS,
3
9
  generateInvitationToken,
4
10
  getInvitationExpiresAt,
5
11
  inviteUrlForToken,
12
+ isInvitationEmail,
6
13
  normalizeInvitationEmail,
7
14
  parseInvitationPermission
8
- } from "../chunk-AB63T2LM.js";
9
- import {
10
- generateInviteToken,
11
- isInviteTokenShape,
12
- validateInviteToken
13
- } from "../chunk-DJ4VJIH5.js";
15
+ } from "../chunk-KBJZMR4E.js";
14
16
  import {
15
17
  ASSIGNABLE_WORKSPACE_ROLES,
16
18
  ORGANIZATION_ROLES,
@@ -28,6 +30,7 @@ import {
28
30
  } from "../chunk-6XIAPIW6.js";
29
31
  export {
30
32
  ASSIGNABLE_WORKSPACE_ROLES,
33
+ INVITATION_EMAIL_HINT,
31
34
  INVITATION_EXPIRY_DAYS,
32
35
  ORGANIZATION_ROLES,
33
36
  ORGANIZATION_ROLE_RANK,
@@ -41,6 +44,7 @@ export {
41
44
  hasWorkspaceRole,
42
45
  inviteUrlForToken,
43
46
  isAssignableWorkspaceRole,
47
+ isInvitationEmail,
44
48
  isInviteTokenShape,
45
49
  normalizeInvitationEmail,
46
50
  organizationRoleGrantsWorkspaceOwner,
@@ -1,14 +1,16 @@
1
1
  import {
2
2
  SeatLimitError
3
- } from "../chunk-MEUNTJL5.js";
3
+ } from "../chunk-N3CYCSKK.js";
4
+ import "../chunk-DJ4VJIH5.js";
4
5
  import {
6
+ INVITATION_EMAIL_HINT,
5
7
  generateInvitationToken,
6
8
  getInvitationExpiresAt,
7
9
  inviteUrlForToken,
10
+ isInvitationEmail,
8
11
  normalizeInvitationEmail,
9
12
  parseInvitationPermission
10
- } from "../chunk-AB63T2LM.js";
11
- import "../chunk-DJ4VJIH5.js";
13
+ } from "../chunk-KBJZMR4E.js";
12
14
  import {
13
15
  hasWorkspaceRole
14
16
  } from "../chunk-6XIAPIW6.js";
@@ -40,6 +42,7 @@ function createInvitationsApi(opts) {
40
42
  }
41
43
  const email = normalizeInvitationEmail(input.email);
42
44
  if (!email) return { succeeded: false, status: 400, error: "Missing email" };
45
+ if (!isInvitationEmail(email)) return { succeeded: false, status: 400, error: INVITATION_EMAIL_HINT };
43
46
  const organizationId = accessRow.organization.id;
44
47
  const workspaceName = accessRow.workspace.name;
45
48
  await expirePendingInvitations(input.workspaceId, email, now);