@tangle-network/agent-app 0.43.43 → 0.43.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,84 @@
1
+ // src/chat-routes/file-index.ts
2
+ var DEFAULT_IGNORE_SEGMENTS = [
3
+ "node_modules",
4
+ "dist",
5
+ "build",
6
+ "out",
7
+ "coverage",
8
+ "target",
9
+ "__pycache__",
10
+ "venv"
11
+ ];
12
+ function isIgnored(relPath, ignoreSegments) {
13
+ for (const segment of relPath.split("/")) {
14
+ if (!segment) continue;
15
+ if (segment.startsWith(".")) return true;
16
+ if (ignoreSegments.has(segment)) return true;
17
+ }
18
+ return false;
19
+ }
20
+ function relativeTo(root, path) {
21
+ const prefix = root.endsWith("/") ? root : `${root}/`;
22
+ if (path.startsWith(prefix)) return path.slice(prefix.length);
23
+ if (path === root) return "";
24
+ return path;
25
+ }
26
+ function basename(path) {
27
+ const segments = path.split("/").filter(Boolean);
28
+ return segments[segments.length - 1] ?? path;
29
+ }
30
+ function isMissingRootError(err, root) {
31
+ if (!(err instanceof Error)) return false;
32
+ if (err.code !== "VALIDATION_ERROR") return false;
33
+ return /ENOENT/.test(err.message) && /no such file or directory/.test(err.message) && new RegExp(`\\blstat '${escapeRegExp(root)}'`).test(err.message);
34
+ }
35
+ function escapeRegExp(value) {
36
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
37
+ }
38
+ function createSandboxFileIndexRoute(options) {
39
+ const maxDepth = options.maxDepth ?? 12;
40
+ const maxEntries = options.maxEntries ?? 5e3;
41
+ const cacheTtlSeconds = options.cacheTtlSeconds ?? 20;
42
+ const staticIgnore = /* @__PURE__ */ new Set([...DEFAULT_IGNORE_SEGMENTS, ...options.ignore ?? []]);
43
+ return async function fileIndex(request) {
44
+ const auth = await options.authorize({ request });
45
+ if (auth.status === "denied") return auth.response;
46
+ if (auth.status === "warming") {
47
+ return Response.json({ status: "warming" });
48
+ }
49
+ const cache = options.cache;
50
+ if (cache && auth.cacheKey) {
51
+ const cached = await cache.get(auth.cacheKey);
52
+ if (cached) return Response.json(cached);
53
+ }
54
+ const ignoreSegments = auth.ignore?.length ? /* @__PURE__ */ new Set([...staticIgnore, ...auth.ignore]) : staticIgnore;
55
+ let scan;
56
+ try {
57
+ scan = await auth.fs.tree(auth.root, { maxDepth });
58
+ } catch (err) {
59
+ if (!isMissingRootError(err, auth.root)) throw err;
60
+ return Response.json({ status: "warming" });
61
+ }
62
+ const filtered = scan.files.filter((f) => !isIgnored(relativeTo(scan.root, f.path), ignoreSegments));
63
+ const truncated = scan.stats.truncated || filtered.length > maxEntries;
64
+ const files = filtered.slice(0, maxEntries).map((f) => {
65
+ const path = relativeTo(scan.root, f.path);
66
+ const entry = { path, name: basename(path) };
67
+ if (typeof f.size === "number") entry.size = f.size;
68
+ return entry;
69
+ });
70
+ const body = {
71
+ status: "ready",
72
+ files,
73
+ truncated,
74
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString()
75
+ };
76
+ if (cache && auth.cacheKey) await cache.put(auth.cacheKey, body, { ttlSeconds: cacheTtlSeconds });
77
+ return Response.json(body);
78
+ };
79
+ }
80
+
81
+ export {
82
+ createSandboxFileIndexRoute
83
+ };
84
+ //# sourceMappingURL=chunk-LCNY3DCM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/chat-routes/file-index.ts"],"sourcesContent":["/**\n * `createSandboxFileIndexRoute` — server side of `@`-file-mentions\n * (companion to sandbox-ui#184's composer mention primitive). Serves a flat,\n * ignore-filtered listing of the workspace sandbox so `useFileMentions`\n * (`/web-react`) can filter it client-side without a round trip per\n * keystroke.\n *\n * Same seam style as `createUploadRoute`: `authorize({ request })` resolves a\n * structural `{ tree(path, opts) }` handle (the shape of the sandbox SDK's\n * `box.fs.tree`) — no SDK import here. `authorize` also carries the\n * cold-box signal: a sandbox that isn't running yet answers `{ status:\n * 'warming' }` directly, never provisions-and-waits inside this route.\n *\n * A box can also be running with its workspace root not yet materialised, which\n * `authorize` cannot see; the route recognises that one signal off `fs.tree`\n * and answers `warming` too, so every consumer gets the retry-and-wait state\n * instead of a 500. Every other `tree()` failure propagates.\n */\n\nimport type { FileMention } from './wire'\n\n/** One entry from a structural `tree()` scan. Mirrors the sandbox SDK's\n * `FileTreeFile` (`path`, `size`, `mtime`) — `mtime` is unused here so it's\n * omitted from the structural match. */\nexport interface SandboxTreeFile {\n path: string\n size: number\n}\n\n/** Structural match of the sandbox SDK's `box.fs.tree` result shape\n * (`FileTreeResult`). `stats.truncated` is the only stat this route reads;\n * the rest ride through unread on the real SDK type. */\nexport interface SandboxTreeResult {\n root: string\n files: SandboxTreeFile[]\n stats: { truncated: boolean }\n}\n\n/** Structural match of the sandbox SDK's `box.fs` tree surface. */\nexport interface SandboxFileTreeSource {\n tree(path: string, options?: { maxDepth?: number }): Promise<SandboxTreeResult>\n}\n\nexport interface FileIndexReadyResponse {\n status: 'ready'\n /** Workspace-relative entries. Same shape as `FileMention` (`./wire`) so a\n * client can hand a response entry straight to `fileMentionsToParts` /\n * `buildMentionPromptBlock` without remapping. */\n files: FileMention[]\n /** True when either the underlying scan truncated (SDK-side cap) or this\n * route's own `maxEntries` cap trimmed the filtered list. The client\n * should show \"showing first N files\" rather than imply completeness. */\n truncated: boolean\n generatedAt: string\n}\n\n/** Cold-box answer: no provisioning happened, no files were scanned. The\n * client shows a warming state and retries — this route never blocks on a\n * box coming up. Two situations produce it: `authorize` reporting a box that\n * is not running, and a running box whose workspace root does not exist yet\n * (see `isMissingRootError`). */\nexport interface FileIndexWarmingResponse {\n status: 'warming'\n}\n\nexport type FileIndexResponse = FileIndexReadyResponse | FileIndexWarmingResponse\n\n/** Short-TTL cache seam so repeat popover opens in the same session don't\n * re-scan the workspace. Host-provided (e.g. a KV binding); `key` is\n * whatever `authorize` returns as `cacheKey` — this route treats it opaquely. */\nexport interface FileIndexCache {\n get(key: string): Promise<FileIndexReadyResponse | null> | FileIndexReadyResponse | null\n put(key: string, value: FileIndexReadyResponse, options?: { ttlSeconds?: number }): Promise<void> | void\n}\n\nexport type FileIndexAuthorization =\n | {\n status: 'ready'\n /** Structural sandbox `fs` handle, usually `ensureWorkspaceSandbox(...)` → `box.fs`. */\n fs: SandboxFileTreeSource\n /** Workspace root to index (e.g. `/home/agent`). */\n root: string\n /** Extra ignore segments for this request, merged with the route's\n * defaults + `CreateSandboxFileIndexRouteOptions.ignore`. */\n ignore?: string[]\n /** Opaque cache key for the optional cache seam. Omit to skip caching\n * for this request (e.g. a workspace the host chooses not to cache). */\n cacheKey?: string\n }\n | { status: 'warming' }\n | { status: 'denied'; response: Response }\n\nexport interface CreateSandboxFileIndexRouteOptions {\n /** Authenticate the caller, resolve the sandbox `fs` handle, and signal a\n * cold box — never provisions or waits. */\n authorize(args: { request: Request }): Promise<FileIndexAuthorization>\n /** Extra ignore segments beyond the route's defaults (node_modules, .git,\n * dotfiles/dot-dirs, common build dirs). Matched as exact path-segment\n * names, same rule as the defaults. */\n ignore?: string[]\n /** Passed to `fs.tree` as `options.maxDepth`. Default 12. */\n maxDepth?: number\n /** Hard cap on entries returned after filtering. Default 5000. */\n maxEntries?: number\n /** Optional host-provided cache seam. */\n cache?: FileIndexCache\n /** Cache TTL in seconds when `cache` is set. Default 20. */\n cacheTtlSeconds?: number\n}\n\n/** Segment names ignored anywhere in a path, beyond the generic dotfile rule\n * below. Intentionally small and language/framework-agnostic — callers\n * extend it via `ignore` for anything domain-specific (e.g. a vault's\n * `uploads` dir). */\nconst DEFAULT_IGNORE_SEGMENTS = [\n 'node_modules',\n 'dist',\n 'build',\n 'out',\n 'coverage',\n 'target',\n '__pycache__',\n 'venv',\n]\n\n/** A path segment starting with `.` (`.git`, `.env`, `.next`, `.cache`, …) is\n * always ignored — this single rule covers most dot-prefixed VCS/tooling\n * dirs and dotfiles without enumerating them. */\nfunction isIgnored(relPath: string, ignoreSegments: ReadonlySet<string>): boolean {\n for (const segment of relPath.split('/')) {\n if (!segment) continue\n if (segment.startsWith('.')) return true\n if (ignoreSegments.has(segment)) return true\n }\n return false\n}\n\n/** Strips the tree result's echoed `root` prefix so entries are always\n * workspace-relative, whichever convention the structural `fs.tree` uses\n * (root-relative already, or root-prefixed). */\nfunction relativeTo(root: string, path: string): string {\n const prefix = root.endsWith('/') ? root : `${root}/`\n if (path.startsWith(prefix)) return path.slice(prefix.length)\n if (path === root) return ''\n return path\n}\n\nfunction basename(path: string): string {\n const segments = path.split('/').filter(Boolean)\n return segments[segments.length - 1] ?? path\n}\n\n/**\n * A box can answer `running` before it has materialised the workspace root —\n * `authorize` has already committed to `ready` by then, so `fs.tree` is the\n * first thing to notice, and it rejects with the sandbox SDK's\n * `ValidationError` wrapping a box-side `ENOENT … lstat` on the root. That is\n * the SAME \"not usable yet\" state `authorize` collapses onto `warming` for an\n * absent or stopped box, just discovered one step later, so it gets the same\n * answer instead of escaping as a 500.\n *\n * Matched STRUCTURALLY, not with `instanceof`: importing the SDK's error class\n * would make `@tangle-network/sandbox` a hard dependency of a route factory\n * whose entire `fs` seam is structural (`SandboxFileTreeSource`), and would\n * break any host feeding it a non-SDK handle.\n *\n * Deliberately narrow — the error code, `ENOENT`, the ENOENT message text, AND\n * the failing syscall's own operand all have to line up. A permission error, a\n * timeout, an auth failure, or an ENOENT on some other path inside the tree is\n * a real failure and still surfaces.\n *\n * The operand is matched as the quoted `lstat '<root>'` clause rather than by\n * substring, because the root is a PREFIX of everything under it: a plain\n * `includes(root)` would also swallow an ENOENT on `<root>/gone/x.md`, and on\n * a prefix sibling like `/home/agent-old/...`.\n */\nfunction isMissingRootError(err: unknown, root: string): boolean {\n if (!(err instanceof Error)) return false\n if ((err as { code?: unknown }).code !== 'VALIDATION_ERROR') return false\n return (\n /ENOENT/.test(err.message) &&\n /no such file or directory/.test(err.message) &&\n new RegExp(`\\\\blstat '${escapeRegExp(root)}'`).test(err.message)\n )\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nexport function createSandboxFileIndexRoute(\n options: CreateSandboxFileIndexRouteOptions,\n): (request: Request) => Promise<Response> {\n const maxDepth = options.maxDepth ?? 12\n const maxEntries = options.maxEntries ?? 5000\n const cacheTtlSeconds = options.cacheTtlSeconds ?? 20\n const staticIgnore = new Set([...DEFAULT_IGNORE_SEGMENTS, ...(options.ignore ?? [])])\n\n return async function fileIndex(request: Request): Promise<Response> {\n const auth = await options.authorize({ request })\n if (auth.status === 'denied') return auth.response\n if (auth.status === 'warming') {\n return Response.json({ status: 'warming' } satisfies FileIndexWarmingResponse)\n }\n\n const cache = options.cache\n if (cache && auth.cacheKey) {\n const cached = await cache.get(auth.cacheKey)\n if (cached) return Response.json(cached)\n }\n\n const ignoreSegments = auth.ignore?.length\n ? new Set([...staticIgnore, ...auth.ignore])\n : staticIgnore\n\n let scan: SandboxTreeResult\n try {\n scan = await auth.fs.tree(auth.root, { maxDepth })\n } catch (err) {\n if (!isMissingRootError(err, auth.root)) throw err\n return Response.json({ status: 'warming' } satisfies FileIndexWarmingResponse)\n }\n const filtered = scan.files.filter((f) => !isIgnored(relativeTo(scan.root, f.path), ignoreSegments))\n const truncated = scan.stats.truncated || filtered.length > maxEntries\n const files: FileMention[] = filtered.slice(0, maxEntries).map((f) => {\n const path = relativeTo(scan.root, f.path)\n const entry: FileMention = { path, name: basename(path) }\n if (typeof f.size === 'number') entry.size = f.size\n return entry\n })\n\n const body: FileIndexReadyResponse = {\n status: 'ready',\n files,\n truncated,\n generatedAt: new Date().toISOString(),\n }\n\n if (cache && auth.cacheKey) await cache.put(auth.cacheKey, body, { ttlSeconds: cacheTtlSeconds })\n\n return Response.json(body)\n }\n}\n"],"mappings":";AAkHA,IAAM,0BAA0B;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAKA,SAAS,UAAU,SAAiB,gBAA8C;AAChF,aAAW,WAAW,QAAQ,MAAM,GAAG,GA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ts-1_3y2JmR.js';
2
+
3
+ /**
4
+ * `createSandboxFileIndexRoute` — server side of `@`-file-mentions
5
+ * (companion to sandbox-ui#184's composer mention primitive). Serves a flat,
6
+ * ignore-filtered listing of the workspace sandbox so `useFileMentions`
7
+ * (`/web-react`) can filter it client-side without a round trip per
8
+ * keystroke.
9
+ *
10
+ * Same seam style as `createUploadRoute`: `authorize({ request })` resolves a
11
+ * structural `{ tree(path, opts) }` handle (the shape of the sandbox SDK's
12
+ * `box.fs.tree`) — no SDK import here. `authorize` also carries the
13
+ * cold-box signal: a sandbox that isn't running yet answers `{ status:
14
+ * 'warming' }` directly, never provisions-and-waits inside this route.
15
+ *
16
+ * A box can also be running with its workspace root not yet materialised, which
17
+ * `authorize` cannot see; the route recognises that one signal off `fs.tree`
18
+ * and answers `warming` too, so every consumer gets the retry-and-wait state
19
+ * instead of a 500. Every other `tree()` failure propagates.
20
+ */
21
+
22
+ /** One entry from a structural `tree()` scan. Mirrors the sandbox SDK's
23
+ * `FileTreeFile` (`path`, `size`, `mtime`) — `mtime` is unused here so it's
24
+ * omitted from the structural match. */
25
+ interface SandboxTreeFile {
26
+ path: string;
27
+ size: number;
28
+ }
29
+ /** Structural match of the sandbox SDK's `box.fs.tree` result shape
30
+ * (`FileTreeResult`). `stats.truncated` is the only stat this route reads;
31
+ * the rest ride through unread on the real SDK type. */
32
+ interface SandboxTreeResult {
33
+ root: string;
34
+ files: SandboxTreeFile[];
35
+ stats: {
36
+ truncated: boolean;
37
+ };
38
+ }
39
+ /** Structural match of the sandbox SDK's `box.fs` tree surface. */
40
+ interface SandboxFileTreeSource {
41
+ tree(path: string, options?: {
42
+ maxDepth?: number;
43
+ }): Promise<SandboxTreeResult>;
44
+ }
45
+ interface FileIndexReadyResponse {
46
+ status: 'ready';
47
+ /** Workspace-relative entries. Same shape as `FileMention` (`./wire`) so a
48
+ * client can hand a response entry straight to `fileMentionsToParts` /
49
+ * `buildMentionPromptBlock` without remapping. */
50
+ files: FileMention[];
51
+ /** True when either the underlying scan truncated (SDK-side cap) or this
52
+ * route's own `maxEntries` cap trimmed the filtered list. The client
53
+ * should show "showing first N files" rather than imply completeness. */
54
+ truncated: boolean;
55
+ generatedAt: string;
56
+ }
57
+ /** Cold-box answer: no provisioning happened, no files were scanned. The
58
+ * client shows a warming state and retries — this route never blocks on a
59
+ * box coming up. Two situations produce it: `authorize` reporting a box that
60
+ * is not running, and a running box whose workspace root does not exist yet
61
+ * (see `isMissingRootError`). */
62
+ interface FileIndexWarmingResponse {
63
+ status: 'warming';
64
+ }
65
+ type FileIndexResponse = FileIndexReadyResponse | FileIndexWarmingResponse;
66
+ /** Short-TTL cache seam so repeat popover opens in the same session don't
67
+ * re-scan the workspace. Host-provided (e.g. a KV binding); `key` is
68
+ * whatever `authorize` returns as `cacheKey` — this route treats it opaquely. */
69
+ interface FileIndexCache {
70
+ get(key: string): Promise<FileIndexReadyResponse | null> | FileIndexReadyResponse | null;
71
+ put(key: string, value: FileIndexReadyResponse, options?: {
72
+ ttlSeconds?: number;
73
+ }): Promise<void> | void;
74
+ }
75
+ type FileIndexAuthorization = {
76
+ status: 'ready';
77
+ /** Structural sandbox `fs` handle, usually `ensureWorkspaceSandbox(...)` → `box.fs`. */
78
+ fs: SandboxFileTreeSource;
79
+ /** Workspace root to index (e.g. `/home/agent`). */
80
+ root: string;
81
+ /** Extra ignore segments for this request, merged with the route's
82
+ * defaults + `CreateSandboxFileIndexRouteOptions.ignore`. */
83
+ ignore?: string[];
84
+ /** Opaque cache key for the optional cache seam. Omit to skip caching
85
+ * for this request (e.g. a workspace the host chooses not to cache). */
86
+ cacheKey?: string;
87
+ } | {
88
+ status: 'warming';
89
+ } | {
90
+ status: 'denied';
91
+ response: Response;
92
+ };
93
+ interface CreateSandboxFileIndexRouteOptions {
94
+ /** Authenticate the caller, resolve the sandbox `fs` handle, and signal a
95
+ * cold box — never provisions or waits. */
96
+ authorize(args: {
97
+ request: Request;
98
+ }): Promise<FileIndexAuthorization>;
99
+ /** Extra ignore segments beyond the route's defaults (node_modules, .git,
100
+ * dotfiles/dot-dirs, common build dirs). Matched as exact path-segment
101
+ * names, same rule as the defaults. */
102
+ ignore?: string[];
103
+ /** Passed to `fs.tree` as `options.maxDepth`. Default 12. */
104
+ maxDepth?: number;
105
+ /** Hard cap on entries returned after filtering. Default 5000. */
106
+ maxEntries?: number;
107
+ /** Optional host-provided cache seam. */
108
+ cache?: FileIndexCache;
109
+ /** Cache TTL in seconds when `cache` is set. Default 20. */
110
+ cacheTtlSeconds?: number;
111
+ }
112
+ declare function createSandboxFileIndexRoute(options: CreateSandboxFileIndexRouteOptions): (request: Request) => Promise<Response>;
113
+
114
+ export { type CreateSandboxFileIndexRouteOptions as C, type FileIndexAuthorization as F, type SandboxFileTreeSource as S, type FileIndexCache as a, type FileIndexReadyResponse as b, type FileIndexResponse as c, type FileIndexWarmingResponse as d, type SandboxTreeFile as e, type SandboxTreeResult as f, createSandboxFileIndexRoute as g };
package/dist/index.d.ts CHANGED
@@ -17,7 +17,7 @@ export { KeyCrypto, KeyProvisioner, PlanLimit, PlatformBalanceInfo, PlatformBala
17
17
  export { HttpHeadProbeConfig, PreflightProbe, PreflightProbeResult, PreflightProbeVerdict, PreflightReport, RouterChatProbeConfig, SandboxAuthProbeConfig, formatPreflightReport, httpHeadProbe, routerChatProbe, runPreflight, sandboxAuthProbe } from './preflight/index.js';
18
18
  export { ObjectBody, ObjectKeyParts, ObjectStore, PutObjectOptions, R2LikeBucket, R2LikeObjectBody, R2LikeObjectHead, SignObjectUrlArgs, VerifyObjectUrlResult, assertSafeKeySegment, createProxiedArtifactRoute, createR2ObjectStore, objectKey, signObjectUrl, verifyObjectUrl } from './object-store/index.js';
19
19
  export { B as BULK_DELETE_MAX_THREADS, C as ChatStoreInputError, t as threadTitleFromMessage } from './core-7qIM7svy.js';
20
- export { C as ChatFilePart, a as ChatImagePart, b as ChatInteractionPart, c as ChatMessagePart, d as ChatNoticePart, e as ChatPartTime, f as ChatPlanPart, g as ChatReasoningPart, h as ChatStepFinishPart, i as ChatStepStartPart, j as ChatSubtaskPart, k as ChatTextPart, l as ChatToolPart, m as ChatToolState, n as ChatToolStatus, o as ChatUsageTokens, S as StorableHarnessPartKind, p as isChatInteractionPart, q as isChatPlanPart, r as isChatStepFinishPart, s as isChatTextPart, t as isChatToolPart, u as toChatMessageParts } from './parts-DjX0RRTS.js';
20
+ export { C as ChatFilePart, a as ChatImagePart, b as ChatInteractionPart, c as ChatMentionKind, d as ChatMentionPart, e as ChatMessagePart, f as ChatNoticePart, g as ChatPartTime, h as ChatPlanPart, i as ChatReasoningPart, j as ChatStepFinishPart, k as ChatStepStartPart, l as ChatSubtaskPart, m as ChatTextPart, n as ChatToolPart, o as ChatToolState, p as ChatToolStatus, q as ChatUsageTokens, S as StorableHarnessPartKind, r as isChatInteractionPart, s as isChatMentionPart, t as isChatPlanPart, u as isChatStepFinishPart, v as isChatTextPart, w as isChatToolPart, x as mentionInputToPart, y as mentionPartsFromMessageParts, z as toChatMessageParts } from './parts-1_3y2JmR.js';
21
21
  export { DeriveKeyOptions, createFieldCrypto, decodeHexKey, decryptAesGcm, decryptBytes, decryptWithKey, deriveKey, encryptAesGcm, encryptBytes, encryptWithKey } from './crypto/index.js';
22
22
  export { BufferedTurnEvent, BufferedTurnOptions, BufferedTurnTap, D1LikeForTurns, JsonRecord, PersistedChatMessageForTurn, PumpBufferedTurnOptions, ReplayTurnEventsOptions, ResolvedChatTurn, StreamEvent, TURN_EVENTS_MIGRATION_SQL, TURN_STATUS_SCOPE_MIGRATION_SQL, TurnEventStore, TurnStatus, asRecord, asString, buildUserTextParts, coalesceChatStreamEvents, coalesceDeltas, createBufferedTurnTap, createD1TurnEventStore, createMemoryTurnEventStore, encodeEvent, finalizeAssistantParts, getPartKey, mergePersistedPart, messageHasTurnId, normalizeClientTurnId, normalizePersistedPart, normalizeTime, normalizeToolEvent, pumpBufferedTurn, replayTurnEvents, resolveChatTurn, resolveToolId, resolveToolName } from './stream/index.js';
23
23
  export { HubExecClient, HubExecClientOptions, HubExecErrorCode, HubExecResult, HubInvokeDeps, HubInvokeInput, HubInvokeOutcome, ParsedIntegrationAction, invokeIntegrationHub, resolveIntegrationAction } from './integrations/index.js';
@@ -27,7 +27,7 @@ export { ChatPlan, ChatPlanPersistedPart, ChatPlanStatus, PLAN_SUBMITTED_EVENT,
27
27
  export { CreateDurableInteractionRoutePersistenceOptions, DurableAnswerIntentJournal, DurableAnswerIntentRecord, DurableAnswerIntentState, DurableChatConflictError, DurableChatError, DurableChatErrorCode, DurableChatEventProjection, DurableChatGoneError, DurableChatScope, DurableChatStateStore, DurableChatUnavailableError, DurableFollowUpReceipt, DurableInteractionAcknowledgement, DurableInteractionGuarantee, DurableInteractionProjection, DurableInteractionProjectionAdapter, DurableInteractionSettlement, DurableInteractionSettlementFactoryOptions, DurableInteractionSettlementOptions, DurablePlanAuthority, DurablePlanAuthorityCurrentResult, DurablePlanAuthorityDecision, DurablePlanAuthorityResult, DurablePlanAuthorization, DurablePlanCommandJournal, DurablePlanCommandKey, DurablePlanCommandRecord, DurablePlanCommandState, DurablePlanDecision, DurablePlanEffectRecord, DurablePlanProjection, DurablePlanRouteAuthorizeArgs, DurablePlanRouteOptions, DurablePlanRoutes, DurablePlanStateStore, DurablePlanStore, InMemoryDurableChatStateStore, InMemoryDurableChatStore, PreparedDurableInteractionAnswer, applyDurableInteractionAnswer, applyDurableInteractionAsk, applyDurableInteractionCancel, createDurableChatEventProjection, createDurableChatScope, createDurableInteractionProjectionAdapter, createDurableInteractionRoutePersistence, createDurableInteractionSettlement, createDurablePlanRoutes, createInMemoryDurableChatStateStore, durableChatScopeKey, durableInteractionIntentKey, normalizePlanDecision, planAuthorityIdempotencyKey, planCommandKey, planEffectKey, recordDurableInteractionAnswer, recordDurableInteractionCancel, stablePlanReceipt, upsertDurableInteractionAsk } from './durable-chat/index.js';
28
28
  export { CompleteMissionInput, CreateMissionInput, DEFAULT_MISSION_STEP_KINDS, InMemoryMissionStore, MISSION_CONTROL_CHANNEL_ID, MissionApprovalsPort, MissionAuditEvent, MissionConcurrencyError, MissionCostLedger, MissionEngine, MissionEngineOptions, MissionEventSink, MissionGateKind, MissionGateOptions, MissionGateProposal, MissionOutcome, MissionPlanRunOptions, MissionProposalResolution, MissionRecord, MissionService, MissionServiceOptions, MissionState, MissionStatus, MissionStep, MissionStepState, MissionStepStatus, MissionStorePort, MissionStreamEvent, MissionStreamStatus, MissionStreamStep, MissionStreamStepStatus, MissionUpdateGuard, MissionUpdatePatch, ParseMissionBlocksOptions, ParsedMission, ParsedMissionStep, PlanOutcome, RetryableStepError, SandboxDispatch, SandboxDispatchDoneResult, SandboxDispatchInProgressResult, SandboxDispatchInput, SandboxDispatchResult, SetStepStatusPatch, StepGateClassification, StepOutcome, applyMissionEvent, asMissionStreamEvent, budgetGateProposalId, buildAgentMissionPlan, createInMemoryMissionStore, createMissionEngine, createMissionService, isMissionStopRequested, isMissionTerminal, mergeMissionState, noopEventSink, parseMissionBlocks, parseSessionStreamEnvelope, reduceMissionEvents, stepGateProposalId, volumeGateProposalId } from './missions/index.js';
29
29
  export { S as StepAgentActivity, W as WithAgentActivity, s as stepAgentActivity } from './agent-activity-C8ZG0F0M.js';
30
- export { AppToolDescriptor, AuthenticatedSandboxUser, BuildAppToolMcpServersOptions, BuildSandboxToolFileMountsOptions, DEFAULT_SANDBOX_RESOURCES, DriveSandboxTurnOptions, ENV_TOTAL_MAX_BYTES, ENV_VALUE_MAX_BYTES, EnsureWorkspaceSandboxOptions, LivenessProbeConfig, MemberSyncSeam, Outcome, PROVISION_PAYLOAD_MAX_BYTES, ProfileComposeOptions, PromptInputPart, ProviderResolutionConfig, ProvisionPayloadSections, ProvisionProfileSection, ResolveSandboxClientCredentialsOptions, ResolvedModel, SandboxApiCredentials, SandboxBuildContext, SandboxClientCredentials, SandboxCredentialEnvironment, SandboxPermissionLevel, SandboxResourceConfig, SandboxRestoreSpec, SandboxRuntimeAuthRefreshError, SandboxRuntimeConfig, SandboxRuntimeConnection, SandboxScope, SandboxStepTransition, SandboxTerminalTokenOptions, SandboxTerminalTokenResult, SandboxTerminalTokenSubject, SandboxTerminalWsMatch, SandboxToolPathOptions, SandboxToolSpec, ScopedTokenResult, SecretStore, StoppedSandboxResumeFailure, StoppedSandboxResumeRecovery, StreamSandboxPromptOptions, TerminalProxyIdentity, WorkspaceSandboxConnectionArgs, WorkspaceSandboxConnectionHandlerOptions, WorkspaceSandboxEnsureContext, WorkspaceSandboxInstanceLike, WorkspaceSandboxManager, WorkspaceSandboxManagerOptions, WorkspaceSandboxRuntimeProxyArgs, WorkspaceSandboxRuntimeProxyHandlerOptions, WorkspaceSandboxTerminalUpgradeHandlerOptions, WriteProfileFilesOptions, assertEnvWithinLimits, assertProvisionPayloadWithinCap, attachReasoningEffort, bearerSubprotocolToken, bearerToken, buildAppToolMcpServers, buildSandboxRuntimeProxyHeaders, buildSandboxToolFileMounts, buildSandboxToolPathSetupScript, classifySeveredStream, createSandboxTerminalToken, createWorkspaceSandboxConnectionHandler, createWorkspaceSandboxManager, createWorkspaceSandboxRuntimeProxyHandler, createWorkspaceSandboxTerminalUpgradeHandler, deferredCorpusHash, deleteSecret, detectInteractiveQuestion, driveSandboxTurn, encodeSandboxRuntimePath, ensureWorkspaceSandbox, flattenHistory, getClient, isSandboxTerminalWsUpgrade, isTerminalPromptEvent, matchSandboxTerminalWsPath, mergeExtraMcp, mergeHistoryIntoParts, mintSandboxScopedToken, mintTerminalProxyToken, readSecret, resetClientCache, resolveModel, resolveSandboxClientCredentials, runSandboxPrompt, runSandboxToolPathSetup, sandboxToolBinDir, sandboxToolPath, sandboxToolRootDir, secretStoreFromClient, splitDeferredProfileFiles, storeSecret, streamSandboxPrompt, syncSandboxMemberAdd, syncSandboxMemberRemove, syncSandboxMemberRole, terminalTokenFromRequest, verifySandboxTerminalToken, verifyTerminalProxyToken, writeProfileFilesToBox } from './sandbox/index.js';
30
+ export { AppToolDescriptor, AuthenticatedSandboxUser, BuildAppToolMcpServersOptions, BuildSandboxToolFileMountsOptions, DEFAULT_SANDBOX_RESOURCES, DriveSandboxTurnOptions, ENV_TOTAL_MAX_BYTES, ENV_VALUE_MAX_BYTES, EnsureWorkspaceSandboxOptions, LivenessProbeConfig, MemberSyncSeam, Outcome, PROVISION_PAYLOAD_MAX_BYTES, PeekWorkspaceSandboxOutcome, ProfileComposeOptions, PromptInputPart, ProviderResolutionConfig, ProvisionPayloadSections, ProvisionProfileSection, ResolveSandboxClientCredentialsOptions, ResolvedModel, SandboxApiCredentials, SandboxBuildContext, SandboxClientCredentials, SandboxCredentialEnvironment, SandboxExecChannel, SandboxExecOptions, SandboxFileBytesOutcome, SandboxFileSizeOutcome, SandboxPermissionLevel, SandboxResourceConfig, SandboxRestoreSpec, SandboxRuntimeAuthRefreshError, SandboxRuntimeConfig, SandboxRuntimeConnection, SandboxScope, SandboxStepTransition, SandboxTerminalTokenOptions, SandboxTerminalTokenResult, SandboxTerminalTokenSubject, SandboxTerminalWsMatch, SandboxToolPathOptions, SandboxToolSpec, ScopedTokenResult, SecretStore, StoppedSandboxResumeFailure, StoppedSandboxResumeRecovery, StreamSandboxPromptOptions, TerminalProxyIdentity, WorkspaceSandboxConnectionArgs, WorkspaceSandboxConnectionHandlerOptions, WorkspaceSandboxEnsureContext, WorkspaceSandboxInstanceLike, WorkspaceSandboxManager, WorkspaceSandboxManagerOptions, WorkspaceSandboxRuntimeProxyArgs, WorkspaceSandboxRuntimeProxyHandlerOptions, WorkspaceSandboxTerminalUpgradeHandlerOptions, WriteProfileFilesOptions, assertEnvWithinLimits, assertProvisionPayloadWithinCap, attachReasoningEffort, bearerSubprotocolToken, bearerToken, buildAppToolMcpServers, buildSandboxRuntimeProxyHeaders, buildSandboxToolFileMounts, buildSandboxToolPathSetupScript, classifySeveredStream, createSandboxTerminalToken, createWorkspaceSandboxConnectionHandler, createWorkspaceSandboxManager, createWorkspaceSandboxRuntimeProxyHandler, createWorkspaceSandboxTerminalUpgradeHandler, deferredCorpusHash, deleteSecret, detectInteractiveQuestion, driveSandboxTurn, encodeSandboxRuntimePath, ensureWorkspaceSandbox, flattenHistory, getClient, isSandboxTerminalWsUpgrade, isTerminalPromptEvent, matchSandboxTerminalWsPath, mergeExtraMcp, mergeHistoryIntoParts, mintSandboxScopedToken, mintTerminalProxyToken, peekWorkspaceSandbox, readSandboxBinaryBytes, readSecret, resetClientCache, resolveModel, resolveSandboxClientCredentials, runSandboxPrompt, runSandboxToolPathSetup, sandboxToolBinDir, sandboxToolPath, sandboxToolRootDir, secretStoreFromClient, shellQuote, splitDeferredProfileFiles, statSandboxFileSize, storeSecret, streamSandboxPrompt, syncSandboxMemberAdd, syncSandboxMemberRemove, syncSandboxMemberRole, terminalTokenFromRequest, verifySandboxTerminalToken, verifyTerminalProxyToken, writeProfileFilesToBox } from './sandbox/index.js';
31
31
  export { CookieOptions, JsonObject, KvLike, RateLimitResult, RequestContext, SecurityHeaderOptions, addSecurityHeaders, assertMediaUrl, checkRateLimit, clearCookieHeader, extractRequestContext, parseJsonObjectBody, readCookieValue, requireString, serializeCookie } from './web/index.js';
32
32
  export { BuildRedactedDocumentOptions, DEFAULT_REDACTION_PATTERNS, RedactForIngestionOptions, RedactedDocSegment, RedactedDocument, RedactionPattern, RedactionSpan, RevealResult, RevealSpanOptions, buildRedactedDocument, detectSpans, maskSpans, redactForIngestion, revealSpan } from './redact/index.js';
33
33
  export { ApprovalEvent, ApprovalEventSchema, AssetContentMap, AssetFormat, AssetSpec, AssetStatus, AssetVariant, BrandTokens, BrandTokensSchema, ConversionMetrics, ConversionMetricsSchema, CopyContent, CopyContentSchema, CopyPlatform, EmailBodySection, EmailContent, EmailContentSchema, EmailCtaSection, EmailDividerSection, EmailFeatureSection, EmailHeroSection, EmailSection, EmailTestimonialSection, ImageBackground, ImageContent, ImageContentSchema, ImageImageLayer, ImageLayer, ImageLayerType, ImageLogoLayer, ImageShapeLayer, ImageSlide, ImageTextLayer, VideoCaption, VideoContent, VideoContentSchema, VideoCountdownScene, VideoImageRevealScene, VideoScene, VideoSlideScene, VideoTextAnimationScene, parseAssetSpec, safeParseAssetSpec } from './assets/index.js';
package/dist/index.js CHANGED
@@ -289,12 +289,15 @@ import {
289
289
  } from "./chunk-HFC4BTWJ.js";
290
290
  import {
291
291
  isChatInteractionPart,
292
+ isChatMentionPart,
292
293
  isChatPlanPart,
293
294
  isChatStepFinishPart,
294
295
  isChatTextPart,
295
296
  isChatToolPart,
297
+ mentionInputToPart,
298
+ mentionPartsFromMessageParts,
296
299
  toChatMessageParts
297
- } from "./chunk-I2ATYB7R.js";
300
+ } from "./chunk-6E2XJSCT.js";
298
301
  import {
299
302
  INTERACTION_CANCEL_EVENT,
300
303
  INTERACTION_EVENT,
@@ -382,6 +385,8 @@ import {
382
385
  mergeHistoryIntoParts,
383
386
  mintSandboxScopedToken,
384
387
  mintTerminalProxyToken,
388
+ peekWorkspaceSandbox,
389
+ readSandboxBinaryBytes,
385
390
  readSecret,
386
391
  resetClientCache,
387
392
  resolveModel,
@@ -392,7 +397,9 @@ import {
392
397
  sandboxToolPath,
393
398
  sandboxToolRootDir,
394
399
  secretStoreFromClient,
400
+ shellQuote,
395
401
  splitDeferredProfileFiles,
402
+ statSandboxFileSize,
396
403
  storeSecret,
397
404
  streamSandboxPrompt,
398
405
  syncSandboxMemberAdd,
@@ -402,7 +409,7 @@ import {
402
409
  verifySandboxTerminalToken,
403
410
  verifyTerminalProxyToken,
404
411
  writeProfileFilesToBox
405
- } from "./chunk-5GWXCSLQ.js";
412
+ } from "./chunk-5RJNEEO2.js";
406
413
  import {
407
414
  DEFAULT_HARNESS,
408
415
  KNOWN_HARNESSES,
@@ -743,6 +750,7 @@ export {
743
750
  invokeIntegrationHub,
744
751
  isAppToolName,
745
752
  isChatInteractionPart,
753
+ isChatMentionPart,
746
754
  isChatPlanPart,
747
755
  isChatStepFinishPart,
748
756
  isChatTextPart,
@@ -767,6 +775,8 @@ export {
767
775
  maskSpans,
768
776
  matchPreset,
769
777
  matchSandboxTerminalWsPath,
778
+ mentionInputToPart,
779
+ mentionPartsFromMessageParts,
770
780
  mergeExtraMcp,
771
781
  mergeHistoryIntoParts,
772
782
  mergeMissionState,
@@ -797,6 +807,7 @@ export {
797
807
  parsePlanSubmittedEvent,
798
808
  parseSequenceOperations,
799
809
  parseSessionStreamEnvelope,
810
+ peekWorkspaceSandbox,
800
811
  persistedPartToInteraction,
801
812
  persistedPartToPlan,
802
813
  planAuthorityIdempotencyKey,
@@ -811,6 +822,7 @@ export {
811
822
  pumpBufferedTurn,
812
823
  questionInteractionContentSignature,
813
824
  readCookieValue,
825
+ readSandboxBinaryBytes,
814
826
  readSecret,
815
827
  readToolArgs,
816
828
  recordDurableInteractionAnswer,
@@ -860,6 +872,7 @@ export {
860
872
  secondsToFrames,
861
873
  secretStoreFromClient,
862
874
  serializeCookie,
875
+ shellQuote,
863
876
  signObjectUrl,
864
877
  snapHarnessToModel,
865
878
  snapModelToHarness,
@@ -867,6 +880,7 @@ export {
867
880
  splitDeferredProfileFiles,
868
881
  stablePlanReceipt,
869
882
  stampInteractionAnswers,
883
+ statSandboxFileSize,
870
884
  stepActivityFlowTrace,
871
885
  stepAgentActivity,
872
886
  stepGateProposalId,