@peer-agent/runtime-core 0.0.1-beta.44 → 0.0.1-beta.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,381 @@
1
+ /**
2
+ * Goal-mode bounded keep policy.
3
+ *
4
+ * Goal compaction must preserve a *bounded* executable scene, not the entire
5
+ * current-turn tool tail. Plan/checkpoint own long-term progress; keep only
6
+ * owns protocol locality for the next recovery turn.
7
+ *
8
+ * See peer-knowledge/knowledge/architecture/24-goal-runner-context-checkpoint-and-seamless-resume.md
9
+ */
10
+ import { splitMessagesForCompaction, } from "./context-compaction.js";
11
+ import { estimateContextMessagesTokens, estimateContextTextTokens, } from "./context-projection.js";
12
+ import { microcompactMessagesForContext } from "./microcompact.js";
13
+ export const GOAL_KEEP_POLICY = Object.freeze({
14
+ maxRecentUserTurns: 2,
15
+ maxRecentMessages: 20,
16
+ maxCompletedToolResults: 4,
17
+ minKeepTokens: 4_096,
18
+ maxKeepTokens: 16_384,
19
+ keepContextRatio: 0.10,
20
+ checkpointMaxTokens: 4_096,
21
+ continuityMaxTokens: 12_000,
22
+ targetRequestRatio: 0.55,
23
+ softTriggerRatio: 0.72,
24
+ hardTriggerRatio: 0.88,
25
+ largeToolPreviewChars: 800,
26
+ largeToolTailChars: 400,
27
+ largeToolTriggerChars: 1_500,
28
+ });
29
+ function clamp(value, min, max) {
30
+ return Math.min(max, Math.max(min, value));
31
+ }
32
+ function contentBlocks(message) {
33
+ return Array.isArray(message.content)
34
+ ? message.content.filter((block) => Boolean(block && typeof block === 'object'))
35
+ : [];
36
+ }
37
+ function toolUseIds(message) {
38
+ const openAiCalls = [...(message.toolCalls ?? []), ...(message.tool_calls ?? [])]
39
+ .map((call) => call?.id)
40
+ .filter((id) => typeof id === 'string' && id.length > 0);
41
+ const anthropicCalls = contentBlocks(message)
42
+ .filter((block) => block.type === 'tool_use')
43
+ .map((block) => block.id)
44
+ .filter((id) => typeof id === 'string' && id.length > 0);
45
+ return [...openAiCalls, ...anthropicCalls];
46
+ }
47
+ function toolResultIds(message) {
48
+ const direct = message.toolCallId ?? message.tool_call_id;
49
+ const blockIds = contentBlocks(message)
50
+ .filter((block) => block.type === 'tool_result')
51
+ .map((block) => block.tool_use_id)
52
+ .filter((id) => typeof id === 'string' && id.length > 0);
53
+ return typeof direct === 'string' && direct.length > 0 ? [direct, ...blockIds] : blockIds;
54
+ }
55
+ function hasToolResult(message) {
56
+ return message.role === 'tool' || toolResultIds(message).length > 0;
57
+ }
58
+ function isHumanUserMessage(message) {
59
+ if (message.role !== 'user' || message._compaction)
60
+ return false;
61
+ const blocks = contentBlocks(message);
62
+ return blocks.length === 0 || blocks.some((block) => block.type !== 'tool_result');
63
+ }
64
+ function truncateText(text, headChars, tailChars) {
65
+ if (text.length <= headChars + tailChars + 32)
66
+ return text;
67
+ const omitted = text.length - headChars - tailChars;
68
+ return `${text.slice(0, headChars)}\n…[goal-keep truncated ${omitted} chars]…\n${text.slice(-tailChars)}`;
69
+ }
70
+ function skeletonizeValue(value, headChars, tailChars) {
71
+ if (typeof value === 'string') {
72
+ return truncateText(value, headChars, tailChars);
73
+ }
74
+ if (Array.isArray(value)) {
75
+ return value.map((item) => skeletonizeValue(item, headChars, tailChars));
76
+ }
77
+ if (value && typeof value === 'object') {
78
+ const record = value;
79
+ // local_*_ref already carries retrieval route; do not re-expand.
80
+ if (typeof record.kind === 'string' && record.kind.startsWith('local_') && record.kind.endsWith('_ref')) {
81
+ return value;
82
+ }
83
+ const next = {};
84
+ for (const [key, item] of Object.entries(record)) {
85
+ if (key === 'content' || key === 'text' || key === 'output' || key === 'stdout' || key === 'stderr') {
86
+ next[key] = skeletonizeValue(item, headChars, tailChars);
87
+ }
88
+ else if (typeof item === 'string' && item.length > headChars + tailChars) {
89
+ next[key] = truncateText(item, headChars, Math.min(tailChars, 200));
90
+ }
91
+ else {
92
+ next[key] = item;
93
+ }
94
+ }
95
+ return next;
96
+ }
97
+ return value;
98
+ }
99
+ function skeletonizeMessageContent(message, headChars, tailChars) {
100
+ if (typeof message.content === 'string') {
101
+ return {
102
+ ...message,
103
+ content: truncateText(message.content, headChars, tailChars),
104
+ };
105
+ }
106
+ if (Array.isArray(message.content)) {
107
+ return {
108
+ ...message,
109
+ content: message.content.map((block) => {
110
+ if (!block || typeof block !== 'object')
111
+ return block;
112
+ const record = block;
113
+ if (typeof record.text === 'string') {
114
+ return { ...record, text: truncateText(record.text, headChars, tailChars) };
115
+ }
116
+ if (record.content !== undefined) {
117
+ return { ...record, content: skeletonizeValue(record.content, headChars, tailChars) };
118
+ }
119
+ return record;
120
+ }),
121
+ };
122
+ }
123
+ if (message.content && typeof message.content === 'object') {
124
+ return {
125
+ ...message,
126
+ content: skeletonizeValue(message.content, headChars, tailChars),
127
+ };
128
+ }
129
+ return message;
130
+ }
131
+ /**
132
+ * Convert oversized tool-result payloads in keep to short previews / refs.
133
+ * Structure (role, tool_call_id, call/result pairing) is preserved.
134
+ */
135
+ export function skeletonizeKeepToolResults(keepMessages, options = {}) {
136
+ const headChars = options.headChars ?? GOAL_KEEP_POLICY.largeToolPreviewChars;
137
+ const tailChars = options.tailChars ?? GOAL_KEEP_POLICY.largeToolTailChars;
138
+ const triggerChars = options.triggerChars ?? GOAL_KEEP_POLICY.largeToolTriggerChars;
139
+ let changed = false;
140
+ const messages = keepMessages.map((message) => {
141
+ if (!hasToolResult(message) && message.role !== 'user') {
142
+ return message;
143
+ }
144
+ // First pass: aggressive microcompact even for latest turn.
145
+ // MICROCOMPACTION_CONFIG is a frozen literal object, so Partial<> rejects
146
+ // keepRecentCount=0 / custom thresholds. Cast through unknown intentionally.
147
+ const micro = microcompactMessagesForContext([message], {
148
+ keepRecentCount: 0,
149
+ triggerChars,
150
+ previewChars: headChars,
151
+ });
152
+ let next = (micro.messages[0] ?? message);
153
+ if ((micro.stats?.compactedCount ?? 0) > 0) {
154
+ changed = true;
155
+ }
156
+ // Second pass: hard truncate residual large payloads.
157
+ const before = JSON.stringify(next.content ?? null);
158
+ const skeletonized = skeletonizeMessageContent(next, headChars, tailChars);
159
+ const after = JSON.stringify(skeletonized.content ?? null);
160
+ if (before !== after) {
161
+ changed = true;
162
+ next = skeletonized;
163
+ }
164
+ return next;
165
+ });
166
+ return { messages, changed };
167
+ }
168
+ export function resolveGoalKeepBudget(contextWindow, config = {}) {
169
+ const policy = { ...GOAL_KEEP_POLICY, ...config };
170
+ const window = typeof contextWindow === 'number' && contextWindow > 0
171
+ ? Math.floor(contextWindow)
172
+ : null;
173
+ let keepBudgetTokens = policy.maxKeepTokens;
174
+ if (window !== null) {
175
+ keepBudgetTokens = clamp(Math.floor(window * policy.keepContextRatio), policy.minKeepTokens, policy.maxKeepTokens);
176
+ // Tiny windows: never force minKeepTokens above half the window.
177
+ keepBudgetTokens = Math.min(keepBudgetTokens, Math.max(1_024, Math.floor(window * 0.5)));
178
+ }
179
+ return {
180
+ contextWindow: window,
181
+ keepBudgetTokens,
182
+ targetRequestTokens: window === null ? null : Math.floor(window * policy.targetRequestRatio),
183
+ softTriggerTokens: window === null ? null : Math.floor(window * policy.softTriggerRatio),
184
+ hardTriggerTokens: window === null ? null : Math.floor(window * policy.hardTriggerRatio),
185
+ maxRecentUserTurns: policy.maxRecentUserTurns,
186
+ maxRecentMessages: policy.maxRecentMessages,
187
+ maxCompletedToolResults: policy.maxCompletedToolResults,
188
+ };
189
+ }
190
+ function countHumanUserTurns(messages) {
191
+ return messages.reduce((count, message) => count + (isHumanUserMessage(message) ? 1 : 0), 0);
192
+ }
193
+ function findLatestHumanAnchorIndex(messages) {
194
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
195
+ if (isHumanUserMessage(messages[index]))
196
+ return index;
197
+ }
198
+ return -1;
199
+ }
200
+ function dropLeadingOrphanToolResults(keep) {
201
+ let next = keep;
202
+ while (next.length > 0 && hasToolResult(next[0]) && toolUseIds(next[0]).length === 0) {
203
+ const firstIds = new Set(toolResultIds(next[0]));
204
+ const owned = next.some((message) => toolUseIds(message).some((id) => firstIds.has(id)));
205
+ if (owned)
206
+ break;
207
+ next = next.slice(1);
208
+ }
209
+ return next;
210
+ }
211
+ function trimKeepToLimits(keepMessages, budget) {
212
+ let keep = [...keepMessages];
213
+ // Message-count ceiling.
214
+ if (keep.length > budget.maxRecentMessages) {
215
+ keep = keep.slice(-budget.maxRecentMessages);
216
+ }
217
+ // User-turn ceiling (from the end).
218
+ while (countHumanUserTurns(keep) > budget.maxRecentUserTurns && keep.length > 1) {
219
+ // Drop from front, but never leave orphan tool results at the new head.
220
+ keep = keep.slice(1);
221
+ keep = dropLeadingOrphanToolResults(keep);
222
+ }
223
+ // Completed tool-result ceiling (keep newest N tool results).
224
+ const toolResultIndexes = [];
225
+ keep.forEach((message, index) => {
226
+ if (hasToolResult(message))
227
+ toolResultIndexes.push(index);
228
+ });
229
+ if (toolResultIndexes.length > budget.maxCompletedToolResults) {
230
+ const drop = new Set(toolResultIndexes.slice(0, toolResultIndexes.length - budget.maxCompletedToolResults));
231
+ keep = keep.filter((_, index) => !drop.has(index));
232
+ }
233
+ // If still over token budget, skeletonize tool payloads first so we do not
234
+ // erase the whole keep window just because one tool_result is huge.
235
+ if (estimateContextMessagesTokens(keep) > budget.keepBudgetTokens) {
236
+ const skeletonized = skeletonizeKeepToolResults(keep, {
237
+ headChars: GOAL_KEEP_POLICY.largeToolPreviewChars,
238
+ tailChars: GOAL_KEEP_POLICY.largeToolTailChars,
239
+ triggerChars: GOAL_KEEP_POLICY.largeToolTriggerChars,
240
+ });
241
+ keep = skeletonized.messages;
242
+ }
243
+ // Token ceiling: drop oldest keep messages until under budget, but never drop
244
+ // the latest human anchor + its trailing protocol skeleton entirely.
245
+ while (keep.length > 1 && estimateContextMessagesTokens(keep) > budget.keepBudgetTokens) {
246
+ const anchorIndex = findLatestHumanAnchorIndex(keep);
247
+ // If the first message is at/after the anchor, further drops would remove
248
+ // the recovery scene; stop and leave residual (already skeletonized).
249
+ if (anchorIndex <= 0)
250
+ break;
251
+ keep = keep.slice(1);
252
+ keep = dropLeadingOrphanToolResults(keep);
253
+ }
254
+ // Final protocol hygiene: if we still start with orphan tool results, drop them.
255
+ keep = dropLeadingOrphanToolResults(keep);
256
+ // Absolute fallback: never return an empty keep when input was non-empty.
257
+ if (keep.length === 0 && keepMessages.length > 0) {
258
+ const anchorIndex = findLatestHumanAnchorIndex(keepMessages);
259
+ if (anchorIndex >= 0) {
260
+ keep = keepMessages.slice(anchorIndex);
261
+ }
262
+ else {
263
+ keep = keepMessages.slice(-1);
264
+ }
265
+ const skeletonized = skeletonizeKeepToolResults(keep, {
266
+ headChars: 300,
267
+ tailChars: 120,
268
+ triggerChars: 400,
269
+ });
270
+ keep = skeletonized.messages;
271
+ }
272
+ return keep;
273
+ }
274
+ /**
275
+ * Select a Goal-mode keep window with hard bounds.
276
+ *
277
+ * recoveryLevel:
278
+ * - 0/1/2: normal bounded keep (turn/message/token limits)
279
+ * - 3: aggressive tool microcompact/skeletonize inside keep
280
+ * - 4: closed tool results → skeleton only (same pass, more aggressive)
281
+ * - 5: shrink to latest human anchor + open tool skeleton
282
+ * - 6+: same as 5 (further levels belong to tools/system projection outside keep)
283
+ */
284
+ export function selectGoalKeepMessages(messages, options = {}) {
285
+ const recoveryLevel = (options.recoveryLevel ?? 0);
286
+ const budget = resolveGoalKeepBudget(options.contextWindow, options.config);
287
+ const policy = { ...GOAL_KEEP_POLICY, ...(options.config ?? {}) };
288
+ const baseSplit = splitMessagesForCompaction(messages, {
289
+ preserveLatestUserTurn: true,
290
+ // Goal mode preserves a short recent window, not only 1 turn.
291
+ preserveRecentTurns: Math.max(1, budget.maxRecentUserTurns),
292
+ });
293
+ let keepMessages = [...baseSplit.keepMessages];
294
+ let oldMessages = [...baseSplit.oldMessages];
295
+ let degraded = false;
296
+ let reason = 'bounded_recent_window';
297
+ // Always apply hard ceilings.
298
+ const beforeTrimTokens = estimateContextMessagesTokens(keepMessages);
299
+ keepMessages = trimKeepToLimits(keepMessages, budget);
300
+ if (estimateContextMessagesTokens(keepMessages) < beforeTrimTokens) {
301
+ degraded = true;
302
+ reason = 'trimmed_to_keep_budget';
303
+ }
304
+ // Recompute old as "everything conversational not in keep" while preserving order.
305
+ if (keepMessages.length > 0) {
306
+ const keepSet = new Set(keepMessages);
307
+ const systemMessages = baseSplit.systemMessages;
308
+ const conversation = messages.filter((message) => message.role !== 'system');
309
+ oldMessages = conversation.filter((message) => !keepSet.has(message));
310
+ // system messages remain separate
311
+ void systemMessages;
312
+ }
313
+ if (recoveryLevel >= 3) {
314
+ const skeleton = skeletonizeKeepToolResults(keepMessages, {
315
+ headChars: recoveryLevel >= 4
316
+ ? Math.min(400, policy.largeToolPreviewChars)
317
+ : policy.largeToolPreviewChars,
318
+ tailChars: recoveryLevel >= 4
319
+ ? Math.min(200, policy.largeToolTailChars)
320
+ : policy.largeToolTailChars,
321
+ triggerChars: recoveryLevel >= 4 ? 800 : policy.largeToolTriggerChars,
322
+ });
323
+ keepMessages = skeleton.messages;
324
+ if (skeleton.changed) {
325
+ degraded = true;
326
+ reason = recoveryLevel >= 4 ? 'tool_results_refs_only' : 'aggressive_keep_microcompact';
327
+ }
328
+ // Re-trim after skeletonize (usually not needed, but keeps invariant).
329
+ keepMessages = trimKeepToLimits(keepMessages, budget);
330
+ }
331
+ if (recoveryLevel >= 5) {
332
+ // Shrink to latest human anchor + trailing open-tool skeleton.
333
+ let anchorIndex = -1;
334
+ for (let index = keepMessages.length - 1; index >= 0; index -= 1) {
335
+ if (isHumanUserMessage(keepMessages[index])) {
336
+ anchorIndex = index;
337
+ break;
338
+ }
339
+ }
340
+ if (anchorIndex >= 0) {
341
+ const anchor = keepMessages[anchorIndex];
342
+ const tail = keepMessages.slice(anchorIndex + 1);
343
+ // Keep only tool calls/results after anchor (protocol skeleton), drop other assistant prose if needed.
344
+ const skeletonTail = tail.filter((message) => (toolUseIds(message).length > 0
345
+ || hasToolResult(message)
346
+ || message.role === 'assistant'));
347
+ keepMessages = [anchor, ...skeletonTail];
348
+ const skeletonized = skeletonizeKeepToolResults(keepMessages, {
349
+ headChars: 300,
350
+ tailChars: 120,
351
+ triggerChars: 400,
352
+ });
353
+ keepMessages = trimKeepToLimits(skeletonized.messages, {
354
+ ...budget,
355
+ // At L5, force a tighter budget: half of keepBudget, min 1k.
356
+ keepBudgetTokens: Math.max(1_024, Math.floor(budget.keepBudgetTokens / 2)),
357
+ maxRecentMessages: Math.min(budget.maxRecentMessages, 8),
358
+ maxCompletedToolResults: Math.min(budget.maxCompletedToolResults, 2),
359
+ });
360
+ degraded = true;
361
+ reason = 'anchor_plus_open_tool_skeleton';
362
+ }
363
+ }
364
+ const keepTokens = estimateContextMessagesTokens(keepMessages);
365
+ return {
366
+ systemMessages: [...baseSplit.systemMessages],
367
+ oldMessages,
368
+ keepMessages,
369
+ keepBudgetTokens: budget.keepBudgetTokens,
370
+ keepTokens,
371
+ recoveryLevel,
372
+ degraded,
373
+ reason,
374
+ };
375
+ }
376
+ export function estimateGoalKeepTokens(messages) {
377
+ return estimateContextMessagesTokens(messages);
378
+ }
379
+ export function estimateGoalKeepTextTokens(text) {
380
+ return estimateContextTextTokens(text);
381
+ }
package/dist/index.d.ts CHANGED
@@ -8,6 +8,9 @@ export * from './projection.ts';
8
8
  export * from './projection-materializers.ts';
