@tangle-network/agent-app 4.0.42 → 4.0.45
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assistant/index.js +9 -9
- package/dist/catalog/index.js +1 -1
- package/dist/chat-react/index.js +6 -6
- package/dist/chat-routes/index.js +8 -8
- package/dist/{chunk-C5OTKXHP.js → chunk-4ZCUGJ6O.js} +4 -4
- package/dist/{chunk-WYULRKMG.js → chunk-5XGMMFF5.js} +3 -3
- package/dist/{chunk-725RZ5JQ.js → chunk-AFSDGQIV.js} +2 -2
- package/dist/{chunk-XR2YIVYZ.js → chunk-CZVO2SPE.js} +2 -2
- package/dist/{chunk-BDWSUKUN.js → chunk-E43PMYHD.js} +2 -2
- package/dist/{chunk-YQE2CGIO.js → chunk-FIH4MI6S.js} +2 -1
- package/dist/chunk-FIH4MI6S.js.map +1 -0
- package/dist/{chunk-RSSK6FUF.js → chunk-FIVFWLX7.js} +2 -2
- package/dist/{chunk-3HWTD2HC.js → chunk-FLS3UKQH.js} +3 -3
- package/dist/{chunk-76Y5VOHE.js → chunk-HHMELPDN.js} +8 -8
- package/dist/{chunk-76Y5VOHE.js.map → chunk-HHMELPDN.js.map} +1 -1
- package/dist/{chunk-JP6QSEF5.js → chunk-JQDAYMMZ.js} +1 -2
- package/dist/chunk-JQDAYMMZ.js.map +1 -0
- package/dist/{chunk-KSLTD4FI.js → chunk-KDFW6NO5.js} +5 -3
- package/dist/chunk-KDFW6NO5.js.map +1 -0
- package/dist/{chunk-WGT32NQ4.js → chunk-P6NVRUW6.js} +2 -2
- package/dist/{chunk-WAOZF4EL.js → chunk-S7GZ7XPC.js} +4 -4
- package/dist/{chunk-FCW5NJ4M.js → chunk-Y7FTBDFZ.js} +4 -4
- package/dist/{chunk-MGW25KMR.js → chunk-YLRH77J3.js} +3 -3
- package/dist/{chunk-NQQZVQPR.js → chunk-ZFIKUFAV.js} +2 -2
- package/dist/chunk-ZFIKUFAV.js.map +1 -0
- package/dist/harness/index.d.ts +1 -1
- package/dist/harness/index.js +1 -1
- package/dist/hosted-agent/index.js +1 -1
- package/dist/hosted-agent/index.js.map +1 -1
- package/dist/{mention-editor-VSNY2MCQ.js → mention-editor-TX5LHI6W.js} +3 -3
- package/dist/preset-cloudflare/index.js +2 -2
- package/dist/public-consultation/index.js +7 -7
- package/dist/runtime/index.js +3 -3
- package/dist/runtime/model-catalog.d.ts +3 -0
- package/dist/runtime/router-turn.js +2 -2
- package/dist/sandbox/index.js +3 -3
- package/dist/settings-react/index.js +2 -2
- package/dist/skills-placement/box.js +2 -2
- package/dist/skills-placement/index.js +2 -2
- package/dist/stream/index.js +2 -2
- package/dist/stream/turn-buffer.d.ts +2 -1
- package/dist/studio-react/index.js +2 -2
- package/dist/turn-stream/index.js +1 -1
- package/dist/web-react/agent-profile-editor.js +6 -6
- package/dist/web-react/index.js +9 -9
- package/dist/workspace-react/index.js +4 -4
- package/package.json +3 -3
- package/dist/chunk-JP6QSEF5.js.map +0 -1
- package/dist/chunk-KSLTD4FI.js.map +0 -1
- package/dist/chunk-NQQZVQPR.js.map +0 -1
- package/dist/chunk-YQE2CGIO.js.map +0 -1
- /package/dist/{chunk-C5OTKXHP.js.map → chunk-4ZCUGJ6O.js.map} +0 -0
- /package/dist/{chunk-WYULRKMG.js.map → chunk-5XGMMFF5.js.map} +0 -0
- /package/dist/{chunk-725RZ5JQ.js.map → chunk-AFSDGQIV.js.map} +0 -0
- /package/dist/{chunk-XR2YIVYZ.js.map → chunk-CZVO2SPE.js.map} +0 -0
- /package/dist/{chunk-BDWSUKUN.js.map → chunk-E43PMYHD.js.map} +0 -0
- /package/dist/{chunk-RSSK6FUF.js.map → chunk-FIVFWLX7.js.map} +0 -0
- /package/dist/{chunk-3HWTD2HC.js.map → chunk-FLS3UKQH.js.map} +0 -0
- /package/dist/{chunk-WGT32NQ4.js.map → chunk-P6NVRUW6.js.map} +0 -0
- /package/dist/{chunk-WAOZF4EL.js.map → chunk-S7GZ7XPC.js.map} +0 -0
- /package/dist/{chunk-FCW5NJ4M.js.map → chunk-Y7FTBDFZ.js.map} +0 -0
- /package/dist/{chunk-MGW25KMR.js.map → chunk-YLRH77J3.js.map} +0 -0
- /package/dist/{mention-editor-VSNY2MCQ.js.map → mention-editor-TX5LHI6W.js.map} +0 -0
|
@@ -14,10 +14,10 @@ import {
|
|
|
14
14
|
turnKnowledgeInstructions,
|
|
15
15
|
workspaceKnowledgeForTurn,
|
|
16
16
|
workspaceTurnCheckpoints
|
|
17
|
-
} from "../chunk-
|
|
17
|
+
} from "../chunk-FIVFWLX7.js";
|
|
18
18
|
import "../chunk-D6UJEOZQ.js";
|
|
19
19
|
import "../chunk-VUI4IUIM.js";
|
|
20
|
-
import "../chunk-
|
|
20
|
+
import "../chunk-KDFW6NO5.js";
|
|
21
21
|
export {
|
|
22
22
|
DURABLE_HOP_BUDGET_MS,
|
|
23
23
|
asksForLanguage,
|
package/dist/sandbox/index.js
CHANGED
|
@@ -114,7 +114,7 @@ import {
|
|
|
114
114
|
warmKey,
|
|
115
115
|
warmReceiptId,
|
|
116
116
|
warmWeekdayOf
|
|
117
|
-
} from "../chunk-
|
|
117
|
+
} from "../chunk-YLRH77J3.js";
|
|
118
118
|
import {
|
|
119
119
|
createWarmCache
|
|
120
120
|
} from "../chunk-F4TUZYMX.js";
|
|
@@ -163,7 +163,7 @@ import {
|
|
|
163
163
|
} from "../chunk-2IGXFHUO.js";
|
|
164
164
|
import "../chunk-ALIWB2P3.js";
|
|
165
165
|
import "../chunk-AOSQ5JCO.js";
|
|
166
|
-
import "../chunk-
|
|
166
|
+
import "../chunk-FIH4MI6S.js";
|
|
167
167
|
import "../chunk-6YLVFV3F.js";
|
|
168
168
|
import "../chunk-L3QR274L.js";
|
|
169
169
|
import "../chunk-XELWWXJJ.js";
|
|
@@ -182,7 +182,7 @@ import {
|
|
|
182
182
|
splitDeferredProfileFiles,
|
|
183
183
|
writeProfileFilesToBox
|
|
184
184
|
} from "../chunk-67CSI5PU.js";
|
|
185
|
-
import "../chunk-
|
|
185
|
+
import "../chunk-JQDAYMMZ.js";
|
|
186
186
|
import {
|
|
187
187
|
readSandboxBinaryBytes,
|
|
188
188
|
shellQuote,
|
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
fieldPickerTriggerClass,
|
|
15
15
|
useBrowserLayoutEffect,
|
|
16
16
|
usePopover
|
|
17
|
-
} from "../chunk-
|
|
17
|
+
} from "../chunk-E43PMYHD.js";
|
|
18
18
|
import {
|
|
19
19
|
bindSearchPickerNavigation
|
|
20
20
|
} from "../chunk-ZAMHLXNS.js";
|
|
@@ -27,7 +27,7 @@ import {
|
|
|
27
27
|
import {
|
|
28
28
|
useWorkspaceExport
|
|
29
29
|
} from "../chunk-EZFBGW23.js";
|
|
30
|
-
import "../chunk-
|
|
30
|
+
import "../chunk-KDFW6NO5.js";
|
|
31
31
|
|
|
32
32
|
// src/settings-react/settings-layout.tsx
|
|
33
33
|
import { Button, PageHeader, PageShell } from "@tangle-network/ui/primitives";
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import {
|
|
2
2
|
resolveSkillDir
|
|
3
|
-
} from "../chunk-
|
|
3
|
+
} from "../chunk-ZFIKUFAV.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-JQDAYMMZ.js";
|
|
10
10
|
import {
|
|
11
11
|
shellQuote
|
|
12
12
|
} from "../chunk-INW4FSID.js";
|
|
@@ -4,10 +4,10 @@ import {
|
|
|
4
4
|
skillSupportFileMounts,
|
|
5
5
|
unsupportedSkillHarnesses,
|
|
6
6
|
withSkillSupportFiles
|
|
7
|
-
} from "../chunk-
|
|
7
|
+
} from "../chunk-ZFIKUFAV.js";
|
|
8
8
|
import "../chunk-76MPX7JQ.js";
|
|
9
9
|
import "../chunk-PV33JZKV.js";
|
|
10
|
-
import "../chunk-
|
|
10
|
+
import "../chunk-JQDAYMMZ.js";
|
|
11
11
|
export {
|
|
12
12
|
composeSkillsForHarness,
|
|
13
13
|
resolveSkillDir,
|
package/dist/stream/index.js
CHANGED
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
observeTurnEvent,
|
|
6
6
|
parseTurnObservation,
|
|
7
7
|
settleOrphanedTurns
|
|
8
|
-
} from "../chunk-
|
|
8
|
+
} from "../chunk-P6NVRUW6.js";
|
|
9
9
|
import {
|
|
10
10
|
buildUserTextParts,
|
|
11
11
|
messageHasTurnId,
|
|
@@ -51,7 +51,7 @@ import {
|
|
|
51
51
|
pumpBufferedTurn,
|
|
52
52
|
replayTurnEvents,
|
|
53
53
|
stampReplaySeq
|
|
54
|
-
} from "../chunk-
|
|
54
|
+
} from "../chunk-FIH4MI6S.js";
|
|
55
55
|
import "../chunk-T3C2BX7N.js";
|
|
56
56
|
export {
|
|
57
57
|
DEFAULT_RUNNING_TURN_LEASE_MS,
|
|
@@ -150,7 +150,8 @@ export interface BufferedTurnOptions {
|
|
|
150
150
|
export interface BufferedTurnTap {
|
|
151
151
|
/** Buffer one event: persist (coalesced, on the flush window) + best-effort
|
|
152
152
|
* live-deliver. Wire to a push source's per-event hook (e.g. agent-runtime
|
|
153
|
-
* `handleChatTurn`'s `hooks.onEvent`). Marks the turn 'running' on first call.
|
|
153
|
+
* `handleChatTurn`'s `hooks.onEvent`). Marks the turn 'running' on first call.
|
|
154
|
+
* `execution.started` commits its ordered prefix before this tap's live write. */
|
|
154
155
|
onEvent(raw: unknown): Promise<void>;
|
|
155
156
|
/** Settle the turn: final flush + set status. Call after the producer resolves
|
|
156
157
|
* ('complete') or rejects ('error'). 'error' flushes what was produced first. */
|
|
@@ -26,14 +26,14 @@ import {
|
|
|
26
26
|
POPOVER_SURFACE_ATTR,
|
|
27
27
|
PopoverSurface,
|
|
28
28
|
usePopover
|
|
29
|
-
} from "../chunk-
|
|
29
|
+
} from "../chunk-E43PMYHD.js";
|
|
30
30
|
import {
|
|
31
31
|
containDialogTab
|
|
32
32
|
} from "../chunk-ZAMHLXNS.js";
|
|
33
33
|
import {
|
|
34
34
|
ProviderLogo
|
|
35
35
|
} from "../chunk-RASGKEAL.js";
|
|
36
|
-
import "../chunk-
|
|
36
|
+
import "../chunk-KDFW6NO5.js";
|
|
37
37
|
import {
|
|
38
38
|
GENERATION_TYPES,
|
|
39
39
|
aspectRatioFromOptions,
|
|
@@ -1,16 +1,16 @@
|
|
|
1
1
|
import {
|
|
2
2
|
AGENT_PROFILE_EDITOR_SECTIONS,
|
|
3
3
|
AgentProfileEditor
|
|
4
|
-
} from "../chunk-
|
|
5
|
-
import "../chunk-
|
|
6
|
-
import "../chunk-
|
|
7
|
-
import "../chunk-
|
|
4
|
+
} from "../chunk-4ZCUGJ6O.js";
|
|
5
|
+
import "../chunk-HHMELPDN.js";
|
|
6
|
+
import "../chunk-CZVO2SPE.js";
|
|
7
|
+
import "../chunk-E43PMYHD.js";
|
|
8
8
|
import "../chunk-ZAMHLXNS.js";
|
|
9
9
|
import "../chunk-RASGKEAL.js";
|
|
10
10
|
import "../chunk-B7CL7ENS.js";
|
|
11
|
-
import "../chunk-
|
|
11
|
+
import "../chunk-KDFW6NO5.js";
|
|
12
12
|
import "../chunk-PV33JZKV.js";
|
|
13
|
-
import "../chunk-
|
|
13
|
+
import "../chunk-JQDAYMMZ.js";
|
|
14
14
|
export {
|
|
15
15
|
AGENT_PROFILE_EDITOR_SECTIONS,
|
|
16
16
|
AgentProfileEditor
|
package/dist/web-react/index.js
CHANGED
|
@@ -157,7 +157,7 @@ import {
|
|
|
157
157
|
withoutRecordGridCreated,
|
|
158
158
|
withoutRecordGridRemoved,
|
|
159
159
|
withoutRecordGridUpdate
|
|
160
|
-
} from "../chunk-
|
|
160
|
+
} from "../chunk-FLS3UKQH.js";
|
|
161
161
|
import {
|
|
162
162
|
useInfiniteScroll
|
|
163
163
|
} from "../chunk-UHSUY6H6.js";
|
|
@@ -174,7 +174,7 @@ import {
|
|
|
174
174
|
AGENT_PROFILE_EDITOR_SECTIONS,
|
|
175
175
|
AgentProfileEditor,
|
|
176
176
|
AgentProfileRegistryError
|
|
177
|
-
} from "../chunk-
|
|
177
|
+
} from "../chunk-4ZCUGJ6O.js";
|
|
178
178
|
import {
|
|
179
179
|
EvidenceLineageTable,
|
|
180
180
|
ExceptionList,
|
|
@@ -203,7 +203,7 @@ import {
|
|
|
203
203
|
preloadWhenIdle,
|
|
204
204
|
useComposerAttachments,
|
|
205
205
|
useDictation
|
|
206
|
-
} from "../chunk-
|
|
206
|
+
} from "../chunk-S7GZ7XPC.js";
|
|
207
207
|
import "../chunk-L7MB2LLM.js";
|
|
208
208
|
import {
|
|
209
209
|
AgentSessionControls,
|
|
@@ -215,18 +215,18 @@ import {
|
|
|
215
215
|
filterAcceptedFiles,
|
|
216
216
|
isAcceptedFileType,
|
|
217
217
|
renamePastedImages
|
|
218
|
-
} from "../chunk-
|
|
218
|
+
} from "../chunk-HHMELPDN.js";
|
|
219
219
|
import {
|
|
220
220
|
WorkspaceInitial,
|
|
221
221
|
WorkspaceSwitcher
|
|
222
|
-
} from "../chunk-
|
|
222
|
+
} from "../chunk-5XGMMFF5.js";
|
|
223
223
|
import {
|
|
224
224
|
WorkspacePrewarmContext,
|
|
225
225
|
requestWorkspacePrewarm,
|
|
226
226
|
useWorkspacePrewarm,
|
|
227
227
|
useWorkspacePrewarmHandle
|
|
228
228
|
} from "../chunk-2HQP2CTA.js";
|
|
229
|
-
import "../chunk-
|
|
229
|
+
import "../chunk-CZVO2SPE.js";
|
|
230
230
|
import {
|
|
231
231
|
DEFAULT_EFFORT_LEVELS,
|
|
232
232
|
EFFORT_METER_SEGMENTS,
|
|
@@ -245,7 +245,7 @@ import {
|
|
|
245
245
|
reconcileEffortLevels,
|
|
246
246
|
usePending,
|
|
247
247
|
usePopover
|
|
248
|
-
} from "../chunk-
|
|
248
|
+
} from "../chunk-E43PMYHD.js";
|
|
249
249
|
import "../chunk-ZAMHLXNS.js";
|
|
250
250
|
import "../chunk-SJWIZT7B.js";
|
|
251
251
|
import {
|
|
@@ -333,9 +333,9 @@ import {
|
|
|
333
333
|
mentionKindForPath,
|
|
334
334
|
settleTurnResponse
|
|
335
335
|
} from "../chunk-6YLVFV3F.js";
|
|
336
|
-
import "../chunk-
|
|
336
|
+
import "../chunk-KDFW6NO5.js";
|
|
337
337
|
import "../chunk-PV33JZKV.js";
|
|
338
|
-
import "../chunk-
|
|
338
|
+
import "../chunk-JQDAYMMZ.js";
|
|
339
339
|
import "../chunk-T3C2BX7N.js";
|
|
340
340
|
import "../chunk-TXD5HXLE.js";
|
|
341
341
|
export {
|
|
@@ -3,20 +3,20 @@ import {
|
|
|
3
3
|
ActionDialogButton,
|
|
4
4
|
WorkspaceInitial,
|
|
5
5
|
WorkspaceSwitcher
|
|
6
|
-
} from "../chunk-
|
|
6
|
+
} from "../chunk-5XGMMFF5.js";
|
|
7
7
|
import {
|
|
8
8
|
WorkspacePrewarmContext,
|
|
9
9
|
useWorkspacePrewarm
|
|
10
10
|
} from "../chunk-2HQP2CTA.js";
|
|
11
11
|
import {
|
|
12
12
|
usePopoverDialog
|
|
13
|
-
} from "../chunk-
|
|
13
|
+
} from "../chunk-CZVO2SPE.js";
|
|
14
14
|
import {
|
|
15
15
|
CheckGlyph,
|
|
16
16
|
OVERLAY_SHADOW,
|
|
17
17
|
PopoverSurface,
|
|
18
18
|
usePopover
|
|
19
|
-
} from "../chunk-
|
|
19
|
+
} from "../chunk-E43PMYHD.js";
|
|
20
20
|
import "../chunk-ZAMHLXNS.js";
|
|
21
21
|
import {
|
|
22
22
|
buildSessionNavItem,
|
|
@@ -24,7 +24,7 @@ import {
|
|
|
24
24
|
resolveActiveNavId
|
|
25
25
|
} from "../chunk-SJWIZT7B.js";
|
|
26
26
|
import "../chunk-RASGKEAL.js";
|
|
27
|
-
import "../chunk-
|
|
27
|
+
import "../chunk-KDFW6NO5.js";
|
|
28
28
|
|
|
29
29
|
// src/workspace-react/index.tsx
|
|
30
30
|
import { SidebarLayout } from "@tangle-network/sandbox-ui/dashboard";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/agent-app",
|
|
3
|
-
"version": "4.0.
|
|
3
|
+
"version": "4.0.45",
|
|
4
4
|
"packageManager": "pnpm@11.28.8",
|
|
5
5
|
"description": "Build agent applications with typed chat, tools, sandboxes, integrations, billing, and evaluation.",
|
|
6
6
|
"keywords": [
|
|
@@ -802,7 +802,7 @@
|
|
|
802
802
|
"@tangle-network/agent-eval": "^1.0.32",
|
|
803
803
|
"@tangle-network/agent-gateway": "^1.0.0",
|
|
804
804
|
"@tangle-network/agent-integrations": "^1.0.4",
|
|
805
|
-
"@tangle-network/agent-interface": "^5.10.
|
|
805
|
+
"@tangle-network/agent-interface": "^5.10.28",
|
|
806
806
|
"@tangle-network/agent-knowledge": "^23.0.3",
|
|
807
807
|
"@tangle-network/agent-profile-materialize": "^1.1.64",
|
|
808
808
|
"@tangle-network/agent-runtime": "^10.0.0",
|
|
@@ -873,7 +873,7 @@
|
|
|
873
873
|
"@nanostores/react": ">=0.8.4 <2.0.0",
|
|
874
874
|
"@tangle-network/agent-eval": "^1.0.0",
|
|
875
875
|
"@tangle-network/agent-integrations": ">=0.54.2 <0.58.0 || >=0.59.0 <0.61.0 || >=0.66.0 <0.67.0 || >=0.67.0 <0.68.0 || >=0.68.0 <0.69.0 || >=0.69.0 <0.70.0 || >=0.70.0 <0.71.0 || >=0.75.0 <0.76.0 || >=0.76.2 <0.77.0 || ^1.0.0",
|
|
876
|
-
"@tangle-network/agent-interface": "^5.10.
|
|
876
|
+
"@tangle-network/agent-interface": "^5.10.28",
|
|
877
877
|
"@tangle-network/agent-knowledge": "^23.0.0",
|
|
878
878
|
"@tangle-network/agent-profile-materialize": "^1.0.0",
|
|
879
879
|
"@tangle-network/agent-runtime": "^1.0.0 || ^2.0.0 || ^3.0.0 || ^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0",
|
|
@@ -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 type { HarnessType } from '@tangle-network/agent-interface'\nimport { harnessTypeSchema } from '@tangle-network/agent-interface/harness'\nimport {\n harnessProviders,\n harnessSupportsModel,\n modelProvider,\n preferredHarnessForModel,\n snapHarnessToModel as aiSnapHarnessToModel,\n snapModelToHarness as aiSnapModelToHarness,\n} from '@tangle-network/agent-interface/harness-capabilities'\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 grok: { subagents: false, mcp: 'native', toolControls: 'runtime', skillsDir: null },\n nanocode: { subagents: false, mcp: 'native', toolControls: 'runtime', skillsDir: null },\n exo: { 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":";AAaA,SAAS,yBAAyB;AAClC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,sBAAsB;AAAA,EACtB,sBAAsB;AAAA,OACjB;;;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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AAuC;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/model-catalog.ts"],"sourcesContent":["/**\n * Model catalogue from the Tangle Router.\n *\n * Chat-capable routeable rows are deduped, ranked, and marked when they are a\n * current family. The router owns routeability. Known launch dates fill gaps\n * in its response. Every other routeable model stays searchable.\n */\n\nexport interface RouterModel {\n id: string\n name?: string\n description?: string\n release_date?: string\n released_at?: string\n _provider?: string\n provider?: string\n pricing?: { prompt?: string | null; completion?: string | null }\n context_length?: number\n architecture?: {\n modality?: string\n input_modalities?: string[]\n output_modalities?: string[]\n }\n supported_parameters?: string[]\n routeability?: {\n status?: string\n routeable?: boolean\n provider?: string\n endpoints?: {\n chat_completions?: {\n status?: string\n routeable?: boolean\n }\n }\n }\n}\n\n/** Define the structure and capabilities of a catalog item with optional pricing and feature flags */\nexport interface CatalogModel {\n id: string\n name: string\n provider: string\n /** The brand that made the model when it differs from the host in\n * `provider` (fal serves Seedance, Kling and Veo). The picker draws this\n * brand's logo when present; `provider` still groups and searches. */\n maker?: string\n /** API host when the Router serves the model through someone other than\n * `provider`. GLM 5.3 stays `zai`; Together is `servedBy`. */\n servedBy?: string\n description?: string\n /** Router-supplied or vendor-verified release date; never inferred from an id. */\n releaseDate?: string\n contextLength?: number\n pricing?: { prompt?: string; completion?: string }\n /** What one generation produces. Text when absent. */\n output?: 'text' | 'image' | 'video' | 'audio' | 'speech'\n /** USD for one unit of output, for media models: one image, one second of\n * video, one minute of audio, or 1,000 characters of speech. */\n outputPrice?: { usd: number; unit: 'image' | 'second' | 'minute' | '1k_chars' }\n /** An example of the model's output (an image, or a video poster frame). */\n previewUrl?: string\n /** One line on what the model is for, shown under its name. */\n capability?: string\n /** Whether the model can be sent now. Absent means available. A limited or\n * unavailable model stays selectable; the picker marks it in a warning tone. */\n status?: 'available' | 'limited' | 'unavailable'\n /** Why a limited or unavailable model is so, in words a person can act on. */\n statusReason?: string\n supportsTools: boolean\n supportsReasoning: boolean\n featured: boolean\n}\n\n/** Define a catalog containing models with a default ID and fetch timestamp */\nexport interface ModelCatalog {\n defaultModelId: string | null\n fetchedAt: string\n models: CatalogModel[]\n}\n\n/** Display order. Unlisted providers sort after these, alphabetically. */\nconst PROVIDER_TIER: string[] = [\n 'anthropic',\n 'openai',\n 'google',\n 'xai',\n 'deepseek',\n 'moonshot',\n 'zai',\n 'mistral',\n 'groq',\n 'nvidia',\n 'cohere',\n 'cerebras',\n]\n\n/** Router aliases that are one provider in a user-facing catalogue. */\nfunction normalizeProvider(provider: string): string {\n const normalized = provider.toLowerCase()\n if (normalized === 'moonshotai') return 'moonshot'\n if (normalized === 'z-ai') return 'zai'\n if (normalized === 'x-ai') return 'xai'\n if (normalized === 'mistralai') return 'mistral'\n return normalized\n}\n\n/** Resolve provider metadata across router response versions. */\nfunction providerForModel(model: RouterModel): string {\n const declared = model._provider ?? model.provider ?? model.routeability?.provider\n if (declared) return normalizeProvider(declared)\n\n const id = normalizeModelId(model.id).toLowerCase()\n if (/^claude-/.test(id)) return 'anthropic'\n if (/^(?:gpt-|o\\d)/.test(id)) return 'openai'\n if (/^gemini-/.test(id)) return 'google'\n if (/^grok-/.test(id)) return 'xai'\n if (/^deepseek-/.test(id)) return 'deepseek'\n if (/^kimi-/.test(id)) return 'moonshot'\n if (/^glm-/.test(id)) return 'zai'\n if (/^mistral/.test(id)) return 'mistral'\n return 'unknown'\n}\n\n/** Canonical router-facing id: \"provider/model\". Pickers display, products\n * persist, and turns send this form. The prefix is the RAW router provider\n * ('moonshotai/kimi-k2'), never the normalized display alias, so the id is a\n * live router entry that validation admits. */\nexport function canonicalRouterModelId(model: Pick<RouterModel, 'id' | '_provider' | 'provider' | 'routeability'>): string {\n if (model.id.includes('/')) return model.id\n const raw = model._provider ?? model.provider ?? model.routeability?.provider\n return raw ? `${raw}/${model.id}` : model.id\n}\n\n/** A short, varied first screen. All other routeable entries remain searchable. */\nexport const MAX_RECOMMENDED_MODELS = 8\n\n/** Non-chat endpoints that pollute the router list (matched on normalized id). */\nconst EXCLUDED_ID = /(embedding|tts|transcribe|whisper|audio|realtime|image|lyria|sora|dall-e|moderation|content-safety|search-preview|search-api|deep-research|:batch$)/\n\n/**\n * Default families, in preference order. Each rule finds the highest-version\n * routeable model whose normalized id matches. Patterns anchor on the family\n * name and stop before specialty suffixes (codex, nano, lite, …) so the\n * mainline model wins.\n */\nconst DEFAULT_CANDIDATE_RULES: Array<{ providers: string[]; match: RegExp }> = [\n { providers: ['zai', 'z-ai'], match: /^glm-5\\.3$/ },\n { providers: ['openai'], match: /^gpt-6\\.1-sol$/ },\n { providers: ['openai'], match: /^gpt-6-astra$/ },\n { providers: ['anthropic'], match: /^claude-sonnet-[\\d-]+$/ },\n { providers: ['anthropic'], match: /^claude-opus-[\\d-]+$/ },\n { providers: ['anthropic'], match: /^claude-haiku-[\\d-]+$/ },\n { providers: ['openai'], match: /^gpt-\\d+(\\.\\d+)?$/ },\n { providers: ['openai'], match: /^gpt-\\d+(\\.\\d+)?-mini$/ },\n { providers: ['google'], match: /^gemini-[\\d.]+-pro(-preview)?$/ },\n { providers: ['google'], match: /^gemini-[\\d.]+-flash(-preview)?$/ },\n { providers: ['xai'], match: /^grok-[\\d.]+$/ },\n { providers: ['deepseek'], match: /^deepseek-(chat|v[\\d.]+(-\\w+)?)$/ },\n { providers: ['moonshotai', 'moonshot'], match: /^kimi-k[\\d.]+$/ },\n { providers: ['zai', 'z-ai'], match: /^glm-[\\d.]+$/ },\n { providers: ['mistral'], match: /^mistral-(large|medium)-?[\\d.-]*$/ },\n]\n\n/**\n * Current families are checked against the Router catalogue and live\n * completions. The 2026-09-30 probes served GPT 6.1 Sol, Astra, Gemini 3.7\n * Flash, and GLM 5.3. Opus/Sonnet 5 returned quota 503, so only their 5.5\n * successors may be featured once Router marks them routeable. DeepSeek V4.1\n * Flash and Kimi K3 remain searchable after quota/upstream failures.\n * An undated future member uses its family floor, not an invented launch date.\n */\nconst RECOMMENDED_FAMILIES: Array<{\n provider: string\n match: RegExp\n minVersion: number[]\n}> = [\n { provider: 'anthropic', match: /^claude-opus-\\d+(?:[-.]\\d+)*$/, minVersion: [5, 5] },\n { provider: 'anthropic', match: /^claude-sonnet-\\d+(?:[-.]\\d+)*$/, minVersion: [5, 5] },\n { provider: 'openai', match: /^gpt-\\d+(?:\\.\\d+)?-sol$/, minVersion: [6] },\n { provider: 'openai', match: /^gpt-\\d+(?:\\.\\d+)?-astra$/, minVersion: [6] },\n { provider: 'google', match: /^gemini-\\d+(?:\\.\\d+)?-flash(?:-preview)?$/, minVersion: [3, 5] },\n { provider: 'zai', match: /^glm-\\d+(?:\\.\\d+)?$/, minVersion: [5, 3] },\n]\n\nconst RECOMMENDATION_WINDOW_MS = 120 * 24 * 60 * 60 * 1000\n\n/** Exact launch dates from vendor announcements, checked 2026-09-30. */\nconst VERIFIED_RELEASE_DATES: Record<string, string> = {\n // https://www.anthropic.com/claude-opus-5-5\n 'claude-opus-5-5': '2026-09-22',\n // https://www.anthropic.com/claude-sonnet-5-5\n 'claude-sonnet-5-5': '2026-09-28',\n // https://developers.openai.com/api/docs/changelog\n 'gpt-6.1-sol': '2026-09-29',\n // https://openai.com/index/safety-overview-gpt-6-astra/\n 'gpt-6-astra': '2026-09-03',\n // https://blog.google/innovation-and-ai/models-and-research/gemini-models/introducing-gemini-3-7-flash/\n 'gemini-3.7-flash': '2026-08-13',\n // https://z.ai/blog/glm-5.3\n 'glm-5.3': '2026-08-14',\n}\n\nfunction releaseDateFromRouter(model: RouterModel): string | undefined {\n const value = model.release_date ?? model.released_at\n if (!value || !/^\\d{4}-\\d{2}-\\d{2}(?:T|$)/.test(value)) return undefined\n const time = Date.parse(value)\n return Number.isFinite(time) ? new Date(time).toISOString() : undefined\n}\n\n/** Families known to support tool calls even when router metadata omits it\n * (dated snapshots often lack the supported_parameters of their parent). */\nconst TOOL_CAPABLE_FAMILY = /^(claude|gpt-\\d|gpt-oss|o[134]|gemini|grok|deepseek|glm|kimi|mistral|ministral|magistral|command|nemotron|llama)/\n\n/** Strip provider prefix, :free suffix, and trailing date stamps. */\nexport function normalizeModelId(id: string): string {\n let tail = id.split('/').pop() ?? id\n tail = tail.replace(/:free$/, '')\n tail = tail.replace(/-\\d{8}$/, '')\n tail = tail.replace(/-\\d{4}-\\d{2}-\\d{2}$/, '')\n return tail\n}\n\n/** All numeric groups in a normalized id, for version comparison. */\nfunction versionOf(normId: string): number[] {\n return (normId.match(/\\d+/g) ?? []).map(Number)\n}\n\nfunction compareVersions(a: number[], b: number[]): number {\n const len = Math.max(a.length, b.length)\n for (let i = 0; i < len; i++) {\n const d = (a[i] ?? -1) - (b[i] ?? -1)\n if (d !== 0) return d\n }\n return 0\n}\n\n/**\n * Read the generation attached to a known model family.\n *\n * This deliberately does not read every number in the id. A parameter count\n * such as `gpt-oss-120b` is not newer than GPT 5.6.\n */\nfunction releaseVersion(id: string): number[] {\n const normalized = normalizeModelId(id).toLowerCase()\n const patterns = [\n /^claude-[a-z0-9]+-(\\d+(?:[.-]\\d+)*)/,\n /^gpt-(\\d+(?:\\.\\d+)*)/,\n /^o(\\d+(?:\\.\\d+)*)/,\n /^gemini-(\\d+(?:\\.\\d+)*)/,\n /^deepseek-v(\\d+(?:\\.\\d+)*)/,\n /^kimi-k(\\d+(?:\\.\\d+)*)/,\n /^glm-(\\d+(?:\\.\\d+)*)/,\n /^grok-(\\d+(?:\\.\\d+)*)/,\n /^mistral-(?:large|medium)-?(\\d+(?:[.-]\\d+)*)/,\n /^qwen-?(\\d+(?:\\.\\d+)*)/,\n /^llama-?(\\d+(?:\\.\\d+)*)/,\n ]\n for (const pattern of patterns) {\n const match = normalized.match(pattern)\n if (match?.[1]) return match[1].split(/[.-]/).map(Number)\n }\n return []\n}\n\n/**\n * Return a copy sorted for a model menu.\n *\n * Providers keep the shared display order. Within each provider, current\n * generations come first across families. Stable ids win ties with previews.\n * Callers can sort separate sections without changing `featured` or defaults.\n */\nexport function sortModelsByFreshness(models: readonly CatalogModel[]): CatalogModel[] {\n return [...models].sort((a, b) => {\n const providerA = normalizeProvider(a.provider)\n const providerB = normalizeProvider(b.provider)\n const providerOrder = providerRank(providerA) - providerRank(providerB)\n if (providerOrder !== 0) return providerOrder\n if (providerA !== providerB) return providerA.localeCompare(providerB)\n\n const generationOrder = compareVersions(releaseVersion(b.id), releaseVersion(a.id))\n if (generationOrder !== 0) return generationOrder\n\n const previewOrder = Number(/preview/i.test(a.id)) - Number(/preview/i.test(b.id))\n if (previewOrder !== 0) return previewOrder\n return a.id.localeCompare(b.id)\n })\n}\n\n/** Lower = preferred representative for an alias group. */\nfunction aliasPenalty(id: string): number {\n let p = 0\n if (id.includes('/')) p += 4\n if (/-\\d{8}$|-\\d{4}-\\d{2}-\\d{2}$/.test(id.replace(/:free$/, ''))) p += 2\n if (id.endsWith(':free')) p += 1\n return p\n}\n\nfunction providerRank(provider: string): number {\n const i = PROVIDER_TIER.indexOf(normalizeProvider(provider))\n return i === -1 ? PROVIDER_TIER.length : i\n}\n\n/**\n * Can this router entry serve a text chat turn?\n *\n * The router lists every routeable endpoint, which is not the same list a chat\n * picker should show: measured against the live catalogue (504 entries), this\n * rejects 35 — image generators, TTS voices, embedding models, and the\n * audio-IN transcription endpoints (`whisper-1`, `gpt-4o-transcribe`, …) that\n * emit text but cannot take a text prompt.\n *\n * A model whose metadata omits either modality list is KEPT. The router is the\n * source of that metadata and it is occasionally sparse; dropping a usable\n * model because a field is missing is the worse failure of the two.\n *\n * Exported because a picker needs the same answer `buildCatalog` uses — the\n * fleet had this predicate copied into a product component, where its narrower\n * spelling let the 10 transcription endpoints through.\n */\nexport function isChatCapableModel(m: RouterModel): boolean {\n const arch = m.architecture\n if (!arch?.input_modalities || !arch?.output_modalities) return true\n return arch.input_modalities.includes('text') && arch.output_modalities.includes('text')\n}\n\nconst isChatModel = isChatCapableModel\n\nfunction isRouteable(m: RouterModel): boolean {\n const routeability = m.routeability\n if (!routeability) return true\n const chatEndpoint = routeability.endpoints?.chat_completions\n if (chatEndpoint?.routeable === false) return false\n if (chatEndpoint?.status !== undefined && chatEndpoint.status !== 'routeable') return false\n if (routeability.routeable === true || routeability.status === 'routeable') return true\n if (routeability.routeable === false) return false\n return routeability.status === undefined\n}\n\n/** Find a catalogue row by direct or provider-prefixed model id. */\nexport function catalogModelForId(\n models: readonly CatalogModel[],\n requestedId: string | undefined,\n): CatalogModel | undefined {\n const requested = requestedId?.trim()\n if (!requested) return undefined\n\n const exact = models.find((model) => model.id === requested)\n if (exact) return exact\n\n const slash = requested.indexOf('/')\n const requestedProvider = slash > 0 ? normalizeProvider(requested.slice(0, slash)) : undefined\n const normalized = normalizeModelId(requested)\n return models.find((model) => {\n if (normalizeModelId(model.id) !== normalized) return false\n return requestedProvider === undefined || normalizeProvider(model.provider) === requestedProvider\n })\n}\n\n/**\n * Reconcile a persisted selection against the live catalogue.\n *\n * The returned id is always a catalogue id once the catalogue has entries.\n * This keeps a removed model from remaining selected while preserving the\n * current value during the brief empty/loading state.\n */\nexport function resolveCatalogModelId(\n models: readonly CatalogModel[],\n selectedId?: string,\n fallbackId?: string,\n): string | undefined {\n if (models.length === 0) return selectedId?.trim() || fallbackId?.trim()\n return catalogModelForId(models, selectedId)?.id\n ?? catalogModelForId(models, fallbackId)?.id\n ?? models[0]?.id\n}\n\n/**\n * Pure catalogue pipeline. `preferredDefault` (typically the MODEL_NAME env\n * var) wins when it survives filtering; otherwise the first featured model.\n */\nexport function buildCatalog(raw: RouterModel[], opts?: { preferredDefault?: string }): ModelCatalog {\n // Filter to chat-capable, routeable, non-specialty models\n const candidates = raw.filter(\n (m) =>\n m.id &&\n isRouteable(m) &&\n isChatModel(m) &&\n !EXCLUDED_ID.test(normalizeModelId(m.id)),\n )\n\n // Dedupe alias groups (dated snapshots, provider prefixes, :free variants).\n // Within a group, merge metadata so the representative keeps the richest\n // supported_parameters claim (snapshots often omit what the parent lists).\n const groups = new Map<string, RouterModel[]>()\n for (const m of candidates) {\n const key = `${providerForModel(m)}::${normalizeModelId(m.id)}`\n const g = groups.get(key)\n if (g) g.push(m)\n else groups.set(key, [m])\n }\n\n const reps: Array<{ model: RouterModel; normId: string; mergedParams: Set<string>; releaseDate?: string }> = []\n for (const group of groups.values()) {\n group.sort((a, b) => aliasPenalty(a.id) - aliasPenalty(b.id) || a.id.length - b.id.length)\n const rep = group[0]!\n const mergedParams = new Set<string>(group.flatMap((m) => m.supported_parameters ?? []))\n const verifiedDate = VERIFIED_RELEASE_DATES[normalizeModelId(rep.id)]\n const releaseDate = group.map(releaseDateFromRouter).find((date) => date !== undefined) ??\n (verifiedDate ? new Date(verifiedDate).toISOString() : undefined)\n reps.push({ model: rep, normId: normalizeModelId(rep.id), mergedParams, releaseDate })\n }\n\n // Resolve the default independently from menu recommendations.\n const defaultCandidateIds: string[] = []\n for (const rule of DEFAULT_CANDIDATE_RULES) {\n const matches = reps.filter(\n (r) =>\n rule.providers.map(normalizeProvider).includes(providerForModel(r.model)) &&\n rule.match.test(r.normId) &&\n !defaultCandidateIds.includes(r.model.id),\n )\n if (!matches.length) continue\n matches.sort(\n (a, b) =>\n compareVersions(versionOf(b.normId), versionOf(a.normId)) ||\n Number(a.normId.includes('preview')) - Number(b.normId.includes('preview')) ||\n a.model.id.length - b.model.id.length,\n )\n defaultCandidateIds.push(matches[0]!.model.id)\n }\n\n const toCatalogModel = (r: (typeof reps)[number]): CatalogModel => {\n const m = r.model\n const provider = providerForModel(m)\n const routeHost = normalizeProvider(m.routeability?.provider ?? '')\n const servedBy = routeHost && routeHost !== 'unknown' && routeHost !== provider ? routeHost : undefined\n return {\n id: canonicalRouterModelId(m),\n name: m.name ?? m.id,\n provider,\n ...(servedBy ? { servedBy } : {}),\n description: m.description ? m.description.slice(0, 160) : undefined,\n releaseDate: r.releaseDate,\n contextLength: m.context_length,\n pricing:\n m.pricing?.prompt || m.pricing?.completion\n ? { prompt: m.pricing.prompt ?? undefined, completion: m.pricing.completion ?? undefined }\n : undefined,\n supportsTools: r.mergedParams.has('tools') || TOOL_CAPABLE_FAMILY.test(r.normId),\n supportsReasoning: r.mergedParams.has('reasoning') || r.mergedParams.has('include_reasoning'),\n featured: false,\n }\n }\n\n // Family rules retain the intentional default preference. Display order is\n // independent: every catalogue consumer gets provider-grouped freshness,\n // even when it does not render ModelPicker.\n const defaultCandidatesInRuleOrder = defaultCandidateIds\n .map((id) => reps.find((r) => r.model.id === id)!)\n .map(toCatalogModel)\n const sorted = sortModelsByFreshness(reps.map(toCatalogModel))\n const recommendedIds = new Set<string>()\n const recentSince = Date.now() - RECOMMENDATION_WINDOW_MS\n for (const family of RECOMMENDED_FAMILIES) {\n const current = sorted.find((model) =>\n normalizeProvider(model.provider) === family.provider &&\n family.match.test(normalizeModelId(model.id)) &&\n compareVersions(releaseVersion(model.id), family.minVersion) >= 0 &&\n (model.releaseDate === undefined || Date.parse(model.releaseDate) >= recentSince),\n )\n if (current) recommendedIds.add(current.id)\n if (recommendedIds.size >= MAX_RECOMMENDED_MODELS) break\n }\n const models = sorted.map((model) =>\n recommendedIds.has(model.id) ? { ...model, featured: true } : model,\n )\n\n const preferred = opts?.preferredDefault\n const defaultModelId =\n (preferred && models.find((m) => m.id === preferred || normalizeModelId(m.id) === normalizeModelId(preferred))?.id) ||\n defaultCandidatesInRuleOrder.find((m) => m.supportsTools)?.id ||\n models[0]?.id ||\n null\n\n return { defaultModelId, fetchedAt: new Date().toISOString(), models }\n}\n\n// ── Cached fetch ─────────────────────────────────────────────────────────\n\nconst CATALOG_TTL_MS = 5 * 60 * 1000\n\nlet _cache: { catalog: ModelCatalog; at: number } | null = null\n\n/**\n * Fetch the router model list and build the catalogue, with an in-isolate\n * cache (TTL 5 min). On router failure a stale catalogue is served rather\n * than erroring the picker.\n */\nexport async function fetchModelCatalog(cfg: {\n baseUrl: string\n apiKey: string\n preferredDefault?: string\n}): Promise<ModelCatalog> {\n if (_cache && Date.now() - _cache.at < CATALOG_TTL_MS) {\n return _cache.catalog\n }\n try {\n const res = await fetch(`${cfg.baseUrl}/models`, {\n headers: { Authorization: `Bearer ${cfg.apiKey}` },\n })\n if (!res.ok) throw new Error(`Router /models returned ${res.status}`)\n const data = (await res.json()) as { data?: RouterModel[] }\n const catalog = buildCatalog(data.data ?? [], { preferredDefault: cfg.preferredDefault })\n _cache = { catalog, at: Date.now() }\n return catalog\n } catch (err) {\n if (_cache) return _cache.catalog\n throw err\n }\n}\n\n/** Test-only: clear the catalogue cache. */\nexport function __resetCatalogCache(): void {\n _cache = null\n}\n"],"mappings":";AAiFA,IAAM,gBAA0B;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGA,SAAS,kBAAkB,UAA0B;AACnD,QAAM,aAAa,SAAS,YAAY;AACxC,MAAI,eAAe,aAAc,QAAO;AACxC,MAAI,eAAe,OAAQ,QAAO;AAClC,MAAI,eAAe,OAAQ,QAAO;AAClC,MAAI,eAAe,YAAa,QAAO;AACvC,SAAO;AACT;AAGA,SAAS,iBAAiB,OAA4B;AACpD,QAAM,WAAW,MAAM,aAAa,MAAM,YAAY,MAAM,cAAc;AAC1E,MAAI,SAAU,QAAO,kBAAkB,QAAQ;AAE/C,QAAM,KAAK,iBAAiB,MAAM,EAAE,EAAE,YAAY;AAClD,MAAI,WAAW,KAAK,EAAE,EAAG,QAAO;AAChC,MAAI,gBAAgB,KAAK,EAAE,EAAG,QAAO;AACrC,MAAI,WAAW,KAAK,EAAE,EAAG,QAAO;AAChC,MAAI,SAAS,KAAK,EAAE,EAAG,QAAO;AAC9B,MAAI,aAAa,KAAK,EAAE,EAAG,QAAO;AAClC,MAAI,SAAS,KAAK,EAAE,EAAG,QAAO;AAC9B,MAAI,QAAQ,KAAK,EAAE,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MAAM,EAAE,aAAa,GAAG,MAC3D,OAAO,CAAC,GAAG,MACX;AAEF,SAAO,EAAE,gBAAgB,YAAW,oBAAI,KAAK,GAAE,YAAY,GAAG,OAAO;AACvE;AAIA,IAAM,iBAAiB,IAAI,KAAK;AAEhC,IAAI,SAAuD;AAO3D,eAAsB,kBAAkB,KAId;AACxB,MAAI,UAAU,KAAK,IAAI,IAAI,OAAO,KAAK,gBAAgB;AACrD,WAAO,OAAO;AAAA,EAChB;AACA,MAAI;AACF,UAAM,MAAM,MAAM,MAAM,GAAG,IAAI,OAAO,WAAW;AAAA,MAC/C,SAAS,EAAE,eAAe,UAAU,IAAI,MAAM,GAAG;AAAA,IACnD,CAAC;AACD,QAAI,CAAC,IAAI,GAAI,OAAM,IAAI,MAAM,2BAA2B,IAAI,MAAM,EAAE;AACpE,UAAM,OAAQ,MAAM,IAAI,KAAK;AAC7B,UAAM,UAAU,aAAa,KAAK,QAAQ,CAAC,GAAG,EAAE,kBAAkB,IAAI,iBAAiB,CAAC;AACxF,aAAS,EAAE,SAAS,IAAI,KAAK,IAAI,EAAE;AACnC,WAAO;AAAA,EACT,SAAS,KAAK;AACZ,QAAI,OAAQ,QAAO,OAAO;AAC1B,UAAM;AAAA,EACR;AACF;AAGO,SAAS,sBAA4B;AAC1C,WAAS;AACX;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/skills-placement/index.ts"],"sourcesContent":["/**\n * Harness-native skill directory resolution — the one place agent-app binds\n * to the platform's authoritative per-harness skill-dir map.\n *\n * `../skills` renders skill CONTENT (parse, tier-filter, `inline`/`mounted`\n * delivery) but deliberately stops short of naming WHICH cwd path a `mounted`\n * skill lands at on a given harness — that mapping is owned by the platform\n * materializer (`@tangle-network/agent-profile-materialize`'s\n * `skillDirForHarness`), not by app-shell. This subpath exists so no product\n * — and no other agent-app module — ever writes a skill path literal\n * (`~/.claude/skills/...`, `.opencode/skills`, ...) of its own; it bridges\n * agent-app's `Harness` taxonomy onto the platform's `HarnessId` and asks the\n * platform for the answer.\n *\n * Requires the OPTIONAL peer `@tangle-network/agent-profile-materialize`.\n * Products that don't install it simply don't import this subpath — every\n * other agent-app skills surface (`../skills`, `ProfileChannels.skillRefs`)\n * works without it, falling back to `inline` delivery.\n */\n\nimport type { AgentProfile, AgentProfileFileMount } from '@tangle-network/agent-interface'\nimport { defineInlineResource } from '@tangle-network/agent-interface/profile'\nimport { KNOWN_HARNESSES, type Harness } from '../harness/index'\nimport { skillDirForHarness, type HarnessId } from '@tangle-network/agent-profile-materialize'\nimport { composeSkills, renderInlineSkills, type ComposedSkills, type SkillEntry } from '../skills/index'\n\n/** agent-app `Harness` -> platform `HarnessId`, identity-mapped for exactly\n * the harnesses the platform map covers. Harnesses absent here (`amp`,\n * `factory-droids`, `forge`, `grok`, `nanocode`, `exo`, `acp`, `cursor`, `cli-base`) resolve to `null` —\n * {@link composeSkillsForHarness} refuses by default rather than silently\n * delivering `inline`; a caller that genuinely needs `inline` on one of\n * these opts in explicitly (`onNoSkillDir: 'inline'`). `cursor`'s adapter\n * supports `resources.skills` bespokely but isn't in the platform map yet;\n * treating it as unbridged is the safe posture until the map covers it,\n * rather than guessing its cwd skill dir here. */\nconst HARNESS_BRIDGE: Partial<Record<Harness, HarnessId>> = {\n opencode: 'opencode',\n 'claude-code': 'claude-code',\n nanoclaw: 'nanoclaw',\n 'kimi-code': 'kimi-code',\n codex: 'codex',\n pi: 'pi',\n prime: 'prime',\n hermes: 'hermes',\n openclaw: 'openclaw',\n}\n\n/** Resolve the cwd-relative skill dir `resources.skills` refs materialize\n * into on `harness` — via the platform's `skillDirForHarness`. `null` when\n * `harness` isn't bridged (see {@link HARNESS_BRIDGE}) or when the platform\n * itself has no cwd skill primitive for it (e.g. `hermes`, user-dir-only). */\nexport function resolveSkillDir(harness: Harness): string | null {\n const bridged = HARNESS_BRIDGE[harness]\n if (!bridged) return null\n return skillDirForHarness(bridged)\n}\n\n/** Filter `harnesses` down to those with no mounted skill dir (deduped,\n * first-seen order preserved) — the set that must fall back to `inline`\n * delivery, or that a caller should warn about before offering \"mounted\"\n * install UX. */\nexport function unsupportedSkillHarnesses(harnesses: Iterable<Harness>): Harness[] {\n const seen = new Set<Harness>()\n const out: Harness[] = []\n for (const harness of harnesses) {\n if (resolveSkillDir(harness) !== null) continue\n if (seen.has(harness)) continue\n seen.add(harness)\n out.push(harness)\n }\n return out\n}\n\n/** Inputs to {@link composeSkillsForHarness}. */\nexport interface ComposeSkillsForHarnessInput {\n skills: SkillEntry[]\n harness: Harness\n tier?: string\n heading?: string\n /**\n * What to do when `harness` has no native skill-mount directory (see\n * {@link resolveSkillDir}). Default `'throw'`: refuse rather than silently\n * inlining every skill BODY into the system prompt. Pass `'inline'` only as\n * a deliberate, auditable opt-in — the caller has decided every skill must\n * reach this harness even though it will be concatenated into the prompt.\n */\n onNoSkillDir?: 'throw' | 'inline'\n}\n\n/** `KNOWN_HARNESSES` filtered to those the platform materializer can mount\n * skill files onto natively (a non-null {@link resolveSkillDir}). Computed\n * fresh rather than cached — the platform map can grow without a release\n * here. Used only to build the actionable error in\n * {@link composeSkillsForHarness}; not exported because it duplicates\n * {@link unsupportedSkillHarnesses}'s complement and callers should reach\n * for that instead when they need the harness list at runtime. */\nfunction nativeSkillMountHarnesses(): Harness[] {\n return KNOWN_HARNESSES.filter((harness) => resolveSkillDir(harness) !== null)\n}\n\n/**\n * Compose {@link ComposedSkills} for `harness`.\n *\n * `mounted` delivery is the standard path: whenever the platform names a cwd\n * skill dir for `harness`, skills ride the typed `resources.skills` channel\n * and the platform materializer writes each one to that directory as a real\n * file — the agent reads it on demand with its own file tools.\n *\n * `inline` delivery — every skill BODY rendered straight into the system\n * prompt — is a NARROW fallback for harnesses with no native skill dir, never\n * a co-equal mode. An `AgentProfile` is a RECIPE that materializes into a\n * sandbox, not a prompt template: skill bodies belong in a file mount, and\n * `prompt.systemPrompt` should carry only what the agent must obey without a\n * tool call (identity, tool-call contract, safety rules, output format) plus\n * a short index of what's mounted. Concatenating skill bodies into the prompt\n * degrades the model toward empty answers once it grows large enough — one\n * product reproduced a 151,882-byte prompt exactly this way, from an\n * unnoticed inline fallback.\n *\n * Because of that, `onNoSkillDir` defaults to `'throw'`: a harness with no\n * skill dir refuses instead of silently inlining. The thrown error names the\n * harness, the skill count, the byte size that would have been inlined, and\n * the harnesses that DO support native mounting. Pass `onNoSkillDir:\n * 'inline'` only as a deliberate, auditable opt-in when every skill genuinely\n * must reach this harness regardless of prompt cost.\n *\n * The one function a product calls instead of hand-checking `resolveSkillDir`\n * and branching between {@link composeSkills}'s two modes itself.\n */\nexport function composeSkillsForHarness(input: ComposeSkillsForHarnessInput): ComposedSkills {\n const { skills, harness, tier, heading, onNoSkillDir = 'throw' } = input\n const skillDir = resolveSkillDir(harness)\n if (skillDir) return composeSkills({ skills, mode: 'mounted', skillDir, tier, heading })\n if (onNoSkillDir === 'inline') return composeSkills({ skills, mode: 'inline', tier, heading })\n\n const relevant = tier ? skills.filter((s) => s.tier === tier) : skills\n const promptSection = renderInlineSkills({ skills, tier, heading })\n const bytes = new TextEncoder().encode(promptSection).byteLength\n const mountable = nativeSkillMountHarnesses()\n throw new Error(\n `composeSkillsForHarness: \"${harness}\" has no native skill-mount directory. ` +\n `Inlining ${relevant.length} skill(s) (${bytes} bytes) into its system prompt would silently ` +\n `convert mounted skills into prompt text — a 151,882-byte prompt shipped this way once, and ` +\n `oversized prompts degrade toward empty answers. Mount the skills instead: pick a harness with ` +\n `native skill support (${mountable.join(', ')}), or pass onNoSkillDir: 'inline' to opt in ` +\n `explicitly and accept the inlined bytes.`,\n )\n}\n\nexport type { ComposedSkills, SkillEntry } from '../skills/index'\n\n/** A file that rides BESIDE a skill entry (kit sources, references, pinned\n * requirements — anything the SKILL.md tells the agent to read or run).\n * `path` is skill-dir-relative (`kit/iso-kit.mjs`, `references/x.md`). */\nexport interface SkillSupportFile {\n path: string\n content: string\n}\n\n/** Optional naming and reconciliation policies for skill support files. */\nexport interface SkillSupportFileOptions {\n /** Resource name for newly created mounts. Defaults to `<skillId>/<path>`. */\n resourceName?: (file: SkillSupportFile) => string\n /**\n * `retain` (default) keeps identical mounts at their desired paths.\n * `replace` removes owned mounts and appends canonical mounts in file order.\n * Foreign mounts always keep their paths. On a supported harness, if they\n * occupy every desired path, `replace` leaves the original profile unchanged.\n */\n reconcileExisting?: 'retain' | 'replace'\n}\n\n/** Inline file mounts placing a skill's support files beside its entry on\n * `harness`: `<skillDir>/<skillId>/<path>`. Empty when the harness has no\n * cwd skill dir — the same posture as `resources.skills` itself (the\n * platform skips skills there too), so nothing orphan lands in a workspace\n * a harness will never read.\n *\n * This is the placement primitive for kit-carrying skills (vendored\n * executable kits, reference trees). A growing program belongs in THESE\n * mounts — never in an env var: runtimeSecrets values are capped (8192\n * chars on the sandbox SDK) and a skill tree outgrew that cap in production\n * once, taking every isolated turn down with a secret-provider refusal. */\nexport function skillSupportFileMounts(\n harness: Harness,\n skillId: string,\n files: readonly SkillSupportFile[],\n options: Pick<SkillSupportFileOptions, 'resourceName'> = {},\n): AgentProfileFileMount[] {\n const skillDir = resolveSkillDir(harness)\n if (!skillDir || files.length === 0) return []\n return files.map((file) => ({\n path: `${skillDir}/${skillId}/${file.path}`,\n resource: defineInlineResource(\n options.resourceName ? options.resourceName(file) : `${skillId}/${file.path}`,\n file.content,\n ),\n }))\n}\n\n/** Attach a skill's support files to `profile` for `harness`, idempotently.\n *\n * Replacement is by EXACT CONTENT under the skill's own subtree (any path\n * ending `/<skillId>/<path>` whose bytes match a support file of THIS call):\n * re-deriving the same profile for another harness replaces this skill's\n * own mounts wherever they previously pointed, while pack-declared files\n * with similar paths stay untouched. With no skill dir the skill's own\n * mounts are dropped (and nothing added) — mirroring how the platform\n * treats the skill entry itself on that harness. `options` can customize\n * new resource names and opt into replacing owned mounts in file order. */\nexport function withSkillSupportFiles<\n P extends { resources?: AgentProfile['resources'] },\n>(\n profile: P,\n harness: Harness,\n skillId: string,\n files: readonly SkillSupportFile[],\n options: SkillSupportFileOptions = {},\n): P {\n const hasSkillDir = resolveSkillDir(harness) !== null\n const desired = skillSupportFileMounts(harness, skillId, files, options)\n const desiredByPath = new Map(\n desired.map((mount) => [mount.path, mount.resource] as const),\n )\n const byRelPath = new Map(files.map((file) => [file.path, file.content] as const))\n const suffix = `/${skillId}/`\n const relUnderSkill = (path: string): string | null => {\n const at = path.lastIndexOf(suffix)\n return at < 0 ? null : path.slice(at + suffix.length)\n }\n // \"Ours\" = a mount under THIS skill's subtree whose bytes match a support\n // file of this call. It is STALE when the harness has no skill dir (there\n // is nowhere to place it — mirroring how the platform skips the skill\n // entry itself) or when this call would place it at a different path\n // (re-derivation for another harness). Exact-content identity only: a\n // foreign mount at one of our paths keeps the location (pack-declared\n // files win at their declared paths). By default an identical mount is\n // kept as-is; the replace policy regenerates owned mounts in file order.\n const shouldDropMount = (mount: AgentProfileFileMount): boolean => {\n if (mount.resource.kind !== 'inline') return false\n const rel = relUnderSkill(mount.path)\n if (rel === null || byRelPath.get(rel) !== mount.resource.content) return false\n if (options.reconcileExisting === 'replace') return true\n const desiredHere = desiredByPath.get(mount.path)\n return (\n !hasSkillDir ||\n desiredHere === undefined ||\n desiredHere.kind !== 'inline' ||\n desiredHere.content !== mount.resource.content\n )\n }\n const existing = profile.resources?.files ?? []\n const retained = existing.filter((mount) => !shouldDropMount(mount))\n const taken = new Set(retained.map((mount) => mount.path))\n const additions = desired.filter((mount) => !taken.has(mount.path))\n // Preserve the replace policy's no-op when foreign mounts occupy every\n // destination; without a skill dir, owned mounts are still removed.\n if (additions.length === 0 && (\n retained.length === existing.length ||\n (hasSkillDir && options.reconcileExisting === 'replace')\n )) return profile\n return {\n ...profile,\n resources: { ...(profile.resources ?? {}), files: [...retained, ...additions] },\n }\n}\n"],"mappings":";;;;;;;;;AAqBA,SAAS,4BAA4B;AAErC,SAAS,0BAA0C;AAYnD,IAAM,iBAAsD;AAAA,EAC1D,UAAU;AAAA,EACV,eAAe;AAAA,EACf,UAA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AAY,YAAY,MAAM,SAAS;AAAA,EAE3C;AACA,QAAM,WAAW,QAAQ,WAAW,SAAS,CAAC;AAC9C,QAAM,WAAW,SAAS,OAAO,CAAC,UAAU,CAAC,gBAAgB,KAAK,CAAC;AACnE,QAAM,QAAQ,IAAI,IAAI,SAAS,IAAI,CAAC,UAAU,MAAM,IAAI,CAAC;AACzD,QAAM,YAAY,QAAQ,OAAO,CAAC,UAAU,CAAC,MAAM,IAAI,MAAM,IAAI,CAAC;AAGlE,MAAI,UAAU,WAAW,MACvB,SAAS,WAAW,SAAS,UAC5B,eAAe,QAAQ,sBAAsB,WAC7C,QAAO;AACV,SAAO;AAAA,IACL,GAAG;AAAA,IACH,WAAW,EAAE,GAAI,QAAQ,aAAa,CAAC,GAAI,OAAO,CAAC,GAAG,UAAU,GAAG,SAAS,EAAE;AAAA,EAChF;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/stream/turn-buffer.ts"],"sourcesContent":["/**\n * Resumable chat turns — the router-path answer to \"streams resume on\n * disconnect\" (issue #27). A turn's loop events are teed into a store as they\n * stream; the turn keeps running under `ctx.waitUntil` when the client drops;\n * a reconnecting client replays the buffered tail by sequence number and\n * keeps following until the turn completes.\n *\n * POST /chat/stream → pumpBufferedTurn(...) + live NDJSON\n * GET /chat/stream/:turnId → replayTurnEvents({ fromSeq }) → NDJSON\n *\n * Storage is a structural seam ({@link TurnEventStore}); a D1 implementation\n * ships here because that's what Cloudflare products have (KV is unsuitable:\n * eventually consistent cross-isolate). Per-token deltas would mean hundreds\n * of rows per turn, so consecutive text/reasoning deltas are coalesced within\n * a flush window before they are persisted — replay yields slightly chunkier\n * deltas with identical concatenation.\n */\n\nexport type TurnStatus = 'running' | 'complete' | 'error'\n\n/** A running row is a renewable lease, not permanent truth. If the process\n * driving a turn dies before writing a terminal status, reconnect discovery\n * must eventually stop returning that abandoned row. */\nexport const DEFAULT_RUNNING_TURN_LEASE_MS = 5 * 60_000\n\n/** Keep a healthy turn's lease comfortably ahead of expiry without turning\n * per-token streaming into status-write traffic. */\nexport const DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS = 30_000\n\n/** Represent a buffered turn event with a sequence number and serialized event data */\nexport interface BufferedTurnEvent {\n seq: number\n /** The serialized event line (JSON string, no trailing newline). */\n event: string\n}\n\n/** Manage and query turn events and their lifecycle statuses within a scoped event store */\nexport interface TurnEventStore {\n /**\n * Append rows while the turn is live. Implementations must ignore rows that\n * arrive after `setStatus` publishes `complete` or `error`; the terminal\n * status is the replay fence for a detached live projection.\n */\n append(turnId: string, events: BufferedTurnEvent[]): Promise<void>\n read(turnId: string, fromSeq: number): Promise<BufferedTurnEvent[]>\n /** Record turn lifecycle. `scopeId` (a thread/session id) is optional and lets\n * {@link TurnEventStore.listRunning} rediscover this turn after a client reload\n * loses the turnId; stores that don't track scope ignore it. */\n setStatus(turnId: string, status: TurnStatus, scopeId?: string, options?: TurnStatusWriteOptions): Promise<void>\n getStatus(turnId: string): Promise<TurnStatus | null>\n /** Unexpired running turnIds for a scope, newest first — so a reloaded client\n * (clientRunId lost) can find and resume the in-flight turn without reviving\n * a row abandoned by a dead process. Optional: a store records it only if\n * `setStatus` was given a `scopeId`. */\n listRunning?(scopeId: string): Promise<string[]>\n /** Remove one turn's buffered events and keep its status, so a genuine\n * re-stream after a crash starts at seq 0 without interleaving orphaned\n * rows. `runDetachedTurn` requires it to recover a `running` turn. */\n resetEvents?(turnId: string): Promise<void>\n /** Explicitly remove one turn's events and status. Optional so existing\n * custom stores remain source-compatible; the built-in D1 and memory stores\n * provide it. */\n deleteTurn?(turnId: string): Promise<void>\n /** Remove terminal turns whose status was updated before `before` (Unix\n * milliseconds or a Date). Running turns are never eligible. */\n pruneTerminalTurns?(before: number | Date): Promise<number>\n /** Running turns last renewed before `before` (Unix ms), oldest first, at most\n * `limit`: the candidates {@link settleOrphanedTurns} settles. */\n listStaleRunning?(before: number, limit: number): Promise<StaleRunningTurn[]>\n /** The last `count` events of a turn, newest first; a bounded read of the tail. */\n readTail?(turnId: string, count: number): Promise<BufferedTurnEvent[]>\n}\n\n/** A running turn nothing has renewed since `updatedAt`. */\nexport interface StaleRunningTurn {\n turnId: string\n scopeId: string | null\n /** Unix ms of the last status write. */\n updatedAt: number\n /** Set on a plan follow-up claim (`createD1PlanFollowUpGate`), which keeps its own staleness and does not renew. */\n leaseToken?: string | null\n}\n\n/**\n * Settling a stream nothing produces any more. A sweep that ends an orphaned\n * stream must not move it in time, since reports place a stream by its update\n * time, and must not end one whose producer came back meanwhile.\n */\nexport interface TurnStatusWriteOptions {\n /** Keep the row's update time; a new row still takes the current time. */\n preserveUpdatedAt?: boolean\n /** Write only when the row is still `running` and was last updated before this time (Unix ms). */\n onlyIfRunningBefore?: number\n}\n\n/** Configure running-turn lease evaluation. The clock is injectable so store\n * contract tests do not sleep. Keep the default in production unless a\n * deployment also tunes the buffer's renewal interval. */\nexport interface TurnEventStoreOptions {\n runningTurnLeaseMs?: number\n now?: () => number\n}\n\n// ── coalescing ────────────────────────────────────────────────────────────\n\ntype AnyRecord = Record<string, unknown>\n\nfunction deltaTypeOf(ev: unknown): 'text' | 'reasoning' | null {\n const e = ev as AnyRecord | null\n if (!e || typeof e !== 'object') return null\n const inner = (e.kind === 'event' ? (e.event as AnyRecord | undefined) : e) as AnyRecord | undefined\n if (!inner || typeof inner !== 'object') return null\n if ((inner.type === 'text' || inner.type === 'reasoning') && typeof inner.text === 'string') {\n return inner.type\n }\n return null\n}\n\nfunction innerOf(ev: unknown): AnyRecord | null {\n const e = ev as AnyRecord | null\n if (!e || typeof e !== 'object') return null\n const inner = (e.kind === 'event' ? e.event : e) as AnyRecord | undefined\n return inner && typeof inner === 'object' ? inner : null\n}\n\n/**\n * The key of a live-state event whose latest value supersedes earlier ones:\n * the model-processing heartbeat, and a harness's raw update of a text or\n * reasoning part (it carries the part's whole state, keyed by part id). Null\n * for every other event.\n */\nfunction liveStateKeyOf(ev: unknown): string | null {\n const inner = innerOf(ev)\n if (!inner) return null\n if (inner.type === 'model-processing') return 'model-processing'\n if (inner.type !== 'raw') return null\n const raw = (inner.data as AnyRecord | undefined)?.event as AnyRecord | undefined\n const part = raw?.part as AnyRecord | undefined\n if ((raw?.type === 'text' || raw?.type === 'reasoning') && typeof part?.id === 'string') return `raw:${part.id}`\n return null\n}\n\n/** Whether an event only projects live progress, so it may wait for the flush window and be coalesced. */\nexport function isLiveProgressEvent(ev: unknown): boolean {\n return deltaTypeOf(ev) !== null || liveStateKeyOf(ev) !== null\n}\n\n/**\n * Merge text and reasoning deltas of the same type into one event, across the\n * live-state events a harness interleaves with them, and keep only the latest\n * of each live-state event. A reasoning model streams three events per token\n * (its raw part update, a model-processing heartbeat and the delta); merging\n * only adjacent deltas wrote all three as rows (1.63 M rows in a\n * day, 59,659 in one turn). Any other event is a boundary nothing merges\n * across. Concatenation-preserving: replaying the coalesced stream produces\n * the same accumulated text, and the latest state of every part.\n */\nexport function coalesceDeltas(events: unknown[]): unknown[] {\n const out: unknown[] = []\n let run: { type: 'text' | 'reasoning'; index: number } | null = null\n let stateSlots = new Map<string, number>()\n for (const ev of events) {\n const type = deltaTypeOf(ev)\n if (type) {\n if (run && run.type === type) {\n const merged = JSON.parse(JSON.stringify(out[run.index])) as AnyRecord\n innerOf(merged)!.text = String(innerOf(out[run.index])!.text) + String(innerOf(ev)!.text)\n out[run.index] = merged\n } else {\n out.push(ev)\n run = { type, index: out.length - 1 }\n }\n continue\n }\n const key = liveStateKeyOf(ev)\n if (key) {\n const slot = stateSlots.get(key)\n if (slot === undefined) {\n out.push(ev)\n stateSlots.set(key, out.length - 1)\n } else {\n out[slot] = ev\n }\n continue\n }\n out.push(ev)\n run = null\n stateSlots = new Map()\n }\n return out\n}\n\nfunction asPartUpdate(ev: unknown): { partId: unknown; delta: unknown } | null {\n const e = ev as AnyRecord | null\n if (!e || typeof e !== 'object' || e.type !== 'message.part.updated') return null\n const data = e.data as AnyRecord | undefined\n if (!data || typeof data !== 'object') return null\n const part = data.part as AnyRecord | undefined\n const partId = part?.id ?? data.partId ?? part?.partId ?? null\n return { partId, delta: data.delta }\n}\n\n/**\n * Coalesce consecutive `message.part.updated` deltas for the SAME part into one\n * event. agent-runtime products stream `ChatStreamEvent` NDJSON\n * (`{type:'message.part.updated', data:{part, delta}}`); pumped through the\n * buffer with the default tool-loop coalescer, every per-token delta persists as\n * its own row because that coalescer never recognizes the shape. Pass this as\n * {@link PumpBufferedTurnOptions.coalesce} instead.\n *\n * Concatenation-preserving for BOTH consumer styles: the merged event keeps the\n * LATEST event's `data.part` (already the cumulative accumulation) and sets\n * `data.delta` to the concatenation of the merged deltas, so a client that\n * appends `delta` and one that reads the cumulative `part` both reconstruct the\n * identical final text.\n */\nexport function coalesceChatStreamEvents(events: unknown[]): unknown[] {\n const out: unknown[] = []\n for (const ev of events) {\n const cur = asPartUpdate(ev)\n const prevEv = out[out.length - 1]\n const prev = prevEv ? asPartUpdate(prevEv) : null\n if (cur && prev && cur.partId != null && cur.partId === prev.partId) {\n // Base the merged row on the latest event (its `part` is the most complete\n // accumulation); carry forward the summed delta.\n const merged = JSON.parse(JSON.stringify(ev)) as AnyRecord\n ;(merged.data as AnyRecord).delta = String(prev.delta ?? '') + String(cur.delta ?? '')\n out[out.length - 1] = merged\n continue\n }\n out.push(ev)\n }\n return out\n}\n\n// ── buffering core (the tap) ────────────────────────────────────────────────\n\n/** Define options for buffering and flushing turn events with optional live client delivery and event coalescing */\nexport interface BufferedTurnOptions {\n store: TurnEventStore\n turnId: string\n /** Deliver one serialized line to the live client. Throwing here (client\n * disconnected) does NOT stop buffering — events keep persisting. */\n write?: (line: string) => Promise<void> | void\n /** Flush buffered events to the store at most this often. Default 400ms. */\n flushIntervalMs?: number\n /** Flush window once a durable owner has taken the turn ({@link BufferedTurnTap.detach}). Live-progress events\n * wait for it; any other event flushes at once, after them. Default 2000ms. */\n detachedFlushIntervalMs?: number\n /** Per-flush coalescer. Default {@link coalesceDeltas} (tool-loop text/reasoning\n * deltas). agent-runtime products streaming `ChatStreamEvent` pass\n * {@link coalesceChatStreamEvents} so per-token deltas don't each persist as a\n * row. Must be concatenation-preserving. */\n coalesce?: (events: unknown[]) => unknown[]\n /** Optional scope (thread/session id) recorded with the turn status, so\n * {@link TurnEventStore.listRunning} can find this turn after a reload. */\n scopeId?: string\n /** How often to renew the running-turn lease while a producer is alive.\n * The timer is backed up by event-driven renewal when a runtime freezes\n * unreferenced timers during remote I/O. Default\n * {@link DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS}. */\n runningTurnRenewIntervalMs?: number\n}\n\n/** A push-driven buffer for a turn whose producer the caller does NOT own. */\nexport interface BufferedTurnTap {\n /** Buffer one event: persist (coalesced, on the flush window) + best-effort\n * live-deliver. Wire to a push source's per-event hook (e.g. agent-runtime\n * `handleChatTurn`'s `hooks.onEvent`). Marks the turn 'running' on first call. */\n onEvent(raw: unknown): Promise<void>\n /** Settle the turn: final flush + set status. Call after the producer resolves\n * ('complete') or rejects ('error'). 'error' flushes what was produced first. */\n done(status?: Extract<TurnStatus, 'complete' | 'error'>): Promise<void>\n /**\n * Give terminal-status ownership to an external durable runner. Stops this\n * tap's running-lease renewal and flushes its current projection, but keeps\n * `onEvent` available as an append-only live-observation path. After the\n * handoff, an event that is not live progress (a marker, interaction, tool\n * event, error or terminal event) flushes before `onEvent` returns, so a\n * durable owner cannot publish terminal status ahead of it; live progress\n * (deltas, heartbeats, raw part updates) is coalesced over\n * `detachedFlushIntervalMs`. Call it again when observation ends to flush any\n * final event.\n *\n * A caller MUST have registered that durable owner before detaching: this\n * method intentionally writes no replacement status.\n */\n detach(): Promise<void>\n}\n\n/**\n * The buffering core. Sequence-numbers every event, delivers it to `write`\n * (best-effort — a disconnected client never stops buffering), and flushes to\n * the store in coalesced batches. Drives both transports:\n *\n * • {@link pumpBufferedTurn} — when you OWN an `AsyncIterable` producer.\n * • this tap (`onEvent`/`done`) — when the producer owns iteration and only\n * hands you a push callback (agent-runtime `handleChatTurn`'s `hooks.onEvent`\n * + the finished body). Durability stays here in the shell; the engine needs\n * no `TurnEventStore` seam.\n */\n/** Serialized characters of pending events that force a flush before the window ends. */\nconst MAX_PENDING_CHARS = 64 * 1024\n\nexport function createBufferedTurnTap(opts: BufferedTurnOptions): BufferedTurnTap {\n const flushIntervalMs = opts.flushIntervalMs ?? 400\n const detachedFlushIntervalMs = opts.detachedFlushIntervalMs ?? 2000\n let pendingChars = 0\n const coalesce = opts.coalesce ?? coalesceDeltas\n const startedAt = Date.now()\n let seq = 0\n let clientGone = false\n let pending: unknown[] = []\n let lastFlush = Date.now()\n let started = false\n let settled = false\n let detached = false\n let renewalTimer: ReturnType<typeof setTimeout> | undefined\n let renewal: Promise<void> = Promise.resolve()\n let lastRenewedAt = 0\n const runningTurnRenewIntervalMs = Math.max(\n 1,\n opts.runningTurnRenewIntervalMs ?? DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS,\n )\n\n function clearRenewalTimer(): void {\n if (renewalTimer !== undefined) clearTimeout(renewalTimer)\n renewalTimer = undefined\n }\n\n function scheduleRenewal(): void {\n if (settled || detached || !opts.scopeId) return\n clearRenewalTimer()\n const elapsedMs = Math.max(0, Date.now() - lastRenewedAt)\n const delayMs = Math.max(1, runningTurnRenewIntervalMs - elapsedMs)\n renewalTimer = setTimeout(() => {\n renewalTimer = undefined\n void renewLease()\n }, delayMs)\n // A deliberately abandoned tap in a Node test must not keep the process\n // alive until the production renewal interval elapses.\n if (typeof renewalTimer === 'object' && 'unref' in renewalTimer) {\n renewalTimer.unref()\n }\n }\n\n async function renewLease(): Promise<void> {\n if (settled || detached || !opts.scopeId) return\n clearRenewalTimer()\n lastRenewedAt = Date.now()\n renewal = renewal\n .then(() => opts.store.setStatus(opts.turnId, 'running', opts.scopeId))\n .catch(() => {})\n await renewal\n scheduleRenewal()\n }\n\n async function flush(): Promise<void> {\n if (pending.length === 0) return\n const batch = coalesce(pending)\n pending = []\n pendingChars = 0\n const rows = batch.map((ev) => ({ seq: ++seq, event: JSON.stringify(ev) }))\n await opts.store.append(opts.turnId, rows)\n lastFlush = Date.now()\n }\n\n async function ensureStarted(): Promise<void> {\n if (started) return\n started = true\n // An external durable owner may have detached before the first observed\n // event. It owns status from that point, so this tap must never resurrect\n // its running lease.\n if (detached) return\n await opts.store.setStatus(opts.turnId, 'running', opts.scopeId)\n lastRenewedAt = Date.now()\n scheduleRenewal()\n }\n\n return {\n async onEvent(raw) {\n await ensureStarted()\n // Cloudflare may freeze an unreferenced timer while a producer is\n // awaiting remote I/O. A real event (including the route heartbeat)\n // therefore also renews any lease whose interval has elapsed.\n if (\n !detached &&\n opts.scopeId &&\n Date.now() - lastRenewedAt >= runningTurnRenewIntervalMs\n ) {\n await renewLease()\n }\n // Stamp ms-since-turn-start so any stored turn is replayable AND traceable\n // (see ../trace) from the same buffered rows.\n const ev = raw && typeof raw === 'object' ? { ...(raw as Record<string, unknown>), _t: Date.now() - startedAt } : raw\n const line = JSON.stringify(ev)\n pending.push(ev)\n pendingChars += line?.length ?? 0\n if (!clientGone && opts.write) {\n try {\n // Live delivery carries a provisional ordering hint, not the persisted\n // seq (coalescing changes seq assignment); clients resume with the\n // seqs from replay, or 0 for \"everything\".\n await opts.write(line)\n } catch {\n clientGone = true\n }\n }\n // Once detached, a turn marker, interaction, tool event, error or terminal event persists at once (with the\n // progress before it), and live progress waits for the window, so a reasoning model's per-token events do\n // not each become a row. An external owner's terminal status can fence at most the last window of progress.\n const due = detached\n ? !isLiveProgressEvent(ev) || Date.now() - lastFlush >= detachedFlushIntervalMs\n : Date.now() - lastFlush >= flushIntervalMs\n if (due || pendingChars >= MAX_PENDING_CHARS) await flush()\n },\n async done(status = 'complete') {\n await ensureStarted()\n if (detached) {\n await flush()\n return\n }\n settled = true\n clearRenewalTimer()\n await renewal\n if (status === 'error') {\n await flush().catch(() => {})\n await opts.store.setStatus(opts.turnId, 'error', opts.scopeId).catch(() => {})\n return\n }\n await flush()\n await opts.store.setStatus(opts.turnId, 'complete', opts.scopeId)\n },\n async detach() {\n detached = true\n clearRenewalTimer()\n // A renewal already queued before detach may be writing `running`. Wait\n // for it before returning so the durable owner can safely publish a\n // terminal status after the awaited handoff.\n await renewal\n await flush()\n },\n }\n}\n\n// ── pump (producer side) ──────────────────────────────────────────────────\n\n/** Define options to pump data from an asynchronous iterable source with buffered turn control */\nexport interface PumpBufferedTurnOptions extends BufferedTurnOptions {\n source: AsyncIterable<unknown>\n}\n\n/**\n * Drive a turn to completion regardless of the live client, when you OWN the\n * producer as an `AsyncIterable`. A thin driver over {@link createBufferedTurnTap}.\n * Returns a promise that resolves when the turn finishes — hand it to\n * `ctx.waitUntil` so a disconnect can't kill the turn. Never rejects on\n * client-write failure; a source error marks the turn 'error' (after flushing\n * what was produced) and rethrows.\n */\nexport async function pumpBufferedTurn(opts: PumpBufferedTurnOptions): Promise<void> {\n const tap = createBufferedTurnTap(opts)\n try {\n for await (const raw of opts.source) await tap.onEvent(raw)\n await tap.done('complete')\n } catch (err) {\n await tap.done('error')\n throw err\n }\n}\n\n// ── replay (consumer side) ────────────────────────────────────────────────\n\n/** Define options for replaying turn events with control over sequence, polling, and timeout */\nexport interface ReplayTurnEventsOptions {\n store: TurnEventStore\n turnId: string\n /** Replay strictly after this sequence number (0 = from the beginning). */\n fromSeq?: number\n /** Poll cadence while the turn is still running. Default 500ms. */\n pollMs?: number\n /** Give up following a 'running' turn after this long. Default 120s. */\n timeoutMs?: number\n}\n\n/**\n * Yield buffered events after `fromSeq`, then keep polling while the turn is\n * still 'running' until it completes, errors, or times out. Terminates with a\n * final `{seq: -1, event: '{\"type\":\"turn_status\",...}'}` marker so clients\n * know why the replay ended.\n */\nexport async function* replayTurnEvents(opts: ReplayTurnEventsOptions): AsyncGenerator<BufferedTurnEvent> {\n const pollMs = opts.pollMs ?? 500\n const timeoutMs = opts.timeoutMs ?? 120_000\n let cursor = opts.fromSeq ?? 0\n const deadline = Date.now() + timeoutMs\n\n for (;;) {\n const batch = await opts.store.read(opts.turnId, cursor)\n for (const row of batch) {\n cursor = Math.max(cursor, row.seq)\n yield row\n }\n const status = await opts.store.getStatus(opts.turnId)\n if (status !== 'running') {\n // Writers flush before publishing terminal status; include rows committed after the first read.\n yield* await opts.store.read(opts.turnId, cursor)\n yield { seq: -1, event: JSON.stringify({ type: 'turn_status', status: status ?? 'unknown' }) }\n return\n }\n if (Date.now() >= deadline) {\n yield { seq: -1, event: JSON.stringify({ type: 'turn_status', status: 'timeout' }) }\n return\n }\n await new Promise((r) => setTimeout(r, pollMs))\n }\n}\n\n/**\n * Serialize a replayed row for the wire, stamping the buffer ordinal ONTO the\n * line so a reconnecting client can continue from `?fromSeq=<lastSeq>`.\n *\n * The seq lives on the {@link BufferedTurnEvent} row wrapper, not inside the\n * serialized event — `flush()` builds `{seq: ++seq, event: JSON.stringify(ev)}`.\n * A route that enqueues `row.event` alone therefore emits lines with no seq at\n * all, and every client cursor silently pins to 0: each reconnect refetches the\n * whole turn and re-applies every delta onto already-rendered state. This\n * restores the contract `web-react/chat-stream` already documents (\"replayed\n * lines carry an extra `seq` — transparently ignored\").\n *\n * The `{seq: -1}` `turn_status` sentinel is passed through unstamped: it is a\n * terminator, not a cursor position, and stamping it would move a client's\n * cursor to -1.\n *\n * Fail-soft by construction — a line that is not a JSON object passes through\n * verbatim. A stamping bug must degrade to today's behaviour, never break a\n * replay.\n */\nexport function stampReplaySeq(row: BufferedTurnEvent): string {\n if (row.seq <= 0) return row.event\n const line = row.event\n // Cheap splice instead of parse+stringify: these rows are already canonical\n // JSON objects from `JSON.stringify`, and replay is a hot per-event path.\n if (line.charCodeAt(0) !== 0x7b /* { */) return line\n const rest = line.slice(1)\n return rest.trimStart().startsWith('}')\n ? `{\"seq\":${row.seq}${rest}`\n : `{\"seq\":${row.seq},${rest}`\n}\n\n// ── D1 store ──────────────────────────────────────────────────────────────\n\n/** A bound D1 statement used by the turn store. */\nexport interface D1BoundForTurns {\n run(): Promise<unknown>\n all<T = Record<string, unknown>>(): Promise<{ results: T[] }>\n first<T = Record<string, unknown>>(): Promise<T | null>\n}\n\n/** Minimal structural D1 contract (Cloudflare `D1Database` satisfies it). */\nexport interface D1LikeForTurns {\n prepare(sql: string): {\n bind(...values: unknown[]): D1BoundForTurns\n }\n /** D1's only atomic primitive. Retention refuses a driver without it rather\n * than deleting events and status in separate, reorderable requests. */\n batch?(statements: D1BoundForTurns[]): Promise<unknown[]>\n}\n\nfunction normalizeTurnCutoff(before: number | Date): { milliseconds: number; iso: string } {\n const milliseconds = before instanceof Date ? before.getTime() : before\n if (!Number.isFinite(milliseconds)) {\n throw new RangeError('turn retention cutoff must be a finite Unix-millisecond timestamp or a valid Date')\n }\n const date = new Date(milliseconds)\n if (!Number.isFinite(date.getTime())) {\n throw new RangeError('turn retention cutoff is outside the supported Date range')\n }\n return { milliseconds, iso: date.toISOString() }\n}\n\nasync function runAtomicTurnBatch(\n db: D1LikeForTurns,\n statements: D1BoundForTurns[],\n): Promise<unknown[]> {\n if (typeof db.batch !== 'function') {\n throw new Error('turn retention requires D1 batch() for atomic deletion')\n }\n return db.batch(statements)\n}\n\nfunction changesFromD1Result(result: unknown): number {\n if (!result || typeof result !== 'object') return 0\n const meta = (result as { meta?: unknown }).meta\n if (meta && typeof meta === 'object') {\n const changes = (meta as { changes?: unknown }).changes\n if (typeof changes === 'number' && Number.isFinite(changes)) return changes\n }\n const changes = (result as { changes?: unknown }).changes\n return typeof changes === 'number' && Number.isFinite(changes) ? changes : 0\n}\n\n/** Schema for the D1 store — append to the product's migrations. */\nexport const TURN_EVENTS_MIGRATION_SQL = `\nCREATE TABLE IF NOT EXISTS turn_events (\n turnId TEXT NOT NULL,\n seq INTEGER NOT NULL,\n event TEXT NOT NULL,\n PRIMARY KEY (turnId, seq)\n);\nCREATE TABLE IF NOT EXISTS turn_status (\n turnId TEXT PRIMARY KEY,\n status TEXT NOT NULL,\n scopeId TEXT,\n updatedAt TEXT NOT NULL\n);\nCREATE INDEX IF NOT EXISTS idx_turn_status_scope ON turn_status (scopeId, status);\nCREATE INDEX IF NOT EXISTS idx_turn_status_retention ON turn_status (status, updatedAt);\n`\n\n/** For deployments whose `turn_status` table predates `scopeId`/`listRunning` —\n * run once to add the column (the CREATE above already includes it for new\n * deployments). SQLite ignores a duplicate-add error if already applied. */\nexport const TURN_STATUS_SCOPE_MIGRATION_SQL = `ALTER TABLE turn_status ADD COLUMN scopeId TEXT;`\n\n/** Run once before using `createD1PlanFollowUpGate`: it adds the lease column\n * the gate fences its claims on. Stores that never take follow-up claims do\n * not need it, so the base turn tables leave it out. */\nexport const TURN_STATUS_LEASE_MIGRATION_SQL = 'ALTER TABLE turn_status ADD COLUMN leaseToken TEXT;'\n\n/** For deployments that already have the turn tables, add the index used by\n * terminal-turn retention without rerunning the table migration. */\nexport const TURN_STATUS_RETENTION_MIGRATION_SQL = 'CREATE INDEX IF NOT EXISTS idx_turn_status_retention ON turn_status (status, updatedAt);'\n\n/** Resolve a TurnEventStore that appends and reads turn events using a D1-like database interface */\n/** A store that lists running turns by scope, as the turn lock's default reclaim needs. */\nexport type ListingTurnEventStore = TurnEventStore & Required<Pick<TurnEventStore, 'listRunning'>>\n\n/** 100 D1 variables per statement, three per row. */\nconst D1_APPEND_CHUNK = 33\n\nexport function createD1TurnEventStore(\n db: D1LikeForTurns,\n options: TurnEventStoreOptions = {},\n): ListingTurnEventStore {\n const now = options.now ?? Date.now\n const runningTurnLeaseMs = Math.max(\n 1,\n options.runningTurnLeaseMs ?? DEFAULT_RUNNING_TURN_LEASE_MS,\n )\n return {\n async append(turnId, events) {\n if (!events.length) return\n // One multi-row insert per flush window keeps write volume bounded, but\n // D1 caps a statement at 100 bound variables, so a burst of more than 33\n // events (a subagent finishing, a long tool result) failed the whole\n // flush with `D1_ERROR: too many SQL variables` and killed the turn.\n // Rows are appended in order across chunks; a partial failure leaves a\n // prefix, which the ordered `seq` column already tolerates on replay.\n for (let start = 0; start < events.length; start += D1_APPEND_CHUNK) {\n const chunk = events.slice(start, start + D1_APPEND_CHUNK)\n const placeholders = chunk.map(() => '(?, ?, ?)').join(', ')\n const values = chunk.flatMap((e) => [turnId, e.seq, e.event])\n await db\n .prepare(\n `WITH pending(turnId, seq, event) AS (VALUES ${placeholders})\n INSERT OR IGNORE INTO turn_events (turnId, seq, event)\n SELECT pending.turnId, pending.seq, pending.event\n FROM pending\n WHERE NOT EXISTS (\n SELECT 1 FROM turn_status\n WHERE turn_status.turnId = pending.turnId\n AND turn_status.status IN ('complete', 'error')\n )`,\n )\n .bind(...values)\n .run()\n }\n },\n async read(turnId, fromSeq) {\n const { results } = await db\n .prepare('SELECT seq, event FROM turn_events WHERE turnId = ? AND seq > ? ORDER BY seq ASC')\n .bind(turnId, fromSeq)\n .all<{ seq: number; event: string }>()\n return results\n },\n async setStatus(turnId, status, scopeId, options = {}) {\n const at = new Date(now()).toISOString()\n if (options.onlyIfRunningBefore !== undefined) {\n // A guarded write never creates a row: it settles one that exists, is running and is stale.\n await db\n .prepare(\n `UPDATE turn_status SET status = ?, scopeId = COALESCE(?, scopeId)${options.preserveUpdatedAt ? '' : ', updatedAt = ?'} WHERE turnId = ? AND status = 'running' AND updatedAt < ?`,\n )\n .bind(...[status, scopeId ?? null, ...(options.preserveUpdatedAt ? [] : [at]), turnId, new Date(options.onlyIfRunningBefore).toISOString()])\n .run()\n return\n }\n // COALESCE preserves a scopeId set on the initial 'running' write when a\n // later 'complete'/'error' write passes none.\n await db\n .prepare(\n `INSERT INTO turn_status (turnId, status, scopeId, updatedAt) VALUES (?, ?, ?, ?) ON CONFLICT(turnId) DO UPDATE SET status = excluded.status, scopeId = COALESCE(excluded.scopeId, turn_status.scopeId)${options.preserveUpdatedAt ? '' : ', updatedAt = excluded.updatedAt'}`,\n )\n .bind(turnId, status, scopeId ?? null, at)\n .run()\n },\n async getStatus(turnId) {\n const row = await db.prepare('SELECT status FROM turn_status WHERE turnId = ?').bind(turnId).first<{ status: TurnStatus }>()\n return row?.status ?? null\n },\n async listRunning(scopeId) {\n const { results } = await db\n .prepare(\n \"SELECT turnId FROM turn_status WHERE scopeId = ? AND status = 'running' AND updatedAt >= ? ORDER BY updatedAt DESC, rowid DESC\",\n )\n .bind(scopeId, new Date(now() - runningTurnLeaseMs).toISOString())\n .all<{ turnId: string }>()\n return results.map((r) => r.turnId)\n },\n async resetEvents(turnId) {\n await db.prepare('DELETE FROM turn_events WHERE turnId = ?').bind(turnId).run()\n },\n async deleteTurn(turnId) {\n await runAtomicTurnBatch(db, [\n db.prepare('DELETE FROM turn_events WHERE turnId = ?').bind(turnId),\n db.prepare('DELETE FROM turn_status WHERE turnId = ?').bind(turnId),\n ])\n },\n async listStaleRunning(before, limit) {\n const { results } = await db\n // `*` so a deployment that applied TURN_STATUS_LEASE_MIGRATION_SQL also returns its follow-up claims' leaseToken.\n .prepare(\"SELECT * FROM turn_status WHERE status = 'running' AND updatedAt < ? ORDER BY updatedAt ASC LIMIT ?\")\n .bind(new Date(before).toISOString(), Math.max(1, Math.floor(limit)))\n .all<{ turnId: string; scopeId: string | null; updatedAt: string; leaseToken?: string | null }>()\n return results.map((row) => ({\n turnId: row.turnId,\n scopeId: row.scopeId ?? null,\n updatedAt: Date.parse(row.updatedAt),\n ...(row.leaseToken ? { leaseToken: row.leaseToken } : {}),\n }))\n },\n async readTail(turnId, count) {\n const { results } = await db\n .prepare('SELECT seq, event FROM turn_events WHERE turnId = ? ORDER BY seq DESC LIMIT ?')\n .bind(turnId, Math.max(1, Math.floor(count)))\n .all<{ seq: number; event: string }>()\n return results\n },\n async pruneTerminalTurns(before) {\n const cutoff = normalizeTurnCutoff(before)\n const terminalBefore = \"status IN ('complete', 'error') AND updatedAt < ?\"\n const results = await runAtomicTurnBatch(db, [\n db\n .prepare(\n `DELETE FROM turn_events WHERE turnId IN (SELECT turnId FROM turn_status WHERE ${terminalBefore})`,\n )\n .bind(cutoff.iso),\n db.prepare(`DELETE FROM turn_status WHERE ${terminalBefore}`).bind(cutoff.iso),\n ])\n return changesFromD1Result(results[1])\n },\n }\n}\n\n/** In-memory store for tests and keyless local dev. */\nexport function createMemoryTurnEventStore(\n options: TurnEventStoreOptions = {},\n): ListingTurnEventStore {\n const events = new Map<string, BufferedTurnEvent[]>()\n const status = new Map<string, TurnStatus>()\n const scopes = new Map<string, string>()\n const order: string[] = []\n const updatedAt = new Map<string, number>()\n const now = options.now ?? Date.now\n const runningTurnLeaseMs = Math.max(\n 1,\n options.runningTurnLeaseMs ?? DEFAULT_RUNNING_TURN_LEASE_MS,\n )\n return {\n async append(turnId, rows) {\n if (status.get(turnId) === 'complete' || status.get(turnId) === 'error') return\n const list = events.get(turnId) ?? []\n list.push(...rows)\n events.set(turnId, list)\n },\n async read(turnId, fromSeq) {\n return (events.get(turnId) ?? []).filter((e) => e.seq > fromSeq)\n },\n async setStatus(turnId, s, scopeId, options = {}) {\n if (options.onlyIfRunningBefore !== undefined) {\n const stale = status.get(turnId) === 'running' && (updatedAt.get(turnId) ?? Number.POSITIVE_INFINITY) < options.onlyIfRunningBefore\n if (!stale) return\n }\n const existed = status.has(turnId)\n status.set(turnId, s)\n if (scopeId) scopes.set(turnId, scopeId)\n if (!order.includes(turnId)) order.push(turnId)\n if (!(options.preserveUpdatedAt && existed)) updatedAt.set(turnId, now())\n },\n async getStatus(turnId) {\n return status.get(turnId) ?? null\n },\n async listRunning(scopeId) {\n const cutoff = now() - runningTurnLeaseMs\n return order\n .filter(\n (turnId) =>\n status.get(turnId) === 'running' &&\n scopes.get(turnId) === scopeId &&\n (updatedAt.get(turnId) ?? Number.NEGATIVE_INFINITY) >= cutoff,\n )\n .sort((left, right) => {\n const updatedDelta = (updatedAt.get(right) ?? 0) - (updatedAt.get(left) ?? 0)\n return updatedDelta || order.indexOf(right) - order.indexOf(left)\n })\n },\n async resetEvents(turnId) {\n events.delete(turnId)\n },\n async deleteTurn(turnId) {\n events.delete(turnId)\n status.delete(turnId)\n scopes.delete(turnId)\n updatedAt.delete(turnId)\n const index = order.indexOf(turnId)\n if (index >= 0) order.splice(index, 1)\n },\n async listStaleRunning(before, limit) {\n return order\n .filter((turnId) => status.get(turnId) === 'running' && (updatedAt.get(turnId) ?? Number.POSITIVE_INFINITY) < before)\n .sort((left, right) => (updatedAt.get(left) ?? 0) - (updatedAt.get(right) ?? 0))\n .slice(0, Math.max(1, Math.floor(limit)))\n .map((turnId) => ({ turnId, scopeId: scopes.get(turnId) ?? null, updatedAt: updatedAt.get(turnId)! }))\n },\n async readTail(turnId, count) {\n return (events.get(turnId) ?? []).slice(-Math.max(1, Math.floor(count))).reverse()\n },\n async pruneTerminalTurns(before) {\n const cutoff = normalizeTurnCutoff(before).milliseconds\n const removable = order.filter((turnId) => {\n const s = status.get(turnId)\n return (s === 'complete' || s === 'error') && (updatedAt.get(turnId) ?? Number.POSITIVE_INFINITY) < cutoff\n })\n for (const turnId of removable) {\n events.delete(turnId)\n status.delete(turnId)\n scopes.delete(turnId)\n updatedAt.delete(turnId)\n }\n if (removable.length) {\n const removed = new Set(removable)\n for (let i = order.length - 1; i >= 0; i--) {\n if (removed.has(order[i]!)) order.splice(i, 1)\n }\n }\n return removable.length\n },\n }\n}\n"],"mappings":";AAuBO,IAAM,gCAAgC,IAAI;AAI1C,IAAM,yCAAyC;AAgFtD,SAAS,YAAY,IAA0C;AAC7D,QAAM,IAAI;AACV,MAAI,CAAC,KAAK,OAAO,MAAM,SAAU,QAAO;AACxC,QAAM,QAAS,EAAE,SAAS,UAAW,EAAE,QAAkC;AACzE,MAAI,CAAC,SAAS,OAAO,UAAU,SAAU,QAAO;AAChD,OAAK,MAAM,SAAS,UAAU,MAAM,SAAS,gBAAgB,OAAO,MAAM,SAAS,UAAU;AAC3F,WAAO,MAAM;AAAA,EACf;AACA,SAAO;AACT;AAEA,SAAS,QAAQ,IAA+B;AAC9C,QAAM,IAAI;AACV,MAAI,CAAC,KAAK,OAAO,MAAM,SAAU,QAAO;AACxC,QAAM,QAAS,EAAE,SAAS,UAAU,EAAE,QAAQ;AAC9C,SAAO,SAAS,OAAO,UAAU,WAAW,QAAQ;AACtD;AA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