@tangle-network/agent-runtime 0.317.0 → 0.319.3
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/{activation-CvdE2HIU.js → activation-ClcJ6wO1.js} +3 -3
- package/dist/{activation-CvdE2HIU.js.map → activation-ClcJ6wO1.js.map} +1 -1
- package/dist/{activation-BFDmjaKP.d.ts → activation-OColGsfd.d.ts} +2 -2
- package/dist/agent.d.ts +3 -3
- package/dist/agent.js +3 -3
- package/dist/{bundle-RgHpAFDY.js → bundle-Cw-QdGmH.js} +2 -2
- package/dist/{bundle-RgHpAFDY.js.map → bundle-Cw-QdGmH.js.map} +1 -1
- package/dist/candidate-execution/index.d.ts +40 -3
- package/dist/candidate-execution/index.js +86 -7
- package/dist/candidate-execution/index.js.map +1 -1
- package/dist/{coordination-driver-DGhN8GO9.js → coordination-driver-Culvomn2.js} +3 -3
- package/dist/{coordination-driver-DGhN8GO9.js.map → coordination-driver-Culvomn2.js.map} +1 -1
- package/dist/{delegate-B5pmSbQa.js → delegate-CpMbpiIR.js} +2 -2
- package/dist/{delegate-B5pmSbQa.js.map → delegate-CpMbpiIR.js.map} +1 -1
- package/dist/durable.d.ts +1 -1
- package/dist/durable.js +4 -4
- package/dist/{graph-G0j1ysqe.js → graph-DnfSGUM8.js} +5 -5
- package/dist/{graph-G0j1ysqe.js.map → graph-DnfSGUM8.js.map} +1 -1
- package/dist/graph-registry-BuJbzTzF.js +211 -0
- package/dist/graph-registry-BuJbzTzF.js.map +1 -0
- package/dist/{improvement-cycle-D7yR6GC2.js → improvement-cycle-xnQwUaC3.js} +7 -7
- package/dist/{improvement-cycle-D7yR6GC2.js.map → improvement-cycle-xnQwUaC3.js.map} +1 -1
- package/dist/{index-CUh40yUJ.d.ts → index-Da7w2H86.d.ts} +351 -132
- package/dist/index.d.ts +5 -5
- package/dist/index.js +10 -10
- package/dist/intelligence.d.ts +4 -4
- package/dist/intelligence.js +7 -7
- package/dist/kernel.d.ts +3 -2
- package/dist/kernel.js +12 -11
- package/dist/{loop-runner-bin-DQKLUt0l.d.ts → loop-runner-bin-CbBoLC9D.d.ts} +2 -2
- package/dist/{loop-runner-bin-CFVX4oi0.js → loop-runner-bin-uoeGHNZA.js} +3 -3
- package/dist/{loop-runner-bin-CFVX4oi0.js.map → loop-runner-bin-uoeGHNZA.js.map} +1 -1
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +2 -2
- package/dist/mcp/index.js +6 -6
- package/dist/{model-policy-DhvyZ8-O.js → model-policy-CNe257pB.js} +37 -2
- package/dist/model-policy-CNe257pB.js.map +1 -0
- package/dist/{openai-tools-u3gWBi3x.d.ts → openai-tools-Cu9E1Bda.d.ts} +2 -2
- package/dist/placement.d.ts +1 -1
- package/dist/{prepare-CD9kR0gS.js → prepare-DjCLEN-q.js} +3 -3
- package/dist/prepare-DjCLEN-q.js.map +1 -0
- package/dist/{profile-CHXYmpGd.js → profile-DmVM4Gxb.js} +9 -2
- package/dist/profile-DmVM4Gxb.js.map +1 -0
- package/dist/{profile-materialization-Cca615eu.d.ts → profile-materialization-C5-t3HJ7.d.ts} +14 -3
- package/dist/profiles.d.ts +1 -1
- package/dist/profiles.js +1 -1
- package/dist/{protected-model-port-C9QtEf3y.d.ts → protected-model-port-CQg2gstJ.d.ts} +3 -3
- package/dist/{protected-model-port-B0pHd65J.js → protected-model-port-D1fcnYdj.js} +4 -4
- package/dist/{protected-model-port-B0pHd65J.js.map → protected-model-port-D1fcnYdj.js.map} +1 -1
- package/dist/{provision-supervisor-BQLLrUtn.js → provision-supervisor-DiZTjzdp.js} +5 -5
- package/dist/{provision-supervisor-BQLLrUtn.js.map → provision-supervisor-DiZTjzdp.js.map} +1 -1
- package/dist/{runtime-B9BOFyEp.js → runtime-6qzuLTJ7.js} +514 -277
- package/dist/runtime-6qzuLTJ7.js.map +1 -0
- package/dist/{search-executor-B5ZVFsDV.js → search-executor-DlaLafvy.js} +4 -4
- package/dist/{search-executor-B5ZVFsDV.js.map → search-executor-DlaLafvy.js.map} +1 -1
- package/dist/{server-TwpH9aik.js → server-sLrmWqKw.js} +4 -4
- package/dist/{server-TwpH9aik.js.map → server-sLrmWqKw.js.map} +1 -1
- package/dist/{supervise-CU6AuxWY.js → supervise-D4CnC-cl.js} +5 -5
- package/dist/{supervise-CU6AuxWY.js.map → supervise-D4CnC-cl.js.map} +1 -1
- package/dist/{supervisor-CbFyf48U.js → supervisor-Cqhu3xH-.js} +709 -80
- package/dist/supervisor-Cqhu3xH-.js.map +1 -0
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +14 -14
- package/dist/tool-loop.d.ts +5 -1
- package/dist/tool-loop.js +4 -3
- package/dist/tool-loop.js.map +1 -1
- package/dist/tui/index.d.ts +1 -1
- package/dist/tui/index.js +1 -1
- package/dist/workspace-store/index.d.ts +171 -3
- package/dist/workspace-store/index.js +529 -8
- package/dist/workspace-store/index.js.map +1 -1
- package/dist/{workspace-streams-DkijayqX.js → workspace-streams-DFAhW7hF.js} +300 -42
- package/dist/workspace-streams-DFAhW7hF.js.map +1 -0
- package/dist/{workspace-streams-CpSmt3zx.d.ts → workspace-streams-U6_UfOXu.d.ts} +10 -2
- package/package.json +15 -11
- package/skills/agent-graphs/references/authoring.md +7 -0
- package/skills/codemode/SKILL.md +6 -4
- package/skills/codemode/references/runtime-execution.md +63 -11
- package/skills/graph-designer/SKILL.md +57 -0
- package/skills/profile-authoring/SKILL.md +17 -15
- package/dist/model-policy-DhvyZ8-O.js.map +0 -1
- package/dist/prepare-CD9kR0gS.js.map +0 -1
- package/dist/profile-CHXYmpGd.js.map +0 -1
- package/dist/runtime-B9BOFyEp.js.map +0 -1
- package/dist/supervisor-CbFyf48U.js.map +0 -1
- package/dist/workspace-streams-DkijayqX.js.map +0 -1
|
@@ -1,4 +1,215 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
+
//#region src/workspace-store/codec.ts
|
|
3
|
+
/** A value did not open: unknown key, wrong tenant or path, tampering, or plaintext where a seal was required. */
|
|
4
|
+
var WorkspaceCodecError = class extends Error {
|
|
5
|
+
code = "codec";
|
|
6
|
+
constructor(message) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = "WorkspaceCodecError";
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
const VERSION = 1;
|
|
12
|
+
const IV_BYTES = 12;
|
|
13
|
+
const KEY_ID = /^[A-Za-z0-9_-]{1,64}$/;
|
|
14
|
+
const encoder = new TextEncoder();
|
|
15
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
16
|
+
function bytesOf(value) {
|
|
17
|
+
if (typeof value !== "string") return value;
|
|
18
|
+
const binary = atob(value.replace(/-/g, "+").replace(/_/g, "/"));
|
|
19
|
+
return Uint8Array.from(binary, (char) => char.charCodeAt(0));
|
|
20
|
+
}
|
|
21
|
+
function base64(bytes) {
|
|
22
|
+
let binary = "";
|
|
23
|
+
for (let offset = 0; offset < bytes.length; offset += 32768) binary += String.fromCharCode(...bytes.subarray(offset, offset + 32768));
|
|
24
|
+
return btoa(binary);
|
|
25
|
+
}
|
|
26
|
+
/** A copy in a plain ArrayBuffer, which every Web Crypto typing accepts (this package has no DOM lib). */
|
|
27
|
+
function arrayBuffer(bytes) {
|
|
28
|
+
return bytes.slice().buffer;
|
|
29
|
+
}
|
|
30
|
+
function concat(...parts) {
|
|
31
|
+
const out = new Uint8Array(parts.reduce((total, part) => total + part.length, 0));
|
|
32
|
+
let offset = 0;
|
|
33
|
+
for (const part of parts) {
|
|
34
|
+
out.set(part, offset);
|
|
35
|
+
offset += part.length;
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
/** Strings joined with a 4-byte length before each, so no two lists encode alike. */
|
|
40
|
+
function framed(...values) {
|
|
41
|
+
return concat(...values.flatMap((value) => {
|
|
42
|
+
const bytes = encoder.encode(value);
|
|
43
|
+
const length = /* @__PURE__ */ new Uint8Array(4);
|
|
44
|
+
new DataView(length.buffer).setUint32(0, bytes.length);
|
|
45
|
+
return [length, bytes];
|
|
46
|
+
}));
|
|
47
|
+
}
|
|
48
|
+
/** The authenticated data: the tenant and path a value belongs to. */
|
|
49
|
+
const associated = ({ tenant, path }) => framed(tenant, path);
|
|
50
|
+
/**
|
|
51
|
+
* AES-256-GCM with a key id per value. `keys` maps key id to 32 raw bytes
|
|
52
|
+
* (base64 or base64url when a string). The encryption key and the key that
|
|
53
|
+
* derives replay-stable IVs are both derived from the raw key with HKDF, so the
|
|
54
|
+
* raw key is never used for two algorithms.
|
|
55
|
+
*
|
|
56
|
+
* Without an `operationId` every seal uses a random 96-bit IV. With one, the IV
|
|
57
|
+
* is an HMAC of the tenant, path, operation and plaintext, as in SIV: only an
|
|
58
|
+
* identical write repeats it, and that repeat reveals only that the write was
|
|
59
|
+
* repeated.
|
|
60
|
+
*/
|
|
61
|
+
function createAesGcmContentCodec(options) {
|
|
62
|
+
const raw = /* @__PURE__ */ new Map();
|
|
63
|
+
for (const [id, value] of Object.entries(options.keys)) {
|
|
64
|
+
if (!KEY_ID.test(id)) throw new TypeError(`workspace store key id is not [A-Za-z0-9_-]{1,64}: ${id}`);
|
|
65
|
+
const bytes = bytesOf(value);
|
|
66
|
+
if (bytes.length !== 32) throw new TypeError(`workspace store key ${id} must be 32 bytes, got ${bytes.length}`);
|
|
67
|
+
raw.set(id, bytes);
|
|
68
|
+
}
|
|
69
|
+
if (!raw.has(options.activeKeyId)) throw new TypeError(`the active workspace store key ${options.activeKeyId} is not among the keys`);
|
|
70
|
+
const derived = /* @__PURE__ */ new Map();
|
|
71
|
+
const keyFor = (id) => {
|
|
72
|
+
const bytes = raw.get(id);
|
|
73
|
+
if (!bytes) return Promise.reject(new WorkspaceCodecError(`unknown workspace store key id: ${id}`));
|
|
74
|
+
let key = derived.get(id);
|
|
75
|
+
if (!key) {
|
|
76
|
+
key = (async () => {
|
|
77
|
+
const base = await crypto.subtle.importKey("raw", arrayBuffer(bytes), "HKDF", false, ["deriveKey"]);
|
|
78
|
+
const hkdf = (info) => ({
|
|
79
|
+
name: "HKDF",
|
|
80
|
+
hash: "SHA-256",
|
|
81
|
+
salt: /* @__PURE__ */ new Uint8Array(32),
|
|
82
|
+
info: encoder.encode(`workspace-store/${info}`)
|
|
83
|
+
});
|
|
84
|
+
return {
|
|
85
|
+
seal: await crypto.subtle.deriveKey(hkdf("aes-256-gcm"), base, {
|
|
86
|
+
name: "AES-GCM",
|
|
87
|
+
length: 256
|
|
88
|
+
}, false, ["encrypt", "decrypt"]),
|
|
89
|
+
iv: await crypto.subtle.deriveKey(hkdf("siv"), base, {
|
|
90
|
+
name: "HMAC",
|
|
91
|
+
hash: "SHA-256",
|
|
92
|
+
length: 256
|
|
93
|
+
}, false, ["sign"])
|
|
94
|
+
};
|
|
95
|
+
})();
|
|
96
|
+
derived.set(id, key);
|
|
97
|
+
}
|
|
98
|
+
return key;
|
|
99
|
+
};
|
|
100
|
+
return {
|
|
101
|
+
async seal(plain, context) {
|
|
102
|
+
const id = options.activeKeyId;
|
|
103
|
+
const key = await keyFor(id);
|
|
104
|
+
const aad = associated(context);
|
|
105
|
+
const iv = context.operationId === void 0 ? crypto.getRandomValues(new Uint8Array(IV_BYTES)) : new Uint8Array(await crypto.subtle.sign("HMAC", key.iv, arrayBuffer(concat(framed(context.tenant, context.path, context.operationId), plain)))).slice(0, IV_BYTES);
|
|
106
|
+
const sealed = new Uint8Array(await crypto.subtle.encrypt({
|
|
107
|
+
name: "AES-GCM",
|
|
108
|
+
iv: arrayBuffer(iv),
|
|
109
|
+
additionalData: arrayBuffer(aad)
|
|
110
|
+
}, key.seal, arrayBuffer(plain)));
|
|
111
|
+
const keyId = encoder.encode(id);
|
|
112
|
+
return concat(Uint8Array.of(VERSION, keyId.length), keyId, iv, sealed);
|
|
113
|
+
},
|
|
114
|
+
async open(sealed, context) {
|
|
115
|
+
if (sealed.length < 2 || sealed[0] !== VERSION) throw new WorkspaceCodecError("not a sealed workspace value");
|
|
116
|
+
const start = 2 + sealed[1];
|
|
117
|
+
if (sealed.length < start + IV_BYTES + 16) throw new WorkspaceCodecError("a sealed workspace value is truncated");
|
|
118
|
+
const key = await keyFor(new TextDecoder().decode(sealed.subarray(2, start)));
|
|
119
|
+
try {
|
|
120
|
+
return new Uint8Array(await crypto.subtle.decrypt({
|
|
121
|
+
name: "AES-GCM",
|
|
122
|
+
iv: arrayBuffer(sealed.subarray(start, start + IV_BYTES)),
|
|
123
|
+
additionalData: arrayBuffer(associated(context))
|
|
124
|
+
}, key.seal, arrayBuffer(sealed.subarray(start + IV_BYTES))));
|
|
125
|
+
} catch {
|
|
126
|
+
throw new WorkspaceCodecError(`${context.path}: the sealed value does not open for this tenant and path`);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* The AES-256-GCM codec from an app's env, or `null` when neither variable is
|
|
133
|
+
* set. `WORKSPACE_STORE_KEYS` is `id:base64,id:base64`; `WORKSPACE_STORE_KEY_ID`
|
|
134
|
+
* names the key new writes use. Setting one without the other is refused.
|
|
135
|
+
*/
|
|
136
|
+
function aesGcmContentCodecFromEnv(env) {
|
|
137
|
+
const list = env.WORKSPACE_STORE_KEYS?.trim();
|
|
138
|
+
const active = env.WORKSPACE_STORE_KEY_ID?.trim();
|
|
139
|
+
if (!list && !active) return null;
|
|
140
|
+
if (!list || !active) throw new TypeError("set both WORKSPACE_STORE_KEYS and WORKSPACE_STORE_KEY_ID");
|
|
141
|
+
const keys = {};
|
|
142
|
+
for (const pair of list.split(",")) {
|
|
143
|
+
const at = pair.indexOf(":");
|
|
144
|
+
if (at <= 0) throw new TypeError("WORKSPACE_STORE_KEYS is id:base64,id:base64");
|
|
145
|
+
keys[pair.slice(0, at).trim()] = pair.slice(at + 1).trim();
|
|
146
|
+
}
|
|
147
|
+
return createAesGcmContentCodec({
|
|
148
|
+
keys,
|
|
149
|
+
activeKeyId: active
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
/** Stored text of a sealed `content`: a prefix, then the sealed bytes in base64. */
|
|
153
|
+
const SEALED_CONTENT_PREFIX = "wsc1:";
|
|
154
|
+
/** Seal bytes a host is about to upload (an R2 object) under the entry's tenant and path. */
|
|
155
|
+
function sealWorkspaceBytes(codec, context, bytes) {
|
|
156
|
+
return codec.seal(bytes, context);
|
|
157
|
+
}
|
|
158
|
+
/** Open bytes a host downloaded for an entry's `bytes` reference. */
|
|
159
|
+
function openWorkspaceBytes(codec, context, sealed) {
|
|
160
|
+
return codec.open(sealed, context);
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* `store` with every entry's `content` sealed at rest. Index fields, `bytes`
|
|
164
|
+
* references and tombstones pass through untouched; the host seals the bytes
|
|
165
|
+
* themselves. `idempotentOperations` is the inner store's: a replayed put with
|
|
166
|
+
* an `operationId` seals to the same bytes, so the inner replay check holds.
|
|
167
|
+
*/
|
|
168
|
+
function withContentCodec(store, codec, options = {}) {
|
|
169
|
+
const open = async (entry) => {
|
|
170
|
+
if (entry.content === void 0) return entry;
|
|
171
|
+
if (!entry.content.startsWith("wsc1:")) {
|
|
172
|
+
if (options.readPlaintext) return entry;
|
|
173
|
+
throw new WorkspaceCodecError(`${entry.path}: stored content is not sealed`);
|
|
174
|
+
}
|
|
175
|
+
const plain = await codec.open(bytesOf(entry.content.slice(5)), {
|
|
176
|
+
tenant: entry.workspaceId,
|
|
177
|
+
path: entry.path
|
|
178
|
+
});
|
|
179
|
+
return {
|
|
180
|
+
...entry,
|
|
181
|
+
content: decoder.decode(plain)
|
|
182
|
+
};
|
|
183
|
+
};
|
|
184
|
+
return {
|
|
185
|
+
...store.idempotentOperations !== void 0 ? { idempotentOperations: store.idempotentOperations } : {},
|
|
186
|
+
async get(workspaceId, path) {
|
|
187
|
+
const entry = await store.get(workspaceId, path);
|
|
188
|
+
return entry ? open(entry) : null;
|
|
189
|
+
},
|
|
190
|
+
async list(workspaceId, prefix) {
|
|
191
|
+
return Promise.all((await store.list(workspaceId, prefix)).map(open));
|
|
192
|
+
},
|
|
193
|
+
async put(input) {
|
|
194
|
+
if (input.content === void 0) return store.put(input);
|
|
195
|
+
const sealed = await codec.seal(encoder.encode(input.content), {
|
|
196
|
+
tenant: input.workspaceId,
|
|
197
|
+
path: input.path,
|
|
198
|
+
...input.operationId !== void 0 ? { operationId: input.operationId } : {}
|
|
199
|
+
});
|
|
200
|
+
return {
|
|
201
|
+
...await store.put({
|
|
202
|
+
...input,
|
|
203
|
+
content: `${SEALED_CONTENT_PREFIX}${base64(sealed)}`
|
|
204
|
+
}),
|
|
205
|
+
content: input.content
|
|
206
|
+
};
|
|
207
|
+
},
|
|
208
|
+
delete: (input) => store.delete(input),
|
|
209
|
+
tombstones: (workspaceId, prefix) => store.tombstones(workspaceId, prefix)
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
//#endregion
|
|
2
213
|
//#region src/workspace-store/store.ts
|
|
3
214
|
/** A write lost a compare-and-set race or targeted the wrong revision. Re-read and retry. */
|
|
4
215
|
var WorkspaceConflictError = class extends Error {
|
|
@@ -34,6 +245,21 @@ function checkWorkspacePut(input) {
|
|
|
34
245
|
if (!input.actor) throw new TypeError("actor is required");
|
|
35
246
|
if (input.content === void 0 === (input.bytes === void 0)) throw new TypeError(`${input.path}: exactly one of content and bytes is required`);
|
|
36
247
|
if (input.ifRevision !== null && !Number.isSafeInteger(input.ifRevision)) throw new TypeError(`${input.path}: ifRevision must be an integer or null`);
|
|
248
|
+
checkOperationId(input.path, input.operationId);
|
|
249
|
+
}
|
|
250
|
+
const MAX_OPERATION_ID = 256;
|
|
251
|
+
/** Refuse an `operationId` that is present but empty, not a string, or over 256 chars. */
|
|
252
|
+
function checkOperationId(path, operationId) {
|
|
253
|
+
if (operationId === void 0) return;
|
|
254
|
+
if (typeof operationId !== "string" || !operationId || operationId.length > MAX_OPERATION_ID) throw new TypeError(`${path}: operationId must be a non-empty string of at most ${MAX_OPERATION_ID} chars`);
|
|
255
|
+
}
|
|
256
|
+
function sameBytes(left, right) {
|
|
257
|
+
if (!left || !right) return left === right;
|
|
258
|
+
return left.key === right.key && left.size === right.size && left.contentType === right.contentType && left.sha256 === right.sha256;
|
|
259
|
+
}
|
|
260
|
+
/** Whether `entry` is exactly what `input` would write: same kind, content and bytes. */
|
|
261
|
+
function isSameWorkspaceWrite(entry, input) {
|
|
262
|
+
return entry.kind === input.kind && entry.content === input.content && sameBytes(entry.bytes, input.bytes);
|
|
37
263
|
}
|
|
38
264
|
/** Process-local adapter for tests, previews, and single-instance hosts. */
|
|
39
265
|
function createInMemoryWorkspaceStore(options = {}) {
|
|
@@ -42,6 +268,9 @@ function createInMemoryWorkspaceStore(options = {}) {
|
|
|
42
268
|
const live = /* @__PURE__ */ new Map();
|
|
43
269
|
const lastRevision = /* @__PURE__ */ new Map();
|
|
44
270
|
const erased = [];
|
|
271
|
+
const wroteLive = /* @__PURE__ */ new Map();
|
|
272
|
+
const erasedBy = /* @__PURE__ */ new Map();
|
|
273
|
+
const pathKey = (workspaceId, path) => `${workspaceId}\u0000${path}`;
|
|
45
274
|
const tenant = (workspaceId) => {
|
|
46
275
|
let entries = live.get(workspaceId);
|
|
47
276
|
if (!entries) {
|
|
@@ -51,6 +280,7 @@ function createInMemoryWorkspaceStore(options = {}) {
|
|
|
51
280
|
return entries;
|
|
52
281
|
};
|
|
53
282
|
return {
|
|
283
|
+
idempotentOperations: true,
|
|
54
284
|
async get(workspaceId, path) {
|
|
55
285
|
const entry = live.get(workspaceId)?.get(path);
|
|
56
286
|
return entry ? structuredClone(entry) : null;
|
|
@@ -62,8 +292,9 @@ function createInMemoryWorkspaceStore(options = {}) {
|
|
|
62
292
|
checkWorkspacePut(input);
|
|
63
293
|
const entries = tenant(input.workspaceId);
|
|
64
294
|
const current = entries.get(input.path);
|
|
295
|
+
const key = pathKey(input.workspaceId, input.path);
|
|
296
|
+
if (current && input.operationId !== void 0 && wroteLive.get(key) === input.operationId && isSameWorkspaceWrite(current, input)) return structuredClone(current);
|
|
65
297
|
if ((current?.revision ?? null) !== input.ifRevision) throw new WorkspaceConflictError(input.path, input.ifRevision, current?.revision ?? null);
|
|
66
|
-
const key = `${input.workspaceId}\u0000${input.path}`;
|
|
67
298
|
const revision = (lastRevision.get(key) ?? 0) + 1;
|
|
68
299
|
const at = now();
|
|
69
300
|
const entry = {
|
|
@@ -82,12 +313,18 @@ function createInMemoryWorkspaceStore(options = {}) {
|
|
|
82
313
|
};
|
|
83
314
|
entries.set(input.path, entry);
|
|
84
315
|
lastRevision.set(key, revision);
|
|
316
|
+
if (input.operationId === void 0) wroteLive.delete(key);
|
|
317
|
+
else wroteLive.set(key, input.operationId);
|
|
85
318
|
return structuredClone(entry);
|
|
86
319
|
},
|
|
87
320
|
async delete(input) {
|
|
88
321
|
assertWorkspacePath(input.path);
|
|
322
|
+
checkOperationId(input.path, input.operationId);
|
|
89
323
|
const entries = tenant(input.workspaceId);
|
|
90
324
|
const current = entries.get(input.path);
|
|
325
|
+
const key = pathKey(input.workspaceId, input.path);
|
|
326
|
+
const previous = erasedBy.get(key);
|
|
327
|
+
if (!current && input.operationId !== void 0 && previous?.operationId === input.operationId) return { ...previous.tombstone };
|
|
91
328
|
if (input.ifRevision !== void 0 && current?.revision !== input.ifRevision) throw new WorkspaceConflictError(input.path, input.ifRevision, current?.revision ?? null);
|
|
92
329
|
if (!current) return null;
|
|
93
330
|
const revision = current.revision + 1;
|
|
@@ -100,7 +337,13 @@ function createInMemoryWorkspaceStore(options = {}) {
|
|
|
100
337
|
deletedAt: now()
|
|
101
338
|
};
|
|
102
339
|
entries.delete(input.path);
|
|
103
|
-
lastRevision.set(
|
|
340
|
+
lastRevision.set(key, revision);
|
|
341
|
+
wroteLive.delete(key);
|
|
342
|
+
if (input.operationId === void 0) erasedBy.delete(key);
|
|
343
|
+
else erasedBy.set(key, {
|
|
344
|
+
operationId: input.operationId,
|
|
345
|
+
tombstone
|
|
346
|
+
});
|
|
104
347
|
erased.push(tombstone);
|
|
105
348
|
return { ...tombstone };
|
|
106
349
|
},
|
|
@@ -156,6 +399,7 @@ function defaultMemoryPolicy(options = {}) {
|
|
|
156
399
|
...options.admit ? { admit: options.admit } : {}
|
|
157
400
|
};
|
|
158
401
|
}
|
|
402
|
+
/** Policy check shared by the memory tools and harness ingest; not part of the public entry. */
|
|
159
403
|
async function guard(context, turn, access, text) {
|
|
160
404
|
const policy = context.policy ?? defaultMemoryPolicy();
|
|
161
405
|
const refusal = policy.authorize(turn, access);
|
|
@@ -556,9 +800,81 @@ function toolsFor(store, turn, policy) {
|
|
|
556
800
|
return tool.run(args);
|
|
557
801
|
};
|
|
558
802
|
}
|
|
803
|
+
const idempotentOperationCase = ["operationId: a repeated put or delete returns its result instead of a conflict", async (store) => {
|
|
804
|
+
check(store.idempotentOperations === true, "the store declares idempotentOperations");
|
|
805
|
+
const base = {
|
|
806
|
+
workspaceId: W,
|
|
807
|
+
path: "/files/op.md",
|
|
808
|
+
kind: "file",
|
|
809
|
+
actor: "alice"
|
|
810
|
+
};
|
|
811
|
+
const first = await store.put({
|
|
812
|
+
...base,
|
|
813
|
+
content: "one",
|
|
814
|
+
ifRevision: null,
|
|
815
|
+
operationId: "op-1"
|
|
816
|
+
});
|
|
817
|
+
const replay = await store.put({
|
|
818
|
+
...base,
|
|
819
|
+
content: "one",
|
|
820
|
+
ifRevision: null,
|
|
821
|
+
operationId: "op-1"
|
|
822
|
+
});
|
|
823
|
+
check(replay.revision === first.revision && replay.id === first.id && replay.content === "one", "a repeated put returns the entry it wrote");
|
|
824
|
+
await rejects(() => store.put({
|
|
825
|
+
...base,
|
|
826
|
+
content: "other",
|
|
827
|
+
ifRevision: null,
|
|
828
|
+
operationId: "op-1"
|
|
829
|
+
}), WorkspaceConflictError, "the same operation with different content");
|
|
830
|
+
await rejects(() => store.put({
|
|
831
|
+
...base,
|
|
832
|
+
content: "one",
|
|
833
|
+
ifRevision: null,
|
|
834
|
+
operationId: "op-other"
|
|
835
|
+
}), WorkspaceConflictError, "another operation with the same content");
|
|
836
|
+
const second = await store.put({
|
|
837
|
+
...base,
|
|
838
|
+
content: "two",
|
|
839
|
+
ifRevision: first.revision,
|
|
840
|
+
operationId: "op-2"
|
|
841
|
+
});
|
|
842
|
+
await rejects(() => store.put({
|
|
843
|
+
...base,
|
|
844
|
+
content: "one",
|
|
845
|
+
ifRevision: null,
|
|
846
|
+
operationId: "op-1"
|
|
847
|
+
}), WorkspaceConflictError, "an operation a later write superseded");
|
|
848
|
+
const erase = {
|
|
849
|
+
workspaceId: W,
|
|
850
|
+
path: base.path,
|
|
851
|
+
ifRevision: second.revision,
|
|
852
|
+
actor: "bob"
|
|
853
|
+
};
|
|
854
|
+
const tombstone = await store.delete({
|
|
855
|
+
...erase,
|
|
856
|
+
operationId: "op-3"
|
|
857
|
+
});
|
|
858
|
+
const again = await store.delete({
|
|
859
|
+
...erase,
|
|
860
|
+
operationId: "op-3"
|
|
861
|
+
});
|
|
862
|
+
check(tombstone !== null && again?.revision === tombstone.revision, "a repeated delete returns its tombstone");
|
|
863
|
+
await rejects(() => store.delete({
|
|
864
|
+
...erase,
|
|
865
|
+
operationId: "op-4"
|
|
866
|
+
}), WorkspaceConflictError, "another operation deleting the erased path");
|
|
867
|
+
check((await store.tombstones(W, base.path)).length === 1, "a repeated delete erases once");
|
|
868
|
+
await rejects(() => store.put({
|
|
869
|
+
...base,
|
|
870
|
+
content: "x",
|
|
871
|
+
ifRevision: null,
|
|
872
|
+
operationId: ""
|
|
873
|
+
}), TypeError, "an empty operationId");
|
|
874
|
+
}];
|
|
559
875
|
/** The contract as named cases; each case builds its own store. */
|
|
560
|
-
function workspaceStoreContractCases(makeStore) {
|
|
561
|
-
|
|
876
|
+
function workspaceStoreContractCases(makeStore, options = {}) {
|
|
877
|
+
const cases = [
|
|
562
878
|
["compare-and-set: create, stale update, and re-create conflict with a typed error", async (store) => {
|
|
563
879
|
const base = {
|
|
564
880
|
workspaceId: W,
|
|
@@ -824,7 +1140,9 @@ function workspaceStoreContractCases(makeStore) {
|
|
|
824
1140
|
const small = renderPinnedMemory(entries, { maxTokens: 120 });
|
|
825
1141
|
check(small.length <= 480 && /\d+ more not shown\./.test(small), "a small budget truncates and counts");
|
|
826
1142
|
}]
|
|
827
|
-
]
|
|
1143
|
+
];
|
|
1144
|
+
if (options.idempotentOperations) cases.push(idempotentOperationCase);
|
|
1145
|
+
return cases.map(([name, body]) => ({
|
|
828
1146
|
name,
|
|
829
1147
|
async run() {
|
|
830
1148
|
await body(await makeStore());
|
|
@@ -832,9 +1150,9 @@ function workspaceStoreContractCases(makeStore) {
|
|
|
832
1150
|
}));
|
|
833
1151
|
}
|
|
834
1152
|
/** Run every contract case against fresh stores; never throws for a failing case. */
|
|
835
|
-
async function runWorkspaceStoreContract(makeStore) {
|
|
1153
|
+
async function runWorkspaceStoreContract(makeStore, options = {}) {
|
|
836
1154
|
const results = [];
|
|
837
|
-
for (const contractCase of workspaceStoreContractCases(makeStore)) try {
|
|
1155
|
+
for (const contractCase of workspaceStoreContractCases(makeStore, options)) try {
|
|
838
1156
|
await contractCase.run();
|
|
839
1157
|
results.push({
|
|
840
1158
|
name: contractCase.name,
|
|
@@ -850,6 +1168,209 @@ async function runWorkspaceStoreContract(makeStore) {
|
|
|
850
1168
|
return results;
|
|
851
1169
|
}
|
|
852
1170
|
//#endregion
|
|
853
|
-
|
|
1171
|
+
//#region src/workspace-store/harness.ts
|
|
1172
|
+
/** Opening marker for the generated block in a harness's native memory file. */
|
|
1173
|
+
const HARNESS_MEMORY_BEGIN = "<!-- workspace-store:memory begin. Generated from the workspace store; save memories with memory.remember. -->";
|
|
1174
|
+
/** Closing marker for the generated block in a harness's native memory file. */
|
|
1175
|
+
const HARNESS_MEMORY_END = "<!-- workspace-store:memory end -->";
|
|
1176
|
+
/** The generated block a host writes into a harness's native memory location. */
|
|
1177
|
+
function renderHarnessMemory(entries, options = {}) {
|
|
1178
|
+
return [
|
|
1179
|
+
HARNESS_MEMORY_BEGIN,
|
|
1180
|
+
renderPinnedMemory(entries, options),
|
|
1181
|
+
HARNESS_MEMORY_END
|
|
1182
|
+
].join("\n");
|
|
1183
|
+
}
|
|
1184
|
+
/** Replace the generated block in `native`, or append one; text outside it is kept byte for byte. */
|
|
1185
|
+
function projectHarnessMemory(native, block) {
|
|
1186
|
+
const { before, after, found } = splitGenerated(native);
|
|
1187
|
+
if (found) return `${before}${block}${after}`;
|
|
1188
|
+
return native.length === 0 ? `${block}\n` : `${native}${native.endsWith("\n") ? "\n" : "\n\n"}${block}\n`;
|
|
1189
|
+
}
|
|
1190
|
+
function splitGenerated(native) {
|
|
1191
|
+
const start = native.indexOf(HARNESS_MEMORY_BEGIN);
|
|
1192
|
+
const end = start < 0 ? -1 : native.indexOf(HARNESS_MEMORY_END, start);
|
|
1193
|
+
if (start < 0 || end < 0) return {
|
|
1194
|
+
before: native,
|
|
1195
|
+
block: "",
|
|
1196
|
+
after: "",
|
|
1197
|
+
found: false
|
|
1198
|
+
};
|
|
1199
|
+
const stop = end + 35;
|
|
1200
|
+
return {
|
|
1201
|
+
before: native.slice(0, start),
|
|
1202
|
+
block: native.slice(start, stop),
|
|
1203
|
+
after: native.slice(stop),
|
|
1204
|
+
found: true
|
|
1205
|
+
};
|
|
1206
|
+
}
|
|
1207
|
+
/** Ids listed in a generated block (`- [id] kind, scope: text`). */
|
|
1208
|
+
function projectedIds(block) {
|
|
1209
|
+
const ids = /* @__PURE__ */ new Map();
|
|
1210
|
+
for (const match of block.matchAll(/^- \[([A-Za-z0-9_-]{1,64})\] [a-z]+, (?:me|workspace): (.*)$/gm)) ids.set(match[1], match[2]);
|
|
1211
|
+
return ids;
|
|
1212
|
+
}
|
|
1213
|
+
/** Lowercase, collapse spaces, drop a leading "Remember:" and trailing punctuation: the duplicate key. */
|
|
1214
|
+
function normalizeMemoryText(text) {
|
|
1215
|
+
return text.replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)?/, "").replace(/^(?:remember|note)\b\s*(?:that\b)?\s*:?\s*/i, "").replace(/\s+/g, " ").trim().replace(/[.!;,\s]+$/, "").toLowerCase();
|
|
1216
|
+
}
|
|
1217
|
+
function stripFrontmatter(text) {
|
|
1218
|
+
return text.startsWith("---\n") ? text.slice(text.indexOf("\n---", 4) + 4).replace(/^\n+/, "") : text;
|
|
1219
|
+
}
|
|
1220
|
+
/** Lines that read as one memory: bullets and plain sentences, not headings, markers or fences. */
|
|
1221
|
+
function memoryLines(text) {
|
|
1222
|
+
const lines = [];
|
|
1223
|
+
let fenced = false;
|
|
1224
|
+
for (const raw of stripFrontmatter(text).split("\n")) {
|
|
1225
|
+
const line = raw.trim();
|
|
1226
|
+
if (line.startsWith("```")) {
|
|
1227
|
+
fenced = !fenced;
|
|
1228
|
+
continue;
|
|
1229
|
+
}
|
|
1230
|
+
if (fenced || !line || line.startsWith("#") || line.startsWith("<!--") || line.startsWith("@")) continue;
|
|
1231
|
+
const fact = line.replace(/^(?:[-*+]\s+|\d+[.)]\s+)/, "").trim();
|
|
1232
|
+
if (fact.length >= 3 && fact.length <= 1e3) lines.push(fact);
|
|
1233
|
+
}
|
|
1234
|
+
return lines;
|
|
1235
|
+
}
|
|
1236
|
+
/**
|
|
1237
|
+
* What the harness added during the turn, outside the generated block: new
|
|
1238
|
+
* lines in files that existed, and the body of new files (a Claude Code memory
|
|
1239
|
+
* directory entry). Lines removed or present before are ignored; a removal is
|
|
1240
|
+
* not a forget, which only `memory.forget` performs.
|
|
1241
|
+
*/
|
|
1242
|
+
function captureHarnessMemory(before, after) {
|
|
1243
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1244
|
+
const facts = [];
|
|
1245
|
+
for (const [path, next] of Object.entries(after)) {
|
|
1246
|
+
if (next === void 0) continue;
|
|
1247
|
+
const old = new Set(memoryLines(outside(before[path] ?? "")).map(normalizeMemoryText));
|
|
1248
|
+
for (const fact of memoryLines(outside(next))) {
|
|
1249
|
+
const key = normalizeMemoryText(fact);
|
|
1250
|
+
if (!key || old.has(key) || seen.has(key)) continue;
|
|
1251
|
+
seen.add(key);
|
|
1252
|
+
facts.push(fact);
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
return facts;
|
|
1256
|
+
}
|
|
1257
|
+
function outside(native) {
|
|
1258
|
+
const { before, after, found } = splitGenerated(native);
|
|
1259
|
+
return found ? `${before}\n${after}` : native;
|
|
1260
|
+
}
|
|
1261
|
+
const ACTOR = /^harness:([a-z0-9][a-z0-9._-]{0,40})\/turn:([^/\s]{1,128})\/member:([^/\s]{1,128})$/;
|
|
1262
|
+
/** The entry `actor` for a captured memory, so `createdBy` carries its provenance. */
|
|
1263
|
+
function harnessActor({ harness, turnId, memberId }) {
|
|
1264
|
+
const actor = `harness:${harness}/turn:${turnId}/member:${memberId}`;
|
|
1265
|
+
if (!ACTOR.test(actor)) throw new TypeError(`invalid harness provenance: ${actor}`);
|
|
1266
|
+
return actor;
|
|
1267
|
+
}
|
|
1268
|
+
/** Read the harness, turn, and member provenance encoded by {@link harnessActor}. */
|
|
1269
|
+
function parseHarnessActor(actor) {
|
|
1270
|
+
const match = ACTOR.exec(actor);
|
|
1271
|
+
return match ? {
|
|
1272
|
+
harness: match[1],
|
|
1273
|
+
turnId: match[2],
|
|
1274
|
+
memberId: match[3]
|
|
1275
|
+
} : null;
|
|
1276
|
+
}
|
|
1277
|
+
/**
|
|
1278
|
+
* Save captured facts as workspace memories through the same policy as
|
|
1279
|
+
* `memory.remember`, with the harness and turn as the actor. Duplicates of a
|
|
1280
|
+
* memory the turn can see, or of an earlier fact in the batch, are skipped.
|
|
1281
|
+
*/
|
|
1282
|
+
async function ingestHarnessMemories(context, input) {
|
|
1283
|
+
const turn = await context.activeTurn();
|
|
1284
|
+
const actor = harnessActor({
|
|
1285
|
+
harness: input.harness,
|
|
1286
|
+
turnId: input.turnId,
|
|
1287
|
+
memberId: turn.memberId
|
|
1288
|
+
});
|
|
1289
|
+
const newId = context.newId ?? (() => crypto.randomUUID());
|
|
1290
|
+
const known = new Set((await readTurnMemories(context.store, turn)).map((entry) => normalizeMemoryText(entry.content ?? "")));
|
|
1291
|
+
const saved = [];
|
|
1292
|
+
const duplicates = [];
|
|
1293
|
+
const refused = [];
|
|
1294
|
+
for (const raw of input.facts) {
|
|
1295
|
+
const text = raw.replace(/\s+/g, " ").trim();
|
|
1296
|
+
const key = normalizeMemoryText(text);
|
|
1297
|
+
if (!key) continue;
|
|
1298
|
+
if (known.has(key)) {
|
|
1299
|
+
duplicates.push(text);
|
|
1300
|
+
continue;
|
|
1301
|
+
}
|
|
1302
|
+
const id = newId();
|
|
1303
|
+
const path = `/memories/workspace/${id}`;
|
|
1304
|
+
try {
|
|
1305
|
+
await guard(context, turn, {
|
|
1306
|
+
op: "write",
|
|
1307
|
+
path,
|
|
1308
|
+
kind: "fact"
|
|
1309
|
+
}, text);
|
|
1310
|
+
} catch (error) {
|
|
1311
|
+
refused.push({
|
|
1312
|
+
text,
|
|
1313
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
1314
|
+
});
|
|
1315
|
+
continue;
|
|
1316
|
+
}
|
|
1317
|
+
known.add(key);
|
|
1318
|
+
saved.push(await context.store.put({
|
|
1319
|
+
workspaceId: turn.workspaceId,
|
|
1320
|
+
path,
|
|
1321
|
+
kind: "fact",
|
|
1322
|
+
ifRevision: null,
|
|
1323
|
+
actor,
|
|
1324
|
+
content: text,
|
|
1325
|
+
id
|
|
1326
|
+
}));
|
|
1327
|
+
}
|
|
1328
|
+
return {
|
|
1329
|
+
saved,
|
|
1330
|
+
duplicates,
|
|
1331
|
+
refused
|
|
1332
|
+
};
|
|
1333
|
+
}
|
|
1334
|
+
/**
|
|
1335
|
+
* Compare each native file with the store as `turn` sees it, after ingest ran.
|
|
1336
|
+
* `before` is the files as projected at session start, `after` as they are now:
|
|
1337
|
+
* only what the harness added since then can be uncaptured, so the profile's own
|
|
1338
|
+
* generated text in the same file never counts. Files that held a generated
|
|
1339
|
+
* block at session start are projection targets: losing the block counts every
|
|
1340
|
+
* visible memory as missing. Other files (a new memory-directory entry) can
|
|
1341
|
+
* only hold uncaptured facts.
|
|
1342
|
+
*/
|
|
1343
|
+
async function memoryDivergence(store, turn, before, after) {
|
|
1344
|
+
const entries = (await readTurnMemories(store, turn)).filter((entry) => entry.content !== void 0);
|
|
1345
|
+
const byId = new Map(entries.map((entry) => [entry.id, entry.content.replace(/\s+/g, " ").trim()]));
|
|
1346
|
+
const stored = new Set(entries.map((entry) => normalizeMemoryText(entry.content)));
|
|
1347
|
+
const files = {};
|
|
1348
|
+
let missing = 0;
|
|
1349
|
+
let stale = 0;
|
|
1350
|
+
let uncaptured = 0;
|
|
1351
|
+
for (const [path, native] of Object.entries(after)) {
|
|
1352
|
+
if (native === void 0) continue;
|
|
1353
|
+
const target = splitGenerated(before[path] ?? "").found || splitGenerated(native).found;
|
|
1354
|
+
const listed = projectedIds(splitGenerated(native).block);
|
|
1355
|
+
const report = {
|
|
1356
|
+
missing: target ? [...byId.keys()].filter((id) => !listed.has(id)) : [],
|
|
1357
|
+
stale: [...listed].filter(([id, text]) => byId.get(id) !== text).map(([id]) => id),
|
|
1358
|
+
uncaptured: captureHarnessMemory({ [path]: before[path] }, { [path]: native }).filter((fact) => !stored.has(normalizeMemoryText(fact)))
|
|
1359
|
+
};
|
|
1360
|
+
missing += report.missing.length;
|
|
1361
|
+
stale += report.stale.length;
|
|
1362
|
+
uncaptured += report.uncaptured.length;
|
|
1363
|
+
files[path] = report;
|
|
1364
|
+
}
|
|
1365
|
+
return {
|
|
1366
|
+
total: missing + stale + uncaptured,
|
|
1367
|
+
missing,
|
|
1368
|
+
stale,
|
|
1369
|
+
uncaptured,
|
|
1370
|
+
files
|
|
1371
|
+
};
|
|
1372
|
+
}
|
|
1373
|
+
//#endregion
|
|
1374
|
+
export { HARNESS_MEMORY_BEGIN, HARNESS_MEMORY_END, SEALED_CONTENT_PREFIX, WorkspaceCodecError, WorkspaceConflictError, WorkspacePolicyError, aesGcmContentCodecFromEnv, assertWorkspacePath, captureHarnessMemory, checkOperationId, checkWorkspacePut, createAesGcmContentCodec, createFileTools, createInMemoryWorkspaceStore, createMemoryTools, defaultMemoryPolicy, harnessActor, ingestHarnessMemories, isSameWorkspaceWrite, memberIdFromPath, memoryDivergence, normalizeMemoryText, openWorkspaceBytes, parseHarnessActor, projectHarnessMemory, rankEntries, readTurnMemories, renderHarnessMemory, renderPinnedMemory, runWorkspaceStoreContract, sealWorkspaceBytes, withContentCodec, workspaceStoreContractCases };
|
|
854
1375
|
|
|
855
1376
|
//# sourceMappingURL=index.js.map
|