@tangle-network/agent-app 0.60.249 → 0.60.251
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/DesignCanvas-L6J72JQ2.js +15 -0
- package/dist/DesignCanvasEditor-QFQD63MR.js +18 -0
- package/dist/agent-enrollment/drizzle.js +3 -3
- package/dist/agent-enrollment/index.js +3 -3
- package/dist/app-auth/drizzle.d.ts +561 -0
- package/dist/app-auth/drizzle.js +72 -0
- package/dist/app-auth/drizzle.js.map +1 -0
- package/dist/app-auth/index.js +5 -3
- package/dist/app-auth/index.js.map +1 -1
- package/dist/app-oauth/drizzle.d.ts +2080 -0
- package/dist/app-oauth/drizzle.js +161 -0
- package/dist/app-oauth/drizzle.js.map +1 -0
- package/dist/app-oauth/index.d.ts +4 -0
- package/dist/app-oauth/index.js +8 -222
- package/dist/app-oauth/index.js.map +1 -1
- package/dist/app-oauth/issuer.d.ts +133 -0
- package/dist/app-oauth/issuer.js +247 -0
- package/dist/app-oauth/issuer.js.map +1 -0
- package/dist/assistant/index.js +13 -13
- package/dist/chat-react/index.js +4 -4
- package/dist/chat-routes/dispatch-first.d.ts +43 -0
- package/dist/chat-routes/index.js +37 -67
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/chat-routes/promote-file-part.d.ts +2 -3
- package/dist/chat-routes/turn-execution.d.ts +3 -1
- package/dist/chat-routes/turn-route-contracts.d.ts +31 -0
- package/dist/chat-store/index.js +4 -4
- package/dist/{chunk-MY3EJJ6Y.js → chunk-4FEH6266.js} +2 -2
- package/dist/{chunk-5Y7Z5G3Y.js → chunk-4GCPADYG.js} +20 -336
- package/dist/chunk-4GCPADYG.js.map +1 -0
- package/dist/{chunk-X556WVBG.js → chunk-4ZSLX3LY.js} +2 -2
- package/dist/chunk-57XPEL7X.js +26 -0
- package/dist/chunk-57XPEL7X.js.map +1 -0
- package/dist/chunk-6Z7TZVKZ.js +26 -0
- package/dist/chunk-6Z7TZVKZ.js.map +1 -0
- package/dist/{chunk-7KKOFMLD.js → chunk-AWIQQEFP.js} +1 -1
- package/dist/chunk-AWIQQEFP.js.map +1 -0
- package/dist/{chunk-VBKP2NLI.js → chunk-BTKI4XMM.js} +2 -2
- package/dist/{chunk-63QAQP7I.js → chunk-CNBVWPQC.js} +7 -7
- package/dist/{chunk-FENBDSIW.js → chunk-CQGEGPY7.js} +75 -3
- package/dist/chunk-CQGEGPY7.js.map +1 -0
- package/dist/chunk-CTREXL3O.js +335 -0
- package/dist/chunk-CTREXL3O.js.map +1 -0
- package/dist/chunk-DLWO3J7D.js +238 -0
- package/dist/chunk-DLWO3J7D.js.map +1 -0
- package/dist/{chunk-LWSJK546.js → chunk-DSMGS4IV.js} +5 -5
- package/dist/{chunk-LWSJK546.js.map → chunk-DSMGS4IV.js.map} +1 -1
- package/dist/{chunk-BDCC6UVW.js → chunk-EFPIHR6F.js} +161 -40
- package/dist/chunk-EFPIHR6F.js.map +1 -0
- package/dist/chunk-FRAICFTZ.js +191 -0
- package/dist/chunk-FRAICFTZ.js.map +1 -0
- package/dist/chunk-GS7VWV26.js +61 -0
- package/dist/chunk-GS7VWV26.js.map +1 -0
- package/dist/{chunk-NMSAZFRL.js → chunk-H5GQMLHA.js} +2 -2
- package/dist/{chunk-OQE6WMDP.js → chunk-HN6MZ2XL.js} +5 -5
- package/dist/chunk-HY57QRRW.js +11 -0
- package/dist/chunk-HY57QRRW.js.map +1 -0
- package/dist/{chunk-TCGZFSN5.js → chunk-KH4QSBNI.js} +2 -2
- package/dist/{chunk-JH3CKHF4.js → chunk-KJODHPWM.js} +8 -8
- package/dist/chunk-LSBI5MWS.js +66 -0
- package/dist/chunk-LSBI5MWS.js.map +1 -0
- package/dist/chunk-MDRH3SDA.js +106 -0
- package/dist/chunk-MDRH3SDA.js.map +1 -0
- package/dist/{chunk-VBWYH7UZ.js → chunk-NHYRIM4I.js} +3 -3
- package/dist/{chunk-BYP54FMI.js → chunk-O2RCDK5D.js} +30 -15
- package/dist/{chunk-BYP54FMI.js.map → chunk-O2RCDK5D.js.map} +1 -1
- package/dist/{chunk-EWOJATDS.js → chunk-PDD5A43Y.js} +3 -3
- package/dist/{chunk-23JUSUUB.js → chunk-RZLCBWGG.js} +2 -2
- package/dist/chunk-SFZELD6V.js +52 -0
- package/dist/chunk-SFZELD6V.js.map +1 -0
- package/dist/{chunk-Y4W6GK5X.js → chunk-UGFCLD32.js} +2 -2
- package/dist/{chunk-ZGUXI5SI.js → chunk-VUBJZEZB.js} +2 -2
- package/dist/{chunk-LQYIBL3G.js → chunk-WL7PZK7Q.js} +71 -1
- package/dist/chunk-WL7PZK7Q.js.map +1 -0
- package/dist/{chunk-7HZCFG2A.js → chunk-WP2GYFZ4.js} +38 -1
- package/dist/chunk-WP2GYFZ4.js.map +1 -0
- package/dist/{chunk-JK7R7BZQ.js → chunk-ZWJ3SZ2G.js} +2 -2
- package/dist/crypto/digest.d.ts +2 -0
- package/dist/crypto/index.d.ts +1 -0
- package/dist/crypto/index.js +6 -2
- package/dist/design-canvas/index.js +5 -3
- package/dist/design-canvas/index.js.map +1 -1
- package/dist/design-canvas-react/engine.js +7 -5
- package/dist/design-canvas-react/index.js +14 -12
- package/dist/design-canvas-react/index.js.map +1 -1
- package/dist/design-canvas-react/lazy.js +1 -1
- package/dist/eval/index.d.ts +4 -0
- package/dist/eval/index.js +125 -0
- package/dist/eval/index.js.map +1 -1
- package/dist/eval/persona-driver.d.ts +37 -0
- package/dist/eval/research-plan.d.ts +25 -0
- package/dist/eval/research-plan.js +55 -0
- package/dist/eval/research-plan.js.map +1 -0
- package/dist/eval/scorecard.d.ts +38 -0
- package/dist/forms/blank.d.ts +2 -2
- package/dist/forms/index.js +4 -5
- package/dist/forms/index.js.map +1 -1
- package/dist/hosted-agent/application.js +2 -2
- package/dist/interactions/index.js +3 -3
- package/dist/knowledge/prelaunch-audit.d.ts +17 -0
- package/dist/knowledge/prelaunch-audit.js +67 -0
- package/dist/knowledge/prelaunch-audit.js.map +1 -0
- package/dist/media/drizzle.d.ts +207 -0
- package/dist/media/drizzle.js +26 -0
- package/dist/media/drizzle.js.map +1 -0
- package/dist/media/generate-request.d.ts +53 -0
- package/dist/media/generation-record.d.ts +68 -0
- package/dist/media/index.d.ts +13 -0
- package/dist/media/index.js +653 -0
- package/dist/media/index.js.map +1 -0
- package/dist/media/model-catalog.d.ts +109 -0
- package/dist/media/router-client.d.ts +40 -0
- package/dist/media/router-generation.d.ts +44 -0
- package/dist/media/speech-script.d.ts +20 -0
- package/dist/openui/index.js +1 -1
- package/dist/operator/index.js +4 -5
- package/dist/operator/index.js.map +1 -1
- package/dist/plans/decision.d.ts +48 -0
- package/dist/plans/drizzle.d.ts +25 -0
- package/dist/plans/drizzle.js +97 -0
- package/dist/plans/drizzle.js.map +1 -0
- package/dist/plans/index.d.ts +1 -1
- package/dist/plans/index.js +11 -3
- package/dist/platform/billing-config.d.ts +22 -0
- package/dist/platform/billing-config.js +36 -0
- package/dist/platform/billing-config.js.map +1 -0
- package/dist/platform/index.js +13 -11
- package/dist/platform/index.js.map +1 -1
- package/dist/preset-cloudflare/index.js +2 -1
- package/dist/preset-cloudflare/index.js.map +1 -1
- package/dist/profile/index.js +4 -5
- package/dist/profile/index.js.map +1 -1
- package/dist/public-consultation/index.js +13 -11
- package/dist/public-consultation/index.js.map +1 -1
- package/dist/runtime/telemetry-cap.d.ts +24 -0
- package/dist/runtime/telemetry-cap.js +36 -0
- package/dist/runtime/telemetry-cap.js.map +1 -0
- package/dist/sandbox/index.js +12 -9
- package/dist/sequences/index.js +4 -2
- package/dist/sequences/index.js.map +1 -1
- package/dist/skills-placement/box.d.ts +50 -0
- package/dist/skills-placement/box.js +204 -0
- package/dist/skills-placement/box.js.map +1 -0
- package/dist/skills-placement/index.js +8 -96
- package/dist/skills-placement/index.js.map +1 -1
- package/dist/spend/budget.d.ts +13 -0
- package/dist/spend/drizzle.d.ts +55 -0
- package/dist/spend/drizzle.js +131 -0
- package/dist/spend/drizzle.js.map +1 -0
- package/dist/spend/index.d.ts +2 -1
- package/dist/spend/index.js +77 -58
- package/dist/spend/index.js.map +1 -1
- package/dist/spend/platform-settlements.d.ts +46 -0
- package/dist/stream/index.js +19 -19
- package/dist/studio/generated-media/index.d.ts +6 -0
- package/dist/studio/generated-media/index.js +590 -0
- package/dist/studio/generated-media/index.js.map +1 -0
- package/dist/studio/generated-media/output.d.ts +27 -0
- package/dist/studio/generated-media/store.d.ts +175 -0
- package/dist/studio-react/download-generations.d.ts +7 -0
- package/dist/studio-react/index.d.ts +1 -0
- package/dist/studio-react/index.js +85 -0
- package/dist/studio-react/index.js.map +1 -1
- package/dist/studio-react/use-studio-route.d.ts +44 -0
- package/dist/teams/invitations-api.d.ts +4 -0
- package/dist/teams/invitations-api.js +44 -32
- package/dist/teams/invitations-api.js.map +1 -1
- package/dist/theme/dom.d.ts +22 -0
- package/dist/theme/dom.js +18 -0
- package/dist/theme/dom.js.map +1 -0
- package/dist/vault/collaboration.d.ts +83 -0
- package/dist/vault/collaboration.js +215 -0
- package/dist/vault/collaboration.js.map +1 -0
- package/dist/vault/server.js +6 -53
- package/dist/vault/server.js.map +1 -1
- package/dist/vault/store/coordinator.d.ts +64 -0
- package/dist/vault/store/index.d.ts +12 -0
- package/dist/vault/store/index.js +1202 -0
- package/dist/vault/store/index.js.map +1 -0
- package/dist/vault/store/paths.d.ts +65 -0
- package/dist/vault/store/revisions.d.ts +211 -0
- package/dist/vault/store/sandbox-sync.d.ts +74 -0
- package/dist/vault/store/store.d.ts +161 -0
- package/dist/vault/store/tree.d.ts +11 -0
- package/dist/web/entry-server.d.ts +7 -0
- package/dist/web/entry-server.js +29 -0
- package/dist/web/entry-server.js.map +1 -0
- package/dist/web/fetch-guard.d.ts +6 -0
- package/dist/web/index.d.ts +3 -0
- package/dist/web/index.js +20 -4
- package/dist/web/mime.d.ts +16 -0
- package/dist/web/rate-limit.d.ts +25 -0
- package/dist/web/timeout.d.ts +9 -0
- package/dist/web-react/agent-profile-editor.js +3 -3
- package/dist/web-react/api-access-panel.d.ts +4 -2
- package/dist/web-react/document.d.ts +41 -0
- package/dist/web-react/document.js +103 -0
- package/dist/web-react/document.js.map +1 -0
- package/dist/web-react/index.js +31 -31
- package/dist/workspace-react/index.js +5 -5
- package/package.json +95 -4
- package/dist/DesignCanvas-OW3W2QXW.js +0 -13
- package/dist/DesignCanvasEditor-TCHZF25W.js +0 -16
- package/dist/chunk-5Y7Z5G3Y.js.map +0 -1
- package/dist/chunk-7HZCFG2A.js.map +0 -1
- package/dist/chunk-7KKOFMLD.js.map +0 -1
- package/dist/chunk-BDCC6UVW.js.map +0 -1
- package/dist/chunk-FENBDSIW.js.map +0 -1
- package/dist/chunk-LQYIBL3G.js.map +0 -1
- /package/dist/{DesignCanvas-OW3W2QXW.js.map → DesignCanvas-L6J72JQ2.js.map} +0 -0
- /package/dist/{DesignCanvasEditor-TCHZF25W.js.map → DesignCanvasEditor-QFQD63MR.js.map} +0 -0
- /package/dist/{chunk-MY3EJJ6Y.js.map → chunk-4FEH6266.js.map} +0 -0
- /package/dist/{chunk-X556WVBG.js.map → chunk-4ZSLX3LY.js.map} +0 -0
- /package/dist/{chunk-VBKP2NLI.js.map → chunk-BTKI4XMM.js.map} +0 -0
- /package/dist/{chunk-63QAQP7I.js.map → chunk-CNBVWPQC.js.map} +0 -0
- /package/dist/{chunk-NMSAZFRL.js.map → chunk-H5GQMLHA.js.map} +0 -0
- /package/dist/{chunk-OQE6WMDP.js.map → chunk-HN6MZ2XL.js.map} +0 -0
- /package/dist/{chunk-TCGZFSN5.js.map → chunk-KH4QSBNI.js.map} +0 -0
- /package/dist/{chunk-JH3CKHF4.js.map → chunk-KJODHPWM.js.map} +0 -0
- /package/dist/{chunk-VBWYH7UZ.js.map → chunk-NHYRIM4I.js.map} +0 -0
- /package/dist/{chunk-EWOJATDS.js.map → chunk-PDD5A43Y.js.map} +0 -0
- /package/dist/{chunk-23JUSUUB.js.map → chunk-RZLCBWGG.js.map} +0 -0
- /package/dist/{chunk-Y4W6GK5X.js.map → chunk-UGFCLD32.js.map} +0 -0
- /package/dist/{chunk-ZGUXI5SI.js.map → chunk-VUBJZEZB.js.map} +0 -0
- /package/dist/{chunk-JK7R7BZQ.js.map → chunk-ZWJ3SZ2G.js.map} +0 -0
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Delivery of a profile's declared skill corpus onto a running box.
|
|
3
|
+
*
|
|
4
|
+
* The platform materializer is add-or-skip-identical only: it refuses to
|
|
5
|
+
* replace a `SKILL.md` whose content changed and never removes a skill dropped
|
|
6
|
+
* from a later selection. Products edit skill bodies on deploy while boxes live
|
|
7
|
+
* for hours, so this reconcile supplies replace-on-change and prune-on-removal,
|
|
8
|
+
* keyed on a content manifest on the box so an unchanged corpus transfers no
|
|
9
|
+
* bodies. `resolveSkillDir` decides the directory; no path literal lives here.
|
|
10
|
+
*
|
|
11
|
+
* The SDK file API replaces complete files, so identical concurrent reconciles
|
|
12
|
+
* converge without a lock; a concurrent stale delete may return not found.
|
|
13
|
+
*/
|
|
14
|
+
import type { AgentProfileResourceRef } from '@tangle-network/agent-interface';
|
|
15
|
+
import { type SandboxInstance } from '@tangle-network/sandbox';
|
|
16
|
+
import type { Harness } from '../harness/index';
|
|
17
|
+
import type { Outcome } from '../sandbox/outcome';
|
|
18
|
+
export interface ProfileSkillPlacerConfig {
|
|
19
|
+
/** Manifest schema id written on the box, e.g. `acme-skill-corpus-v1`.
|
|
20
|
+
* Changing it makes every box re-place its corpus once. */
|
|
21
|
+
manifestSchema: string;
|
|
22
|
+
/** Home-relative directory holding one manifest per harness, e.g. `~/.tangle/acme-skill-corpora`. */
|
|
23
|
+
manifestDir: string;
|
|
24
|
+
/** Resource name prefix for the manifest file mount, e.g. `acme` gives `<harness>-acme-skill-manifest`. */
|
|
25
|
+
manifestName: string;
|
|
26
|
+
/**
|
|
27
|
+
* The box filesystem's identity, when the product can read it. With it, a
|
|
28
|
+
* corpus this isolate already placed on the same filesystem skips the
|
|
29
|
+
* on-box manifest read entirely; a replaced filesystem has a new id, so its
|
|
30
|
+
* receipt never matches. Return null when the filesystem is not identified.
|
|
31
|
+
*/
|
|
32
|
+
filesystemIncarnation?: (box: SandboxInstance) => string | null;
|
|
33
|
+
/**
|
|
34
|
+
* Serialize placement on the box with a `mkdir` lock beside the manifest
|
|
35
|
+
* (30 s wait, a lock older than 2 minutes is reclaimed). Without it, two
|
|
36
|
+
* isolates placing different corpora at once (a rolling deploy) can leave a
|
|
37
|
+
* manifest that names a skill the other one pruned.
|
|
38
|
+
*/
|
|
39
|
+
boxLock?: boolean;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Build the product's skill placer. `placeProfileSkillsOnBox` makes the box's
|
|
43
|
+
* skill directory for a harness match the declared corpus exactly: every
|
|
44
|
+
* declared body present, every previously placed body no longer declared
|
|
45
|
+
* removed. Empty `refs`, or a harness with no skill directory, is a no-op.
|
|
46
|
+
*/
|
|
47
|
+
export declare function createProfileSkillPlacer(config: ProfileSkillPlacerConfig): {
|
|
48
|
+
placeProfileSkillsOnBox: (box: SandboxInstance, harness: Harness, refs: readonly AgentProfileResourceRef[]) => Promise<Outcome<void>>;
|
|
49
|
+
sameSkillCorpus: (left: readonly AgentProfileResourceRef[] | undefined, right: readonly AgentProfileResourceRef[]) => Promise<boolean>;
|
|
50
|
+
};
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import {
|
|
2
|
+
shellQuote,
|
|
3
|
+
writeProfileFilesToBox
|
|
4
|
+
} from "../chunk-CTREXL3O.js";
|
|
5
|
+
import {
|
|
6
|
+
resolveSkillDir
|
|
7
|
+
} from "../chunk-MDRH3SDA.js";
|
|
8
|
+
import "../chunk-FPNZMIAW.js";
|
|
9
|
+
import "../chunk-TXUAGSFR.js";
|
|
10
|
+
import "../chunk-LTWJYNEC.js";
|
|
11
|
+
import "../chunk-PV33JZKV.js";
|
|
12
|
+
import {
|
|
13
|
+
sha256Hex
|
|
14
|
+
} from "../chunk-HY57QRRW.js";
|
|
15
|
+
|
|
16
|
+
// src/skills-placement/box.ts
|
|
17
|
+
import { NotFoundError } from "@tangle-network/sandbox";
|
|
18
|
+
var SKILL_ID_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
19
|
+
var PLACED_CORPORA_LIMIT = 512;
|
|
20
|
+
function homeRelative(path) {
|
|
21
|
+
if (!path.startsWith("~/")) throw new Error(`Expected a home-relative path, got ${path}`);
|
|
22
|
+
return path.slice(2);
|
|
23
|
+
}
|
|
24
|
+
function shellHomePath(path) {
|
|
25
|
+
return `~/${shellQuote(homeRelative(path))}`;
|
|
26
|
+
}
|
|
27
|
+
async function acquireBoxLock(box, manifestDir, lockPath) {
|
|
28
|
+
const command = [
|
|
29
|
+
`mkdir -p ${shellHomePath(manifestDir)}`,
|
|
30
|
+
`lock=${shellHomePath(lockPath)}`,
|
|
31
|
+
"deadline=$(( $(date +%s) + 30 ))",
|
|
32
|
+
'while ! mkdir "$lock" 2>/dev/null; do',
|
|
33
|
+
" now=$(date +%s)",
|
|
34
|
+
' if [ -n "$(find "$lock" -maxdepth 0 -mmin +2 -print 2>/dev/null)" ]; then rm -rf "$lock"; continue; fi',
|
|
35
|
+
' if [ "$now" -ge "$deadline" ]; then echo "timed out waiting for skill placement lock" >&2; exit 42; fi',
|
|
36
|
+
" sleep 0.1",
|
|
37
|
+
"done"
|
|
38
|
+
].join("\n");
|
|
39
|
+
try {
|
|
40
|
+
const acquired = await box.exec(command);
|
|
41
|
+
if (acquired.exitCode === 0) return { succeeded: true, value: void 0 };
|
|
42
|
+
return { succeeded: false, error: new Error(`placeProfileSkillsOnBox: ${acquired.stderr || "failed to acquire skill placement lock"}`) };
|
|
43
|
+
} catch (error) {
|
|
44
|
+
return { succeeded: false, error: new Error("placeProfileSkillsOnBox: failed to acquire the skill placement lock", { cause: error }) };
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
async function releaseBoxLock(box, lockPath) {
|
|
48
|
+
try {
|
|
49
|
+
const released = await box.exec(`rm -rf ${shellHomePath(lockPath)}`);
|
|
50
|
+
if (released.exitCode === 0) return { succeeded: true, value: void 0 };
|
|
51
|
+
return { succeeded: false, error: new Error(`placeProfileSkillsOnBox: failed to release skill placement lock: ${released.stderr}`) };
|
|
52
|
+
} catch (error) {
|
|
53
|
+
return { succeeded: false, error: new Error("placeProfileSkillsOnBox: failed to release the skill placement lock", { cause: error }) };
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function declaredSkills(refs) {
|
|
57
|
+
const skills = [];
|
|
58
|
+
for (const ref of refs) {
|
|
59
|
+
if (ref.kind !== "inline") return null;
|
|
60
|
+
skills.push({ id: ref.name, content: ref.content });
|
|
61
|
+
}
|
|
62
|
+
return skills;
|
|
63
|
+
}
|
|
64
|
+
function skillFileMounts(root, skills) {
|
|
65
|
+
return skills.map((skill) => ({
|
|
66
|
+
path: `~/${root}/${skill.id}/SKILL.md`,
|
|
67
|
+
resource: { kind: "inline", name: skill.id, content: skill.content }
|
|
68
|
+
}));
|
|
69
|
+
}
|
|
70
|
+
function createProfileSkillPlacer(config) {
|
|
71
|
+
const { manifestSchema, manifestDir, manifestName, filesystemIncarnation, boxLock = false } = config;
|
|
72
|
+
const placedCorpora = /* @__PURE__ */ new Map();
|
|
73
|
+
const corpusManifests = /* @__PURE__ */ new WeakMap();
|
|
74
|
+
async function skillManifest(skills) {
|
|
75
|
+
const normalized = [...skills].sort((a, b) => a.id.localeCompare(b.id));
|
|
76
|
+
return {
|
|
77
|
+
schema: manifestSchema,
|
|
78
|
+
hash: await sha256Hex(JSON.stringify(normalized)),
|
|
79
|
+
ids: normalized.map((skill) => skill.id)
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
function corpusManifest(refs, skills) {
|
|
83
|
+
let manifest = corpusManifests.get(refs);
|
|
84
|
+
if (!manifest) {
|
|
85
|
+
manifest = skillManifest(skills);
|
|
86
|
+
manifest.catch(() => corpusManifests.delete(refs));
|
|
87
|
+
corpusManifests.set(refs, manifest);
|
|
88
|
+
}
|
|
89
|
+
return manifest;
|
|
90
|
+
}
|
|
91
|
+
function parseSkillManifest(raw) {
|
|
92
|
+
try {
|
|
93
|
+
const value = JSON.parse(raw);
|
|
94
|
+
if (value.schema !== manifestSchema || typeof value.hash !== "string") return null;
|
|
95
|
+
if (!Array.isArray(value.ids) || value.ids.some((id) => typeof id !== "string" || !SKILL_ID_RE.test(id))) return null;
|
|
96
|
+
return { schema: manifestSchema, hash: value.hash, ids: value.ids };
|
|
97
|
+
} catch {
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
function receiptKey(box, harness) {
|
|
102
|
+
const incarnation = filesystemIncarnation?.(box);
|
|
103
|
+
return box.id && incarnation ? `${box.id}\0${incarnation}\0${harness}` : null;
|
|
104
|
+
}
|
|
105
|
+
function recordPlacement(key, hash) {
|
|
106
|
+
if (!key) return;
|
|
107
|
+
if (placedCorpora.size >= PLACED_CORPORA_LIMIT) placedCorpora.clear();
|
|
108
|
+
placedCorpora.set(key, hash);
|
|
109
|
+
}
|
|
110
|
+
async function placeSkills(box, harness, root, skills, expected) {
|
|
111
|
+
const markerPath = `${manifestDir}/${harness}.json`;
|
|
112
|
+
let current = null;
|
|
113
|
+
try {
|
|
114
|
+
current = parseSkillManifest(await box.fs.read(homeRelative(markerPath)));
|
|
115
|
+
} catch (err) {
|
|
116
|
+
if (!(err instanceof NotFoundError)) {
|
|
117
|
+
return {
|
|
118
|
+
succeeded: false,
|
|
119
|
+
error: new Error("placeProfileSkillsOnBox: failed to read the sandbox skill manifest", { cause: err })
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
if (current?.hash === expected.hash) return { succeeded: true, value: void 0 };
|
|
124
|
+
const written = await writeProfileFilesToBox(box, skillFileMounts(root, skills));
|
|
125
|
+
if (!written.succeeded) {
|
|
126
|
+
return {
|
|
127
|
+
succeeded: false,
|
|
128
|
+
error: new Error("placeProfileSkillsOnBox: failed to write the sandbox skill corpus", { cause: written.error })
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
const expectedIds = new Set(expected.ids);
|
|
132
|
+
for (const id of (current?.ids ?? []).filter((id2) => !expectedIds.has(id2))) {
|
|
133
|
+
try {
|
|
134
|
+
await box.fs.delete(homeRelative(`~/${root}/${id}`), { recursive: true });
|
|
135
|
+
} catch (err) {
|
|
136
|
+
if (err instanceof NotFoundError) continue;
|
|
137
|
+
return {
|
|
138
|
+
succeeded: false,
|
|
139
|
+
error: new Error("placeProfileSkillsOnBox: stale skill cleanup failed", { cause: err })
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
const manifestWritten = await writeProfileFilesToBox(box, [{
|
|
144
|
+
path: markerPath,
|
|
145
|
+
resource: { kind: "inline", name: `${harness}-${manifestName}-skill-manifest`, content: JSON.stringify(expected) }
|
|
146
|
+
}]);
|
|
147
|
+
if (!manifestWritten.succeeded) {
|
|
148
|
+
return {
|
|
149
|
+
succeeded: false,
|
|
150
|
+
error: new Error("placeProfileSkillsOnBox: failed to write the sandbox skill manifest", { cause: manifestWritten.error })
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
return { succeeded: true, value: void 0 };
|
|
154
|
+
}
|
|
155
|
+
async function placeProfileSkillsOnBox(box, harness, refs) {
|
|
156
|
+
const root = resolveSkillDir(harness);
|
|
157
|
+
if (!root || refs.length === 0) return { succeeded: true, value: void 0 };
|
|
158
|
+
const skills = declaredSkills(refs);
|
|
159
|
+
if (!skills) {
|
|
160
|
+
return { succeeded: false, error: new Error("placeProfileSkillsOnBox: every declared skill ref must be an inline body") };
|
|
161
|
+
}
|
|
162
|
+
const ids = skills.map((skill) => skill.id);
|
|
163
|
+
if (ids.some((id) => !SKILL_ID_RE.test(id)) || new Set(ids).size !== ids.length) {
|
|
164
|
+
return { succeeded: false, error: new Error("placeProfileSkillsOnBox: skill ids must be unique path-safe slugs") };
|
|
165
|
+
}
|
|
166
|
+
let expected;
|
|
167
|
+
try {
|
|
168
|
+
expected = await corpusManifest(refs, skills);
|
|
169
|
+
} catch (err) {
|
|
170
|
+
return {
|
|
171
|
+
succeeded: false,
|
|
172
|
+
error: new Error("placeProfileSkillsOnBox: failed to hash the declared skill corpus", { cause: err })
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
const key = receiptKey(box, harness);
|
|
176
|
+
if (key && placedCorpora.get(key) === expected.hash) return { succeeded: true, value: void 0 };
|
|
177
|
+
if (!boxLock) {
|
|
178
|
+
const placed2 = await placeSkills(box, harness, root, skills, expected);
|
|
179
|
+
if (placed2.succeeded) recordPlacement(key, expected.hash);
|
|
180
|
+
return placed2;
|
|
181
|
+
}
|
|
182
|
+
const lockPath = `${manifestDir}/${harness}.json.lock`;
|
|
183
|
+
const acquired = await acquireBoxLock(box, manifestDir, lockPath);
|
|
184
|
+
if (!acquired.succeeded) return acquired;
|
|
185
|
+
const placed = await placeSkills(box, harness, root, skills, expected);
|
|
186
|
+
const released = await releaseBoxLock(box, lockPath);
|
|
187
|
+
if (placed.succeeded && released.succeeded) recordPlacement(key, expected.hash);
|
|
188
|
+
return released.succeeded ? placed : released;
|
|
189
|
+
}
|
|
190
|
+
async function sameSkillCorpus(left, right) {
|
|
191
|
+
if (!left) return right.length === 0;
|
|
192
|
+
if (left === right) return true;
|
|
193
|
+
const leftSkills = declaredSkills(left);
|
|
194
|
+
const rightSkills = declaredSkills(right);
|
|
195
|
+
if (!leftSkills || !rightSkills) return false;
|
|
196
|
+
const [a, b] = await Promise.all([corpusManifest(left, leftSkills), corpusManifest(right, rightSkills)]);
|
|
197
|
+
return a.hash === b.hash;
|
|
198
|
+
}
|
|
199
|
+
return { placeProfileSkillsOnBox, sameSkillCorpus };
|
|
200
|
+
}
|
|
201
|
+
export {
|
|
202
|
+
createProfileSkillPlacer
|
|
203
|
+
};
|
|
204
|
+
//# sourceMappingURL=box.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/skills-placement/box.ts"],"sourcesContent":["/**\n * Delivery of a profile's declared skill corpus onto a running box.\n *\n * The platform materializer is add-or-skip-identical only: it refuses to\n * replace a `SKILL.md` whose content changed and never removes a skill dropped\n * from a later selection. Products edit skill bodies on deploy while boxes live\n * for hours, so this reconcile supplies replace-on-change and prune-on-removal,\n * keyed on a content manifest on the box so an unchanged corpus transfers no\n * bodies. `resolveSkillDir` decides the directory; no path literal lives here.\n *\n * The SDK file API replaces complete files, so identical concurrent reconciles\n * converge without a lock; a concurrent stale delete may return not found.\n */\nimport type { AgentProfileFileMount, AgentProfileResourceRef } from '@tangle-network/agent-interface'\nimport { NotFoundError, type SandboxInstance } from '@tangle-network/sandbox'\nimport type { Harness } from '../harness/index'\nimport type { Outcome } from '../sandbox/outcome'\nimport { writeProfileFilesToBox } from '../sandbox/profile-files'\nimport { shellQuote } from '../sandbox/binary-read'\nimport { resolveSkillDir } from './index'\nimport { sha256Hex } from '../crypto/digest'\n\ninterface DeclaredSkill {\n id: string\n content: string\n}\n\ninterface SkillCorpusManifest {\n schema: string\n hash: string\n ids: string[]\n}\n\nconst SKILL_ID_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/\nconst PLACED_CORPORA_LIMIT = 512\n\nexport interface ProfileSkillPlacerConfig {\n /** Manifest schema id written on the box, e.g. `acme-skill-corpus-v1`.\n * Changing it makes every box re-place its corpus once. */\n manifestSchema: string\n /** Home-relative directory holding one manifest per harness, e.g. `~/.tangle/acme-skill-corpora`. */\n manifestDir: string\n /** Resource name prefix for the manifest file mount, e.g. `acme` gives `<harness>-acme-skill-manifest`. */\n manifestName: string\n /**\n * The box filesystem's identity, when the product can read it. With it, a\n * corpus this isolate already placed on the same filesystem skips the\n * on-box manifest read entirely; a replaced filesystem has a new id, so its\n * receipt never matches. Return null when the filesystem is not identified.\n */\n filesystemIncarnation?: (box: SandboxInstance) => string | null\n /**\n * Serialize placement on the box with a `mkdir` lock beside the manifest\n * (30 s wait, a lock older than 2 minutes is reclaimed). Without it, two\n * isolates placing different corpora at once (a rolling deploy) can leave a\n * manifest that names a skill the other one pruned.\n */\n boxLock?: boolean\n}\n\nfunction homeRelative(path: string): string {\n if (!path.startsWith('~/')) throw new Error(`Expected a home-relative path, got ${path}`)\n return path.slice(2)\n}\n\nfunction shellHomePath(path: string): string {\n return `~/${shellQuote(homeRelative(path))}`\n}\n\nasync function acquireBoxLock(box: SandboxInstance, manifestDir: string, lockPath: string): Promise<Outcome<void>> {\n const command = [\n `mkdir -p ${shellHomePath(manifestDir)}`,\n `lock=${shellHomePath(lockPath)}`,\n 'deadline=$(( $(date +%s) + 30 ))',\n 'while ! mkdir \"$lock\" 2>/dev/null; do',\n ' now=$(date +%s)',\n ' if [ -n \"$(find \"$lock\" -maxdepth 0 -mmin +2 -print 2>/dev/null)\" ]; then rm -rf \"$lock\"; continue; fi',\n ' if [ \"$now\" -ge \"$deadline\" ]; then echo \"timed out waiting for skill placement lock\" >&2; exit 42; fi',\n ' sleep 0.1',\n 'done',\n ].join('\\n')\n try {\n const acquired = await box.exec(command)\n if (acquired.exitCode === 0) return { succeeded: true, value: undefined }\n return { succeeded: false, error: new Error(`placeProfileSkillsOnBox: ${acquired.stderr || 'failed to acquire skill placement lock'}`) }\n } catch (error) {\n return { succeeded: false, error: new Error('placeProfileSkillsOnBox: failed to acquire the skill placement lock', { cause: error }) }\n }\n}\n\nasync function releaseBoxLock(box: SandboxInstance, lockPath: string): Promise<Outcome<void>> {\n try {\n const released = await box.exec(`rm -rf ${shellHomePath(lockPath)}`)\n if (released.exitCode === 0) return { succeeded: true, value: undefined }\n return { succeeded: false, error: new Error(`placeProfileSkillsOnBox: failed to release skill placement lock: ${released.stderr}`) }\n } catch (error) {\n return { succeeded: false, error: new Error('placeProfileSkillsOnBox: failed to release the skill placement lock', { cause: error }) }\n }\n}\n\n/** `null` when any ref is not an inline body: a github ref needs async\n * pre-resolution, which the platform materializer also refuses. */\nfunction declaredSkills(refs: readonly AgentProfileResourceRef[]): DeclaredSkill[] | null {\n const skills: DeclaredSkill[] = []\n for (const ref of refs) {\n if (ref.kind !== 'inline') return null\n skills.push({ id: ref.name, content: ref.content })\n }\n return skills\n}\n\nfunction skillFileMounts(root: string, skills: readonly DeclaredSkill[]): AgentProfileFileMount[] {\n return skills.map((skill) => ({\n path: `~/${root}/${skill.id}/SKILL.md`,\n resource: { kind: 'inline' as const, name: skill.id, content: skill.content },\n }))\n}\n\n/**\n * Build the product's skill placer. `placeProfileSkillsOnBox` makes the box's\n * skill directory for a harness match the declared corpus exactly: every\n * declared body present, every previously placed body no longer declared\n * removed. Empty `refs`, or a harness with no skill directory, is a no-op.\n */\nexport function createProfileSkillPlacer(config: ProfileSkillPlacerConfig) {\n const { manifestSchema, manifestDir, manifestName, filesystemIncarnation, boxLock = false } = config\n\n // Corpora this isolate placed or verified, by box, filesystem and harness. Digests only.\n const placedCorpora = new Map<string, string>()\n // A composed corpus is one cached array per harness, so its digest is too.\n const corpusManifests = new WeakMap<readonly AgentProfileResourceRef[], Promise<SkillCorpusManifest>>()\n\n async function skillManifest(skills: readonly DeclaredSkill[]): Promise<SkillCorpusManifest> {\n const normalized = [...skills].sort((a, b) => a.id.localeCompare(b.id))\n return {\n schema: manifestSchema,\n hash: await sha256Hex(JSON.stringify(normalized)),\n ids: normalized.map((skill) => skill.id),\n }\n }\n\n function corpusManifest(refs: readonly AgentProfileResourceRef[], skills: readonly DeclaredSkill[]) {\n let manifest = corpusManifests.get(refs)\n if (!manifest) {\n manifest = skillManifest(skills)\n manifest.catch(() => corpusManifests.delete(refs))\n corpusManifests.set(refs, manifest)\n }\n return manifest\n }\n\n function parseSkillManifest(raw: string): SkillCorpusManifest | null {\n try {\n const value = JSON.parse(raw) as Partial<SkillCorpusManifest>\n if (value.schema !== manifestSchema || typeof value.hash !== 'string') return null\n if (!Array.isArray(value.ids) || value.ids.some((id) => typeof id !== 'string' || !SKILL_ID_RE.test(id))) return null\n return { schema: manifestSchema, hash: value.hash, ids: value.ids }\n } catch {\n return null\n }\n }\n\n function receiptKey(box: SandboxInstance, harness: Harness): string | null {\n const incarnation = filesystemIncarnation?.(box)\n return box.id && incarnation ? `${box.id}\\0${incarnation}\\0${harness}` : null\n }\n\n function recordPlacement(key: string | null, hash: string): void {\n if (!key) return\n if (placedCorpora.size >= PLACED_CORPORA_LIMIT) placedCorpora.clear()\n placedCorpora.set(key, hash)\n }\n\n async function placeSkills(\n box: SandboxInstance,\n harness: Harness,\n root: string,\n skills: readonly DeclaredSkill[],\n expected: SkillCorpusManifest,\n ): Promise<Outcome<void>> {\n const markerPath = `${manifestDir}/${harness}.json`\n let current: SkillCorpusManifest | null = null\n try {\n current = parseSkillManifest(await box.fs.read(homeRelative(markerPath)))\n } catch (err) {\n if (!(err instanceof NotFoundError)) {\n return {\n succeeded: false,\n error: new Error('placeProfileSkillsOnBox: failed to read the sandbox skill manifest', { cause: err }),\n }\n }\n }\n if (current?.hash === expected.hash) return { succeeded: true, value: undefined }\n\n const written = await writeProfileFilesToBox(box, skillFileMounts(root, skills))\n if (!written.succeeded) {\n return {\n succeeded: false,\n error: new Error('placeProfileSkillsOnBox: failed to write the sandbox skill corpus', { cause: written.error }),\n }\n }\n\n const expectedIds = new Set(expected.ids)\n for (const id of (current?.ids ?? []).filter((id) => !expectedIds.has(id))) {\n try {\n await box.fs.delete(homeRelative(`~/${root}/${id}`), { recursive: true })\n } catch (err) {\n // Another identical reconcile may have removed it first; any other failure stays visible.\n if (err instanceof NotFoundError) continue\n return {\n succeeded: false,\n error: new Error('placeProfileSkillsOnBox: stale skill cleanup failed', { cause: err }),\n }\n }\n }\n\n const manifestWritten = await writeProfileFilesToBox(box, [{\n path: markerPath,\n resource: { kind: 'inline', name: `${harness}-${manifestName}-skill-manifest`, content: JSON.stringify(expected) },\n }])\n if (!manifestWritten.succeeded) {\n return {\n succeeded: false,\n error: new Error('placeProfileSkillsOnBox: failed to write the sandbox skill manifest', { cause: manifestWritten.error }),\n }\n }\n return { succeeded: true, value: undefined }\n }\n\n async function placeProfileSkillsOnBox(\n box: SandboxInstance,\n harness: Harness,\n refs: readonly AgentProfileResourceRef[],\n ): Promise<Outcome<void>> {\n const root = resolveSkillDir(harness)\n if (!root || refs.length === 0) return { succeeded: true, value: undefined }\n\n const skills = declaredSkills(refs)\n if (!skills) {\n return { succeeded: false, error: new Error('placeProfileSkillsOnBox: every declared skill ref must be an inline body') }\n }\n const ids = skills.map((skill) => skill.id)\n if (ids.some((id) => !SKILL_ID_RE.test(id)) || new Set(ids).size !== ids.length) {\n return { succeeded: false, error: new Error('placeProfileSkillsOnBox: skill ids must be unique path-safe slugs') }\n }\n\n let expected: SkillCorpusManifest\n try {\n expected = await corpusManifest(refs, skills)\n } catch (err) {\n return {\n succeeded: false,\n error: new Error('placeProfileSkillsOnBox: failed to hash the declared skill corpus', { cause: err }),\n }\n }\n\n const key = receiptKey(box, harness)\n if (key && placedCorpora.get(key) === expected.hash) return { succeeded: true, value: undefined }\n if (!boxLock) {\n const placed = await placeSkills(box, harness, root, skills, expected)\n if (placed.succeeded) recordPlacement(key, expected.hash)\n return placed\n }\n const lockPath = `${manifestDir}/${harness}.json.lock`\n const acquired = await acquireBoxLock(box, manifestDir, lockPath)\n if (!acquired.succeeded) return acquired\n const placed = await placeSkills(box, harness, root, skills, expected)\n const released = await releaseBoxLock(box, lockPath)\n if (placed.succeeded && released.succeeded) recordPlacement(key, expected.hash)\n return released.succeeded ? placed : released\n }\n\n /** Whether two skill declarations carry the same inline corpus. */\n async function sameSkillCorpus(\n left: readonly AgentProfileResourceRef[] | undefined,\n right: readonly AgentProfileResourceRef[],\n ): Promise<boolean> {\n if (!left) return right.length === 0\n if (left === right) return true\n const leftSkills = declaredSkills(left)\n const rightSkills = declaredSkills(right)\n if (!leftSkills || !rightSkills) return false\n const [a, b] = await Promise.all([corpusManifest(left, leftSkills), corpusManifest(right, rightSkills)])\n return a.hash === b.hash\n }\n\n return { placeProfileSkillsOnBox, sameSkillCorpus }\n}\n"],"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AG,CAAC,IAAI,MAAM,QAAQ,IAAI,CAAC,eAAe,MAAM,UAAU,GAAG,eAAe,OAAO,WAAW,CAAC,CAAC;AACvG,WAAO,EAAE,SAAS,EAAE;AAAA,EACtB;AAEA,SAAO,EAAE,yBAAyB,gBAAgB;AACpD;","names":["id","placed"]}
|
|
@@ -1,102 +1,14 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
} from "../chunk-
|
|
2
|
+
composeSkillsForHarness,
|
|
3
|
+
resolveSkillDir,
|
|
4
|
+
skillSupportFileMounts,
|
|
5
|
+
unsupportedSkillHarnesses,
|
|
6
|
+
withSkillSupportFiles
|
|
7
|
+
} from "../chunk-MDRH3SDA.js";
|
|
8
|
+
import "../chunk-FPNZMIAW.js";
|
|
9
|
+
import "../chunk-TXUAGSFR.js";
|
|
8
10
|
import "../chunk-LTWJYNEC.js";
|
|
9
11
|
import "../chunk-PV33JZKV.js";
|
|
10
|
-
|
|
11
|
-
// src/skills-placement/index.ts
|
|
12
|
-
import {
|
|
13
|
-
defineInlineResource
|
|
14
|
-
} from "@tangle-network/agent-interface";
|
|
15
|
-
import { skillDirForHarness } from "@tangle-network/agent-profile-materialize";
|
|
16
|
-
var HARNESS_BRIDGE = {
|
|
17
|
-
opencode: "opencode",
|
|
18
|
-
"claude-code": "claude-code",
|
|
19
|
-
nanoclaw: "nanoclaw",
|
|
20
|
-
"kimi-code": "kimi-code",
|
|
21
|
-
codex: "codex",
|
|
22
|
-
pi: "pi",
|
|
23
|
-
prime: "prime",
|
|
24
|
-
hermes: "hermes",
|
|
25
|
-
openclaw: "openclaw"
|
|
26
|
-
};
|
|
27
|
-
function resolveSkillDir(harness) {
|
|
28
|
-
const bridged = HARNESS_BRIDGE[harness];
|
|
29
|
-
if (!bridged) return null;
|
|
30
|
-
return skillDirForHarness(bridged);
|
|
31
|
-
}
|
|
32
|
-
function unsupportedSkillHarnesses(harnesses) {
|
|
33
|
-
const seen = /* @__PURE__ */ new Set();
|
|
34
|
-
const out = [];
|
|
35
|
-
for (const harness of harnesses) {
|
|
36
|
-
if (resolveSkillDir(harness) !== null) continue;
|
|
37
|
-
if (seen.has(harness)) continue;
|
|
38
|
-
seen.add(harness);
|
|
39
|
-
out.push(harness);
|
|
40
|
-
}
|
|
41
|
-
return out;
|
|
42
|
-
}
|
|
43
|
-
function nativeSkillMountHarnesses() {
|
|
44
|
-
return KNOWN_HARNESSES.filter((harness) => resolveSkillDir(harness) !== null);
|
|
45
|
-
}
|
|
46
|
-
function composeSkillsForHarness(input) {
|
|
47
|
-
const { skills, harness, tier, heading, onNoSkillDir = "throw" } = input;
|
|
48
|
-
const skillDir = resolveSkillDir(harness);
|
|
49
|
-
if (skillDir) return composeSkills({ skills, mode: "mounted", skillDir, tier, heading });
|
|
50
|
-
if (onNoSkillDir === "inline") return composeSkills({ skills, mode: "inline", tier, heading });
|
|
51
|
-
const relevant = tier ? skills.filter((s) => s.tier === tier) : skills;
|
|
52
|
-
const promptSection = renderInlineSkills({ skills, tier, heading });
|
|
53
|
-
const bytes = new TextEncoder().encode(promptSection).byteLength;
|
|
54
|
-
const mountable = nativeSkillMountHarnesses();
|
|
55
|
-
throw new Error(
|
|
56
|
-
`composeSkillsForHarness: "${harness}" has no native skill-mount directory. Inlining ${relevant.length} skill(s) (${bytes} bytes) into its system prompt would silently convert mounted skills into prompt text \u2014 a 151,882-byte prompt shipped this way once, and oversized prompts degrade toward empty answers. Mount the skills instead: pick a harness with native skill support (${mountable.join(", ")}), or pass onNoSkillDir: 'inline' to opt in explicitly and accept the inlined bytes.`
|
|
57
|
-
);
|
|
58
|
-
}
|
|
59
|
-
function skillSupportFileMounts(harness, skillId, files, options = {}) {
|
|
60
|
-
const skillDir = resolveSkillDir(harness);
|
|
61
|
-
if (!skillDir || files.length === 0) return [];
|
|
62
|
-
return files.map((file) => ({
|
|
63
|
-
path: `${skillDir}/${skillId}/${file.path}`,
|
|
64
|
-
resource: defineInlineResource(
|
|
65
|
-
options.resourceName ? options.resourceName(file) : `${skillId}/${file.path}`,
|
|
66
|
-
file.content
|
|
67
|
-
)
|
|
68
|
-
}));
|
|
69
|
-
}
|
|
70
|
-
function withSkillSupportFiles(profile, harness, skillId, files, options = {}) {
|
|
71
|
-
const hasSkillDir = resolveSkillDir(harness) !== null;
|
|
72
|
-
const desired = skillSupportFileMounts(harness, skillId, files, options);
|
|
73
|
-
const desiredByPath = new Map(
|
|
74
|
-
desired.map((mount) => [mount.path, mount.resource])
|
|
75
|
-
);
|
|
76
|
-
const byRelPath = new Map(files.map((file) => [file.path, file.content]));
|
|
77
|
-
const suffix = `/${skillId}/`;
|
|
78
|
-
const relUnderSkill = (path) => {
|
|
79
|
-
const at = path.lastIndexOf(suffix);
|
|
80
|
-
return at < 0 ? null : path.slice(at + suffix.length);
|
|
81
|
-
};
|
|
82
|
-
const shouldDropMount = (mount) => {
|
|
83
|
-
if (mount.resource.kind !== "inline") return false;
|
|
84
|
-
const rel = relUnderSkill(mount.path);
|
|
85
|
-
if (rel === null || byRelPath.get(rel) !== mount.resource.content) return false;
|
|
86
|
-
if (options.reconcileExisting === "replace") return true;
|
|
87
|
-
const desiredHere = desiredByPath.get(mount.path);
|
|
88
|
-
return !hasSkillDir || desiredHere === void 0 || desiredHere.kind !== "inline" || desiredHere.content !== mount.resource.content;
|
|
89
|
-
};
|
|
90
|
-
const existing = profile.resources?.files ?? [];
|
|
91
|
-
const retained = existing.filter((mount) => !shouldDropMount(mount));
|
|
92
|
-
const taken = new Set(retained.map((mount) => mount.path));
|
|
93
|
-
const additions = desired.filter((mount) => !taken.has(mount.path));
|
|
94
|
-
if (additions.length === 0 && (retained.length === existing.length || hasSkillDir && options.reconcileExisting === "replace")) return profile;
|
|
95
|
-
return {
|
|
96
|
-
...profile,
|
|
97
|
-
resources: { ...profile.resources ?? {}, files: [...retained, ...additions] }
|
|
98
|
-
};
|
|
99
|
-
}
|
|
100
12
|
export {
|
|
101
13
|
composeSkillsForHarness,
|
|
102
14
|
resolveSkillDir,
|
|
@@ -1 +1 @@
|
|
|
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 {\n defineInlineResource,\n type AgentProfile,\n type AgentProfileFileMount,\n} from '@tangle-network/agent-interface'\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`, `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":";;;;;;;;;;;AAoBA;AAAA,EACE;AAAA,OAGK;AAEP,SAAS,0BAA0C;AAYnD,IAAM,iBAAsD;AAAA,EAC1D,UAAU;AAAA,EACV,eAAe;AAAA,EACf,UAAU;AAAA,EACV,aAAa;AAAA,EACb,OAAO;AAAA,EACP,IAAI;AAAA,EACJ,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,UAAU;AACZ;AAMO,SAAS,gBAAgB,SAAiC;AAC/D,QAAM,UAAU,eAAe,OAAO;AACtC,MAAI,CAAC,QAAS,QAAO;AACrB,SAAO,mBAAmB,OAAO;AACnC;AAMO,SAAS,0BAA0B,WAAyC;AACjF,QAAM,OAAO,oBAAI,IAAa;AAC9B,QAAM,MAAiB,CAAC;AACxB,aAAW,WAAW,WAAW;AAC/B,QAAI,gBAAgB,OAAO,MAAM,KAAM;AACvC,QAAI,KAAK,IAAI,OAAO,EAAG;AACvB,SAAK,IAAI,OAAO;AAChB,QAAI,KAAK,OAAO;AAAA,EAClB;AACA,SAAO;AACT;AAyBA,SAAS,4BAAuC;AAC9C,SAAO,gBAAgB,OAAO,CAAC,YAAY,gBAAgB,OAAO,MAAM,IAAI;AAC9E;AA+BO,SAAS,wBAAwB,OAAqD;AAC3F,QAAM,EAAE,QAAQ,SAAS,MAAM,SAAS,eAAe,QAAQ,IAAI;AACnE,QAAM,WAAW,gBAAgB,OAAO;AACxC,MAAI,SAAU,QAAO,cAAc,EAAE,QAAQ,MAAM,WAAW,UAAU,MAAM,QAAQ,CAAC;AACvF,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rD,UAAM,KAAK,KAAK,YAAY,MAAM;AAClC,WAAO,KAAK,IAAI,OAAO,KAAK,MAAM,KAAK,OAAO,MAAM;AAAA,EACtD;AASA,QAAM,kBAAkB,CAAC,UAA0C;AACjE,QAAI,MAAM,SAAS,SAAS,SAAU,QAAO;AAC7C,UAAM,MAAM,cAAc,MAAM,IAAI;AACpC,QAAI,QAAQ,QAAQ,UAAU,IAAI,GAAG,MAAM,MAAM,SAAS,QAAS,QAAO;AAC1E,QAAI,QAAQ,sBAAsB,UAAW,QAAO;AACpD,UAAM,cAAc,cAAc,IAAI,MAAM,IAAI;AAChD,WACE,CAAC,eACD,gBAAgB,UAChB,YAAY,SAAS,YACrB,YAAY,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
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/dist/spend/budget.d.ts
CHANGED
|
@@ -1,4 +1,17 @@
|
|
|
1
1
|
import type { SpendLedger } from './store';
|
|
2
|
+
/**
|
|
3
|
+
* Default compute-spend ceiling for a workspace that enables the guard without
|
|
4
|
+
* naming its own limit: ten times the cost of running one 2 vCPU / 4 GB box for
|
|
5
|
+
* a 24-hour max lifetime, at the incident's calibrated price
|
|
6
|
+
* ($0.114055255/hour — reverse-derived in `fixtures/incident-parked-time.ts`
|
|
7
|
+
* so its 23 incident rows sum to the refunded $514.161090533 exactly).
|
|
8
|
+
*
|
|
9
|
+
* 10 x 24h x $0.114055255/h = $27.3732612 -> 27_373_261_200 nanodollars
|
|
10
|
+
*
|
|
11
|
+
* Deliberately generous: there is no spend history to ground a tighter number,
|
|
12
|
+
* and a guard that refuses ordinary usage is itself an incident.
|
|
13
|
+
*/
|
|
14
|
+
export declare const DEFAULT_WORKSPACE_SPEND_BUDGET_NANO_USD = 27373261200;
|
|
2
15
|
/** Why provisioning was refused, with every number the decision used. */
|
|
3
16
|
export interface ComputeBudgetRefusal {
|
|
4
17
|
readonly workspaceId: string;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { AnySQLiteColumn, AnySQLiteTable, BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core';
|
|
2
|
+
import type { SpendLedgerStorePort } from './store';
|
|
3
|
+
/** Any SQLite drizzle database — `any` erases the driver-specific run-result
|
|
4
|
+
* and schema generics so better-sqlite3, D1, and libsql handles all fit. */
|
|
5
|
+
export type SpendDatabase = BaseSQLiteDatabase<'sync' | 'async', any, any>;
|
|
6
|
+
/** Required Drizzle column properties of the expectation ledger; SQL column
|
|
7
|
+
* names, foreign keys and indexes remain product-owned. */
|
|
8
|
+
export type SpendBoxLedgerTable = AnySQLiteTable & {
|
|
9
|
+
sandboxId: AnySQLiteColumn;
|
|
10
|
+
workspaceId: AnySQLiteColumn;
|
|
11
|
+
createdAt: AnySQLiteColumn;
|
|
12
|
+
idleTimeoutSeconds: AnySQLiteColumn;
|
|
13
|
+
maxLifetimeSeconds: AnySQLiteColumn;
|
|
14
|
+
lastActivityAt: AnySQLiteColumn;
|
|
15
|
+
openDetachedRunIds: AnySQLiteColumn;
|
|
16
|
+
stoppedAt: AnySQLiteColumn;
|
|
17
|
+
deletedAt: AnySQLiteColumn;
|
|
18
|
+
extras: AnySQLiteColumn;
|
|
19
|
+
};
|
|
20
|
+
/** The ledger a store or query reads: a database and the product's table. */
|
|
21
|
+
export interface SpendLedgerTableOptions {
|
|
22
|
+
readonly db: SpendDatabase;
|
|
23
|
+
readonly table: SpendBoxLedgerTable;
|
|
24
|
+
}
|
|
25
|
+
/** Build the expectation-ledger store over the product's drizzle table. */
|
|
26
|
+
export declare function createDrizzleSpendStore(options: SpendLedgerTableOptions): SpendLedgerStorePort;
|
|
27
|
+
/** Every distinct platform-user id the ledger has recorded as a box's
|
|
28
|
+
* `extras.billingOwnerId` — the set of wallets a full pass needs to read. */
|
|
29
|
+
export declare function listLedgerBillingOwnerIds(options: SpendLedgerTableOptions): Promise<string[]>;
|
|
30
|
+
/** Every sandbox id the ledger attributes to this workspace — the only place
|
|
31
|
+
* the workspace-to-sandbox mapping exists; the platform does not model a workspace. */
|
|
32
|
+
export declare function listWorkspaceSandboxIds(options: SpendLedgerTableOptions & {
|
|
33
|
+
readonly workspaceId: string;
|
|
34
|
+
}): Promise<Set<string>>;
|
|
35
|
+
/** The product's workspace table columns holding the compute-budget opt-in. */
|
|
36
|
+
export type SpendBudgetWorkspaceTable = AnySQLiteTable & {
|
|
37
|
+
id: AnySQLiteColumn;
|
|
38
|
+
spendBudgetEnabled: AnySQLiteColumn;
|
|
39
|
+
spendBudgetLimitNanoUsd: AnySQLiteColumn;
|
|
40
|
+
};
|
|
41
|
+
export interface WorkspaceSpendBudgetConfig {
|
|
42
|
+
readonly enabled: boolean;
|
|
43
|
+
readonly limitNanoUsd: number;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Opt-in per-workspace budget read. Absent or disabled — the default for every
|
|
47
|
+
* workspace until it opts in — short-circuits the caller before any settlement
|
|
48
|
+
* read runs, so an unopted workspace's provisioning path makes no extra network
|
|
49
|
+
* call. A null limit falls back to {@link DEFAULT_WORKSPACE_SPEND_BUDGET_NANO_USD}.
|
|
50
|
+
*/
|
|
51
|
+
export declare function loadWorkspaceSpendBudgetConfig(options: {
|
|
52
|
+
readonly db: SpendDatabase;
|
|
53
|
+
readonly workspaces: SpendBudgetWorkspaceTable;
|
|
54
|
+
readonly workspaceId: string;
|
|
55
|
+
}): Promise<WorkspaceSpendBudgetConfig>;
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_WORKSPACE_SPEND_BUDGET_NANO_USD
|
|
3
|
+
} from "../chunk-LSBI5MWS.js";
|
|
4
|
+
|
|
5
|
+
// src/spend/drizzle.ts
|
|
6
|
+
import { and, eq, gte, isNull, lte, or, sql } from "drizzle-orm";
|
|
7
|
+
function rowToRecord(row) {
|
|
8
|
+
return {
|
|
9
|
+
sandboxId: row.sandboxId,
|
|
10
|
+
workspaceId: row.workspaceId,
|
|
11
|
+
createdAt: row.createdAt,
|
|
12
|
+
idleTimeoutSeconds: row.idleTimeoutSeconds,
|
|
13
|
+
maxLifetimeSeconds: row.maxLifetimeSeconds,
|
|
14
|
+
lastActivityAt: row.lastActivityAt,
|
|
15
|
+
openDetachedRunIds: row.openDetachedRunIds ?? [],
|
|
16
|
+
stoppedAt: row.stoppedAt,
|
|
17
|
+
deletedAt: row.deletedAt,
|
|
18
|
+
...row.extras ? { extras: row.extras } : {}
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
function createDrizzleSpendStore(options) {
|
|
22
|
+
const { db, table } = options;
|
|
23
|
+
async function load(sandboxId) {
|
|
24
|
+
const [row] = await db.select().from(table).where(eq(table.sandboxId, sandboxId)).limit(1);
|
|
25
|
+
return row ? rowToRecord(row) : null;
|
|
26
|
+
}
|
|
27
|
+
return {
|
|
28
|
+
load,
|
|
29
|
+
/**
|
|
30
|
+
* Every box that could have been live at some point inside `window`.
|
|
31
|
+
*
|
|
32
|
+
* Deliberately COARSE: the box existed by the window's end and was not
|
|
33
|
+
* recorded deleted before it began. The reconciler re-derives liveness from
|
|
34
|
+
* the same fold `computeExpectedCeiling` uses (delete, stop, open detached
|
|
35
|
+
* run, last activity plus idle timeout, capped by max lifetime), so this
|
|
36
|
+
* only has to be a superset it can filter down. Encoding the real rule here
|
|
37
|
+
* would put a second definition of "live" in SQL, free to drift from the one
|
|
38
|
+
* the ceiling check uses. `stopped_at` is therefore not a filter: later
|
|
39
|
+
* activity can clear a stop, and the fold decides which stop closed the box.
|
|
40
|
+
*
|
|
41
|
+
* Over-returning is correct; under-returning is the only real failure — a
|
|
42
|
+
* box this query omits is a box the pass never notices went unbilled.
|
|
43
|
+
*/
|
|
44
|
+
async listLiveBetween(window) {
|
|
45
|
+
const rows = await db.select().from(table).where(and(lte(table.createdAt, window.endAt), or(isNull(table.deletedAt), gte(table.deletedAt, window.startAt))));
|
|
46
|
+
return rows.map((row) => rowToRecord(row));
|
|
47
|
+
},
|
|
48
|
+
async insert(record, extras) {
|
|
49
|
+
const [row] = await db.insert(table).values({
|
|
50
|
+
sandboxId: record.sandboxId,
|
|
51
|
+
workspaceId: record.workspaceId,
|
|
52
|
+
createdAt: record.createdAt,
|
|
53
|
+
idleTimeoutSeconds: record.idleTimeoutSeconds,
|
|
54
|
+
maxLifetimeSeconds: record.maxLifetimeSeconds,
|
|
55
|
+
lastActivityAt: record.lastActivityAt,
|
|
56
|
+
openDetachedRunIds: [...record.openDetachedRunIds],
|
|
57
|
+
stoppedAt: record.stoppedAt,
|
|
58
|
+
deletedAt: record.deletedAt,
|
|
59
|
+
// Written in the SAME statement — a second UPDATE to attach extras
|
|
60
|
+
// would leave a window where the reconciler cannot tell whose wallet
|
|
61
|
+
// this box bills.
|
|
62
|
+
extras: extras ?? null
|
|
63
|
+
}).returning();
|
|
64
|
+
return rowToRecord(row);
|
|
65
|
+
},
|
|
66
|
+
async update(sandboxId, patch) {
|
|
67
|
+
const hasActivity = patch.observedActivityAt !== void 0;
|
|
68
|
+
const hasStop = patch.stoppedAt !== void 0;
|
|
69
|
+
const activityValue = patch.observedActivityAt;
|
|
70
|
+
const stopValue = patch.stoppedAt;
|
|
71
|
+
const set = {};
|
|
72
|
+
if (hasActivity) {
|
|
73
|
+
set.lastActivityAt = sql`MAX(${table.lastActivityAt}, ${activityValue})`;
|
|
74
|
+
}
|
|
75
|
+
if (hasActivity || hasStop) {
|
|
76
|
+
const newLastActivityAtExpr = hasActivity ? sql`MAX(${table.lastActivityAt}, ${activityValue})` : sql`${table.lastActivityAt}`;
|
|
77
|
+
const afterActivityClearExpr = hasActivity ? sql`(CASE WHEN ${table.stoppedAt} IS NOT NULL AND ${activityValue} > ${table.stoppedAt} THEN NULL ELSE ${table.stoppedAt} END)` : sql`${table.stoppedAt}`;
|
|
78
|
+
set.stoppedAt = hasStop ? sql`(CASE WHEN ${stopValue} >= (${newLastActivityAtExpr}) THEN ${stopValue} ELSE ${afterActivityClearExpr} END)` : afterActivityClearExpr;
|
|
79
|
+
}
|
|
80
|
+
if (patch.deletedAt !== void 0) {
|
|
81
|
+
set.deletedAt = sql`COALESCE(${table.deletedAt}, ${patch.deletedAt})`;
|
|
82
|
+
}
|
|
83
|
+
let runIdsExpr;
|
|
84
|
+
if (patch.openDetachedRunAdd !== void 0) {
|
|
85
|
+
runIdsExpr = sql`(
|
|
86
|
+
CASE
|
|
87
|
+
WHEN EXISTS (SELECT 1 FROM json_each(${table.openDetachedRunIds}) WHERE value = ${patch.openDetachedRunAdd})
|
|
88
|
+
THEN ${table.openDetachedRunIds}
|
|
89
|
+
ELSE json_insert(${table.openDetachedRunIds}, '$[#]', ${patch.openDetachedRunAdd})
|
|
90
|
+
END
|
|
91
|
+
)`;
|
|
92
|
+
}
|
|
93
|
+
if (patch.openDetachedRunRemove !== void 0) {
|
|
94
|
+
const source = runIdsExpr ?? sql`${table.openDetachedRunIds}`;
|
|
95
|
+
runIdsExpr = sql`(
|
|
96
|
+
SELECT COALESCE(json_group_array(value), '[]') FROM json_each(${source}) WHERE value != ${patch.openDetachedRunRemove}
|
|
97
|
+
)`;
|
|
98
|
+
}
|
|
99
|
+
if (runIdsExpr) set.openDetachedRunIds = runIdsExpr;
|
|
100
|
+
if (Object.keys(set).length === 0) return await load(sandboxId);
|
|
101
|
+
const rows = await db.update(table).set(set).where(eq(table.sandboxId, sandboxId)).returning();
|
|
102
|
+
const [row] = rows;
|
|
103
|
+
return row ? rowToRecord(row) : null;
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
async function listLedgerBillingOwnerIds(options) {
|
|
108
|
+
const { db, table } = options;
|
|
109
|
+
const rows = await db.select({ billingOwnerId: sql`json_extract(${table.extras}, '$.billingOwnerId')` }).from(table).where(sql`json_extract(${table.extras}, '$.billingOwnerId') IS NOT NULL`);
|
|
110
|
+
return [...new Set(rows.map((row) => row.billingOwnerId).filter((id) => Boolean(id)))];
|
|
111
|
+
}
|
|
112
|
+
async function listWorkspaceSandboxIds(options) {
|
|
113
|
+
const { db, table, workspaceId } = options;
|
|
114
|
+
const rows = await db.select({ sandboxId: table.sandboxId }).from(table).where(eq(table.workspaceId, workspaceId));
|
|
115
|
+
return new Set(rows.map((row) => row.sandboxId));
|
|
116
|
+
}
|
|
117
|
+
async function loadWorkspaceSpendBudgetConfig(options) {
|
|
118
|
+
const { db, workspaces, workspaceId } = options;
|
|
119
|
+
const [row] = await db.select({ enabled: workspaces.spendBudgetEnabled, limit: workspaces.spendBudgetLimitNanoUsd }).from(workspaces).where(eq(workspaces.id, workspaceId)).limit(1);
|
|
120
|
+
return {
|
|
121
|
+
enabled: row?.enabled ?? false,
|
|
122
|
+
limitNanoUsd: row?.limit ?? DEFAULT_WORKSPACE_SPEND_BUDGET_NANO_USD
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
export {
|
|
126
|
+
createDrizzleSpendStore,
|
|
127
|
+
listLedgerBillingOwnerIds,
|
|
128
|
+
listWorkspaceSandboxIds,
|
|
129
|
+
loadWorkspaceSpendBudgetConfig
|
|
130
|
+
};
|
|
131
|
+
//# sourceMappingURL=drizzle.js.map
|