@tangle-network/agent-app 0.63.52 → 0.63.53
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.
- package/dist/agent-profiles/d1.js +1 -1
- package/dist/agent-profiles/d1.js.map +1 -1
- package/dist/assistant/index.js +8 -8
- package/dist/chat-react/index.js +3 -3
- package/dist/chat-routes/index.js +15 -15
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/chat-routes/protected-runtime-producer.d.ts +1 -1
- package/dist/chat-store/index.js +3 -3
- package/dist/{chunk-G3LZITCA.js → chunk-6XEW5YXP.js} +9 -11
- package/dist/chunk-6XEW5YXP.js.map +1 -0
- package/dist/{chunk-CRZXEKCX.js → chunk-AICYKYYF.js} +2 -2
- package/dist/{chunk-KHJE7JAG.js → chunk-ARCXYOMS.js} +2 -2
- package/dist/{chunk-XJXAULNI.js → chunk-GGJYAV7R.js} +2 -2
- package/dist/{chunk-AZRPDSRQ.js → chunk-H7CSSEP7.js} +3 -3
- package/dist/{chunk-BMCC2BUP.js → chunk-HHPQMFKP.js} +3 -3
- package/dist/{chunk-GQW4DBFS.js → chunk-IDQ7N36R.js} +4 -6
- package/dist/chunk-IDQ7N36R.js.map +1 -0
- package/dist/{chunk-LCOKBYAS.js → chunk-KFO5R4SN.js} +7 -7
- package/dist/{chunk-D3HATHVU.js → chunk-ML4DMZLN.js} +2 -2
- package/dist/chunk-ML4DMZLN.js.map +1 -0
- package/dist/{chunk-6A7MYOUI.js → chunk-OY7A6M7S.js} +3 -6
- package/dist/chunk-OY7A6M7S.js.map +1 -0
- package/dist/{chunk-JNEWZCRF.js → chunk-R7PEKDCG.js} +3 -3
- package/dist/{chunk-ELX5YITO.js → chunk-RCSAAWOH.js} +3 -3
- package/dist/chunk-RCSAAWOH.js.map +1 -0
- package/dist/{chunk-Z3IJ7XEW.js → chunk-RILVJYXJ.js} +3 -3
- package/dist/{chunk-CWO2LHXH.js → chunk-SBHFMDR7.js} +2 -2
- package/dist/{chunk-SRZTL3Z5.js → chunk-TB6KNPFI.js} +2 -4
- package/dist/chunk-TB6KNPFI.js.map +1 -0
- package/dist/{chunk-ZNWJJRHP.js → chunk-U4F6NHAA.js} +2 -2
- package/dist/{chunk-WPPDNS63.js → chunk-XCUT52I3.js} +3 -5
- package/dist/chunk-XCUT52I3.js.map +1 -0
- package/dist/{chunk-J5GT37ZX.js → chunk-YE7S5UAE.js} +2 -2
- package/dist/design-canvas/index.js +1 -1
- package/dist/harness/index.d.ts +2 -1
- package/dist/harness/index.js +1 -1
- package/dist/hosted-agent/general.d.ts +1 -1
- package/dist/hosted-agent/index.js +3 -6
- package/dist/hosted-agent/index.js.map +1 -1
- package/dist/interactions/contract.d.ts +1 -1
- package/dist/interactions/index.js +2 -2
- package/dist/preset-cloudflare/index.js +5 -5
- package/dist/profile/index.js +2 -2
- package/dist/profile/index.js.map +1 -1
- package/dist/public-consultation/index.js +10 -10
- package/dist/runtime/index.js +1 -1
- package/dist/runtime/protected-model.d.ts +1 -1
- package/dist/runtime/protected-router-turn.d.ts +1 -1
- package/dist/sandbox/index.js +4 -4
- package/dist/sandbox/prompt-profile.d.ts +1 -1
- package/dist/sequences/index.js +1 -1
- package/dist/skills-placement/box.js +2 -2
- package/dist/skills-placement/index.d.ts +1 -1
- package/dist/skills-placement/index.js +2 -2
- package/dist/stream/index.js +2 -2
- package/dist/tools/index.js +2 -2
- package/dist/tools/mcp.d.ts +1 -1
- package/dist/web-react/agent-profile-editor.js +3 -3
- package/dist/web-react/index.js +8 -8
- package/package.json +1 -1
- package/dist/chunk-6A7MYOUI.js.map +0 -1
- package/dist/chunk-D3HATHVU.js.map +0 -1
- package/dist/chunk-ELX5YITO.js.map +0 -1
- package/dist/chunk-G3LZITCA.js.map +0 -1
- package/dist/chunk-GQW4DBFS.js.map +0 -1
- package/dist/chunk-SRZTL3Z5.js.map +0 -1
- package/dist/chunk-WPPDNS63.js.map +0 -1
- /package/dist/{chunk-CRZXEKCX.js.map → chunk-AICYKYYF.js.map} +0 -0
- /package/dist/{chunk-KHJE7JAG.js.map → chunk-ARCXYOMS.js.map} +0 -0
- /package/dist/{chunk-XJXAULNI.js.map → chunk-GGJYAV7R.js.map} +0 -0
- /package/dist/{chunk-AZRPDSRQ.js.map → chunk-H7CSSEP7.js.map} +0 -0
- /package/dist/{chunk-BMCC2BUP.js.map → chunk-HHPQMFKP.js.map} +0 -0
- /package/dist/{chunk-LCOKBYAS.js.map → chunk-KFO5R4SN.js.map} +0 -0
- /package/dist/{chunk-JNEWZCRF.js.map → chunk-R7PEKDCG.js.map} +0 -0
- /package/dist/{chunk-Z3IJ7XEW.js.map → chunk-RILVJYXJ.js.map} +0 -0
- /package/dist/{chunk-CWO2LHXH.js.map → chunk-SBHFMDR7.js.map} +0 -0
- /package/dist/{chunk-ZNWJJRHP.js.map → chunk-U4F6NHAA.js.map} +0 -0
- /package/dist/{chunk-J5GT37ZX.js.map → chunk-YE7S5UAE.js.map} +0 -0
package/dist/runtime/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import type { AgentCandidateModelGrantClient, AgentCandidateModelPort } from '@tangle-network/agent-runtime/candidate-execution';
|
|
2
2
|
export interface RouterProtectedModelPortOptions {
|
|
3
3
|
apiKey: string;
|
|
4
4
|
maxCostUsd: number;
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
* - Anything else is the turn's own failure (`turn_aborted`, `turn_tool_limit`,
|
|
24
24
|
* `model_http_<status>`, ...), settled as `failed`.
|
|
25
25
|
*/
|
|
26
|
-
import {
|
|
26
|
+
import type { RunProtectedAgentCandidateModelGrantOptions } from '@tangle-network/agent-runtime/candidate-execution';
|
|
27
27
|
import { type RouterTurnOptions, type RouterTurnOutcome } from './router-turn';
|
|
28
28
|
/** Runtime's grant inputs for one turn: the port, the model request, the reservation and its deadline. */
|
|
29
29
|
export type RouterTurnGrant = Omit<RunProtectedAgentCandidateModelGrantOptions<void>, 'execute'>;
|
package/dist/sandbox/index.js
CHANGED
|
@@ -112,7 +112,7 @@ import {
|
|
|
112
112
|
warmKey,
|
|
113
113
|
warmReceiptId,
|
|
114
114
|
warmWeekdayOf
|
|
115
|
-
} from "../chunk-
|
|
115
|
+
} from "../chunk-IDQ7N36R.js";
|
|
116
116
|
import {
|
|
117
117
|
createWarmCache
|
|
118
118
|
} from "../chunk-F4TUZYMX.js";
|
|
@@ -165,8 +165,8 @@ import "../chunk-QGJOT6R6.js";
|
|
|
165
165
|
import "../chunk-L3QR274L.js";
|
|
166
166
|
import "../chunk-XELWWXJJ.js";
|
|
167
167
|
import "../chunk-DSMGS4IV.js";
|
|
168
|
-
import "../chunk-
|
|
169
|
-
import "../chunk-
|
|
168
|
+
import "../chunk-YE7S5UAE.js";
|
|
169
|
+
import "../chunk-OY7A6M7S.js";
|
|
170
170
|
import "../chunk-O7UX55EU.js";
|
|
171
171
|
import "../chunk-RDIHNSVZ.js";
|
|
172
172
|
import "../chunk-S5SRJJQG.js";
|
|
@@ -179,7 +179,7 @@ import {
|
|
|
179
179
|
splitDeferredProfileFiles,
|
|
180
180
|
writeProfileFilesToBox
|
|
181
181
|
} from "../chunk-67CSI5PU.js";
|
|
182
|
-
import "../chunk-
|
|
182
|
+
import "../chunk-RCSAAWOH.js";
|
|
183
183
|
import {
|
|
184
184
|
readSandboxBinaryBytes,
|
|
185
185
|
shellQuote,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { SandboxInstance } from '@tangle-network/sandbox';
|
|
2
|
-
import {
|
|
2
|
+
import type { AgentProfileMcpServer, AgentProfile, ReasoningEffort } from '@tangle-network/agent-interface';
|
|
3
3
|
import { type Harness } from '../harness/index';
|
|
4
4
|
import type { SandboxRuntimeConfig } from './configuration';
|
|
5
5
|
import type { StreamSandboxPromptOptions } from './prompt-options';
|
package/dist/sequences/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
2
|
resolveSkillDir
|
|
3
|
-
} from "../chunk-
|
|
3
|
+
} from "../chunk-XCUT52I3.js";
|
|
4
4
|
import "../chunk-76MPX7JQ.js";
|
|
5
5
|
import "../chunk-PV33JZKV.js";
|
|
6
6
|
import {
|
|
7
7
|
writeProfileFilesToBox
|
|
8
8
|
} from "../chunk-67CSI5PU.js";
|
|
9
|
-
import "../chunk-
|
|
9
|
+
import "../chunk-RCSAAWOH.js";
|
|
10
10
|
import {
|
|
11
11
|
shellQuote
|
|
12
12
|
} from "../chunk-INW4FSID.js";
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
* other agent-app skills surface (`../skills`, `ProfileChannels.skillRefs`)
|
|
18
18
|
* works without it, falling back to `inline` delivery.
|
|
19
19
|
*/
|
|
20
|
-
import {
|
|
20
|
+
import type { AgentProfile, AgentProfileFileMount } from '@tangle-network/agent-interface';
|
|
21
21
|
import { type Harness } from '../harness/index';
|
|
22
22
|
import { type ComposedSkills, type SkillEntry } from '../skills/index';
|
|
23
23
|
/** Resolve the cwd-relative skill dir `resources.skills` refs materialize
|
|
@@ -4,10 +4,10 @@ import {
|
|
|
4
4
|
skillSupportFileMounts,
|
|
5
5
|
unsupportedSkillHarnesses,
|
|
6
6
|
withSkillSupportFiles
|
|
7
|
-
} from "../chunk-
|
|
7
|
+
} from "../chunk-XCUT52I3.js";
|
|
8
8
|
import "../chunk-76MPX7JQ.js";
|
|
9
9
|
import "../chunk-PV33JZKV.js";
|
|
10
|
-
import "../chunk-
|
|
10
|
+
import "../chunk-RCSAAWOH.js";
|
|
11
11
|
export {
|
|
12
12
|
composeSkillsForHarness,
|
|
13
13
|
resolveSkillDir,
|
package/dist/stream/index.js
CHANGED
|
@@ -33,8 +33,8 @@ import {
|
|
|
33
33
|
terminalizeDanglingAssistantToolUpdates,
|
|
34
34
|
terminalizeDanglingToolPart,
|
|
35
35
|
terminalizeDanglingToolParts
|
|
36
|
-
} from "../chunk-
|
|
37
|
-
import "../chunk-
|
|
36
|
+
} from "../chunk-U4F6NHAA.js";
|
|
37
|
+
import "../chunk-TB6KNPFI.js";
|
|
38
38
|
import {
|
|
39
39
|
DEFAULT_RUNNING_TURN_LEASE_MS,
|
|
40
40
|
DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS,
|
package/dist/tools/index.js
CHANGED
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
outcomeStatus,
|
|
6
6
|
resolveToolCapabilities,
|
|
7
7
|
restrictTaxonomy
|
|
8
|
-
} from "../chunk-
|
|
8
|
+
} from "../chunk-YE7S5UAE.js";
|
|
9
9
|
import {
|
|
10
10
|
DEFAULT_APP_TOOL_PATHS,
|
|
11
11
|
DEFAULT_HEADER_NAMES,
|
|
@@ -17,7 +17,7 @@ import {
|
|
|
17
17
|
createMcpToolHandler,
|
|
18
18
|
readToolArgs,
|
|
19
19
|
unresolvableSurfaceCredential
|
|
20
|
-
} from "../chunk-
|
|
20
|
+
} from "../chunk-OY7A6M7S.js";
|
|
21
21
|
import {
|
|
22
22
|
createCapabilityToken,
|
|
23
23
|
createExpiringCapabilityToken,
|
package/dist/tools/mcp.d.ts
CHANGED
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
* referenced safely; {@link unresolvableSurfaceCredential} names that blocker
|
|
36
36
|
* instead of emitting a reference that resolves to nothing.
|
|
37
37
|
*/
|
|
38
|
-
import {
|
|
38
|
+
import type { AgentProfileConfigValue } from '@tangle-network/agent-interface';
|
|
39
39
|
import type { AppToolContext } from './types';
|
|
40
40
|
import type { AppToolName } from './openai';
|
|
41
41
|
import type { AppToolDefinition } from './registry';
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
2
|
AGENT_PROFILE_EDITOR_SECTIONS,
|
|
3
3
|
AgentProfileEditor
|
|
4
|
-
} from "../chunk-
|
|
5
|
-
import "../chunk-
|
|
4
|
+
} from "../chunk-R7PEKDCG.js";
|
|
5
|
+
import "../chunk-ARCXYOMS.js";
|
|
6
6
|
import "../chunk-QAHBSKWG.js";
|
|
7
7
|
import "../chunk-RO25WIVS.js";
|
|
8
8
|
import "../chunk-ZAMHLXNS.js";
|
|
@@ -10,7 +10,7 @@ import "../chunk-RASGKEAL.js";
|
|
|
10
10
|
import "../chunk-B7CL7ENS.js";
|
|
11
11
|
import "../chunk-AMUXRAUO.js";
|
|
12
12
|
import "../chunk-PV33JZKV.js";
|
|
13
|
-
import "../chunk-
|
|
13
|
+
import "../chunk-RCSAAWOH.js";
|
|
14
14
|
export {
|
|
15
15
|
AGENT_PROFILE_EDITOR_SECTIONS,
|
|
16
16
|
AgentProfileEditor
|
package/dist/web-react/index.js
CHANGED
|
@@ -146,7 +146,7 @@ import {
|
|
|
146
146
|
withoutRecordGridCreated,
|
|
147
147
|
withoutRecordGridRemoved,
|
|
148
148
|
withoutRecordGridUpdate
|
|
149
|
-
} from "../chunk-
|
|
149
|
+
} from "../chunk-H7CSSEP7.js";
|
|
150
150
|
import {
|
|
151
151
|
useInfiniteScroll
|
|
152
152
|
} from "../chunk-UHSUY6H6.js";
|
|
@@ -159,7 +159,7 @@ import {
|
|
|
159
159
|
AGENT_PROFILE_EDITOR_SECTIONS,
|
|
160
160
|
AgentProfileEditor,
|
|
161
161
|
AgentProfileRegistryError
|
|
162
|
-
} from "../chunk-
|
|
162
|
+
} from "../chunk-R7PEKDCG.js";
|
|
163
163
|
import {
|
|
164
164
|
EvidenceLineageTable,
|
|
165
165
|
ExceptionList,
|
|
@@ -188,7 +188,7 @@ import {
|
|
|
188
188
|
preloadWhenIdle,
|
|
189
189
|
useComposerAttachments,
|
|
190
190
|
useDictation
|
|
191
|
-
} from "../chunk-
|
|
191
|
+
} from "../chunk-GGJYAV7R.js";
|
|
192
192
|
import "../chunk-L7MB2LLM.js";
|
|
193
193
|
import {
|
|
194
194
|
AgentSessionControls,
|
|
@@ -199,7 +199,7 @@ import {
|
|
|
199
199
|
filterAcceptedFiles,
|
|
200
200
|
isAcceptedFileType,
|
|
201
201
|
renamePastedImages
|
|
202
|
-
} from "../chunk-
|
|
202
|
+
} from "../chunk-ARCXYOMS.js";
|
|
203
203
|
import {
|
|
204
204
|
WorkspaceInitial,
|
|
205
205
|
WorkspaceSwitcher
|
|
@@ -257,11 +257,11 @@ import {
|
|
|
257
257
|
isChatAttachmentPart,
|
|
258
258
|
mentionInputToPart,
|
|
259
259
|
mentionPartsFromMessageParts
|
|
260
|
-
} from "../chunk-
|
|
260
|
+
} from "../chunk-AICYKYYF.js";
|
|
261
261
|
import "../chunk-ZVEEWGDK.js";
|
|
262
262
|
import {
|
|
263
263
|
attachmentPartKey
|
|
264
|
-
} from "../chunk-
|
|
264
|
+
} from "../chunk-U4F6NHAA.js";
|
|
265
265
|
import {
|
|
266
266
|
INTERACTION_CANCEL_EVENT,
|
|
267
267
|
INTERACTION_EVENT,
|
|
@@ -286,7 +286,7 @@ import {
|
|
|
286
286
|
persistedPartToInteraction,
|
|
287
287
|
questionInteractionContentSignature,
|
|
288
288
|
stampInteractionAnswers
|
|
289
|
-
} from "../chunk-
|
|
289
|
+
} from "../chunk-TB6KNPFI.js";
|
|
290
290
|
import {
|
|
291
291
|
DISPATCH_MAX_MEDIA_PARTS,
|
|
292
292
|
DISPATCH_MAX_PARTS,
|
|
@@ -312,7 +312,7 @@ import {
|
|
|
312
312
|
} from "../chunk-QGJOT6R6.js";
|
|
313
313
|
import "../chunk-AMUXRAUO.js";
|
|
314
314
|
import "../chunk-PV33JZKV.js";
|
|
315
|
-
import "../chunk-
|
|
315
|
+
import "../chunk-RCSAAWOH.js";
|
|
316
316
|
import "../chunk-4PIN6QYQ.js";
|
|
317
317
|
import "../chunk-TXD5HXLE.js";
|
|
318
318
|
export {
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/tools/auth.ts","../src/tools/mcp-rpc.ts","../src/tools/mcp.ts"],"sourcesContent":["import type { AppToolContext } from './types'\n\n/**\n * Header names carrying the server-set per-turn context + the capability token.\n * Defaults are product-neutral (`X-Agent-App-*`); a product that already ships\n * a header convention (e.g. `X-Acme-User-Id`) passes its own.\n */\nexport interface ToolHeaderNames {\n userId: string\n workspaceId: string\n threadId: string\n}\n\n/** Provide default HTTP header names for user, workspace, and thread identification */\nexport const DEFAULT_HEADER_NAMES: ToolHeaderNames = {\n userId: 'X-Agent-App-User-Id',\n workspaceId: 'X-Agent-App-Workspace-Id',\n threadId: 'X-Agent-App-Thread-Id',\n}\n\n/**\n * Which identity the bearer is bound to.\n *\n * `'userId'` (default) is right when the product mints a token per user and can\n * deliver it per turn.\n *\n * `'workspaceId'` is the only workable choice when the token lives in the BOX\n * ENVIRONMENT. Since agent-interface 0.38 a credential may reach a profile\n * only as a reference the sandbox resolves from that environment. `env` writes\n * at creation and `runtimeEnv` can refresh retained boxes, but the environment\n * remains workspace-wide. A per-user token therefore cannot be delivered as a\n * safe box credential — and a per-user token that IS written there was never\n * per-user in any meaningful sense, because every member of that workspace's\n * box can read it.\n *\n * Binding the bearer to the workspace does NOT collapse the identity: the user\n * header is still required, still server-set, still returned on `ctx`, and is\n * what downstream domain code attributes work to. Only the question \"may this\n * caller act at all\" moves from the user to the workspace — which is what the\n * shared box already implies.\n */\nexport type CapabilitySubject = 'userId' | 'workspaceId'\n\n/** Define options to verify bearer tokens and customize authentication header names */\nexport interface AuthenticateOptions {\n /** Verify the bearer capability token belongs to the subject named by\n * {@link AuthenticateOptions.subject}. The product's HMAC/JWT impl — the\n * seam that keeps token crypto out of this package. */\n verifyToken: (subject: string, bearer: string) => Promise<boolean>\n headerNames?: ToolHeaderNames\n /** What the bearer is bound to. Defaults to `'userId'`, so an existing caller\n * is byte-unchanged. */\n subject?: CapabilitySubject\n}\n\n/** Represent the result of tool authentication with success context or failure response */\nexport type ToolAuthResult =\n | { ok: true; ctx: AppToolContext }\n | { ok: false; response: Response }\n\n/**\n * Recover + verify the trusted context for a tool request.\n *\n * Both the user and the workspace come from server-set headers — never from\n * tool args — so the model can neither forge identity nor target another\n * workspace. The bearer must verify against whichever of the two the product\n * declares as its {@link CapabilitySubject}.\n *\n * Fail-closed, and deliberately in this order: a missing credential or a token\n * minted for another subject yields 401 before anything else is read. When the\n * subject is the workspace, its header is required BEFORE verification rather\n * than after — verifying against an absent subject is not a check at all.\n */\nexport async function authenticateToolRequest(request: Request, opts: AuthenticateOptions): Promise<ToolAuthResult> {\n const h = opts.headerNames ?? DEFAULT_HEADER_NAMES\n const userId = request.headers.get(h.userId)?.trim()\n const workspaceId = request.headers.get(h.workspaceId)?.trim()\n const threadId = request.headers.get(h.threadId)?.trim() || null\n const bearer = request.headers.get('authorization')?.match(/^Bearer\\s+(.+)$/i)?.[1]\n\n if (!userId || !bearer) {\n return { ok: false, response: Response.json({ error: 'Missing capability credentials' }, { status: 401 }) }\n }\n const subject = opts.subject === 'workspaceId' ? workspaceId : userId\n if (!subject) {\n return { ok: false, response: Response.json({ error: 'Missing workspace context' }, { status: 400 }) }\n }\n if (!(await opts.verifyToken(subject, bearer))) {\n return { ok: false, response: Response.json({ error: 'Invalid capability token' }, { status: 401 }) }\n }\n if (!workspaceId) {\n return { ok: false, response: Response.json({ error: 'Missing workspace context' }, { status: 400 }) }\n }\n return { ok: true, ctx: { userId, workspaceId, threadId } }\n}\n\n/** Read a tool's argument object from the request body, tolerant of direct\n * aliases (`args` / `arguments`), Streamable HTTP MCP (`params.arguments`),\n * or a bare body. Returns null on non-JSON. */\nexport async function readToolArgs<T>(request: Request): Promise<T | null> {\n let body: unknown\n try {\n body = await request.json()\n } catch {\n return null\n }\n if (typeof body !== 'object' || body === null || Array.isArray(body)) return body as T\n const record = body as Record<string, unknown>\n if ('jsonrpc' in record) {\n const params = record.params\n if (typeof params === 'object' && params !== null && !Array.isArray(params)) {\n return ((params as Record<string, unknown>).arguments ?? {}) as T\n }\n return {} as T\n }\n return (record.args ?? record.arguments ?? record) as T\n}\n","/**\n * Generic streamable-HTTP JSON-RPC 2.0 envelope for a tools-only MCP server.\n * Stateless, Workers-compatible: no session table, no SSE — every request gets\n * a single `application/json` response, which the streamable-HTTP transport\n * explicitly permits for tools-only servers.\n *\n * Protocol surface:\n * initialize → echo client's protocolVersion if supported, else latest\n * ping → empty result {}\n * notifications/* (no `id`) → 202 with no body\n * tools/list → tool manifest\n * tools/call → run + surface execution failures as isError text results\n * anything else → -32601\n *\n * Execution failures (argument shape, validation, store throws) become `isError`\n * tool results carrying the thrown message verbatim — the model reads WHY and\n * retries. Protocol misuse becomes a JSON-RPC error object.\n */\n\nexport const MCP_PROTOCOL_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05'] as const\n/** Resolve a valid protocol version from the predefined MCP_PROTOCOL_VERSIONS array */\nexport type McpProtocolVersion = (typeof MCP_PROTOCOL_VERSIONS)[number]\n\nconst LATEST_PROTOCOL_VERSION: McpProtocolVersion = MCP_PROTOCOL_VERSIONS[0]\n\n/** Describe the structure of server information including name and version */\nexport interface McpServerInfo {\n name: string\n version: string\n}\n\n/** One tool entry in the registry the handler owns. */\nexport interface McpToolDefinition<TEnv = Record<string, never>> {\n name: string\n description: string\n /** JSON Schema for the `params.arguments` object. */\n inputSchema: Record<string, unknown>\n /** Receive validated (Record) args + the env the handler threaded; throw to\n * surface an isError result — never throw for protocol/framing issues. */\n run(args: Record<string, unknown>, env: TEnv): Promise<unknown>\n}\n\n/** Define options for creating a handler that manages MCP tools with environment support */\nexport interface CreateMcpToolHandlerOptions<TEnv = Record<string, never>> {\n serverInfo: McpServerInfo\n /** Full tool list; order IS the tools/list order. */\n tools: McpToolDefinition<TEnv>[]\n /** Per-request environment threaded into every `run` call. If your tools are\n * stateless (or carry state through closure) pass an empty builder:\n * `() => ({} as TEnv)`. */\n buildEnv(request: Request): TEnv | Promise<TEnv>\n /** Optional result formatter for callers that need structured tool errors. */\n formatResult?: (result: unknown, tool: McpToolDefinition<TEnv>) => McpToolCallContent\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\ntype JsonRpcId = string | number | null\n\nexport interface McpToolCallContent {\n content: Array<{ type: 'text'; text: string }>\n isError?: true\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nfunction rpcResult(id: JsonRpcId, result: unknown): Response {\n return Response.json({ jsonrpc: '2.0', id, result })\n}\n\nfunction rpcError(id: JsonRpcId, code: number, message: string, status = 200): Response {\n return Response.json({ jsonrpc: '2.0', id, error: { code, message } }, { status })\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Build a request handler for a tools-only MCP server. The returned function\n * accepts a standard `Request` and resolves to a `Response` — mount it on any\n * Cloudflare Worker route or Remix `loader`.\n *\n * The handler calls `buildEnv` exactly ONCE per `tools/call` request (after\n * the tool is found, before `run`) — non-`tools/call` paths skip it entirely\n * so metadata requests do not pay env-build cost.\n */\nexport function createMcpToolHandler<TEnv = Record<string, never>>(\n opts: CreateMcpToolHandlerOptions<TEnv>,\n): (request: Request) => Promise<Response> {\n const toolMap = new Map<string, McpToolDefinition<TEnv>>()\n for (const tool of opts.tools) {\n if (toolMap.has(tool.name)) throw new Error(`duplicate MCP tool name: ${tool.name}`)\n toolMap.set(tool.name, tool)\n }\n\n return async (request: Request): Promise<Response> => {\n if (request.method !== 'POST') {\n return new Response('MCP server accepts JSON-RPC 2.0 over POST only', {\n status: 405,\n headers: { Allow: 'POST' },\n })\n }\n\n let body: unknown\n try {\n body = await request.json()\n } catch {\n return rpcError(null, -32700, 'Parse error: request body is not valid JSON', 400)\n }\n\n if (Array.isArray(body)) {\n return rpcError(null, -32600, 'Invalid request: JSON-RPC batching is not supported', 400)\n }\n if (!isRecord(body) || body.jsonrpc !== '2.0' || typeof body.method !== 'string') {\n return rpcError(\n null,\n -32600,\n 'Invalid request: expected a JSON-RPC 2.0 object with jsonrpc \"2.0\" and a string method',\n 400,\n )\n }\n\n const method = body.method\n const params = isRecord(body.params) ? body.params : {}\n\n // Notifications have no `id` — acknowledge without a JSON-RPC body.\n if (!('id' in body) || body.id === undefined) {\n return new Response(null, { status: 202 })\n }\n const id = body.id as JsonRpcId\n\n switch (method) {\n case 'initialize': {\n const requested = typeof params.protocolVersion === 'string' ? params.protocolVersion : undefined\n const protocolVersion =\n requested !== undefined && (MCP_PROTOCOL_VERSIONS as readonly string[]).includes(requested)\n ? requested\n : LATEST_PROTOCOL_VERSION\n return rpcResult(id, {\n protocolVersion,\n capabilities: { tools: { listChanged: false } },\n serverInfo: opts.serverInfo,\n })\n }\n\n case 'ping':\n return rpcResult(id, {})\n\n case 'tools/list':\n return rpcResult(id, {\n tools: opts.tools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n })),\n })\n\n case 'tools/call': {\n const name = params.name\n if (typeof name !== 'string' || name.length === 0) {\n return rpcError(id, -32602, 'tools/call requires params.name (string)')\n }\n const tool = toolMap.get(name)\n if (!tool) {\n return rpcError(\n id,\n -32602,\n `Unknown tool: ${name}. Available tools: ${opts.tools.map((t) => t.name).join(', ')}`,\n )\n }\n if (params.arguments !== undefined && !isRecord(params.arguments)) {\n return rpcError(id, -32602, 'tools/call params.arguments must be an object when provided')\n }\n const args = isRecord(params.arguments) ? params.arguments : {}\n let env: TEnv\n try {\n env = await opts.buildEnv(request)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n const payload: McpToolCallContent = {\n content: [{ type: 'text', text: `${name} failed to build env: ${message}` }],\n isError: true,\n }\n return rpcResult(id, payload)\n }\n try {\n const result = await tool.run(args, env)\n const payload = opts.formatResult\n ? opts.formatResult(result, tool)\n : { content: [{ type: 'text', text: JSON.stringify(result) }] }\n return rpcResult(id, payload)\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err)\n const payload: McpToolCallContent = {\n content: [{ type: 'text', text: `${name} failed: ${message}` }],\n isError: true,\n }\n return rpcResult(id, payload)\n }\n }\n\n default:\n return rpcError(id, -32601, `Method not found: ${method}`)\n }\n }\n}\n","/**\n * The tagged-configuration contract for every MCP server this package emits.\n *\n * An `AgentProfile` is digested, diffed, stored, and logged, so a credential\n * that rides it as plain text is a leak by construction. `@tangle-network/\n * agent-interface` closed that at **0.38.0**: `args`, `env`, and `headers` on\n * an `AgentProfileMcpServer` no longer take strings. Every value is either\n * deliberately public profile material (`defineAgentProfilePublicConfig`) or an\n * opaque reference to a credential (`defineAgentProfileSecretRef`) resolved\n * privately at materialization, validated by a `z.discriminatedUnion('kind')`.\n *\n * The schema also refuses to let a secret hide as public material: a `public`\n * value under a credential-bearing key name (`Authorization`, `*_TOKEN`,\n * `*_API_KEY`, `*_SECRET`, `Cookie`, …) is rejected with \"credential-bearing\n * config names require a secret-ref\", and any value whose bytes look like a\n * credential (`Bearer …`, `sk-…`, `ghp_…`) is rejected outright. So the\n * capability token this package used to inline as `Bearer <token>` cannot be\n * expressed at all — it must become a reference.\n *\n * **A reference resolves ONLY from an environment variable present on the box,\n * named by `key`.** That is why the builders below take a `tokenEnvKey` (the\n * box-env variable NAME) instead of a token VALUE: agent-app cannot guess the\n * name, and a reference to a key nothing places fails the turn at\n * materialization rather than running credential-less. The box env is what\n * `SandboxRuntimeConfig.env` (and the platform secret store via\n * `SandboxRuntimeConfig.secrets`) writes at sandbox creation.\n * `SandboxRuntimeConfig.runtimeEnv` can also supply expiring workspace\n * credentials at creation and refresh them on retained boxes before\n * bootstrap. The key must name a variable one of those places — and it must\n * therefore be a real environment-variable name, which this module enforces.\n *\n * A workspace credential may be renewed through `runtimeEnv`; it still has\n * workspace-wide authority because every member and turn shares the box. A\n * token scoped narrower than the box — per-user, per-document — cannot be\n * referenced safely; {@link unresolvableSurfaceCredential} names that blocker\n * instead of emitting a reference that resolves to nothing.\n */\nimport {\n agentProfileMcpServerSchema,\n defineAgentProfilePublicConfig,\n defineAgentProfileSecretRef,\n type AgentProfileConfigValue,\n} from '@tangle-network/agent-interface'\nimport type { AppToolContext } from './types'\nimport type { AppToolName } from './openai'\nimport type { AppToolDefinition } from './registry'\nimport type { ToolHeaderNames } from './auth'\nimport { DEFAULT_HEADER_NAMES } from './auth'\n\n/** Default route path each app tool is served at. A product mounts its routes\n * at these paths (or supplies its own via {@link BuildMcpServerOptions.paths}). */\nexport const DEFAULT_APP_TOOL_PATHS: Record<AppToolName, string> = {\n submit_proposal: '/api/tools/propose',\n schedule_followup: '/api/tools/followup',\n render_ui: '/api/tools/render-ui',\n add_citation: '/api/tools/citation',\n}\n\n/** The portable MCP server entry the sandbox SDK accepts (transport + url +\n * tagged headers). Assignable to `AgentProfileMcpServer` without a cast —\n * products spread it into their profile's `mcp` map. */\nexport interface AppToolMcpServer {\n transport: 'http'\n url: string\n headers: Record<string, AgentProfileConfigValue>\n enabled: true\n metadata: { description: string }\n}\n\n/** POSIX environment-variable name — the same shape `agent-interface`'s\n * `environmentNameSchema` accepts for an env key. A secret reference resolves\n * from the box environment, so a key outside this shape can never resolve. */\nconst ENV_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/\n\n/**\n * Reject a secret-reference key that names nothing the box can hold.\n *\n * `agent-interface` accepts any non-credential string as a reference key, so a\n * typo or a token VALUE passed where a key belongs validates against the\n * profile schema and fails much later, inside materialization, as an opaque\n * missing-secret error. Failing here names the parameter.\n */\nfunction assertSecretEnvKey(key: string, label: string): string {\n if (!ENV_NAME_PATTERN.test(key)) {\n throw new Error(\n `${label}: tokenEnvKey must be an environment-variable NAME the sandbox box carries ` +\n `(e.g. 'APP_CAPABILITY_TOKEN'), not a token value — got ${JSON.stringify(key)}. ` +\n 'A profile may only REFERENCE a credential; the value is placed on the box by ' +\n 'SandboxRuntimeConfig.env or the platform secret store.',\n )\n }\n return key\n}\n\n/**\n * Validate one emitted entry against the REAL `agentProfileMcpServerSchema`.\n *\n * The contract's rules (which key names demand a reference, which byte patterns\n * read as a credential) live in `agent-interface`. Re-implementing them here\n * would drift the moment that package moves — which it does: 0.36.0 → 0.40.0 in\n * three days. Running the shipped validator instead means a product that passes\n * a credential-bearing custom header name, a relative base URL, or a URL with\n * embedded credentials fails at the builder with the contract's own message.\n *\n * It is also the loud failure for a version skew: if the resolved\n * `@tangle-network/agent-interface` predates 0.38.0, its schema rejects the\n * tagged shape this package now emits, and that surfaces here instead of as a\n * sandbox provisioning error.\n */\nfunction assertProfileMcpServer<T extends AppToolMcpServer>(server: T, label: string): T {\n const result = agentProfileMcpServerSchema.safeParse(server)\n if (!result.success) {\n const issues = result.error.issues\n .map((issue) => `${issue.path.join('.') || '(root)'}: ${issue.message}`)\n .join('; ')\n throw new Error(\n `${label} produced an MCP server the AgentProfile contract rejects: ${issues}. ` +\n 'Requires @tangle-network/agent-interface >= 0.38.0 (tagged MCP config values).',\n )\n }\n return server\n}\n\n/**\n * Refuse to mount a surface whose credential is scoped narrower than the box.\n *\n * A per-user or per-resource capability token is minted per request. The box\n * environment is shared by every turn and every member of the workspace;\n * `env` writes at creation and `runtimeEnv` refreshes workspace-scoped values\n * on retained boxes. Neither path provides a per-turn secret channel, so a\n * narrower token cannot be referenced safely. Widening the channel to a\n * workspace-bound token is not a substitute when the route authenticates the\n * CALLER: the agent can read its own box env, so it could forge that identity.\n *\n * Mounting the surface anyway would emit a plain-string `Authorization` header\n * (rejected by the schema) or a reference to a key nothing places (rejected at\n * materialization). Throwing here names the actual blocker. Exported because\n * every product with per-document MCP surfaces hits it and was writing this\n * message itself.\n */\nexport function unresolvableSurfaceCredential(surface: string): never {\n throw new Error(\n `The ${surface} MCP surface cannot be mounted: its capability token is scoped to a single ` +\n 'user and resource, and an AgentProfile may only reference a credential the sandbox can ' +\n 'resolve from the box environment, which is workspace-wide even when runtimeEnv refreshes it. ' +\n 'Mounting it needs a per-session secret channel on the sandbox API, or a route that ' +\n 'authenticates the workspace rather than the caller.',\n )\n}\n\n/** Define configuration options for building an HTTP MCP server including path, baseUrl, token env key, context, and description */\nexport interface BuildHttpMcpServerOptions {\n /** Route path on the app the sandbox POSTs to (e.g. `/api/tools/propose`). */\n path: string\n /** App base URL the sandbox reaches back to (no trailing slash required). */\n baseUrl: string\n /**\n * NAME of the box-environment variable holding the capability token — never\n * the token itself. The emitted `Authorization` header is a `secret-ref` to\n * this key with `format: 'bearer'`, so the sandbox resolves the value\n * privately and the profile carries only the name.\n *\n * The key MUST name a variable the box actually carries (placed by\n * `SandboxRuntimeConfig.env` at creation, refreshed by\n * `SandboxRuntimeConfig.runtimeEnv` before retained-box bootstrap, or\n * injected from the platform secret store via\n * `SandboxRuntimeConfig.secrets`). The value must be a workspace-scoped token\n * this route accepts for the active box; a per-user or per-resource token is\n * not referenceable: see {@link unresolvableSurfaceCredential}.\n */\n tokenEnvKey: string\n ctx: AppToolContext\n /** Tool description the model sees. */\n description: string\n headerNames?: ToolHeaderNames\n}\n\n/**\n * Build ONE HTTP MCP server entry — the generic agent→app bridge. The\n * capability token (as a secret reference) + the user/workspace/thread ids ride\n * in server-set headers (never tool args), so the model can't forge identity or\n * target another workspace. Workspace/thread headers are omitted when their\n * `ctx` value is empty/null (e.g. an integration-invoke bridge that's\n * user-scoped only). Used directly for non-app-tool bridges\n * (integration_invoke) and via {@link buildAppToolMcpServer} for the four app\n * tools.\n */\nexport function buildHttpMcpServer(opts: BuildHttpMcpServerOptions): AppToolMcpServer {\n const base = opts.baseUrl.replace(/\\/+$/, '')\n const h = opts.headerNames ?? DEFAULT_HEADER_NAMES\n return assertProfileMcpServer(\n {\n transport: 'http',\n url: `${base}${opts.path}`,\n headers: {\n Authorization: defineAgentProfileSecretRef(\n assertSecretEnvKey(opts.tokenEnvKey, 'buildHttpMcpServer'),\n 'bearer',\n ),\n [h.userId]: defineAgentProfilePublicConfig(opts.ctx.userId),\n ...(opts.ctx.workspaceId\n ? { [h.workspaceId]: defineAgentProfilePublicConfig(opts.ctx.workspaceId) }\n : {}),\n ...(opts.ctx.threadId\n ? { [h.threadId]: defineAgentProfilePublicConfig(opts.ctx.threadId) }\n : {}),\n 'Content-Type': defineAgentProfilePublicConfig('application/json'),\n },\n enabled: true,\n metadata: { description: opts.description },\n },\n 'buildHttpMcpServer',\n )\n}\n\n/** Options for a per-document/scoped MCP channel entry (design-canvas,\n * sequences, …). The capability token + path scope ONE resource; the document\n * id lives in the path, never a tool argument. */\nexport interface ScopedMcpServerEntryOptions {\n /** App base URL the sandbox reaches back to (trailing slash tolerated). */\n baseUrl: string\n /** Product route serving the resource's MCP handler — id is part of the path. */\n path: string\n /**\n * NAME of the box-environment variable holding this channel's capability\n * token — never the token itself. See\n * {@link BuildHttpMcpServerOptions.tokenEnvKey}.\n *\n * A per-(user, resource) token cannot satisfy this: the box environment is\n * workspace-wide; `env` writes at creation and `runtimeEnv` refreshes\n * workspace-scoped values on retained boxes. A product whose channel needs\n * a narrower token calls {@link unresolvableSurfaceCredential} rather than\n * mounting an entry that cannot resolve safely.\n */\n tokenEnvKey: string\n /** Override the channel's default tool-server description. */\n description?: string\n /** Identity headers for products whose route recovers the user via\n * `authenticateToolRequest`. Omit when the bearer token is self-contained. */\n ctx?: AppToolContext\n headerNames?: ToolHeaderNames\n}\n\n/**\n * Build the `AgentProfileMcpServer`-shaped entry for a scoped, per-resource MCP\n * channel. The shared mechanism behind the per-domain entry builders\n * (`buildDesignCanvasMcpServerEntry`, `buildSequencesMcpServerEntry`): same\n * token/path guards, same description default, same ctx-vs-self-contained-token\n * branching. The domain is two parameters — `label` (for guard messages) and\n * `defaultDescription` — never baked.\n *\n * The no-`ctx` branch is a GENUINE behavioral path, not a shortcut: it emits a\n * self-contained-token entry with ONLY `Authorization` + `Content-Type`.\n * Routing it through {@link buildHttpMcpServer} would unconditionally write a\n * `userId` identity header (here `undefined`), so it stays a distinct branch.\n */\nexport function buildScopedMcpServerEntry(\n opts: ScopedMcpServerEntryOptions & { label: string; defaultDescription: string },\n): AppToolMcpServer {\n if (opts.tokenEnvKey.trim().length === 0) {\n throw new Error(`${opts.label} requires a capability token env key — omit the MCP server when none is available`)\n }\n if (!opts.path.startsWith('/')) {\n throw new Error(`${opts.label} path must start with \"/\" (got \"${opts.path}\")`)\n }\n const description = opts.description ?? opts.defaultDescription\n\n if (opts.ctx) {\n return buildHttpMcpServer({\n path: opts.path,\n baseUrl: opts.baseUrl,\n tokenEnvKey: opts.tokenEnvKey,\n ctx: opts.ctx,\n description,\n headerNames: opts.headerNames ?? DEFAULT_HEADER_NAMES,\n })\n }\n\n return assertProfileMcpServer(\n {\n transport: 'http',\n url: `${opts.baseUrl.replace(/\\/+$/, '')}${opts.path}`,\n headers: {\n Authorization: defineAgentProfileSecretRef(\n assertSecretEnvKey(opts.tokenEnvKey, opts.label),\n 'bearer',\n ),\n 'Content-Type': defineAgentProfilePublicConfig('application/json'),\n },\n enabled: true,\n metadata: { description },\n },\n opts.label,\n )\n}\n\n/** Define configuration options required to build an MCP server including tool, baseUrl, token, and context */\nexport interface BuildMcpServerOptions {\n /** A built-in app tool name, or a product-registered {@link AppToolDefinition}.\n * A custom tool supplies its route via `AppToolDefinition.path` (or `paths`). */\n tool: AppToolName | AppToolDefinition\n baseUrl: string\n /** NAME of the box-environment variable holding the capability token — see\n * {@link BuildHttpMcpServerOptions.tokenEnvKey}. */\n tokenEnvKey: string\n ctx: AppToolContext\n description: string\n headerNames?: ToolHeaderNames\n paths?: Partial<Record<string, string>>\n}\n\n/** Build one app-tool MCP server entry — a thin wrapper over\n * {@link buildHttpMcpServer} that resolves the tool's route path. Built-ins map\n * through {@link DEFAULT_APP_TOOL_PATHS}; a custom tool uses its own `path`\n * (or a `paths` override). */\nexport function buildAppToolMcpServer(opts: BuildMcpServerOptions): AppToolMcpServer {\n const path =\n typeof opts.tool === 'string'\n ? opts.paths?.[opts.tool] ?? DEFAULT_APP_TOOL_PATHS[opts.tool]\n : opts.paths?.[opts.tool.name] ?? opts.tool.path\n if (!path) {\n const name = typeof opts.tool === 'string' ? opts.tool : opts.tool.name\n throw new Error(`buildAppToolMcpServer: tool \"${name}\" has no route path — set AppToolDefinition.path or pass it via opts.paths`)\n }\n return buildHttpMcpServer({\n path,\n baseUrl: opts.baseUrl,\n tokenEnvKey: opts.tokenEnvKey,\n ctx: opts.ctx,\n description: opts.description,\n headerNames: opts.headerNames,\n })\n}\n"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MACnE;AAAA,MACA,SAAS;AAAA,MACT,UAAU,EAAE,YAAY;AAAA,IAC1B;AAAA,IACA,KAAK;AAAA,EACP;AACF;AAqBO,SAAS,sBAAsB,MAA+C;AACnF,QAAM,OACJ,OAAO,KAAK,SAAS,WACjB,KAAK,QAAQ,KAAK,IAAI,KAAK,uBAAuB,KAAK,IAAI,IAC3D,KAAK,QAAQ,KAAK,KAAK,IAAI,KAAK,KAAK,KAAK;AAChD,MAAI,CAAC,MAAM;AACT,UAAM,OAAO,OAAO,KAAK,SAAS,WAAW,KAAK,OAAO,KAAK,KAAK;AACnE,UAAM,IAAI,MAAM,gCAAgC,IAAI,iFAA4E;AAAA,EAClI;AACA,SAAO,mBAAmB;AAAA,IACxB;AAAA,IACA,SAAS,KAAK;AAAA,IACd,aAAa,KAAK;AAAA,IAClB,KAAK,KAAK;AAAA,IACV,aAAa,KAAK;AAAA,IAClB,aAAa,KAAK;AAAA,EACpB,CAAC;AACH;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/profile/home.ts"],"sourcesContent":["import type { AgentProfile, AgentProfileFileMount } from '@tangle-network/agent-interface'\nimport { defineInlineResource, mergeAgentProfiles } from '@tangle-network/agent-interface'\n\n/** Unicode code-point budgets. The installed writer also bounds UTF-8 bytes. */\nexport const DEFAULT_HOME_LIMITS = {\n 'AGENTS.md': 12_000,\n 'SOUL.md': 8_000,\n 'IDENTITY.md': 4_000,\n 'USER.md': 4_000,\n 'MEMORY.md': 16_000,\n 'BOOTSTRAP.md': 8_000,\n dailyNote: 12_000,\n skill: 32_000,\n} as const\n\nexport const DEFAULT_AGENT_HOME = '/var/lib/tangle-agent/home'\n\nconst AGENTS = `# Home\n\nThis is your durable home in your private Tangle computer. Inspect and use the computer.\nThe platform owns this file and the home writer. Your normal shell is not root.\n\n## Behavior\n- The person's current request comes first.\n- Reply in the person's language. Switch when they switch.\n- In a group, reply only when mentioned or directly addressed.\n- Be genuinely helpful, not performatively helpful. Be resourceful before asking.\n- Have a point of view when useful, and distinguish evidence from uncertainty.\n- Remember you are a guest in the person's or group's space.\n\n## Memory\n- IDENTITY.md starts empty. Fill it during first run.\n- USER.md holds dated preferences, at most 4,000 Unicode characters.\n- MEMORY.md holds curated durable facts. Shared facts must be safe for the whole group.\n- memory/YYYY-MM-DD.md holds daily notes; consolidate durable facts nightly.\n- skills/<name>/SKILL.md holds reusable skills, not new authority.\n- Never write credentials or private third-party records into memory.\n- Use home_read, home_write, home_append, home_status and home_consolidate.\n- Replacements, deletions and consolidation require expectedHead from the home snapshot you read. Reread after a conflict; never blindly retry an unconfirmed append.\n- The protected writer enforces file, character and byte budgets before writes and commits to git.\n- Shell, code and ordinary project files remain available elsewhere in this sandbox.\n- Do not work around a rejected home write by chmod, symlinks, another interpreter or another credential.\n\n## Self edits\nSOUL.md is editable through home_write. Tell the owner what changed and why when ownerNoticeRequired is returned.\nAGENTS.md is platform-owned and cannot be edited. Business rules belong in skills and presets.\n`\n\nconst SOUL = `# Soul\n\nBe genuinely helpful, not performatively helpful.\nHave opinions when judgment is useful.\nBe resourceful before asking.\nRemember you are a guest.\nPrefer clear, direct answers over ceremony.\n`\n\nconst BOOTSTRAP = `# First run\n\nThe user's request always comes first. Do not delay the answer for setup.\n\nAfter answering enough to be useful:\n1. Read AGENTS.md and SOUL.md.\n2. Read IDENTITY.md, then fill it if empty through home_write with its returned commit as expectedHead, using the configured identity, not an invented biography.\n3. Record any stated durable preference as a dated USER.md entry through home_write or home_append.\n4. Add a daily note only when there is something worth remembering.\n5. Call home_bootstrap. It removes this file and returns the git commit.\n`\n\nfunction inline(path: string, content: string): AgentProfileFileMount {\n return { path, resource: defineInlineResource(`default-home:${path}`, content) }\n}\n\n/** Canonical seed records. The trusted image installer materializes these once. */\nexport function defaultHomeFiles(): AgentProfileFileMount[] {\n return [\n inline('AGENTS.md', AGENTS), inline('SOUL.md', SOUL),\n inline('IDENTITY.md', ''), inline('USER.md', ''), inline('MEMORY.md', ''),\n inline('BOOTSTRAP.md', BOOTSTRAP),\n ]\n}\n\n/**\n * Compose home instructions, not per-turn writes to persistent memory.\n * The published install-home command consumes defaultHomeFiles with the same\n * inline resource format as other profile seeds. A privileged, one-time phase\n * is necessary: ordinary resources.files writes run as the agent and cannot\n * make a same-UID shell respect caps or platform file ownership.\n */\nexport function withDefaultAgentHome(profile: AgentProfile): AgentProfile {\n const reserved = new Set(['AGENTS.md', 'SOUL.md', 'IDENTITY.md', 'USER.md', 'MEMORY.md', 'BOOTSTRAP.md', '.tangle/home.py'])\n for (const file of profile.resources?.files ?? []) {\n const parts = file.path.replace(/\\\\/g, '/').split('/').filter(part => part && part !== '.')\n if (parts.includes('..')) throw new Error('Home-aware profiles require canonical file mount paths')\n const path = parts.join('/')\n if (reserved.has(path) || path === 'var/lib/tangle-agent' || path.startsWith('var/lib/tangle-agent/') ||\n path.startsWith('etc/tangle-agent/') || path === 'usr/local/libexec/tangle-agent-home.py') {\n throw new Error('Do not remount the protected home; use the home tools and business skills')\n }\n }\n const merged = mergeAgentProfiles(profile, { prompt: { instructions: [\n `Your git-tracked home is ${DEFAULT_AGENT_HOME}. Read AGENTS.md and SOUL.md there.`,\n 'Use the protected home tools for memory and bootstrap. Native shell remains available for ordinary code and project files. A missing protected-home installation is an infrastructure error, not permission to create an unprotected replacement.',\n ] } })\n if (!merged) throw new Error('Home profile composition returned no profile')\n return merged\n}\n"],"mappings":";AACA,SAAS,sBAAsB,0BAA0B;AAGlD,IAAM,sBAAsB;AAAA,EACjC,aAAa;AAAA,EACb,WAAW;AAAA,EACX,eAAe;AAAA,EACf,WAAW;AAAA,EACX,aAAa;AAAA,EACb,gBAAgB;AAAA,EAChB,WAAW;AAAA,EACX,OAAO;AACT;AAEO,IAAM,qBAAqB;AAElC,IAAM,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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AQ,OAAM,IAAI,MAAM,8CAA8C;AAC3E,SAAO;AACT;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/harness/index.ts","../src/harness/session-selection.ts","../src/harness/presets.ts"],"sourcesContent":["/**\n * Coding-agent harness selection, model compatibility, and the session lock.\n *\n * Known identities are not a deployment's available runners. Products supply\n * server-owned availability to resolveSessionHarness. Historical session IDs\n * remain intact when their runner is unavailable; a harness change requires an\n * explicit transfer, not a fallback or a rewritten session lock.\n *\n * Model compatibility is owned by @tangle-network/agent-interface. The shell\n * owns session selection; the consumer owns storage and deployment policy.\n */\n\nimport {\n harnessProviders,\n harnessSupportsModel,\n harnessTypeSchema,\n modelProvider,\n preferredHarnessForModel,\n snapHarnessToModel as aiSnapHarnessToModel,\n snapModelToHarness as aiSnapModelToHarness,\n type HarnessType,\n} from '@tangle-network/agent-interface'\nimport {\n selectSessionHarness,\n type SelectionAvailability,\n type SessionHarnessSelection,\n type SessionHarnessSelectionInput,\n} from './session-selection'\n\nexport { HarnessSelectionError } from './session-selection'\n\n/** Canonical identities that have no direct Sandbox backend. */\nconst NON_BACKEND_HARNESSES = ['gemini'] as const satisfies readonly HarnessType[]\nconst nonBackendHarnesses = new Set<string>(NON_BACKEND_HARNESSES)\n\n/** A recognized coding-agent backend, not a promise that it is installed. */\nexport type Harness = Exclude<HarnessType, (typeof NON_BACKEND_HARNESSES)[number]>\n\n/**\n * Recognized backend identities, including IDs needed by historical sessions.\n * Use deployment availability, not membership here, to offer or admit new runs.\n */\nexport const KNOWN_HARNESSES: readonly Harness[] = [\n ...harnessTypeSchema.options.filter(\n (harness): harness is Exclude<HarnessType, (typeof NON_BACKEND_HARNESSES)[number]> =>\n !nonBackendHarnesses.has(harness),\n ),\n]\n\n/** Default for an absent choice; never a replacement for an invalid explicit ID. */\nexport const DEFAULT_HARNESS: Harness = 'opencode'\nconst HARNESS_SET: ReadonlySet<string> = new Set(KNOWN_HARNESSES)\n\n/** Determine whether a value is a recognized identity, independently of availability. */\nexport function isHarness(value: unknown): value is Harness {\n return typeof value === 'string' && HARNESS_SET.has(value)\n}\n\n/** Display/config convenience only. Never use coercion to admit an execution or restore a lock. */\nexport function coerceHarness(value: unknown, fallback: Harness = DEFAULT_HARNESS): Harness {\n return isHarness(value) ? value : fallback\n}\n\n/** Server-owned start and resume sets. Existing-only entries are draining. */\nexport type HarnessAvailability = SelectionAvailability<Harness>\n\n/** A saved lock, explicit choice, workspace default, and optional deployment availability. */\nexport type ResolveSessionHarnessInput = SessionHarnessSelectionInput<Harness>\n\n/** The selected identity and the existing session-lock/swap-attempt result. */\nexport type ResolvedSessionHarness = SessionHarnessSelection<Harness>\n\n/**\n * Resolve requested → workspaceDefault → fallback only for a genuinely new session.\n * A non-null saved identity always takes the lock path. Unknown/retired identities\n * and invalid explicit requests throw HarnessSelectionError instead of falling back.\n * A known different request still reports swapAttempted while preserving the lock.\n * The caller must reject that attempt before execution, as in the existing contract.\n */\nexport function resolveSessionHarness(input: ResolveSessionHarnessInput = {}): ResolvedSessionHarness {\n return selectSessionHarness(input, KNOWN_HARNESSES, DEFAULT_HARNESS)\n}\n\n/**\n * An app's harness configuration, read from its deploy configuration (for example the env vars\n * `AGENT_HARNESS` and `AGENT_HARNESS_WORKSPACES`), so no product hard-codes `backend.type`.\n */\nexport interface HarnessConfig {\n /** The app default for new sessions. Unset or blank means {@link DEFAULT_HARNESS}. */\n default?: string\n /** Per-workspace choices: a JSON object mapping a workspace id to a harness. */\n workspaces?: string\n}\n\nfunction configHarness(value: unknown, where: string): Harness {\n if (!isHarness(value)) throw new Error(`${where} names an unknown harness: ${String(value)}`)\n return value\n}\n\n/**\n * The harness a workspace's new sessions start on: its own choice, else the app default, else\n * {@link DEFAULT_HARNESS}. Pass the result to {@link resolveSessionHarness} as `workspaceDefault`\n * so a session that already ran keeps its harness. A value naming an unknown harness throws:\n * a configuration typo must fail loudly, never run a different harness than the one configured.\n */\nexport function configuredHarness(config: HarnessConfig, workspaceId?: string): Harness {\n const appDefault = config.default?.trim()\n ? configHarness(config.default.trim(), 'The harness default') : DEFAULT_HARNESS\n const raw = config.workspaces?.trim()\n if (!raw) return appDefault\n let choices: unknown\n try {\n choices = JSON.parse(raw)\n } catch {\n throw new Error('The per-workspace harness configuration is not JSON')\n }\n if (!choices || typeof choices !== 'object' || Array.isArray(choices)) {\n throw new Error('The per-workspace harness configuration must map workspace ids to harnesses')\n }\n // Every entry is checked, not only the caller's, so one bad entry fails every workspace's\n // first turn after the deploy instead of hiding until that workspace sends a message.\n const parsed = new Map(Object.entries(choices).map(([id, value]) =>\n [id, configHarness(value, `The harness for workspace ${id}`)]))\n return (workspaceId === undefined ? undefined : parsed.get(workspaceId)) ?? appDefault\n}\n\n/** Harness-model compatibility is delegated to the Interface owner. */\nexport { modelProvider }\n\n/** A resolved model and the transport provider that will execute it. */\nexport interface HarnessModelSelection {\n model: string\n provider?: string\n}\n\n/** Provider-less ids (sentinels like \"default\", or a session's own config) are\n * compatible everywhere — every harness honors its own configuration. */\nexport function isModelCompatibleWithHarness(harness: Harness, modelId: string): boolean {\n return harnessSupportsModel(harness, modelId)\n}\n\n/** Keep `modelId` when the harness can run it; else the harness's best compatible\n * catalog id (preferred patterns in order, highest version). When nothing in the\n * catalog fits, return the original so the caller sees the incompatibility. */\nexport function snapModelToHarness(harness: Harness, modelId: string, canonicalIds: readonly string[]): string {\n return aiSnapModelToHarness(harness, modelId, canonicalIds)\n}\n\n/** Keep the harness when it can run `modelId`; else the model's native harness\n * (anthropic → claude-code, openai → codex, moonshot → kimi-code), falling back to opencode. */\nexport function snapHarnessToModel(harness: Harness, modelId: string): Harness {\n const snapped = aiSnapHarnessToModel(harness, modelId)\n if (!isHarness(snapped)) {\n throw new Error(\n `Harness \"${harness}\" snapped to \"${snapped}\" for model \"${modelId}\", which this platform has no backend for.`,\n )\n }\n return snapped\n}\n\n/** Fail-loud server guard: throw when a harness is asked to run a model it can't.\n * A resolved model tuple supplies provider evidence when its id is unqualified.\n * Call before dispatching a sandbox turn so a bypassed UI cannot reach the\n * sidecar with an incompatible or unproven pair. */\nexport function assertHarnessModelCompatible(\n harness: Harness,\n selection: string | HarnessModelSelection,\n): void {\n const modelId = typeof selection === 'string' ? selection : selection.model\n const transportProvider = typeof selection === 'string' ? undefined : selection.provider\n const providers = harnessProviders(harness)\n const provider = modelProvider(modelId) ?? transportProvider ?? null\n // An omitted/default model is deliberately left to the harness. Once a\n // caller names a model, however, a vendor-locked harness must have provider\n // evidence. Interface owns which harnesses are locked: since 5.7 Claude Code\n // and Codex run any Router-served model, and kimi-code stays Moonshot-only.\n const isDefaultSentinel = modelId.trim() === '' || modelId.trim() === 'default'\n const compatible = isDefaultSentinel\n || providers === null\n || (provider !== null && providers.includes(provider))\n if (!compatible) {\n const native = preferredHarnessForModel(modelId)\n const providerDescription = provider ?? 'unqualified'\n throw new Error(\n `Harness \"${harness}\" cannot run model \"${modelId}\" (provider \"${providerDescription}\"). ` +\n `Use ${native ?? 'a router-backed harness (opencode)'} or an allowed model.`,\n )\n }\n}\n\n// Profile-support facts remain here until the materializer supplies its owned descriptor.\n// Do not confuse these facts with deployment availability.\n\n/** What a harness can express, for profile assembly. */\nexport interface HarnessCapabilities {\n /** Lower profile.subagents into native cwd files; false means materialization refuses them. */\n subagents: boolean\n /** How profile.mcp reaches the harness. */\n mcp: 'native' | 'config-file' | 'extension' | 'none'\n /** Whether tool controls are checked before MCP tools register. */\n toolControls: 'startup' | 'runtime'\n /** cwd-relative skill directory, or null when skills must be inlined. */\n skillsDir: string | null\n}\n\nconst HARNESS_CAPABILITIES: Record<Harness, HarnessCapabilities> = {\n 'claude-code': { subagents: true, mcp: 'native', toolControls: 'runtime', skillsDir: '.claude/skills' },\n nanoclaw: { subagents: true, mcp: 'native', toolControls: 'runtime', skillsDir: '.claude/skills' },\n opencode: { subagents: true, mcp: 'config-file', toolControls: 'runtime', skillsDir: '.opencode/skills' },\n codex: { subagents: true, mcp: 'config-file', toolControls: 'runtime', skillsDir: '.codex/skills' },\n 'kimi-code': { subagents: false, mcp: 'config-file', toolControls: 'runtime', skillsDir: '.kimi/skills' },\n pi: { subagents: false, mcp: 'extension', toolControls: 'startup', skillsDir: '.pi/skills' },\n prime: { subagents: true, mcp: 'native', toolControls: 'runtime', skillsDir: '.prime/agent/skills' },\n hermes: { subagents: false, mcp: 'native', toolControls: 'runtime', skillsDir: null },\n openclaw: { subagents: false, mcp: 'config-file', toolControls: 'runtime', skillsDir: 'skills' },\n acp: { subagents: false, mcp: 'native', toolControls: 'runtime', skillsDir: null },\n amp: { subagents: false, mcp: 'native', toolControls: 'runtime', skillsDir: null },\n 'factory-droids': { subagents: false, mcp: 'native', toolControls: 'runtime', skillsDir: null },\n forge: { subagents: false, mcp: 'native', toolControls: 'runtime', skillsDir: null },\n cursor: { subagents: false, mcp: 'native', toolControls: 'runtime', skillsDir: null },\n 'cli-base': { subagents: false, mcp: 'native', toolControls: 'runtime', skillsDir: null },\n}\n\n/** Profile-support facts, independent of whether this deployment enables the harness. */\nexport function harnessCapabilities(harness: Harness): HarnessCapabilities {\n const caps = HARNESS_CAPABILITIES[harness]\n if (!caps) throw new Error(`harnessCapabilities: no capability facts for \"${harness}\"`)\n return caps\n}\n\n// ── Session presets ────────────────────────────────────────────────────────\n//\n// Named (model, harness, effort) pins applied with catalog coherence through\n// the snap helpers above. The contract is semantics; the visual surface stays\n// with the picker canon.\nexport {\n applySessionPreset,\n createInMemorySessionPresetStore,\n validateSessionPreset,\n type AppliedSessionPreset,\n type SessionPreset,\n type SessionPresetCatalogContext,\n type SessionPresetStore,\n} from './presets'\n","/** Pure session admission. Harness identity is not deployment availability. */\nexport interface SelectionAvailability<H extends string> {\n /** Server-owned selection for new sessions. An empty list disables all starts. */\n readonly newSessions: readonly H[]\n /** Includes draining harnesses. Omission uses newSessions, never all known IDs. */\n readonly existingSessions?: readonly H[]\n}\n\nexport interface SessionHarnessSelectionInput<H extends string> {\n sessionHarness?: unknown\n requested?: unknown\n workspaceDefault?: unknown\n fallback?: H\n /** Omit only when the caller deliberately admits every known harness. */\n availability?: SelectionAvailability<H>\n}\n\nexport interface SessionHarnessSelection<H extends string> {\n harness: H\n locked: boolean\n swapAttempted: boolean\n}\n\ntype SelectionSource = 'session' | 'requested' | 'workspace' | 'fallback'\n\n/** An admission failure, never permission to retry on another harness. */\nexport class HarnessSelectionError extends Error {\n readonly code: 'harness_unknown' | 'harness_unavailable'\n readonly harness: string | null\n readonly source: SelectionSource\n\n constructor(\n code: 'harness_unknown' | 'harness_unavailable',\n value: unknown,\n source: SelectionSource,\n ) {\n const harness = typeof value === 'string' ? value : null\n super(`${code}: ${source} harness ${harness === null ? '<invalid>' : JSON.stringify(harness)}`)\n this.name = 'HarnessSelectionError'\n this.code = code\n this.harness = harness\n this.source = source\n }\n}\n\n/**\n * Null/undefined mean no choice. Every other value is an explicit choice and must\n * validate. A retired or unrecognized saved identity must never become a new session.\n * Availability is supplied by the authenticated server, not by a request body.\n */\nexport function selectSessionHarness<H extends string>(\n input: SessionHarnessSelectionInput<H>,\n knownHarnesses: readonly H[],\n defaultHarness: H,\n): SessionHarnessSelection<H> {\n const known = new Set<string>(knownHarnesses)\n const resolve = (value: unknown, source: SelectionSource): H => {\n if (typeof value !== 'string' || !known.has(value)) {\n throw new HarnessSelectionError('harness_unknown', value, source)\n }\n return value as H\n }\n const admit = (harness: H, source: SelectionSource, existing: boolean): void => {\n if (input.availability === undefined) return\n const allowed = existing\n ? input.availability.existingSessions ?? input.availability.newSessions\n : input.availability.newSessions\n if (!allowed.includes(harness)) {\n throw new HarnessSelectionError('harness_unavailable', harness, source)\n }\n }\n\n if (input.sessionHarness !== undefined && input.sessionHarness !== null) {\n const harness = resolve(input.sessionHarness, 'session')\n admit(harness, 'session', true)\n // A known different request remains a swap attempt; it is not executed. An\n // invalid request is refused rather than being misreported as no swap.\n const requested = input.requested === undefined || input.requested === null\n ? undefined : resolve(input.requested, 'requested')\n return { harness, locked: true, swapAttempted: requested !== undefined && requested !== harness }\n }\n\n const source: SelectionSource = input.requested !== undefined && input.requested !== null\n ? 'requested'\n : input.workspaceDefault !== undefined && input.workspaceDefault !== null\n ? 'workspace' : 'fallback'\n const value = source === 'requested' ? input.requested\n : source === 'workspace' ? input.workspaceDefault : input.fallback ?? defaultHarness\n const harness = resolve(value, source)\n admit(harness, source, false)\n return { harness, locked: false, swapAttempted: false }\n}\n","/**\n * Session presets — named (model, harness, effort) combinations a user pins\n * and applies in one action, beside the canonical session controls\n * (`/web-react`'s `AgentSessionControls`).\n *\n * The CONTRACT is coherence, not storage: a preset stores exact catalog ids,\n * and APPLYING it resolves through the harness module's snap helpers so the\n * result is never an invalid combination — if the catalog moved under a\n * pinned preset (model renamed, harness retired), apply snaps to the\n * harness's best compatible catalog option (or the model's native harness)\n * exactly like a manual picker change would, and reports what changed.\n * A preset naming a model the catalog no longer carries is REFUSED at\n * apply time, never silently substituted: a different model is a different\n * decision-maker.\n *\n * Storage is a port: products persist presets wherever they keep workspace\n * state (D1, KV, localStorage). The default store is in-memory for tests\n * and single-instance products — the same shape the self-mount verb uses.\n */\nimport { snapHarnessToModel, snapModelToHarness, type Harness } from './index'\n\n/** A pinned session configuration. `id` is the product's stable key. */\nexport interface SessionPreset {\n readonly id: string\n /** User-facing label; trimmed, non-empty, ≤ 60 chars. */\n readonly name: string\n /** Canonical catalog model id (\"provider/model\"). */\n readonly model: string\n /** Optional pinned harness; omitted = follow the model's native harness. */\n readonly harness?: Harness\n /** Optional pinned reasoning effort (the picker canon's effort levels). */\n readonly effort?: string\n}\n\n/** What applying a preset actually set, with every snap named. */\nexport interface AppliedSessionPreset {\n readonly model: string\n readonly harness: Harness\n readonly effort?: string\n /** Non-empty when the catalog moved under the pinned preset. */\n readonly snapped: ReadonlyArray<'model' | 'harness'>\n}\n\nexport interface SessionPresetCatalogContext {\n /** The catalog's canonical model ids. */\n readonly canonicalIds: readonly string[]\n}\n\n/** Validate one preset at save time: label budget, canonical model id, no\n * unknown fields smuggled in. Throws with the preset's name in the message. */\nexport function validateSessionPreset(preset: SessionPreset): SessionPreset {\n const name = preset.name.trim()\n if (!name) throw new Error('a session preset needs a name')\n if (name.length > 60) {\n throw new Error(`session preset \"${name.slice(0, 30)}…\" exceeds the 60-character name budget`)\n }\n if (!preset.model.trim()) throw new Error(`session preset \"${name}\" pins no model`)\n const allowed = new Set(['id', 'name', 'model', 'harness', 'effort'])\n for (const key of Object.keys(preset)) {\n if (!allowed.has(key)) throw new Error(`session preset \"${name}\" carries an unknown field \"${key}\"`)\n }\n return { ...preset, name }\n}\n\n/** Apply a preset with catalog coherence. Refused (thrown) when the pinned\n * model is gone from the catalog — never silently another model. */\nexport function applySessionPreset(\n preset: SessionPreset,\n context: SessionPresetCatalogContext,\n): AppliedSessionPreset {\n if (!context.canonicalIds.includes(preset.model)) {\n throw new Error(\n `session preset \"${preset.name}\" pins model \"${preset.model}\", which the catalog no longer carries — `\n + `delete or re-pin the preset (a different model is a different decision-maker)`,\n )\n }\n const snapped: Array<'model' | 'harness'> = []\n const pinnedHarness = preset.harness ?? snapHarnessToModel('opencode', preset.model)\n let model = preset.model\n let harness = pinnedHarness\n // The same two-way coherence the manual pickers enforce, in the preset's\n // own order: the pinned harness snaps the model if incompatible, then the\n // (possibly snapped) model snaps the harness back if it moved families.\n const harnessCompatibleModel = snapModelToHarness(harness, model, context.canonicalIds)\n if (harnessCompatibleModel !== model) {\n model = harnessCompatibleModel\n snapped.push('model')\n }\n const modelNativeHarness = snapHarnessToModel(harness, model)\n if (modelNativeHarness !== harness) {\n harness = modelNativeHarness\n snapped.push('harness')\n }\n return {\n model,\n harness,\n ...(preset.effort !== undefined ? { effort: preset.effort } : {}),\n snapped,\n }\n}\n\n/** Durable preset storage port. Products own persistence; the default is\n * non-durable for tests and single-instance products. */\nexport interface SessionPresetStore {\n list(): Promise<readonly SessionPreset[]>\n save(preset: SessionPreset): Promise<void>\n remove(id: string): Promise<void>\n}\n\nexport function createInMemorySessionPresetStore(): SessionPresetStore {\n const state = new Map<string, SessionPreset>()\n return {\n async list() { return [...state.values()].sort((a, b) => a.name.localeCompare(b.name)) },\n async save(preset) { state.set(preset.id, validateSessionPreset(preset)) },\n async remove(id) { state.delete(id) },\n }\n}\n\n/**\n * The composer/controls integration seam: presets render beside the canonical\n * pickers (picker-canon geometry) and apply through {@link applySessionPreset};\n * saving captures the CURRENT picker selection verbatim. The visual surface is\n * deliberately not owned here — the picker canon and the product's design\n * tokens define it; this module guarantees the semantics underneath.\n */\n"],"mappings":";AAYA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,sBAAsB;AAAA,EACtB,sBAAsB;AAAA,OAEjB;;;ACKA,IAAM,wBAAN,cAAoC,MAAM;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EAET,YACE,MACA,OACA,QACA;AACA,UAAM,UAAU,OAAO,UAAU,WAAW,QAAQ;AACpD,UAAM,GAAG,IAAI,KAAK,MAAM,YAAY,YAAY,OAAO,cAAc,KAAK,UAAU,OAAO,CAAC,EAAE;AAC9F,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,UAAU;AACf,SAAK,SAAS;AAAA,EAChB;AACF;AAOO,SAAS,qBACd,OACA,gBACA,gBAC4B;AAC5B,QAAM,QAAQ,IAAI,IAAY,cAAc;AAC5C,QAAM,UAAU,CAACA,QAAgBC,YAA+B;AAC9D,QAAI,OAAOD,WAAU,YAAY,CAAC,MAAM,IAAIA,MAAK,GAAG;AAClD,YAAM,IAAI,sBAAsB,mBAAmBA,QAAOC,OAAM;AAAA,IAClE;AACA,WAAOD;AAAA,EACT;AACA,QAAM,QAAQ,CAACE,UAAYD,SAAyB,aAA4B;AAC9E,QAAI,MAAM,iBAAiB,OAAW;AACtC,UAAM,UAAU,WACZ,MAAM,aAAa,oBAAoB,MAAM,aAAa,cAC1D,MAAM,aAAa;AACvB,QAAI,CAAC,QAAQ,SAASC,QAAO,GAAG;AAC9B,YAAM,IAAI,sBAAsB,uB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,WAAW,eAAe;AAAA,EACxG,IAAI,EAAE,WAAW,OAAO,KAAK,aAAa,cAAc,WAAW,WAAW,aAAa;AAAA,EAC3F,OAAO,EAAE,WAAW,MAAM,KAAK,UAAU,cAAc,WAAW,WAAW,sBAAsB;AAAA,EACnG,QAAQ,EAAE,WAAW,OAAO,KAAK,UAAU,cAAc,WAAW,WAAW,KAAK;AAAA,EACpF,UAAU,EAAE,WAAW,OAAO,KAAK,eAAe,cAAc,WAAW,WAAW,SAAS;AAAA,EAC/F,KAAK,EAAE,WAAW,OAAO,KAAK,UAAU,cAAc,WAAW,WAAW,KAAK;AAAA,EACjF,KAAK,EAAE,WAAW,OAAO,KAAK,UAAU,cAAc,WAAW,WAAW,KAAK;AAAA,EACjF,kBAAkB,EAAE,WAAW,OAAO,KAAK,UAAU,cAAc,WAAW,WAAW,KAAK;AAAA,EAC9F,OAAO,EAAE,WAAW,OAAO,KAAK,UAAU,cAAc,WAAW,WAAW,KAAK;AAAA,EACnF,QAAQ,EAAE,WAAW,OAAO,KAAK,UAAU,cAAc,WAAW,WAAW,KAAK;AAAA,EACpF,YAAY,EAAE,WAAW,OAAO,KAAK,UAAU,cAAc,WAAW,WAAW,KAAK;AAC1F;AAGO,SAAS,oBAAoB,SAAuC;AACzE,QAAM,OAAO,qBAAqB,OAAO;AACzC,MAAI,CAAC,KAAM,OAAM,IAAI,MAAM,iDAAiD,OAAO,GAAG;AACtF,SAAO;AACT;","names":["value","source","harness"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/runtime/protected-model.ts","../src/runtime/protected-router-turn.ts"],"sourcesContent":["import {\n createProtectedAgentCandidateModelPort,\n type AgentCandidateModelGrantClient,\n type AgentCandidateModelPort,\n} from '@tangle-network/agent-runtime/candidate-execution'\n\nconst GATEWAY_ORIGIN = 'https://candidate-router.tangle.tools'\nconst CONTROL_ORIGIN = 'https://router.tangle.tools/v1/candidate-model-grants'\nconst ACTIVATION_NAMES = [\n 'MODEL_GATEWAY_TOKEN', 'MODEL_GATEWAY_BASE_URL', 'OPENAI_API_KEY', 'OPENAI_BASE_URL',\n 'ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'ANTHROPIC_BASE_URL',\n] as const\n\nexport interface RouterProtectedModelPortOptions {\n apiKey: string\n maxCostUsd: number\n clientName?: string\n signal?: AbortSignal\n onSettlement?(receipt: RouterProtectedModelSettlement): Promise<void> | void\n}\n\n/** A validated charge remains authoritative when the product cannot save its audit record. */\nexport class ProtectedModelSettlementError extends Error {\n constructor(readonly settlement: Awaited<ReturnType<AgentCandidateModelPort['settleGrant']>>, cause: unknown) {\n super('Protected model settled, but its audit record could not be saved', { cause })\n this.name = 'ProtectedModelSettlementError'\n }\n}\n\n/** Bind one turn to Router's atomic grant ledger without exposing its parent key. */\nexport function createRouterProtectedModelPort(options: RouterProtectedModelPortOptions): AgentCandidateModelPort {\n if (!options.apiKey || !Number.isFinite(options.maxCostUsd) || options.maxCostUsd <= 0\n || !Number.isSafeInteger(Math.round(options.maxCostUsd * 1_000_000_000))) {\n throw new Error('Protected Router transport requires a parent key and finite positive cap')\n }\n const receipts = new Map<string, RouterProtectedModelSettlement>()\n async function request<T>(operation: string, body: unknown, settling = false): Promise<T> {\n const timeout = AbortSignal.timeout(settling ? 30_000 : 15_000)\n const signal = !settling && options.signal ? AbortSignal.any([timeout, options.signal]) : timeout\n let response: Response\n try {\n response = await fetch(`${CONTROL_ORIGIN}/${operation}`, {\n // Workerd supports manual redirects; non-2xx responses below still fail closed.\n method: 'POST', redirect: 'manual', signal,\n headers: {\n Authorization: `Bearer ${options.apiKey}`,\n 'Content-Type': 'application/json', 'X-Tangle-Client': options.clientName ?? 'agent-app',\n },\n body: JSON.stringify(body),\n })\n } catch {\n if (!settling && options.signal?.aborted) throw options.signal.reason\n throw new Error(`Protected model ${operation} transport failed`)\n }\n if (!response.ok) {\n const body = await response.json().catch(() => null) as { error?: { code?: unknown } } | null\n const code = body?.error?.code\n // Preserve Runtime's draining retry contract without echoing server text or credentials.\n const safeCode = typeof code === 'string' && /^candidate_[a-z_]{1,80}$/.test(code) ? code : 'request_failed'\n throw new Error(`Protected model ${operation}: ${safeCode} (HTTP ${response.status})`)\n }\n return await response.json() as T\n }\n\n const client: AgentCandidateModelGrantClient = {\n reserve: (value) => request('reserve', value),\n activate: async (value) => {\n const activation = await request<Awaited<ReturnType<AgentCandidateModelGrantClient['activate']>>>('activate', value)\n const env = activation?.env\n const token = env?.MODEL_GATEWAY_TOKEN\n if (typeof token !== 'string' || !/^sk-tgr-[A-Za-z0-9_-]{32,}$/.test(token)\n || env.MODEL_GATEWAY_BASE_URL !== `${GATEWAY_ORIGIN}/v1`\n || env.OPENAI_BASE_URL !== `${GATEWAY_ORIGIN}/v1`\n || env.ANTHROPIC_BASE_URL !== GATEWAY_ORIGIN\n || [env.OPENAI_API_KEY, env.ANTHROPIC_API_KEY, env.ANTHROPIC_AUTH_TOKEN].some((value) => value !== token)) {\n throw new Error('Protected model activation changed the gateway or credential binding')\n }\n return activation\n },\n settle: async (value) => {\n const settlement = await request<RouterProtectedModelSettlement>('settle', value, true)\n assertWithinCap(settlement, options.maxCostUsd)\n receipts.set(value.preparationId, settlement)\n return settlement\n },\n }\n const port = createProtectedAgentCandidateModelPort({\n client, resolveModel: (value) => request('resolve', value),\n gatewayDomain: 'candidate-router.tangle.tools', activationEnvNames: ACTIVATION_NAMES,\n })\n return {\n ...port,\n settleGrant: async (value) => {\n const settlement = await port.settleGrant(value)\n const receipt = receipts.get(value.preparationId)\n if (receipt) {\n try {\n await options.onSettlement?.(structuredClone(receipt))\n } catch (error) {\n throw new ProtectedModelSettlementError(settlement, error)\n } finally {\n receipts.delete(value.preparationId)\n }\n }\n return settlement\n },\n }\n}\n\n/**\n * Router's settle response is Runtime's exact settlement ledger. Router keeps\n * the billing hold and charge behind it and refuses a settlement outside the\n * grant's frozen limits; Runtime rejects unknown or missing ledger fields.\n */\nexport type RouterProtectedModelSettlement = Awaited<ReturnType<AgentCandidateModelGrantClient['settle']>>\n\n/** Bound the ledger's cumulative cost by this turn's cap before anything retains it. */\nfunction assertWithinCap(settlement: RouterProtectedModelSettlement, capUsd: number): void {\n if (!Array.isArray(settlement?.calls)) throw new Error('Protected model settlement has no call ledger')\n const capNanos = Math.round(capUsd * 1_000_000_000)\n let cost = 0\n for (const call of settlement.calls) {\n if (!Number.isSafeInteger(call?.costUsdNanos) || call.costUsdNanos < 0) {\n throw new Error('Protected model call cost is invalid')\n }\n cost += call.costUsdNanos\n if (!Number.isSafeInteger(cost) || cost > capNanos) {\n throw new Error('Protected model settlement exceeds its cost cap')\n }\n }\n}\n","/**\n * A Router turn under a protected model grant.\n *\n * Runtime resolves, reserves, activates and settles the grant around exactly\n * one `runRouterTurn` (`runProtectedAgentCandidateModelGrant`); the turn's model\n * calls use the grant's scoped key and base URL; the settled ledger is the\n * turn's only usage. GTM's bounded lane and Legal's paid consultations run here\n * through `createProtectedRuntimeChatProducer`, on the same engine as every\n * other Router turn. This module stays off the `./router-turn` entry: the grant\n * client pulls agent-runtime chunks a Worker bundle cannot build\n * (tests/router-turn-entry.test.ts).\n *\n * Every refusal and failure is a typed outcome. Codes:\n * - `grant_deadline`, `grant_model_unsupported`, `grant_activation_missing`:\n * refused before any model call.\n * - `grant_failed`: the grant could not be resolved, reserved or activated.\n * - `grant_unsettled`: the turn failed and its grant did not settle either.\n * - `settlement_over_limit`, `settlement_unauthorized_reasoning`,\n * `settlement_audit_failed`: the turn answered, but its settled ledger failed\n * a check; the answer stands and the turn still fails.\n * - `turn_deadline`: the turn reached the grant's deadline or its own budget.\n * A grant turn never continues: finishing it would need a second grant.\n * - Anything else is the turn's own failure (`turn_aborted`, `turn_tool_limit`,\n * `model_http_<status>`, ...), settled as `failed`.\n */\nimport {\n runProtectedAgentCandidateModelGrant,\n type RunProtectedAgentCandidateModelGrantOptions,\n} from '@tangle-network/agent-runtime/candidate-execution'\nimport { ProtectedModelSettlementError } from './protected-model'\nimport { runRouterTurn, type RouterTurnFailure, type RouterTurnOptions, type RouterTurnOutcome } from './router-turn'\n\n/** Runtime's grant inputs for one turn: the port, the model request, the reservation and its deadline. */\nexport type RouterTurnGrant = Omit<RunProtectedAgentCandidateModelGrantOptions<void>, 'execute'>\n\ntype GrantSettlement = Awaited<ReturnType<RouterTurnGrant['port']['settleGrant']>>\n\n/** A turn under a grant. The grant supplies the key and base URL; one grant never repeats or continues a turn.\n * Placement is decided before a grant is reserved, so it is not an option here. */\nexport type ProtectedRouterTurnOptions = Omit<RouterTurnOptions, 'apiKey' | 'baseUrl' | 'repeat' | 'placement' | 'continueFrom'> & {\n grant: RouterTurnGrant\n}\n\n/** A grant turn's outcome. It carries no `continuation`: a turn at its deadline fails as `turn_deadline`. */\nexport interface ProtectedRouterTurnOutcome extends Omit<RouterTurnOutcome, 'continuation'> {\n /** What the grant settled, present whenever it settled, including for a failed turn. */\n settlement?: RouterTurnSettlement\n}\n\n/** What the grant settled for the turn. */\nexport interface RouterTurnSettlement {\n /** Runtime's settled ledger, retained even when a check on it fails. */\n receipt: GrantSettlement\n /** The model the grant resolved and reserved. */\n model?: string\n usage: { inputTokens: number; outputTokens: number; reasoningTokens: number; costUsd: number }\n /** Router certified the usage within the grant's limits, and no call reasoned under a grant\n * that disabled reasoning. */\n budgetEnforced: boolean\n}\n\n/**\n * Providers whose client function tools are verified over Chat Completions with\n * reasoning disabled. Router refuses provider-hosted tools and cache markers on\n * candidate grants, so tool-result text is billed as input and accounted input\n * covers OpenAI's automatic cached prefix.\n */\nconst GRANT_PROVIDERS: ReadonlySet<string> = new Set(['anthropic', 'openai'])\n\nclass GrantRefusal extends Error {\n constructor(readonly failure: RouterTurnFailure) {\n super(failure.message)\n this.name = 'GrantRefusal'\n }\n}\n\nconst refuse = (code: string, message: string) => new GrantRefusal({ code, message })\n\nfunction failureOf(error: unknown): RouterTurnFailure {\n if (error instanceof GrantRefusal) return error.failure\n if (error instanceof ProtectedModelSettlementError) return { code: 'settlement_audit_failed', message: error.message }\n if (error instanceof AggregateError) return { code: 'grant_unsettled', message: error.message }\n return { code: 'grant_failed', message: error instanceof Error ? error.message : 'The model grant failed.' }\n}\n\n/** Run one `runRouterTurn` under `options.grant`. */\nexport async function runProtectedRouterTurn(options: ProtectedRouterTurnOptions): Promise<ProtectedRouterTurnOutcome> {\n const { grant, ...turnOptions } = options\n let turn: RouterTurnOutcome | undefined\n let settlement: RouterTurnSettlement | undefined\n let resolvedModel: string | undefined\n const result = (failure?: RouterTurnFailure): ProtectedRouterTurnOutcome => {\n const base: RouterTurnOutcome = turn\n ?? { text: '', servedModel: null, toolCalls: [], usage: { promptTokens: 0, completionTokens: 0, modelCalls: 0 }, toolEvents: [] }\n // The grant's verdict replaces the turn's own failure, and a grant turn never continues.\n const { failure: _turnFailure, continuation: _continuation, ...rest } = base\n return { ...rest, ...(settlement ? { settlement } : {}), ...(failure ? { failure } : {}) }\n }\n if (options.signal?.aborted) return result({ code: 'turn_aborted', message: 'The turn was cancelled.' })\n if (Date.now() >= grant.deadlineAtMs) return result({ code: 'grant_deadline', message: 'Protected execution deadline expired' })\n try {\n await runProtectedAgentCandidateModelGrant({\n ...grant,\n port: {\n resolve: async input => {\n const resolved = await grant.port.resolve(input)\n resolvedModel = resolved.model\n return resolved\n },\n reserveGrant: input => grant.port.reserveGrant(input),\n activateGrant: input => grant.port.activateGrant(input),\n // Runtime settles failed executions before rethrowing. Retain that receipt too.\n settleGrant: async input => {\n let auditError: ProtectedModelSettlementError | undefined\n const receipt = await grant.port.settleGrant(input).catch(error => {\n if (!(error instanceof ProtectedModelSettlementError)) throw error\n auditError = error\n return error.settlement\n })\n const usage = {\n inputTokens: receipt.calls.reduce((sum, call) => sum + call.accountedInputTokens, 0),\n outputTokens: receipt.calls.reduce((sum, call) => sum + call.outputTokens, 0),\n reasoningTokens: receipt.calls.reduce((sum, call) => sum + call.reasoningTokens, 0),\n costUsd: receipt.calls.reduce((sum, call) => sum + call.costUsdNanos, 0) / 1e9,\n }\n // Execution limits carry no reasoning allowance, so a provider that\n // reasons under a disabled-reasoning grant exceeded what was authorized.\n const unauthorizedReasoning = usage.reasoningTokens > 0 && grant.resolve.reasoningEffort === 'none'\n const budgetEnforced = receipt.usageWithinLimits && !unauthorizedReasoning\n settlement = { receipt, ...(resolvedModel ? { model: resolvedModel } : {}), usage, budgetEnforced }\n if (unauthorizedReasoning) {\n throw refuse('settlement_unauthorized_reasoning', 'Provider reported reasoning tokens although reasoning was disabled')\n }\n if (!budgetEnforced) throw refuse('settlement_over_limit', 'Provider settlement exceeded execution limits')\n if (auditError) throw auditError\n return receipt\n },\n },\n execute: async ({ activation, resolved }) => {\n if (options.signal?.aborted) throw refuse('turn_aborted', 'The turn was cancelled.')\n if (Date.now() >= grant.deadlineAtMs) throw refuse('grant_deadline', 'Protected execution deadline expired')\n if (!GRANT_PROVIDERS.has(resolved.provider) || resolved.reasoningEffort !== 'none') {\n throw refuse('grant_model_unsupported', 'Protected chat currently requires an Anthropic or OpenAI model without reasoning')\n }\n const apiKey = activation.env.OPENAI_API_KEY\n const baseUrl = activation.env.OPENAI_BASE_URL\n if (!apiKey || !baseUrl) throw refuse('grant_activation_missing', 'Protected Router activation is missing')\n const remainingMs = Math.max(1, grant.deadlineAtMs - Date.now())\n // One grant is one bounded unit: no automatic second billable call, and the\n // grant's deadline ends the model call in flight.\n turn = await runRouterTurn({\n ...turnOptions, apiKey, baseUrl, repeat: false,\n budgetMs: Math.min(options.budgetMs ?? remainingMs, remainingMs),\n signal: AbortSignal.any([AbortSignal.timeout(remainingMs), ...(options.signal ? [options.signal] : [])]),\n })\n // A turn past its deadline fails here: finishing it would need a second grant.\n // At its budget the turn returns a continuation; under a grant that is the deadline.\n // The grant's timeout aborts the call in flight; that is the deadline too, not a cancellation.\n if (turn.continuation || (turn.failure?.code === 'turn_aborted' && Date.now() >= grant.deadlineAtMs)) {\n throw refuse('turn_deadline', 'Protected execution deadline expired')\n }\n if (turn.failure) throw new GrantRefusal(turn.failure)\n },\n })\n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