granttap-mcp 0.8.130 → 0.8.132

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.
@@ -15,7 +15,6 @@ import { abortProcesses, runProcess } from "./process";
15
15
  import { routingPrompt } from "./payload/routing";
16
16
  import type { DeliveryOptions, ReplyResult } from "./payload/types";
17
17
  import { deliveryIntent } from './payload/identity';
18
- import {NativeTurnCompletions, type NativeCompletionProof} from './native-completion';
19
18
  import {
20
19
  runCursorNew,
21
20
  runCursorResume,
@@ -35,14 +34,11 @@ export function resolveAgentWorkspace(cwd: string | undefined, agent: CodingAgen
35
34
  }
36
35
 
37
36
  const inFlight = new Map<string, Promise<ReplyResult | null>>();
38
- const physicalRuns = new Set<Promise<ReplyResult>>();
39
- const nativeCompletions = new NativeTurnCompletions();
40
37
 
41
38
  export function isDeliveryInFlight(sessionId: string): boolean { return inFlight.has(sessionId); }
42
39
 
43
40
  /** Acknowledging a message does not finish the provider turn or permit a runtime handoff. */
44
- export function hasPendingDeliveries(): boolean { return inFlight.size > 0 || physicalRuns.size > 0; }
45
- export const completeObservedNativeTurn = (key: string, proof: NativeCompletionProof) => nativeCompletions.complete(key, proof);
41
+ export function hasPendingDeliveries(): boolean { return inFlight.size > 0; }
46
42
 
47
43
  /** Request a stop for owned processes; confirmation arrives only on process exit. */
48
44
  export function stopDeliveries(sessionId: string): number {
@@ -168,14 +164,7 @@ export function createGrokSession(
168
164
 
169
165
  function queued(key: string, run: () => Promise<ReplyResult>): Promise<ReplyResult> {
170
166
  const previous = inFlight.get(key) ?? Promise.resolve(null);
171
- const next = previous.then(async () => {
172
- const native = nativeCompletions.begin(key);
173
- const physical = Promise.resolve().then(run);
174
- physicalRuns.add(physical);
175
- void physical.then(() => physicalRuns.delete(physical), () => physicalRuns.delete(physical));
176
- try { return await Promise.race([physical, native.result]); }
177
- finally { native.close(); }
178
- });
167
+ const next = previous.then(run);
179
168
  const settled = next.finally(() => {
180
169
  if (inFlight.get(key) === tracked) inFlight.delete(key);
181
170
  });
@@ -205,8 +194,6 @@ function runClaude(
205
194
  timeoutMs: number,
206
195
  options: DeliveryOptions,
207
196
  ): Promise<ReplyResult> {
208
- nativeCompletions.bind(session.sessionId, text, key => localTaskTransfers()
209
- .nativeSession({...session, sessionId: key}).sessionId);
210
197
  const disabled = loadRuntimeConfig().sessionMcpDisabled[session.sessionId] ?? [];
211
198
  const mcpArgs = disabled.length === 0
212
199
  ? []
@@ -45,7 +45,7 @@ an independently delivered completion. Runtime handoff also waits for owned
45
45
  provider turns to settle, including work already acknowledged to the phone.
46
46
 
47
47
  Fast open-chat heads use bounded native root pages. Closed chats and child
48
- conversations remain on their independent refresh/request paths. A Claude final
49
- can finish its matched logical turn while its physical CLI drains background
50
- work: native identity, exact routed prompt hash and prompt/final timestamps must
51
- all match. Physical processes remain tracked for Stop and runtime handoff.
48
+ conversations remain on their independent refresh/request paths. A model
49
+ end-turn record describes presentation; a CLI invocation may still own background
50
+ work. Queue admission and runtime handoff keep the physical-invocation guard
51
+ until that invocation returns its result.
@@ -11,12 +11,10 @@ import {observeCodexTurn,codexTurnState,type CodexTurnClock} from '../sessions/s
11
11
  import {ts} from '../sessions/support/common';
12
12
  import {grokResumeActivity} from '../providers/grok-activity';
13
13
  import {cursorConversationSession} from '../sessions/cursor';
14
- import {nativePromptDigest, type NativeCompletionProof} from '../reply/native-completion';
15
14
 
16
- type NativeClock={revision:string;identity:string;bytes:number;lastActivityAt:number;claude:ClaudeTurnClock;codex:CodexTurnClock;
17
- promptAt:number;promptDigests:string[];completion?:NativeCompletionProof};
15
+ type NativeClock={revision:string;lastActivityAt:number;claude:ClaudeTurnClock;codex:CodexTurnClock};
18
16
  const clocks=new Map<string,NativeClock>();
19
- export type SessionObservation={session:SessionInfo;revision:string;completion?:NativeCompletionProof};
17
+ export type SessionObservation={session:SessionInfo;revision:string};
20
18
 
21
19
  /** Discovery may have started before an open chat finished its turn. Recheck before publication. */
22
20
  export function refreshObservedCatalog(status: SessionsStatus): SessionsStatus {
@@ -49,22 +47,12 @@ export function observeSessionExecution(input:SessionInfo):SessionObservation|un
49
47
  let clock=clocks.get(key);
50
48
  if(clock?.revision!==revision){
51
49
  const window=previousNativeLines(path,native.sessionId);if(!window)return;
52
- const identity = `${stat.dev}:${stat.ino}`;
53
- const append = clock?.identity === identity && stat.size > clock.bytes;
54
- clock={revision,identity,bytes:stat.size,lastActivityAt:0,claude:append?{...clock!.claude}:{},codex:{},
55
- promptAt:append?clock!.promptAt:0,promptDigests:append?clock!.promptDigests:[],completion:append?clock!.completion:undefined};
50
+ clock={revision,lastActivityAt:0,claude:{},codex:{}};
56
51
  for(const line of window.lines){
57
52
  let row;try{row=JSON.parse(line.text)}catch{continue}
58
53
  if(row.isSidechain===true||row.sessionId&&row.sessionId!==native.sessionId)continue;
59
54
  clock.lastActivityAt=Math.max(clock.lastActivityAt,ts(row.timestamp));
60
- if(native.agent==='claude'){
61
- observeClaudeTurn(row,clock.claude);
62
- const content=row.message?.content;
63
- const texts=typeof content==='string'?[content]:Array.isArray(content)?content.filter(b=>b?.type==='text'&&typeof b.text==='string').map(b=>b.text):[];
64
- if(row.type==='user'&&texts.length){clock.promptAt=ts(row.timestamp);clock.promptDigests=[...texts,texts.join('\n')].map(nativePromptDigest)}
65
- if(row.type==='assistant'&&clock.claude.turnEnded)clock.completion={nativeSessionId:native.sessionId,
66
- promptAt:clock.promptAt,promptDigests:clock.promptDigests,completedAt:ts(row.timestamp),text:texts.join('\n')};
67
- }else observeCodexTurn(row,clock.codex);
55
+ if(native.agent==='claude')observeClaudeTurn(row,clock.claude);else observeCodexTurn(row,clock.codex);
68
56
  }
69
57
  clocks.delete(key);clocks.set(key,clock);
70
58
  while(clocks.size>256)clocks.delete(clocks.keys().next().value!);
@@ -72,7 +60,6 @@ export function observeSessionExecution(input:SessionInfo):SessionObservation|un
72
60
  const at=Math.max(input.lastActivityAt,clock!.lastActivityAt);
73
61
  const state=native.agent==='claude'?claudeTurnState(clock!.claude,at,input.state)
74
62
  :clock!.codex.startedAt||clock!.codex.endedAt?codexTurnState(clock!.codex,at):input.state;
75
- return {session:{...input,state,lastActivityAt:at},revision:`${revision}:${state}`,
76
- ...(native.agent==='claude'&&clock!.claude.turnEnded&&clock!.completion?{completion:clock!.completion}:{})};
63
+ return {session:{...input,state,lastActivityAt:at},revision:`${revision}:${state}`};
77
64
  }catch{return;}
78
65
  }
@@ -1,12 +1,12 @@
1
1
  import { join } from 'node:path';
2
2
  import type { PeerConfig, RelayClient } from '../../../../../packages/core/relay-client';
3
3
  import { configDir, isSessionPaused } from '../../config';
4
- import { completeObservedNativeTurn, isDeliveryInFlight } from '../../reply';
4
+ import { isDeliveryInFlight } from '../../reply';
5
5
  import { publishedCatalog } from '../../session-catalog';
6
6
  import { handleUserMessage } from '../../monitor/handlers/user-message';
7
7
  import { handleTaskCreate } from '../../monitor/handlers/task-create';
8
8
  import { TaskDispatchInbox } from '../index';
9
- import { TaskDispatchWorker } from './index';
9
+ import { TaskDispatchWorker, type TaskJobRemote, type WorkerOptions } from './index';
10
10
  import { relayTaskJobRemote } from './remote';
11
11
  import { NativeTaskQueueSender } from '../sender';
12
12
  import { dispatchSessionObservation, queuedCatalogRefreshDue, taskDispatchReady } from './readiness';
@@ -16,6 +16,7 @@ import { localTaskOrigins, resolveTaskOriginJob } from '../../task-origins';
16
16
  export function startTaskDispatchMonitor(input: {
17
17
  config: PeerConfig; client: RelayClient; isLeader: () => boolean;
18
18
  peerAllowed: (peer: string) => boolean; publish: () => Promise<void>;
19
+ remote?: TaskJobRemote; deliver?: WorkerOptions['deliver'];
19
20
  }): () => void {
20
21
  const inbox = new TaskDispatchInbox(join(configDir(), 'task-dispatch'), input.config.room);
21
22
  const origins = localTaskOrigins();
@@ -24,7 +25,7 @@ export function startTaskDispatchMonitor(input: {
24
25
  let stopped = false, reportedAt = 0, maintainedAt = 0, refreshedAt = 0;
25
26
  const sender = new NativeTaskQueueSender({ root: join(configDir(), 'native-task-queue'), config: input.config });
26
27
  const peerAllowed = (peer: string) => peer === input.config.myPublicKey || input.peerAllowed(peer);
27
- const worker = new TaskDispatchWorker({ inbox, remote: relayTaskJobRemote(input.config),
28
+ const worker = new TaskDispatchWorker({ inbox, remote: input.remote ?? relayTaskJobRemote(input.config),
28
29
  connected: () => !stopped && input.client.isConnected && input.isLeader(),
29
30
  authorized: peerAllowed,
30
31
  onTerminal: job => sender.confirmReceiverOutcome(job),
@@ -43,9 +44,7 @@ export function startTaskDispatchMonitor(input: {
43
44
  const catalog = publishedCatalog(input.client);
44
45
  const session = [...(catalog?.sessions ?? []), ...(catalog?.history ?? [])]
45
46
  .find(item => item.sessionId === job.sessionId);
46
- const native = dispatchSessionObservation(session, catalog?.generatedAt);
47
- if (job.sessionId && native.completion) completeObservedNativeTurn(job.sessionId, native.completion);
48
- const observation = { ...native,
47
+ const observation = { ...dispatchSessionObservation(session, catalog?.generatedAt),
49
48
  inFlight: isDeliveryInFlight(job.sessionId ?? `__new_${job.operation.agent ?? 'codex'}_task__`),
50
49
  paused: !!job.sessionId && isSessionPaused(job.sessionId) };
51
50
  const ready = taskDispatchReady(job, observation);
@@ -56,6 +55,7 @@ export function startTaskDispatchMonitor(input: {
56
55
  return ready;
57
56
  },
58
57
  deliver: async (original, beforeStart, peer) => {
58
+ if (input.deliver) return input.deliver(original, beforeStart, peer);
59
59
  const job = resolve(original, peer).job;
60
60
  if (!job || job.operation.type === 'user.message.continue') return 'rejected';
61
61
  const outcome = job.operation.type === 'user.message'
@@ -5,7 +5,7 @@ import { observeSessionExecution } from '../../session-catalog/observed-state';
5
5
  export function dispatchSessionObservation(session: SessionInfo | undefined, generatedAt?: number) {
6
6
  const fresh = session && observeSessionExecution(session);
7
7
  return { session: fresh?.session ?? session, generatedAt: fresh ? Date.now() : generatedAt,
8
- nativeState: fresh?.session.state, completion: fresh?.completion };
8
+ nativeState: fresh?.session.state };
9
9
  }
10
10
 
11
11
  /** Manual release bypasses busy state only. Pause, native admission and policy still win. */
@@ -10,7 +10,7 @@ keeps each phone response tied to the exact originating chat and prompt.
10
10
  Install the supported CLI on this computer, then run:
11
11
 
12
12
  ```bash
13
- npm install -g granttap-mcp@0.8.130
13
+ npm install -g granttap-mcp@0.8.132
14
14
  granttap setup
15
15
  granttap status
16
16
  ```
@@ -4,7 +4,7 @@
4
4
  "command": "node",
5
5
  "args": [
6
6
  "-e",
7
- "\"use strict\";\n\n// Cursor may start this MCP from any cwd. Execute JavaScript entry points with\n// Node itself: Windows batch shims require shell quoting that differs by host.\nconst { spawn } = require(\"node:child_process\");\nconst { existsSync } = require(\"node:fs\");\nconst { delimiter, dirname, join } = require(\"node:path\");\n\nconst PACKAGE = \"granttap-mcp@0.8.130\";\nconst dryRun = process.env.GRANTTAP_BOOTSTRAP_DRY_RUN === \"1\";\nconst platform = dryRun && process.env.GRANTTAP_BOOTSTRAP_PLATFORM\n ? process.env.GRANTTAP_BOOTSTRAP_PLATFORM : process.platform;\nconst nodeRoot = dryRun && process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT\n ? process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT : dirname(process.execPath);\nconst pathRoots = (process.env.PATH || \"\").split(delimiter).filter(Boolean);\nconst appData = process.env.APPDATA;\nconst roots = [nodeRoot, ...pathRoots, ...(appData ? [join(appData, \"npm\")] : [])];\nconst first = (paths) => paths.find((path) => existsSync(path));\n\nfunction launch() {\n if (platform !== \"win32\") {\n const installed = first(roots.map((root) => join(root, \"granttap-mcp\")));\n if (installed) return { command: installed, args: [] };\n const npx = first(roots.map((root) => join(root, \"npx\"))) || \"npx\";\n return { command: npx, args: [\"-y\", PACKAGE] };\n }\n const installed = first(roots.map((root) =>\n join(root, \"node_modules\", \"granttap-mcp\", \"bin\", \"granttap-mcp.mjs\")));\n if (installed) return { command: process.execPath, args: [installed] };\n const npx = first(roots.map((root) =>\n join(root, \"node_modules\", \"npm\", \"bin\", \"npx-cli.js\")));\n if (npx) return { command: process.execPath, args: [npx, \"-y\", PACKAGE] };\n throw new Error(\"Node.js/npm 22.13.0+ is required on this Windows device. Install npm and retry GrantTap.\");\n}\n\nlet target;\ntry { target = launch(); }\ncatch (error) {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n}\n\nif (dryRun) {\n process.stdout.write(JSON.stringify(target));\n process.exit(0);\n}\n\nconst child = spawn(target.command, target.args, { stdio: \"inherit\", windowsHide: true });\nchild.on(\"error\", (error) => {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n});\nchild.on(\"exit\", (code, signal) => {\n if (signal && platform !== \"win32\") {\n try { process.kill(process.pid, signal); } catch { process.exit(code ?? 1); }\n return;\n }\n process.exit(code ?? 1);\n});\n"
7
+ "\"use strict\";\n\n// Cursor may start this MCP from any cwd. Execute JavaScript entry points with\n// Node itself: Windows batch shims require shell quoting that differs by host.\nconst { spawn } = require(\"node:child_process\");\nconst { existsSync } = require(\"node:fs\");\nconst { delimiter, dirname, join } = require(\"node:path\");\n\nconst PACKAGE = \"granttap-mcp@0.8.132\";\nconst dryRun = process.env.GRANTTAP_BOOTSTRAP_DRY_RUN === \"1\";\nconst platform = dryRun && process.env.GRANTTAP_BOOTSTRAP_PLATFORM\n ? process.env.GRANTTAP_BOOTSTRAP_PLATFORM : process.platform;\nconst nodeRoot = dryRun && process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT\n ? process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT : dirname(process.execPath);\nconst pathRoots = (process.env.PATH || \"\").split(delimiter).filter(Boolean);\nconst appData = process.env.APPDATA;\nconst roots = [nodeRoot, ...pathRoots, ...(appData ? [join(appData, \"npm\")] : [])];\nconst first = (paths) => paths.find((path) => existsSync(path));\n\nfunction launch() {\n if (platform !== \"win32\") {\n const installed = first(roots.map((root) => join(root, \"granttap-mcp\")));\n if (installed) return { command: installed, args: [] };\n const npx = first(roots.map((root) => join(root, \"npx\"))) || \"npx\";\n return { command: npx, args: [\"-y\", PACKAGE] };\n }\n const installed = first(roots.map((root) =>\n join(root, \"node_modules\", \"granttap-mcp\", \"bin\", \"granttap-mcp.mjs\")));\n if (installed) return { command: process.execPath, args: [installed] };\n const npx = first(roots.map((root) =>\n join(root, \"node_modules\", \"npm\", \"bin\", \"npx-cli.js\")));\n if (npx) return { command: process.execPath, args: [npx, \"-y\", PACKAGE] };\n throw new Error(\"Node.js/npm 22.13.0+ is required on this Windows device. Install npm and retry GrantTap.\");\n}\n\nlet target;\ntry { target = launch(); }\ncatch (error) {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n}\n\nif (dryRun) {\n process.stdout.write(JSON.stringify(target));\n process.exit(0);\n}\n\nconst child = spawn(target.command, target.args, { stdio: \"inherit\", windowsHide: true });\nchild.on(\"error\", (error) => {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n});\nchild.on(\"exit\", (code, signal) => {\n if (signal && platform !== \"win32\") {\n try { process.kill(process.pid, signal); } catch { process.exit(code ?? 1); }\n return;\n }\n process.exit(code ?? 1);\n});\n"
8
8
  ]
9
9
  }
10
10
  }
@@ -7,7 +7,7 @@ const { spawn } = require("node:child_process");
7
7
  const { existsSync } = require("node:fs");
8
8
  const { delimiter, dirname, join } = require("node:path");
9
9
 
10
- const PACKAGE = "granttap-mcp@0.8.130";
10
+ const PACKAGE = "granttap-mcp@0.8.132";
11
11
  const dryRun = process.env.GRANTTAP_BOOTSTRAP_DRY_RUN === "1";
12
12
  const platform = dryRun && process.env.GRANTTAP_BOOTSTRAP_PLATFORM
13
13
  ? process.env.GRANTTAP_BOOTSTRAP_PLATFORM : process.platform;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "granttap-mcp",
3
- "version": "0.8.130",
3
+ "version": "0.8.132",
4
4
  "description": "Commercial computer runtime connecting local coding agents to GrantTap on Mac, iPhone, iPad and Apple Watch.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -11,6 +11,8 @@
11
11
  * QR code scanned by the phone). Nothing here ever leaves the device unsealed.
12
12
  */
13
13
  import nacl from "tweetnacl";
14
+ import {sharedBoxKey} from './shared-box';
15
+ export {clearSharedBoxKeys} from './shared-box';
14
16
 
15
17
  export type KeyPair = { publicKey: string; secretKey: string }; // base64
16
18
 
@@ -30,7 +32,7 @@ export function seal(
30
32
  ): { nonce: string; box: string } {
31
33
  const msg = new TextEncoder().encode(JSON.stringify(payload));
32
34
  const nonce = nacl.randomBytes(nacl.box.nonceLength);
33
- const box = nacl.box(msg, nonce, ub64(theirPublicKey), ub64(mySecretKey));
35
+ const box = nacl.box.after(msg, nonce, sharedBoxKey(theirPublicKey, mySecretKey));
34
36
  return { nonce: b64(nonce), box: b64(box) };
35
37
  }
36
38
 
@@ -52,7 +54,7 @@ export function open(
52
54
  ): unknown | null {
53
55
  let opened: Uint8Array | null = null;
54
56
  try {
55
- opened = nacl.box.open(ub64(box), ub64(nonce), ub64(theirPublicKey), ub64(mySecretKey));
57
+ opened = nacl.box.open.after(ub64(box), ub64(nonce), sharedBoxKey(theirPublicKey, mySecretKey));
56
58
  } catch {
57
59
  return null;
58
60
  }
@@ -6,7 +6,7 @@ import { OutboundFrameQueue, sendEncryptedPayload, priorityControlPayload } from
6
6
  import { openRelayMessage, parseRelayControl, waitForRelayPayload } from "./relay-inbound";
7
7
  import { consumeTaskJobOffer, type TaskDispatchListener } from "./task-dispatch";
8
8
  import { Payload, type Role } from "../protocol/schema";
9
- import { peerPublicKeys } from "./crypto";
9
+ import { clearSharedBoxKeys, peerPublicKeys } from "./crypto";
10
10
  import type { PeerConfig, RelayClientOptions, SendOptions } from "./relay-client-types";
11
11
  export type { PeerConfig, RelayClientOptions, SendOptions } from "./relay-client-types";
12
12
  import { RelayMessageAcceptance } from "./replay-store";
@@ -264,6 +264,7 @@ export class RelayClient {
264
264
  }
265
265
 
266
266
  close(): void {
267
+ clearSharedBoxKeys();
267
268
  this.frames?.cancel();
268
269
  this.socketHealth.stop();
269
270
  this.admissionLease.stop();
@@ -0,0 +1,15 @@
1
+ # Shared NaCl box keys
2
+
3
+ Repeated device envelopes reuse NaCl's documented `box.before` precomputation.
4
+ `box.after` and `box.open.after` produce and read the existing NaCl wire format;
5
+ every envelope still uses a fresh random nonce. Both devices' key bytes identify
6
+ the cache entry, so key rotation cannot select an older pairing's shared key.
7
+
8
+ The process-local LRU holds at most 64 keys for 60 seconds of monotonic time.
9
+ Expiration is enforced on lookup. Eviction, expiry and explicit transport close
10
+ zero the cached key material. Decoded private-key scratch buffers are zeroed on
11
+ each lookup; cache identifiers are SHA-256 digests, not raw private keys.
12
+
13
+ Tests in `tests/` cover direct NaCl interoperability, rotation, authentication,
14
+ fresh nonces, bounded derivation and erasure. This module uses the
15
+ GrantTap Commercial Source License.
@@ -0,0 +1,39 @@
1
+ import {createHash} from 'node:crypto';
2
+ import {performance} from 'node:perf_hooks';
3
+ import nacl from 'tweetnacl';
4
+
5
+ /** Bounded, process-local NaCl precomputation; raw private keys never become cache identities. */
6
+ export function createSharedBoxCache(options: {
7
+ capacity?: number; ttlMs?: number; now?: () => number;
8
+ derive?: (publicKey: Uint8Array, secretKey: Uint8Array) => Uint8Array;
9
+ } = {}) {
10
+ const capacity = Number.isSafeInteger(options.capacity) && options.capacity! > 0 ? Math.min(256, options.capacity!) : 64;
11
+ const ttlMs = Number.isFinite(options.ttlMs) && options.ttlMs! > 0 ? options.ttlMs! : 60_000;
12
+ const now = options.now ?? (() => performance.now()), derive = options.derive ?? nacl.box.before;
13
+ const entries = new Map<string, {key: Uint8Array; expiresAt: number}>();
14
+ return {
15
+ get(publicKey: string, secretKey: string): Uint8Array {
16
+ const pub = Buffer.from(publicKey, 'base64'), secret = Buffer.from(secretKey, 'base64');
17
+ try {
18
+ if (pub.length !== nacl.box.publicKeyLength) throw Error('bad public key size');
19
+ if (secret.length !== nacl.box.secretKeyLength) throw Error('bad secret key size');
20
+ const identity = createHash('sha256').update(pub).update(secret).digest('hex'), at = now();
21
+ const hit = entries.get(identity);
22
+ if (hit && hit.expiresAt > at) {entries.delete(identity); entries.set(identity, hit); return hit.key}
23
+ for (const [id, entry] of entries) if (entry.expiresAt <= at) {entry.key.fill(0); entries.delete(id)}
24
+ const key = derive(pub, secret);
25
+ entries.set(identity, {key, expiresAt: at + ttlMs});
26
+ while (entries.size > capacity) {
27
+ const id = entries.keys().next().value!;
28
+ entries.get(id)!.key.fill(0); entries.delete(id);
29
+ }
30
+ return key;
31
+ } finally {secret.fill(0)}
32
+ },
33
+ clear() {for (const entry of entries.values()) entry.key.fill(0); entries.clear()},
34
+ };
35
+ }
36
+
37
+ const sharedBoxes = createSharedBoxCache();
38
+ export const sharedBoxKey = (publicKey: string, secretKey: string) => sharedBoxes.get(publicKey, secretKey);
39
+ export const clearSharedBoxKeys = () => sharedBoxes.clear();
@@ -1,35 +0,0 @@
1
- import {createHash} from 'node:crypto';
2
- import type {ReplyResult} from './payload/types';
3
-
4
- export const nativePromptDigest = (text: string) => createHash('sha256').update(text).digest('hex');
5
- export type NativeCompletionProof = {nativeSessionId: string; promptAt: number; completedAt: number;
6
- promptDigests: string[]; text: string};
7
- type Run = {key: string; startedAt: number; nativeId?: string; digest?: string;
8
- resolve: (result: ReplyResult) => void; result: Promise<ReplyResult>; completed: boolean};
9
-
10
- /** Match this invocation's exact native prompt before releasing its confirmed final answer. */
11
- export class NativeTurnCompletions {
12
- private readonly runs = new Map<string, Run>();
13
- constructor(private readonly now = Date.now) {}
14
- begin(key: string) {
15
- let resolve!: Run['resolve'];
16
- const result = new Promise<ReplyResult>(done => {resolve = done});
17
- const run: Run = {key, startedAt: this.now(), resolve, result, completed: false};
18
- this.runs.set(key, run);
19
- return {result, close: () => {if (this.runs.get(key) === run) this.runs.delete(key)}};
20
- }
21
- bind(nativeId: string, prompt: string, nativeForKey: (key: string) => string) {
22
- const run = [...this.runs.values()].find(item => !item.nativeId && nativeForKey(item.key) === nativeId);
23
- if (run) {run.nativeId = nativeId; run.digest = nativePromptDigest(prompt)}
24
- }
25
- complete(key: string, proof: NativeCompletionProof): boolean {
26
- const run = this.runs.get(key);
27
- if (!run || run.completed || run.nativeId !== proof.nativeSessionId || !run.digest
28
- || !proof.promptDigests.includes(run.digest) || proof.promptAt < run.startedAt
29
- || proof.completedAt < proof.promptAt || proof.completedAt > this.now() + 5_000
30
- || !proof.text.trim()) return false;
31
- run.completed = true;
32
- run.resolve({ok: true, text: proof.text, delivery: 'native'});
33
- return true;
34
- }
35
- }