@tangle-network/agent-app 3.0.30 → 3.0.31

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,193 @@
1
+ // src/workspace-export/secrets.ts
2
+ var REDACTED = "[redacted]";
3
+ var MASK_BYTE = 42;
4
+ var CREDENTIAL_PATTERNS = [
5
+ String.raw`sk-ant-[A-Za-z0-9_-]{16,}`,
6
+ String.raw`sk-(?:proj-|tan-|or-v1-|svcacct-)?[A-Za-z0-9_-]{20,}`,
7
+ String.raw`(?:sk|rk)_(?:live|test|sb)_[A-Za-z0-9_]{12,}`,
8
+ String.raw`whsec_[A-Za-z0-9+/=]{16,}`,
9
+ String.raw`gh[pousr]_[A-Za-z0-9]{30,}`,
10
+ String.raw`github_pat_[A-Za-z0-9_]{40,}`,
11
+ String.raw`xox[abposr]-[A-Za-z0-9-]{10,}`,
12
+ String.raw`AKIA[0-9A-Z]{16}`,
13
+ String.raw`AIza[0-9A-Za-z_-]{35}`,
14
+ String.raw`ya29\.[0-9A-Za-z_-]{20,}`,
15
+ String.raw`glpat-[A-Za-z0-9_-]{20,}`,
16
+ String.raw`npm_[A-Za-z0-9]{36}`,
17
+ String.raw`hf_[A-Za-z0-9]{30,}`,
18
+ String.raw`r8_[A-Za-z0-9]{30,}`,
19
+ String.raw`gsk_[A-Za-z0-9]{40,}`,
20
+ String.raw`xai-[A-Za-z0-9]{40,}`,
21
+ String.raw`lak_[A-Za-z0-9_-]{16,}`,
22
+ String.raw`eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}`,
23
+ String.raw`-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[A-Za-z0-9+/=\r\n\t ]*(?:-----END [A-Z0-9 ]*PRIVATE KEY-----)?`
24
+ ];
25
+ var SECRET_NAME = /(^|_)(secret|secrets|password|passwd|passphrase|token|credential|credentials|ciphertext|encrypted|bearer|apikey|privatekey|cookie)(_|$)|api_?key|private_?key|(key|secret|token|password|challenge|state|nonce|credential)_(hash|digest)$/;
26
+ var TOKEN_METRIC = /token_(count|counts|usage|budget|limit|cost)$|^(input|output|total|max|prompt|completion|reasoning|cached)_tokens?$/;
27
+ function snake(name) {
28
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[-\s.]+/g, "_").toLowerCase();
29
+ }
30
+ function isSecretName(name) {
31
+ const folded = snake(name);
32
+ if (TOKEN_METRIC.test(folded)) return false;
33
+ return SECRET_NAME.test(folded);
34
+ }
35
+ function escapeRegExp(value) {
36
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
37
+ }
38
+ function createSecretScanner(options = {}) {
39
+ const known = [...new Set(options.knownSecrets ?? [])].filter((s) => typeof s === "string" && s.length >= 8).sort((a, b) => b.length - a.length).map(escapeRegExp);
40
+ const source = [...known, ...CREDENTIAL_PATTERNS].join("|");
41
+ const pattern = () => new RegExp(source, "g");
42
+ function maskText(text) {
43
+ let count = 0;
44
+ const out = text.replace(pattern(), () => {
45
+ count += 1;
46
+ return REDACTED;
47
+ });
48
+ return { text: out, count };
49
+ }
50
+ function redactJson(value, depth) {
51
+ if (typeof value === "string") {
52
+ const masked = maskText(value);
53
+ return { value: masked.text, count: masked.count };
54
+ }
55
+ if (depth > 64 || value === null || typeof value !== "object") return { value, count: 0 };
56
+ let count = 0;
57
+ if (Array.isArray(value)) {
58
+ const out2 = value.map((item) => {
59
+ const result = redactJson(item, depth + 1);
60
+ count += result.count;
61
+ return result.value;
62
+ });
63
+ return { value: out2, count };
64
+ }
65
+ const out = {};
66
+ for (const [key, item] of Object.entries(value)) {
67
+ if (isSecretName(key) && item !== null && item !== "" && typeof item !== "boolean") {
68
+ out[key] = REDACTED;
69
+ count += 1;
70
+ continue;
71
+ }
72
+ const result = redactJson(item, depth + 1);
73
+ out[key] = result.value;
74
+ count += result.count;
75
+ }
76
+ return { value: out, count };
77
+ }
78
+ function redactValue(value) {
79
+ if (typeof value === "string") {
80
+ const trimmed = value.trimStart();
81
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
82
+ try {
83
+ const parsed = JSON.parse(value);
84
+ const result = redactJson(parsed, 0);
85
+ return result.count ? { value: JSON.stringify(result.value), count: result.count } : { value, count: 0 };
86
+ } catch {
87
+ }
88
+ }
89
+ const masked = maskText(value);
90
+ return { value: masked.text, count: masked.count };
91
+ }
92
+ if (value instanceof Uint8Array || value instanceof ArrayBuffer) return { value, count: 0 };
93
+ return redactJson(value, 0);
94
+ }
95
+ function maskBytes(onMask) {
96
+ const window = 8192;
97
+ const maxCarry = 65536;
98
+ let carry = new Uint8Array(0);
99
+ function scan(buffer, final) {
100
+ const text = decodeBytes(buffer);
101
+ const regex = pattern();
102
+ let emitEnd = final ? buffer.length : Math.max(0, buffer.length - window);
103
+ let masked = 0;
104
+ for (let match = regex.exec(text); match; match = regex.exec(text)) {
105
+ const start = match.index;
106
+ const end = start + match[0].length;
107
+ if (match[0].length === 0) {
108
+ regex.lastIndex += 1;
109
+ continue;
110
+ }
111
+ if (!final && end === buffer.length) {
112
+ emitEnd = Math.min(emitEnd, start);
113
+ break;
114
+ }
115
+ buffer.fill(MASK_BYTE, start, end);
116
+ masked += 1;
117
+ }
118
+ if (masked) onMask(masked);
119
+ if (!final && buffer.length - emitEnd > maxCarry) emitEnd = buffer.length - window;
120
+ return emitEnd;
121
+ }
122
+ const block = 256 * 1024;
123
+ let pending = [];
124
+ let pendingLength = 0;
125
+ function drain(controller, final) {
126
+ const buffer = new Uint8Array(carry.length + pendingLength);
127
+ buffer.set(carry, 0);
128
+ let offset = carry.length;
129
+ for (const part of pending) {
130
+ buffer.set(part, offset);
131
+ offset += part.length;
132
+ }
133
+ pending = [];
134
+ pendingLength = 0;
135
+ const emitEnd = scan(buffer, final);
136
+ if (emitEnd > 0) controller.enqueue(buffer.slice(0, emitEnd));
137
+ carry = buffer.slice(emitEnd);
138
+ }
139
+ return new TransformStream({
140
+ transform(chunk, controller) {
141
+ pending.push(chunk);
142
+ pendingLength += chunk.length;
143
+ if (pendingLength >= block) drain(controller, false);
144
+ },
145
+ flush(controller) {
146
+ if (carry.length || pendingLength) drain(controller, true);
147
+ }
148
+ });
149
+ }
150
+ return { maskText, redactValue, maskBytes };
151
+ }
152
+ var nativeLatin1 = (() => {
153
+ try {
154
+ const decoder = new TextDecoder("latin1");
155
+ return decoder.decode(new Uint8Array([65, 128, 255])).length === 3 ? decoder : null;
156
+ } catch {
157
+ return null;
158
+ }
159
+ })();
160
+ function decodeBytes(buffer) {
161
+ if (nativeLatin1) return nativeLatin1.decode(buffer);
162
+ let text = "";
163
+ for (let i = 0; i < buffer.length; i += 8192) text += String.fromCharCode(...buffer.subarray(i, i + 8192));
164
+ return text;
165
+ }
166
+ var CREDENTIAL_FILES = [
167
+ /(^|\/)\.git-credentials$/,
168
+ /(^|\/)\.netrc$/,
169
+ /(^|\/)\.pgpass$/,
170
+ /(^|\/)\.npmrc$/,
171
+ /(^|\/)\.pypirc$/,
172
+ /(^|\/)\.docker\/config\.json$/,
173
+ /(^|\/)\.aws\/credentials$/,
174
+ /(^|\/)\.kube\/config$/,
175
+ /(^|\/)\.config\/gh\/hosts\.ya?ml$/,
176
+ /(^|\/)\.codex\/auth\.json$/,
177
+ /(^|\/)\.claude\/\.credentials\.json$/,
178
+ /(^|\/)opencode\/auth\.json$/,
179
+ /(^|\/)\.ssh\/id_[^/]*$/
180
+ ];
181
+ function isCredentialFile(path) {
182
+ const normalized = path.replace(/^\.\//, "");
183
+ if (normalized.endsWith(".pub")) return false;
184
+ return CREDENTIAL_FILES.some((pattern) => pattern.test(normalized));
185
+ }
186
+
187
+ export {
188
+ REDACTED,
189
+ isSecretName,
190
+ createSecretScanner,
191
+ isCredentialFile
192
+ };
193
+ //# sourceMappingURL=chunk-M4QITAQV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/workspace-export/secrets.ts"],"sourcesContent":["/**\n * Keeps credentials out of workspace exports.\n *\n * Three layers, applied to every byte an export writes:\n * 1. Column and JSON-key names that hold credentials are replaced with\n * `[redacted]` (`password`, `*_token`, `*_api_key`, `*_ciphertext`, ...).\n * 2. Values that look like credentials (provider key prefixes, JWTs, private\n * keys) and the exact values the product passes as `knownSecrets` are masked\n * wherever they appear: in row values, in nested JSON, and in file bytes.\n * 3. Well-known credential files inside a sandbox tar are blanked.\n *\n * Byte masking is same-length (`*`), so tar headers and offsets stay valid.\n * Everything here fails toward redaction: a false positive costs the owner one\n * masked value; a false negative would publish a credential.\n */\n\nexport const REDACTED = '[redacted]'\nconst MASK_BYTE = 0x2a\n\nconst CREDENTIAL_PATTERNS: readonly string[] = [\n String.raw`sk-ant-[A-Za-z0-9_-]{16,}`,\n String.raw`sk-(?:proj-|tan-|or-v1-|svcacct-)?[A-Za-z0-9_-]{20,}`,\n String.raw`(?:sk|rk)_(?:live|test|sb)_[A-Za-z0-9_]{12,}`,\n String.raw`whsec_[A-Za-z0-9+/=]{16,}`,\n String.raw`gh[pousr]_[A-Za-z0-9]{30,}`,\n String.raw`github_pat_[A-Za-z0-9_]{40,}`,\n String.raw`xox[abposr]-[A-Za-z0-9-]{10,}`,\n String.raw`AKIA[0-9A-Z]{16}`,\n String.raw`AIza[0-9A-Za-z_-]{35}`,\n String.raw`ya29\\.[0-9A-Za-z_-]{20,}`,\n String.raw`glpat-[A-Za-z0-9_-]{20,}`,\n String.raw`npm_[A-Za-z0-9]{36}`,\n String.raw`hf_[A-Za-z0-9]{30,}`,\n String.raw`r8_[A-Za-z0-9]{30,}`,\n String.raw`gsk_[A-Za-z0-9]{40,}`,\n String.raw`xai-[A-Za-z0-9]{40,}`,\n String.raw`lak_[A-Za-z0-9_-]{16,}`,\n String.raw`eyJ[A-Za-z0-9_-]{10,}\\.eyJ[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}`,\n String.raw`-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[A-Za-z0-9+/=\\r\\n\\t ]*(?:-----END [A-Z0-9 ]*PRIVATE KEY-----)?`,\n]\n\n/** Names whose value is a credential, after camelCase is folded to snake_case. */\nconst SECRET_NAME =\n /(^|_)(secret|secrets|password|passwd|passphrase|token|credential|credentials|ciphertext|encrypted|bearer|apikey|privatekey|cookie)(_|$)|api_?key|private_?key|(key|secret|token|password|challenge|state|nonce|credential)_(hash|digest)$/\n/** Usage counters that merely mention tokens. */\nconst TOKEN_METRIC = /token_(count|counts|usage|budget|limit|cost)$|^(input|output|total|max|prompt|completion|reasoning|cached)_tokens?$/\n\nfunction snake(name: string): string {\n return name\n .replace(/([a-z0-9])([A-Z])/g, '$1_$2')\n .replace(/[-\\s.]+/g, '_')\n .toLowerCase()\n}\n\n/** True when a column or JSON key named `name` holds a credential. */\nexport function isSecretName(name: string): boolean {\n const folded = snake(name)\n if (TOKEN_METRIC.test(folded)) return false\n return SECRET_NAME.test(folded)\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nexport interface SecretScanner {\n /** Replace credential-shaped substrings. Returns the count replaced. */\n maskText(text: string): { text: string; count: number }\n /** Redact a row or any JSON value: credential names and credential values. */\n redactValue(value: unknown): { value: unknown; count: number }\n /** A same-length byte masker for file contents. `onMask` receives each count. */\n maskBytes(onMask: (count: number) => void): TransformStream<Uint8Array, Uint8Array>\n}\n\n/**\n * Build the scanner for one export. `knownSecrets` are exact values the product\n * holds (its own API keys, the workspace's sandbox key) that must never appear,\n * whatever their shape. Values shorter than 8 characters are ignored.\n */\nexport function createSecretScanner(options: { knownSecrets?: readonly string[] } = {}): SecretScanner {\n const known = [...new Set(options.knownSecrets ?? [])]\n .filter((s) => typeof s === 'string' && s.length >= 8)\n .sort((a, b) => b.length - a.length)\n .map(escapeRegExp)\n const source = [...known, ...CREDENTIAL_PATTERNS].join('|')\n const pattern = () => new RegExp(source, 'g')\n\n function maskText(text: string): { text: string; count: number } {\n let count = 0\n const out = text.replace(pattern(), () => {\n count += 1\n return REDACTED\n })\n return { text: out, count }\n }\n\n function redactJson(value: unknown, depth: number): { value: unknown; count: number } {\n if (typeof value === 'string') {\n const masked = maskText(value)\n return { value: masked.text, count: masked.count }\n }\n if (depth > 64 || value === null || typeof value !== 'object') return { value, count: 0 }\n let count = 0\n if (Array.isArray(value)) {\n const out = value.map((item) => {\n const result = redactJson(item, depth + 1)\n count += result.count\n return result.value\n })\n return { value: out, count }\n }\n const out: Record<string, unknown> = {}\n for (const [key, item] of Object.entries(value)) {\n if (isSecretName(key) && item !== null && item !== '' && typeof item !== 'boolean') {\n out[key] = REDACTED\n count += 1\n continue\n }\n const result = redactJson(item, depth + 1)\n out[key] = result.value\n count += result.count\n }\n return { value: out, count }\n }\n\n function redactValue(value: unknown): { value: unknown; count: number } {\n if (typeof value === 'string') {\n const trimmed = value.trimStart()\n if (trimmed.startsWith('{') || trimmed.startsWith('[')) {\n try {\n const parsed = JSON.parse(value) as unknown\n const result = redactJson(parsed, 0)\n return result.count ? { value: JSON.stringify(result.value), count: result.count } : { value, count: 0 }\n } catch {\n // Not JSON; scan it as text.\n }\n }\n const masked = maskText(value)\n return { value: masked.text, count: masked.count }\n }\n if (value instanceof Uint8Array || value instanceof ArrayBuffer) return { value, count: 0 }\n return redactJson(value, 0)\n }\n\n function maskBytes(onMask: (count: number) => void): TransformStream<Uint8Array, Uint8Array> {\n // Keep a tail so a credential split across two chunks is seen whole.\n const window = 8192\n const maxCarry = 65536\n let carry = new Uint8Array(0)\n\n function scan(buffer: Uint8Array, final: boolean): number {\n const text = decodeBytes(buffer)\n const regex = pattern()\n let emitEnd = final ? buffer.length : Math.max(0, buffer.length - window)\n let masked = 0\n for (let match = regex.exec(text); match; match = regex.exec(text)) {\n const start = match.index\n const end = start + match[0].length\n if (match[0].length === 0) {\n regex.lastIndex += 1\n continue\n }\n if (!final && end === buffer.length) {\n // Possibly truncated; leave it for the next chunk to see whole.\n emitEnd = Math.min(emitEnd, start)\n break\n }\n buffer.fill(MASK_BYTE, start, end)\n masked += 1\n }\n if (masked) onMask(masked)\n if (!final && buffer.length - emitEnd > maxCarry) emitEnd = buffer.length - window\n return emitEnd\n }\n\n // Decompressors emit small chunks. Scanning each one re-reads the carry\n // window, which cost 4x on 4 KiB chunks, so input is gathered into blocks.\n const block = 256 * 1024\n let pending: Uint8Array[] = []\n let pendingLength = 0\n\n function drain(controller: TransformStreamDefaultController<Uint8Array>, final: boolean) {\n const buffer = new Uint8Array(carry.length + pendingLength)\n buffer.set(carry, 0)\n let offset = carry.length\n for (const part of pending) {\n buffer.set(part, offset)\n offset += part.length\n }\n pending = []\n pendingLength = 0\n const emitEnd = scan(buffer, final)\n if (emitEnd > 0) controller.enqueue(buffer.slice(0, emitEnd))\n carry = buffer.slice(emitEnd)\n }\n\n return new TransformStream<Uint8Array, Uint8Array>({\n transform(chunk, controller) {\n pending.push(chunk)\n pendingLength += chunk.length\n if (pendingLength >= block) drain(controller, false)\n },\n flush(controller) {\n if (carry.length || pendingLength) drain(controller, true)\n },\n })\n }\n\n return { maskText, redactValue, maskBytes }\n}\n\n/**\n * One UTF-16 code unit per byte, so string indexes are byte offsets. A native\n * windows-1252 decoder keeps that property and is several times faster; the\n * manual decode covers runtimes whose TextDecoder lacks it.\n */\nconst nativeLatin1 = (() => {\n try {\n const decoder = new TextDecoder('latin1')\n return decoder.decode(new Uint8Array([0x41, 0x80, 0xff])).length === 3 ? decoder : null\n } catch {\n return null\n }\n})()\n\nfunction decodeBytes(buffer: Uint8Array): string {\n if (nativeLatin1) return nativeLatin1.decode(buffer)\n let text = ''\n for (let i = 0; i < buffer.length; i += 8192) text += String.fromCharCode(...buffer.subarray(i, i + 8192))\n return text\n}\n\n/** Credential stores that are blanked wholesale inside a sandbox archive. */\nconst CREDENTIAL_FILES = [\n /(^|\\/)\\.git-credentials$/,\n /(^|\\/)\\.netrc$/,\n /(^|\\/)\\.pgpass$/,\n /(^|\\/)\\.npmrc$/,\n /(^|\\/)\\.pypirc$/,\n /(^|\\/)\\.docker\\/config\\.json$/,\n /(^|\\/)\\.aws\\/credentials$/,\n /(^|\\/)\\.kube\\/config$/,\n /(^|\\/)\\.config\\/gh\\/hosts\\.ya?ml$/,\n /(^|\\/)\\.codex\\/auth\\.json$/,\n /(^|\\/)\\.claude\\/\\.credentials\\.json$/,\n /(^|\\/)opencode\\/auth\\.json$/,\n /(^|\\/)\\.ssh\\/id_[^/]*$/,\n]\n\nexport function isCredentialFile(path: string): boolean {\n const normalized = path.replace(/^\\.\\//, '')\n if (normalized.endsWith('.pub')) return false\n return CREDENTIAL_FILES.some((pattern) => pattern.test(normalized))\n}\n"],"mappings":";AAgBO,IAAM,WAAW;AACxB,IAAM,YAAY;AAElB,IAAM,sBAAyC;AAAA,EAC7C,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AAAA,EACP,OAAO;AACT;AAGA,IAAM,cACJ;AAEF,IAAM,eAAe;AAErB,SAAS,MAAM,MAAsB;AACnC,SAAO,KACJ,QAAQ,sBAAsB,OAAO,EACrC,QAAQ,YAAY,GAAG,EACvB,YAAY;AACjB;AAGO,SAAS,aAAa,MAAuB;AAClD,QAAM,SAAS,MAAM,IAAI;AACzB,MAAI,aAAa,KAAK,MAAM,EAAG,QAAO;AACtC,SAAO,YAAY,KAAK,MAAM;AAChC;AAEA,SAAS,aAAa,OAAuB;AAC3C,SAAO,MAAM,QAAQ,uBAAuB,MAAM;AACpD;AAgBO,SAAS,oBAAoB,UAAgD,CAAC,GAAkB;AACrG,QAAM,QAAQ,CAAC,GAAG,IAAI,IAAI,QAAQ,gBAAgB,CAAC,CA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;AAAA,EACT;AACF,GAAG;AAEH,SAAS,YAAY,QAA4B;AAC/C,MAAI,aAAc,QAAO,aAAa,OAAO,MAAM;AACnD,MAAI,OAAO;AACX,WAAS,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK,KAAM,SAAQ,OAAO,aAAa,GAAG,OAAO,SAAS,GAAG,IAAI,IAAI,CAAC;AACzG,SAAO;AACT;AAGA,IAAM,mBAAmB;AAAA,EACvB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,SAAS,iBAAiB,MAAuB;AACtD,QAAM,aAAa,KAAK,QAAQ,SAAS,EAAE;AAC3C,MAAI,WAAW,SAAS,MAAM,EAAG,QAAO;AACxC,SAAO,iBAAiB,KAAK,CAAC,YAAY,QAAQ,KAAK,UAAU,CAAC;AACpE;","names":["out"]}
@@ -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';
@@ -1,12 +1,13 @@
1
1
  import {
2
2
  createChatTurnRoutes,
3
3
  streamChatRouteAsSandboxEvents
4
- } from "../chunk-LRUH36LD.js";
4
+ } from "../chunk-HP5KD7ZI.js";
5
5
  import "../chunk-SBHFMDR7.js";