9
9
  export * from './local-tool-contracts.ts';
10
10
  export * from './context-compaction.ts';
11
+ export * from './goal-keep-policy.ts';
12
+ export * from './goal-checkpoint.ts';
13
+ export * from './goal-idempotency.ts';
11
14
  export * from './compaction-progress.ts';
12
15
  export * from './microcompact.ts';
13
16
  export * from './context-projection.ts';
package/dist/index.js CHANGED
@@ -8,6 +8,9 @@ export * from "./projection.js";
8
8
  export * from "./projection-materializers.js";
9
9
  export * from "./local-tool-contracts.js";
10
10
  export * from "./context-compaction.js";
11
+ export * from "./goal-keep-policy.js";
12
+ export * from "./goal-checkpoint.js";
13
+ export * from "./goal-idempotency.js";
11
14
  export * from "./compaction-progress.js";
12
15
  export * from "./microcompact.js";
13
16
  export * from "./context-projection.js";
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Browser-safe crypto helpers for runtime-core pure modules.
3
+ * Avoid node:crypto so Vite renderer can import the package barrel.
4
+ */
5
+ /**
6
+ * Synchronous SHA-256 hex digest (pure JS, isomorphic).
7
+ */
8
+ export declare function sha256Hex(input: string): string;
9
+ /**
10
+ * UUID v4-ish id. Uses Web Crypto when available (browser + modern Node).
11
+ */
12
+ export declare function randomId(): string;
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Browser-safe crypto helpers for runtime-core pure modules.
3
+ * Avoid node:crypto so Vite renderer can import the package barrel.
4
+ */
5
+ function rightRotate(value, amount) {
6
+ return (value >>> amount) | (value << (32 - amount));
7
+ }
8
+ /**
9
+ * Synchronous SHA-256 hex digest (pure JS, isomorphic).
10
+ */
11
+ export function sha256Hex(input) {
12
+ const bytes = new TextEncoder().encode(input);
13
+ const bitLen = bytes.length * 8;
14
+ const withOne = bytes.length + 1;
15
+ const totalLen = ((withOne + 8 + 63) & ~63);
16
+ const buffer = new Uint8Array(totalLen);
17
+ buffer.set(bytes);
18
+ buffer[bytes.length] = 0x80;
19
+ const view = new DataView(buffer.buffer);
20
+ // length in bits as 64-bit big-endian at end
21
+ // JS strings used here are < 2^53 bits in practice; high word stays 0
22
+ view.setUint32(totalLen - 4, bitLen >>> 0, false);
23
+ const k = new Uint32Array([
24
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
25
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
26
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
27
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
28
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
29
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
30
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
31
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
32
+ ]);
33
+ let h0 = 0x6a09e667;
34
+ let h1 = 0xbb67ae85;
35
+ let h2 = 0x3c6ef372;
36
+ let h3 = 0xa54ff53a;
37
+ let h4 = 0x510e527f;
38
+ let h5 = 0x9b05688c;
39
+ let h6 = 0x1f83d9ab;
40
+ let h7 = 0x5be0cd19;
41
+ const w = new Uint32Array(64);
42
+ for (let offset = 0; offset < totalLen; offset += 64) {
43
+ for (let i = 0; i < 16; i += 1) {
44
+ w[i] = view.getUint32(offset + i * 4, false);
45
+ }
46
+ for (let i = 16; i < 64; i += 1) {
47
+ const s0 = rightRotate(w[i - 15], 7) ^ rightRotate(w[i - 15], 18) ^ (w[i - 15] >>> 3);
48
+ const s1 = rightRotate(w[i - 2], 17) ^ rightRotate(w[i - 2], 19) ^ (w[i - 2] >>> 10);
49
+ w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
50
+ }
51
+ let a = h0;
52
+ let b = h1;
53
+ let c = h2;
54
+ let d = h3;
55
+ let e = h4;
56
+ let f = h5;
57
+ let g = h6;
58
+ let h = h7;
59
+ for (let i = 0; i < 64; i += 1) {
60
+ const S1 = rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25);
61
+ const ch = (e & f) ^ (~e & g);
62
+ const temp1 = (h + S1 + ch + k[i] + w[i]) >>> 0;
63
+ const S0 = rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22);
64
+ const maj = (a & b) ^ (a & c) ^ (b & c);
65
+ const temp2 = (S0 + maj) >>> 0;
66
+ h = g;
67
+ g = f;
68
+ f = e;
69
+ e = (d + temp1) >>> 0;
70
+ d = c;
71
+ c = b;
72
+ b = a;
73
+ a = (temp1 + temp2) >>> 0;
74
+ }
75
+ h0 = (h0 + a) >>> 0;
76
+ h1 = (h1 + b) >>> 0;
77
+ h2 = (h2 + c) >>> 0;
78
+ h3 = (h3 + d) >>> 0;
79
+ h4 = (h4 + e) >>> 0;
80
+ h5 = (h5 + f) >>> 0;
81
+ h6 = (h6 + g) >>> 0;
82
+ h7 = (h7 + h) >>> 0;
83
+ }
84
+ return [h0, h1, h2, h3, h4, h5, h6, h7]
85
+ .map((value) => value.toString(16).padStart(8, '0'))
86
+ .join('');
87
+ }
88
+ /**
89
+ * UUID v4-ish id. Uses Web Crypto when available (browser + modern Node).
90
+ */
91
+ export function randomId() {
92
+ const c = globalThis.crypto;
93
+ if (c && typeof c.randomUUID === 'function') {
94
+ return c.randomUUID();
95
+ }
96
+ if (c && typeof c.getRandomValues === 'function') {
97
+ const bytes = new Uint8Array(16);
98
+ c.getRandomValues(bytes);
99
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
100
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
101
+ const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
102
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
103
+ }
104
+ // Last-resort non-crypto fallback for exotic runtimes.
105
+ let out = '';
106
+ for (let i = 0; i < 36; i += 1) {
107
+ if (i === 8 || i === 13 || i === 18 || i === 23) {
108
+ out += '-';
109
+ }
110
+ else if (i === 14) {
111
+ out += '4';
112
+ }
113
+ else {
114
+ const r = (Math.random() * 16) | 0;
115
+ out += (i === 19 ? (r & 0x3) | 0x8 : r).toString(16);
116
+ }
117
+ }
118
+ return out;
119
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peer-agent/runtime-core",
3
- "version": "0.0.1-beta.44",
3
+ "version": "0.0.1-beta.45",
4
4
  "description": "Host-neutral capability, permission, projection, and Evidence primitives for Peer Agent runtimes.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -26,6 +26,10 @@
26
26
  ".": {
27
27
  "types": "./dist/index.d.ts",
28
28
  "default": "./dist/index.js"
29
+ },
30
+ "./goal-idempotency-durable": {
31
+ "types": "./dist/goal-idempotency-durable.d.ts",
32
+ "default": "./dist/goal-idempotency-durable.js"
29
33
  }
30
34
  },
31
35
  "files": [
@@ -34,7 +38,7 @@
34
38
  "LICENSE"
35
39
  ],
36
40
  "dependencies": {
37
- "@peer-agent/protocol": "0.0.1-beta.44"
41
+ "@peer-agent/protocol": "0.0.1-beta.45"
38
42
  },
39
43
  "devDependencies": {
40
44
  "typescript": "^5.9.3"