6
6
  import "../chunk-H6BRJU5M.js";
7
7
  import "../chunk-4DBHC63F.js";
8
8
  import "../chunk-RN4WPTBH.js";
9
9
  import "../chunk-MM6RLOXF.js";
10
+ import "../chunk-M4QITAQV.js";
10
11
  import "../chunk-3FKIGI3I.js";
11
12
  import "../chunk-F4TUZYMX.js";
12
13
  import "../chunk-MH74DY2I.js";
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/public-consultation/index.ts"],"sourcesContent":["import { searchKnowledge, type KnowledgeIndex, type KnowledgePage } from '@tangle-network/agent-knowledge'\nimport { createChatTurnRoutes, type ChatTurnExecutionLimits, type ChatTurnLock, type ChatTurnMessageStore, type ChatTurnRouteProducer } from '../chat-routes/turn-routes'\nimport { streamChatRouteAsSandboxEvents } from '../chat-routes/gateway-adapter'\nimport type { TurnEventStore } from '../stream/turn-buffer'\nimport type { McpToolDefinition } from '../tools/mcp-rpc'\n\nexport interface PublishedKnowledgePage {\n readonly id: string\n readonly title: string\n readonly text: string\n}\n\n/** A server-created publication. Every selected page's complete text is public. */\nexport interface KnowledgePublication {\n readonly id: string\n readonly revision: string\n readonly ownerId: string\n readonly systemPrompt: string\n read(pageId: string): PublishedKnowledgePage | null\n search(query: string): PublishedKnowledgePage[]\n}\n\n/** Select content at publication time, before any payer or model input exists. */\nexport function createKnowledgePublication(input: {\n id: string\n revision: string\n ownerId: string\n systemPrompt: string\n index: KnowledgeIndex\n pageIds: readonly string[]\n}): KnowledgePublication {\n for (const value of [input.id, input.revision, input.ownerId]) requireIdentity(value)\n const pages: KnowledgePage[] = []\n for (const id of new Set(input.pageIds)) {\n const matches = input.index.pages.filter(page => page.id === id)\n if (matches.length !== 1) throw new Error('Publication page must resolve exactly once')\n const page = matches[0]!\n // Owner metadata, paths, links and source records can refer to private resources.\n pages.push({ id: page.id, title: page.title, text: page.text, path: page.id,\n frontmatter: {}, sourceIds: [], tags: [], outLinks: [] })\n }\n const index: KnowledgeIndex = { root: '', generatedAt: '', sources: [], pages, graph: { nodes: [], edges: [] } }\n const publicPage = (page: KnowledgePage): PublishedKnowledgePage =>\n Object.freeze({ id: page.id, title: page.title, text: page.text })\n return Object.freeze({\n id: input.id, revision: input.revision, ownerId: input.ownerId, systemPrompt: input.systemPrompt,\n read: (id: string) => {\n const page = pages.find(candidate => candidate.id === id)\n return page ? publicPage(page) : null\n },\n search: (query: string) => searchKnowledge(index, query, { limit: 10 }).map(hit => publicPage(hit.page)),\n })\n}\n\n/** Authenticated server identity. Never construct this from model arguments or request JSON. */\nexport interface ConsultationConsumer {\n method: string\n consumerId: string\n keyId?: string\n ownerId?: string\n requestId: string\n threadId?: string\n}\n\nexport interface ConsultationAgent {\n id: string\n ownerId: string\n}\n\nexport interface ConsultationIdentity {\n readonly publicationId: string\n readonly publicationRevision: string\n readonly consumerId: string\n readonly paymentMethod: string\n readonly workspaceId: string\n readonly threadId: string\n}\n\nexport interface ConsultationExecutionControl {\n readonly identity: ConsultationIdentity\n readonly signal: AbortSignal\n readonly executionLimits?: Readonly<ChatTurnExecutionLimits>\n}\n\nexport type PreparedConsultationExecution =\n | { status: 'unsupported'; reason: string }\n | { status: 'prepared'; produce(input: ConsultationExecution): ChatTurnRouteProducer | Promise<ChatTurnRouteProducer> }\n\nexport interface ConsultationExecution extends ConsultationExecutionControl {\n readonly identity: ConsultationIdentity\n readonly systemPrompt: string\n readonly prompt: string\n readonly priorMessages: ReadonlyArray<{ role: string; content: string }>\n readonly tools: McpToolDefinition[]\n}\n\nexport interface PublicConsultationOptions {\n /** Resolve only deliberately published snapshots. Return null after revocation. */\n resolvePublication(agentId: string): Promise<KnowledgePublication | null>\n /** Payment authentication does not substitute for this admission decision. */\n allowConsumer(publication: KnowledgePublication, consumer: ConsultationConsumer): Promise<boolean>\n store: ChatTurnMessageStore\n turnStore: TurnEventStore\n /** Shared durable single-flight lock. Use createDurableTurnLock with thread scope. */\n turnLock: ChatTurnLock<void>\n /** Create or read the stored parent row. Return its actual persisted ownership. */\n ensureConversation(identity: ConsultationIdentity): Promise<{ workspaceId: string; threadId: string }>\n /** Prepare without compute. Refuse limits the isolated executor cannot enforce across all model and tool calls. */\n prepareExecution(input: ConsultationExecutionControl): Promise<PreparedConsultationExecution>\n}\n\ninterface GatewayConsultationContext {\n consumerId: string\n paymentMethod: string\n requestId: string\n threadId?: string\n keyInfo: { keyId: string; ownerId?: string } | null\n messages: Array<{ role: string; content: string }>\n}\n\n/** Compose gateway admission, scoped knowledge and the maintained persisted chat route. */\nexport function createPublicConsultation(options: PublicConsultationOptions) {\n if (typeof options.turnLock?.acquire !== 'function' || typeof options.turnLock.release !== 'function') {\n throw new Error('Public consultation requires a shared turn lock')\n }\n async function ownsConversation(identity: ConsultationIdentity) {\n const conversation = await options.ensureConversation(identity)\n return conversation?.workspaceId === identity.workspaceId && conversation.threadId === identity.threadId\n }\n async function resolve(agent: ConsultationAgent, consumer: ConsultationConsumer) {\n requireIdentity(consumer.consumerId)\n requireIdentity(consumer.method)\n requireIdentity(consumer.threadId)\n const publication = await options.resolvePublication(agent.id)\n if (!publication || publication.id !== agent.id || publication.ownerId !== agent.ownerId\n || await options.allowConsumer(publication, consumer) !== true) return null\n const workspaceId = await scopedId([publication.ownerId, publication.id, publication.revision, consumer.method, consumer.consumerId])\n const threadId = await scopedId([workspaceId, consumer.threadId!])\n const identity: ConsultationIdentity = Object.freeze({\n publicationId: publication.id, publicationRevision: publication.revision,\n consumerId: consumer.consumerId, paymentMethod: consumer.method, workspaceId, threadId,\n })\n return { publication, identity }\n }\n\n return {\n async authorizeConsumer(agent: ConsultationAgent, consumer: ConsultationConsumer) {\n const scope = await resolve(agent, consumer)\n return scope\n ? { allow: true as const }\n : { allow: false as const, reason: 'Consultation access denied', code: 'consultation_forbidden' }\n },\n async readKnowledge(agent: ConsultationAgent, consumer: ConsultationConsumer, pageId: string) {\n const scope = await resolve(agent, consumer)\n if (!scope) throw new Error('Consultation access denied')\n return scope.publication.read(pageId)\n },\n async readHistory(agent: ConsultationAgent, consumer: ConsultationConsumer) {\n const scope = await resolve(agent, consumer)\n if (!scope) throw new Error('Consultation access denied')\n if (!await ownsConversation(scope.identity)) throw new Error('Consultation conversation conflict')\n return (await options.store.listMessages(scope.identity.threadId))\n .map(({ role, content }) => ({ role, content }))\n },\n async getSandbox(agent: ConsultationAgent, context?: GatewayConsultationContext) {\n if (!context) throw new Error('Authenticated consultation identity is required')\n const consumer: ConsultationConsumer = {\n consumerId: context.consumerId, method: context.paymentMethod,\n requestId: context.requestId, threadId: context.threadId,\n keyId: context.keyInfo?.keyId, ownerId: context.keyInfo?.ownerId,\n }\n const scope = await resolve(agent, consumer)\n if (!scope) throw new Error('Consultation access denied')\n // Client-supplied history and owner system prompts never enter this producer.\n const prompt = context.messages.filter(message => message.role === 'user').at(-1)?.content\n if (!prompt) throw new Error('Consultation requires a user message')\n type PromptOptions = { signal?: AbortSignal; executionBudget?: ChatTurnExecutionLimits; maxOutputTokens?: number }\n const prepare = async (streamOptions?: PromptOptions) => {\n const signal = streamOptions?.signal ?? new AbortController().signal\n signal.throwIfAborted()\n const supplied = streamOptions?.executionBudget\n const executionLimits = supplied || streamOptions?.maxOutputTokens !== undefined\n ? Object.freeze({ ...supplied, ...(streamOptions?.maxOutputTokens !== undefined\n ? { maxOutputTokens: Math.min(streamOptions.maxOutputTokens, supplied?.maxOutputTokens ?? Infinity) } : {}) })\n : undefined\n if (executionLimits && Object.values(executionLimits).some(value => typeof value !== 'number' || !Number.isFinite(value) || value < 0)) {\n return { status: 'unsupported' as const, reason: 'Invalid consultation execution limits' }\n }\n const control = Object.freeze({ identity: scope.identity, signal, executionLimits })\n const prepared = await options.prepareExecution(control)\n signal.throwIfAborted()\n if (prepared?.status !== 'prepared' || typeof prepared.produce !== 'function') {\n return { status: 'unsupported' as const, reason: prepared?.status === 'unsupported'\n ? prepared.reason : 'Invalid consultation execution preparation' }\n }\n let started = false\n const start = () => {\n signal.throwIfAborted()\n if (started) throw new Error('Consultation execution already started')\n started = true\n const routes = createChatTurnRoutes({\n projectId: 'public-consultation', store: options.store, turnStore: options.turnStore, turnLock: options.turnLock,\n authorize: async ({ intent, body }) => {\n const current = await resolve(agent, consumer)\n if (intent !== 'turn' || !current\n || current.identity.workspaceId !== scope.identity.workspaceId\n || body?.workspaceId !== scope.identity.workspaceId || body.threadId !== scope.identity.threadId) {\n return { ok: false, response: Response.json({ error: 'Consultation access denied' }, { status: 403 }) }\n }\n if (!await ownsConversation(scope.identity)) {\n return { ok: false, response: Response.json({ error: 'Consultation conversation conflict' }, { status: 403 }) }\n }\n return { ok: true, tenantId: scope.identity.workspaceId,\n userId: scope.identity.consumerId, context: undefined }\n },\n produce: args => {\n signal.throwIfAborted()\n return prepared.produce({\n ...control,\n identity: scope.identity, systemPrompt: scope.publication.systemPrompt, prompt,\n priorMessages: args.priorMessages.map(({ role, content }) => ({ role, content })),\n tools: publicationTools(scope.publication, async () => {\n signal.throwIfAborted()\n const current = await resolve(agent, consumer)\n signal.throwIfAborted()\n if (!current || current.identity.workspaceId !== scope.identity.workspaceId) {\n throw new Error('Consultation access denied')\n }\n }),\n })\n },\n })\n return streamChatRouteAsSandboxEvents({\n routes, request: new Request('https://consultation.invalid/internal'),\n payload: { workspaceId: scope.identity.workspaceId, threadId: scope.identity.threadId,\n content: prompt, turnId: consumer.requestId }, signal, executionLimits,\n })\n }\n return { status: 'prepared' as const, start }\n }\n return {\n prepareBudgetedPrompt: (_message: string, streamOptions: PromptOptions) => prepare(streamOptions),\n streamPrompt: async function* (_message: string, streamOptions?: PromptOptions) {\n const prepared = await prepare(streamOptions)\n if (prepared.status !== 'prepared') throw new Error(prepared.reason)\n yield* prepared.start()\n },\n }\n },\n }\n}\n\nfunction publicationTools(publication: KnowledgePublication, authorize: () => Promise<void>): McpToolDefinition[] {\n return [\n { name: 'knowledge_search', description: 'Search published consultation knowledge.',\n inputSchema: { type: 'object', required: ['query'], properties: { query: { type: 'string' } }, additionalProperties: false },\n run: async args => { await authorize(); return publication.search(singleArgument(args, 'query')) } },\n { name: 'knowledge_read', description: 'Read a published page by its exact citation id.',\n inputSchema: { type: 'object', required: ['pageId'], properties: { pageId: { type: 'string' } }, additionalProperties: false },\n run: async args => { await authorize(); return publication.read(singleArgument(args, 'pageId')) } },\n ]\n}\n\nfunction singleArgument(args: Record<string, unknown>, name: string): string {\n const value = args[name]\n if (Object.keys(args).length !== 1 || typeof value !== 'string' || !value.trim() || value.length > 8192) {\n throw new Error('Invalid published knowledge arguments')\n }\n return value\n}\n\nfunction requireIdentity(value: unknown): asserts value is string {\n if (typeof value !== 'string' || !value.trim() || value.length > 512) throw new Error('Invalid consultation identity')\n}\n\nasync function scopedId(parts: string[]): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify(parts)))\n return `consultation:${Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('')}`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,uBAAgE;AAuBlE,SAAS,2BAA2B,OAOlB;AACvB,aAAW,SAAS,CAAC,MAAM,IAAI,MAAM,UAAU,MAAM,OAAO,EAAG,iBAAgB,KAAK;AACpF,QAAM,QAAyB,CAAC;AAChC,aAAW,MAAM,IAAI,IAAI,MAAM,OAAO,GAAG;AACvC,UAAM,UAAU,MAAM,MAAM,MAAM,OAAO,CAAAA,UAAQA,MAAK,OAAO,EAAE;AAC/D,QAAI,QAAQ,WAAW,EAAG,OAAM,IAAI,MAAM,4CAA4C;AACtF,UAAM,OAAO,QAAQ,CAAC;AAEtB,UAAM,KAAK;AAAA,MAAE,IAAI,KAAK;AAAA,MAAI,OAAO,KAAK;AAAA,MAAO,MAAM,KAAK;AAAA,MAAM,MAAM,KAAK;AAAA,MACvE,aAAa,CAAC;AAAA,MAAG,WAAW,CAAC;AAAA,MAAG,MAAM,CAAC;AAAA,MAAG,UAAU,CAAC;AAAA,IAAE,CAAC;AAAA,EAC5D;AACA,QAAM,QAAwB,EAAE,MAAM,IAAI,aAAa,IAAI,SAAS,CAAC,GAAG,OAAO,OAAO,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,EAAE,EAAE;AAC/G,QAAM,aAAa,CAAC,SAClB,OAAO,OAAO,EAAE,IAAI,KAAK,IAAI,OAAO,KAAK,OAAO,MAAM,KAAK,KAAK,CAAC;AACnE,SAAO,OAAO,OAAO;AAAA,IACn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,QAAQ,KAAK,IAAI;AACvB,MAAI,OAAO,KAAK,IAAI,EAAE,WAAW,KAAK,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,KAAK,MAAM,SAAS,MAAM;AACvG,UAAM,IAAI,MAAM,uCAAuC;AAAA,EACzD;AACA,SAAO;AACT;AAEA,SAAS,gBAAgB,OAAyC;AAChE,MAAI,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,KAAK,MAAM,SAAS,IAAK,OAAM,IAAI,MAAM,+BAA+B;AACvH;AAEA,eAAe,SAAS,OAAkC;AACxD,QAAM,SAAS,MAAM,OAAO,OAAO,OAAO,WAAW,IAAI,YAAY,EAAE,OAAO,KAAK,UAAU,KAAK,CAAC,CAAC;AACpG,SAAO,gBAAgB,MAAM,KAAK,IAAI,WAAW,MAAM,GAAG,UAAQ,KAAK,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC,EAAE,KAAK,EAAE,CAAC;AAChH;","names":["page"]}
1
+ {"version":3,"sources":["../../src/public-consultation/index.ts"],"sourcesContent":["import { searchKnowledge, type KnowledgeIndex, type KnowledgePage } from '@tangle-network/agent-knowledge'\nimport { createChatTurnRoutes, type ChatTurnExecutionLimits, type ChatTurnLock, type ChatTurnMessageStore, type ChatTurnRouteProducer } from '../chat-routes/turn-routes'\nimport { streamChatRouteAsSandboxEvents } from '../chat-routes/gateway-adapter'\nimport type { TurnEventStore } from '../stream/turn-buffer'\nimport type { McpToolDefinition } from '../tools/mcp-rpc'\n\nexport interface PublishedKnowledgePage {\n readonly id: string\n readonly title: string\n readonly text: string\n}\n\n/** A server-created publication. Every selected page's complete text is public. */\nexport interface KnowledgePublication {\n readonly id: string\n readonly revision: string\n readonly ownerId: string\n readonly systemPrompt: string\n read(pageId: string): PublishedKnowledgePage | null\n search(query: string): PublishedKnowledgePage[]\n}\n\n/** Select content at publication time, before any payer or model input exists. */\nexport function createKnowledgePublication(input: {\n id: string\n revision: string\n ownerId: string\n systemPrompt: string\n index: KnowledgeIndex\n pageIds: readonly string[]\n}): KnowledgePublication {\n for (const value of [input.id, input.revision, input.ownerId]) requireIdentity(value)\n const pages: KnowledgePage[] = []\n for (const id of new Set(input.pageIds)) {\n const matches = input.index.pages.filter(page => page.id === id)\n if (matches.length !== 1) throw new Error('Publication page must resolve exactly once')\n const page = matches[0]!\n // Owner metadata, paths, links and source records can refer to private resources.\n pages.push({ id: page.id, title: page.title, text: page.text, path: page.id,\n frontmatter: {}, sourceIds: [], tags: [], outLinks: [] })\n }\n const index: KnowledgeIndex = { root: '', generatedAt: '', sources: [], pages, graph: { nodes: [], edges: [] } }\n const publicPage = (page: KnowledgePage): PublishedKnowledgePage =>\n Object.freeze({ id: page.id, title: page.title, text: page.text })\n return Object.freeze({\n id: input.id, revision: input.revision, ownerId: input.ownerId, systemPrompt: input.systemPrompt,\n read: (id: string) => {\n const page = pages.find(candidate => candidate.id === id)\n return page ? publicPage(page) : null\n },\n search: (query: string) => searchKnowledge(index, query, { limit: 10 }).map(hit => publicPage(hit.page)),\n })\n}\n\n/** Authenticated server identity. Never construct this from model arguments or request JSON. */\nexport interface ConsultationConsumer {\n method: string\n consumerId: string\n keyId?: string\n ownerId?: string\n requestId: string\n threadId?: string\n}\n\nexport interface ConsultationAgent {\n id: string\n ownerId: string\n}\n\nexport interface ConsultationIdentity {\n readonly publicationId: string\n readonly publicationRevision: string\n readonly consumerId: string\n readonly paymentMethod: string\n readonly workspaceId: string\n readonly threadId: string\n}\n\nexport interface ConsultationExecutionControl {\n readonly identity: ConsultationIdentity\n readonly signal: AbortSignal\n readonly executionLimits?: Readonly<ChatTurnExecutionLimits>\n}\n\nexport type PreparedConsultationExecution =\n | { status: 'unsupported'; reason: string }\n | { status: 'prepared'; produce(input: ConsultationExecution): ChatTurnRouteProducer | Promise<ChatTurnRouteProducer> }\n\nexport interface ConsultationExecution extends ConsultationExecutionControl {\n readonly identity: ConsultationIdentity\n readonly systemPrompt: string\n readonly prompt: string\n readonly priorMessages: ReadonlyArray<{ role: string; content: string }>\n readonly tools: McpToolDefinition[]\n}\n\nexport interface PublicConsultationOptions {\n /** Resolve only deliberately published snapshots. Return null after revocation. */\n resolvePublication(agentId: string): Promise<KnowledgePublication | null>\n /** Payment authentication does not substitute for this admission decision. */\n allowConsumer(publication: KnowledgePublication, consumer: ConsultationConsumer): Promise<boolean>\n store: ChatTurnMessageStore\n turnStore: TurnEventStore\n /** Shared durable single-flight lock. Use createDurableTurnLock with thread scope. */\n turnLock: ChatTurnLock<void>\n /** Create or read the stored parent row. Return its actual persisted ownership. */\n ensureConversation(identity: ConsultationIdentity): Promise<{ workspaceId: string; threadId: string }>\n /** Prepare without compute. Refuse limits the isolated executor cannot enforce across all model and tool calls. */\n prepareExecution(input: ConsultationExecutionControl): Promise<PreparedConsultationExecution>\n}\n\ninterface GatewayConsultationContext {\n consumerId: string\n paymentMethod: string\n requestId: string\n threadId?: string\n keyInfo: { keyId: string; ownerId?: string } | null\n messages: Array<{ role: string; content: string }>\n}\n\n/** Compose gateway admission, scoped knowledge and the maintained persisted chat route. */\nexport function createPublicConsultation(options: PublicConsultationOptions) {\n if (typeof options.turnLock?.acquire !== 'function' || typeof options.turnLock.release !== 'function') {\n throw new Error('Public consultation requires a shared turn lock')\n }\n async function ownsConversation(identity: ConsultationIdentity) {\n const conversation = await options.ensureConversation(identity)\n return conversation?.workspaceId === identity.workspaceId && conversation.threadId === identity.threadId\n }\n async function resolve(agent: ConsultationAgent, consumer: ConsultationConsumer) {\n requireIdentity(consumer.consumerId)\n requireIdentity(consumer.method)\n requireIdentity(consumer.threadId)\n const publication = await options.resolvePublication(agent.id)\n if (!publication || publication.id !== agent.id || publication.ownerId !== agent.ownerId\n || await options.allowConsumer(publication, consumer) !== true) return null\n const workspaceId = await scopedId([publication.ownerId, publication.id, publication.revision, consumer.method, consumer.consumerId])\n const threadId = await scopedId([workspaceId, consumer.threadId!])\n const identity: ConsultationIdentity = Object.freeze({\n publicationId: publication.id, publicationRevision: publication.revision,\n consumerId: consumer.consumerId, paymentMethod: consumer.method, workspaceId, threadId,\n })\n return { publication, identity }\n }\n\n return {\n async authorizeConsumer(agent: ConsultationAgent, consumer: ConsultationConsumer) {\n const scope = await resolve(agent, consumer)\n return scope\n ? { allow: true as const }\n : { allow: false as const, reason: 'Consultation access denied', code: 'consultation_forbidden' }\n },\n async readKnowledge(agent: ConsultationAgent, consumer: ConsultationConsumer, pageId: string) {\n const scope = await resolve(agent, consumer)\n if (!scope) throw new Error('Consultation access denied')\n return scope.publication.read(pageId)\n },\n async readHistory(agent: ConsultationAgent, consumer: ConsultationConsumer) {\n const scope = await resolve(agent, consumer)\n if (!scope) throw new Error('Consultation access denied')\n if (!await ownsConversation(scope.identity)) throw new Error('Consultation conversation conflict')\n return (await options.store.listMessages(scope.identity.threadId))\n .map(({ role, content }) => ({ role, content }))\n },\n async getSandbox(agent: ConsultationAgent, context?: GatewayConsultationContext) {\n if (!context) throw new Error('Authenticated consultation identity is required')\n const consumer: ConsultationConsumer = {\n consumerId: context.consumerId, method: context.paymentMethod,\n requestId: context.requestId, threadId: context.threadId,\n keyId: context.keyInfo?.keyId, ownerId: context.keyInfo?.ownerId,\n }\n const scope = await resolve(agent, consumer)\n if (!scope) throw new Error('Consultation access denied')\n // Client-supplied history and owner system prompts never enter this producer.\n const prompt = context.messages.filter(message => message.role === 'user').at(-1)?.content\n if (!prompt) throw new Error('Consultation requires a user message')\n type PromptOptions = { signal?: AbortSignal; executionBudget?: ChatTurnExecutionLimits; maxOutputTokens?: number }\n const prepare = async (streamOptions?: PromptOptions) => {\n const signal = streamOptions?.signal ?? new AbortController().signal\n signal.throwIfAborted()\n const supplied = streamOptions?.executionBudget\n const executionLimits = supplied || streamOptions?.maxOutputTokens !== undefined\n ? Object.freeze({ ...supplied, ...(streamOptions?.maxOutputTokens !== undefined\n ? { maxOutputTokens: Math.min(streamOptions.maxOutputTokens, supplied?.maxOutputTokens ?? Infinity) } : {}) })\n : undefined\n if (executionLimits && Object.values(executionLimits).some(value => typeof value !== 'number' || !Number.isFinite(value) || value < 0)) {\n return { status: 'unsupported' as const, reason: 'Invalid consultation execution limits' }\n }\n const control = Object.freeze({ identity: scope.identity, signal, executionLimits })\n const prepared = await options.prepareExecution(control)\n signal.throwIfAborted()\n if (prepared?.status !== 'prepared' || typeof prepared.produce !== 'function') {\n return { status: 'unsupported' as const, reason: prepared?.status === 'unsupported'\n ? prepared.reason : 'Invalid consultation execution preparation' }\n }\n let started = false\n const start = () => {\n signal.throwIfAborted()\n if (started) throw new Error('Consultation execution already started')\n started = true\n const routes = createChatTurnRoutes({\n projectId: 'public-consultation', store: options.store, turnStore: options.turnStore, turnLock: options.turnLock,\n authorize: async ({ intent, body }) => {\n const current = await resolve(agent, consumer)\n if (intent !== 'turn' || !current\n || current.identity.workspaceId !== scope.identity.workspaceId\n || body?.workspaceId !== scope.identity.workspaceId || body.threadId !== scope.identity.threadId) {\n return { ok: false, response: Response.json({ error: 'Consultation access denied' }, { status: 403 }) }\n }\n if (!await ownsConversation(scope.identity)) {\n return { ok: false, response: Response.json({ error: 'Consultation conversation conflict' }, { status: 403 }) }\n }\n return { ok: true, tenantId: scope.identity.workspaceId,\n userId: scope.identity.consumerId, context: undefined }\n },\n produce: args => {\n signal.throwIfAborted()\n return prepared.produce({\n ...control,\n identity: scope.identity, systemPrompt: scope.publication.systemPrompt, prompt,\n priorMessages: args.priorMessages.map(({ role, content }) => ({ role, content })),\n tools: publicationTools(scope.publication, async () => {\n signal.throwIfAborted()\n const current = await resolve(agent, consumer)\n signal.throwIfAborted()\n if (!current || current.identity.workspaceId !== scope.identity.workspaceId) {\n throw new Error('Consultation access denied')\n }\n }),\n })\n },\n })\n return streamChatRouteAsSandboxEvents({\n routes, request: new Request('https://consultation.invalid/internal'),\n payload: { workspaceId: scope.identity.workspaceId, threadId: scope.identity.threadId,\n content: prompt, turnId: consumer.requestId }, signal, executionLimits,\n })\n }\n return { status: 'prepared' as const, start }\n }\n return {\n prepareBudgetedPrompt: (_message: string, streamOptions: PromptOptions) => prepare(streamOptions),\n streamPrompt: async function* (_message: string, streamOptions?: PromptOptions) {\n const prepared = await prepare(streamOptions)\n if (prepared.status !== 'prepared') throw new Error(prepared.reason)\n yield* prepared.start()\n },\n }\n },\n }\n}\n\nfunction publicationTools(publication: KnowledgePublication, authorize: () => Promise<void>): McpToolDefinition[] {\n return [\n { name: 'knowledge_search', description: 'Search published consultation knowledge.',\n inputSchema: { type: 'object', required: ['query'], properties: { query: { type: 'string' } }, additionalProperties: false },\n run: async args => { await authorize(); return publication.search(singleArgument(args, 'query')) } },\n { name: 'knowledge_read', description: 'Read a published page by its exact citation id.',\n inputSchema: { type: 'object', required: ['pageId'], properties: { pageId: { type: 'string' } }, additionalProperties: false },\n run: async args => { await authorize(); return publication.read(singleArgument(args, 'pageId')) } },\n ]\n}\n\nfunction singleArgument(args: Record<string, unknown>, name: string): string {\n const value = args[name]\n if (Object.keys(args).length !== 1 || typeof value !== 'string' || !value.trim() || value.length > 8192) {\n throw new Error('Invalid published knowledge arguments')\n }\n return value\n}\n\nfunction requireIdentity(value: unknown): asserts value is string {\n if (typeof value !== 'string' || !value.trim() || value.length > 512) throw new Error('Invalid consultation identity')\n}\n\nasync function scopedId(parts: string[]): Promise<string> {\n const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify(parts)))\n return `consultation:${Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('')}`\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,uBAAgE;AAuBlE,SAAS,2BAA2B,OAOlB;AACvB,aAAW,SAAS,CAAC,MAAM,IAAI,MAAM,UAAU,MAAM,OAAO,EAAG,iBAAgB,KAAK;AACpF,QAAM,QAAyB,CAAC;AAChC,aAAW,MAAM,IAAI,IAAI,MAAM,OAAO,GAAG;AACvC,UAAM,UAAU,MAAM,MAAM,MAAM,OAAO,CAAAA,UAAQA,MAAK,OAAO,EAA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7
  signObjectUrl,
8
8
  verifyObjectUrl
9
9
  } from "../chunk-6DOQ6T2O.js";
10
+ import {
11
+ REDACTED,
12
+ createSecretScanner,
13
+ isCredentialFile,
14
+ isSecretName
15
+ } from "../chunk-M4QITAQV.js";
10
16
  import "../chunk-S5SRJJQG.js";
11
17
 
12
- // src/workspace-export/secrets.ts
13
- var REDACTED = "[redacted]";
14
- var MASK_BYTE = 42;
15
- var CREDENTIAL_PATTERNS = [
16
- String.raw`sk-ant-[A-Za-z0-9_-]{16,}`,
17
- String.raw`sk-(?:proj-|tan-|or-v1-|svcacct-)?[A-Za-z0-9_-]{20,}`,
18
- String.raw`(?:sk|rk)_(?:live|test|sb)_[A-Za-z0-9_]{12,}`,
19
- String.raw`whsec_[A-Za-z0-9+/=]{16,}`,
20
- String.raw`gh[pousr]_[A-Za-z0-9]{30,}`,
21
- String.raw`github_pat_[A-Za-z0-9_]{40,}`,
22
- String.raw`xox[abposr]-[A-Za-z0-9-]{10,}`,
23
- String.raw`AKIA[0-9A-Z]{16}`,
24
- String.raw`AIza[0-9A-Za-z_-]{35}`,
25
- String.raw`ya29\.[0-9A-Za-z_-]{20,}`,
26
- String.raw`glpat-[A-Za-z0-9_-]{20,}`,
27
- String.raw`npm_[A-Za-z0-9]{36}`,
28
- String.raw`hf_[A-Za-z0-9]{30,}`,
29
- String.raw`r8_[A-Za-z0-9]{30,}`,
30
- String.raw`gsk_[A-Za-z0-9]{40,}`,
31
- String.raw`xai-[A-Za-z0-9]{40,}`,
32
- String.raw`lak_[A-Za-z0-9_-]{16,}`,
33
- String.raw`eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}`,
34
- String.raw`-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[A-Za-z0-9+/=\r\n\t ]*(?:-----END [A-Z0-9 ]*PRIVATE KEY-----)?`
35
- ];
36
- var SECRET_NAME = /(^|_)(secret|secrets|password|passwd|passphrase|token|credential|credentials|ciphertext|encrypted|bearer|apikey|privatekey|cookie)(_|$)|api_?key|private_?key|(key|secret|token|password|challenge|state|nonce|credential)_(hash|digest)$/;
37
- var TOKEN_METRIC = /token_(count|counts|usage|budget|limit|cost)$|^(input|output|total|max|prompt|completion|reasoning|cached)_tokens?$/;
38
- function snake(name) {
39
- return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[-\s.]+/g, "_").toLowerCase();
40
- }
41
- function isSecretName(name) {
42
- const folded = snake(name);
43
- if (TOKEN_METRIC.test(folded)) return false;
44
- return SECRET_NAME.test(folded);
45
- }
46
- function escapeRegExp(value) {
47
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
48
- }
49
- function createSecretScanner(options = {}) {
50
- const known = [...new Set(options.knownSecrets ?? [])].filter((s) => typeof s === "string" && s.length >= 8).sort((a, b) => b.length - a.length).map(escapeRegExp);
51
- const source = [...known, ...CREDENTIAL_PATTERNS].join("|");
52
- const pattern = () => new RegExp(source, "g");
53
- function maskText(text) {
54
- let count = 0;
55
- const out = text.replace(pattern(), () => {
56
- count += 1;
57
- return REDACTED;
58
- });
59
- return { text: out, count };
60
- }
61
- function redactJson(value, depth) {
62
- if (typeof value === "string") {
63
- const masked = maskText(value);
64
- return { value: masked.text, count: masked.count };
65
- }
66
- if (depth > 64 || value === null || typeof value !== "object") return { value, count: 0 };
67
- let count = 0;
68
- if (Array.isArray(value)) {
69
- const out2 = value.map((item) => {
70
- const result = redactJson(item, depth + 1);
71
- count += result.count;
72
- return result.value;
73
- });
74
- return { value: out2, count };
75
- }
76
- const out = {};
77
- for (const [key, item] of Object.entries(value)) {
78
- if (isSecretName(key) && item !== null && item !== "" && typeof item !== "boolean") {
79
- out[key] = REDACTED;
80
- count += 1;
81
- continue;
82
- }
83
- const result = redactJson(item, depth + 1);
84
- out[key] = result.value;
85
- count += result.count;
86
- }
87
- return { value: out, count };
88
- }
89
- function redactValue(value) {
90
- if (typeof value === "string") {
91
- const trimmed = value.trimStart();
92
- if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
93
- try {
94
- const parsed = JSON.parse(value);
95
- const result = redactJson(parsed, 0);
96
- return result.count ? { value: JSON.stringify(result.value), count: result.count } : { value, count: 0 };
97
- } catch {
98
- }
99
- }
100
- const masked = maskText(value);
101
- return { value: masked.text, count: masked.count };
102
- }
103
- if (value instanceof Uint8Array || value instanceof ArrayBuffer) return { value, count: 0 };
104
- return redactJson(value, 0);
105
- }
106
- function maskBytes(onMask) {
107
- const window = 8192;
108
- const maxCarry = 65536;
109
- let carry = new Uint8Array(0);
110
- function scan(buffer, final) {
111
- const text = decodeBytes(buffer);
112
- const regex = pattern();
113
- let emitEnd = final ? buffer.length : Math.max(0, buffer.length - window);
114
- let masked = 0;
115
- for (let match = regex.exec(text); match; match = regex.exec(text)) {
116
- const start = match.index;
117
- const end = start + match[0].length;
118
- if (match[0].length === 0) {
119
- regex.lastIndex += 1;
120
- continue;
121
- }
122
- if (!final && end === buffer.length) {
123
- emitEnd = Math.min(emitEnd, start);
124
- break;
125
- }
126
- buffer.fill(MASK_BYTE, start, end);
127
- masked += 1;
128
- }
129
- if (masked) onMask(masked);
130
- if (!final && buffer.length - emitEnd > maxCarry) emitEnd = buffer.length - window;
131
- return emitEnd;
132
- }
133
- const block = 256 * 1024;
134
- let pending = [];
135
- let pendingLength = 0;
136
- function drain(controller, final) {
137
- const buffer = new Uint8Array(carry.length + pendingLength);
138
- buffer.set(carry, 0);
139
- let offset = carry.length;
140
- for (const part of pending) {
141
- buffer.set(part, offset);
142
- offset += part.length;
143
- }
144
- pending = [];
145
- pendingLength = 0;
146
- const emitEnd = scan(buffer, final);
147
- if (emitEnd > 0) controller.enqueue(buffer.slice(0, emitEnd));
148
- carry = buffer.slice(emitEnd);
149
- }
150
- return new TransformStream({
151
- transform(chunk, controller) {
152
- pending.push(chunk);
153
- pendingLength += chunk.length;
154
- if (pendingLength >= block) drain(controller, false);
155
- },
156
- flush(controller) {
157
- if (carry.length || pendingLength) drain(controller, true);
158
- }
159
- });
160
- }
161
- return { maskText, redactValue, maskBytes };
162
- }
163
- var nativeLatin1 = (() => {
164
- try {
165
- const decoder = new TextDecoder("latin1");
166
- return decoder.decode(new Uint8Array([65, 128, 255])).length === 3 ? decoder : null;
167
- } catch {
168
- return null;
169
- }
170
- })();
171
- function decodeBytes(buffer) {
172
- if (nativeLatin1) return nativeLatin1.decode(buffer);
173
- let text = "";
174
- for (let i = 0; i < buffer.length; i += 8192) text += String.fromCharCode(...buffer.subarray(i, i + 8192));
175
- return text;
176
- }
177
- var CREDENTIAL_FILES = [
178
- /(^|\/)\.git-credentials$/,
179
- /(^|\/)\.netrc$/,
180
- /(^|\/)\.pgpass$/,
181
- /(^|\/)\.npmrc$/,
182
- /(^|\/)\.pypirc$/,
183
- /(^|\/)\.docker\/config\.json$/,
184
- /(^|\/)\.aws\/credentials$/,
185
- /(^|\/)\.kube\/config$/,
186
- /(^|\/)\.config\/gh\/hosts\.ya?ml$/,
187
- /(^|\/)\.codex\/auth\.json$/,
188
- /(^|\/)\.claude\/\.credentials\.json$/,
189
- /(^|\/)opencode\/auth\.json$/,
190
- /(^|\/)\.ssh\/id_[^/]*$/
191
- ];
192
- function isCredentialFile(path) {
193
- const normalized = path.replace(/^\.\//, "");
194
- if (normalized.endsWith(".pub")) return false;
195
- return CREDENTIAL_FILES.some((pattern) => pattern.test(normalized));
196
- }
197
-
198
18
  // src/workspace-export/tar.ts
199
19
  var BLOCK = 512;
200
20
  var MAX_NAME_RECORD = 1 << 20;