@anusornneal/chat-relay 1.9.0 → 2.1.0
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/README.md +8 -0
- package/agent/activity-capture.mjs +218 -0
- package/agent/auto-session-binding.mjs +46 -0
- package/agent/capability-scheduler.mjs +82 -5
- package/agent/file-manager.mjs +33 -8
- package/agent/full-bridge.mjs +53 -0
- package/agent/full-desktop-actions.mjs +124 -0
- package/agent/full-desktop-auth.mjs +53 -0
- package/agent/full-desktop-broker.mjs +318 -0
- package/agent/full-host.mjs +153 -0
- package/agent/full-job-broker.mjs +360 -0
- package/agent/full-native-job.mjs +205 -0
- package/agent/full-presentation-changes.mjs +191 -0
- package/agent/full-remote-diagnostics.mjs +129 -0
- package/agent/full-resources.mjs +343 -0
- package/agent/full-runtime-supervisor.mjs +67 -0
- package/agent/full-session-dispatch.mjs +167 -0
- package/agent/full-workspace-broker.mjs +290 -0
- package/agent/git-worktree-manager.mjs +171 -4
- package/agent/lifecycle.mjs +11 -0
- package/agent/local-agent.mjs +177 -24
- package/agent/local-usage.mjs +21 -0
- package/agent/monitor-activity.mjs +135 -0
- package/agent/presentation-redaction.mjs +10 -0
- package/agent/process-manager.mjs +32 -0
- package/agent/terminal-manager.mjs +189 -31
- package/agent/toolcall-context.mjs +27 -1
- package/agent/toolcall-summary.mjs +1 -1
- package/agent/windows-desktop-runner.mjs +65 -61
- package/agent/windows-desktop-worker.ps1 +33 -18
- package/agent/windows-powershell.mjs +51 -0
- package/cli/full-background.mjs +69 -0
- package/cli/full-launch.mjs +76 -0
- package/cli/full-prepare-child.mjs +48 -0
- package/cli/full-prepare.mjs +171 -0
- package/cli/full-release-default.json +4 -0
- package/cli/full-release-files.mjs +36 -0
- package/cli/full-release-official.mjs +48 -0
- package/cli/full-release-source.mjs +37 -0
- package/cli/index.mjs +9 -5
- package/cli/mod-cache.mjs +170 -0
- package/cli/mod-loader.mjs +67 -0
- package/cli/mod-manifest.mjs +63 -0
- package/cli/remote.mjs +173 -18
- package/cli/runner-ownership.mjs +116 -3
- package/cli/self-update.mjs +1 -1
- package/cli/tui.mjs +2 -20
- package/package.json +5 -3
- package/packages/full-contracts/auto-session.mjs +14 -0
- package/packages/full-contracts/index.mjs +193 -0
- package/packages/full-contracts/monitor-metadata.mjs +28 -0
- package/packages/full-contracts/native-job.mjs +13 -0
- package/packages/full-contracts/package.json +7 -0
- package/packages/full-contracts/remote-session.mjs +239 -0
package/cli/runner-ownership.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
1
|
+
import { createHash, randomUUID, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
2
|
import fs from "node:fs";
|
|
3
3
|
import net from "node:net";
|
|
4
4
|
import os from "node:os";
|
|
@@ -8,6 +8,10 @@ import { configDir } from "./config.mjs";
|
|
|
8
8
|
|
|
9
9
|
const DEFAULT_STARTUP_GRACE_MS = 1_500;
|
|
10
10
|
const DEFAULT_PROBE_TIMEOUT_MS = 400;
|
|
11
|
+
const CONTROL_MAX_BYTES = 2048;
|
|
12
|
+
const accountIdPattern = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
|
|
13
|
+
const versionPattern = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[A-Za-z0-9.-]+)?$/;
|
|
14
|
+
const controlFailure = error => ({ ok: false, error });
|
|
11
15
|
|
|
12
16
|
export class RunnerAlreadyActiveError extends Error {
|
|
13
17
|
constructor({ agentId, relayUrl, pid }) {
|
|
@@ -84,6 +88,52 @@ function probeOwner(metadata, timeoutMs) {
|
|
|
84
88
|
});
|
|
85
89
|
}
|
|
86
90
|
|
|
91
|
+
/** Explicit same-owner GUI reopen. No takeover, credentials or Core spawn. */
|
|
92
|
+
export async function requestFullDesktopOpen({
|
|
93
|
+
relayUrl, agentId, accountId, version, directory = configDir(), timeoutMs = 11000,
|
|
94
|
+
} = {}) {
|
|
95
|
+
if (!relayUrl || !agentId || typeof accountId !== "string" || !accountIdPattern.test(accountId) ||
|
|
96
|
+
typeof version !== "string" || version.length > 64 || !versionPattern.test(version) ||
|
|
97
|
+
!Number.isSafeInteger(timeoutMs) || timeoutMs < 100 || timeoutMs > 15000)
|
|
98
|
+
return controlFailure("full_invalid_desktop_reopen");
|
|
99
|
+
const key = ownershipKey(relayUrl, agentId);
|
|
100
|
+
const metadata = readMetadata(path.join(directory, "runner-locks", key));
|
|
101
|
+
if (typeof metadata?.token !== "string" || !/^[a-f0-9-]{36}$/.test(metadata.token) ||
|
|
102
|
+
typeof metadata.endpoint !== "string" || !/^[a-f0-9]{64}$/.test(metadata.controlToken ?? "") ||
|
|
103
|
+
metadata.agentId !== String(agentId) || metadata.relayUrl !== normalizeRelayUrl(relayUrl) ||
|
|
104
|
+
metadata.endpoint !== socketEndpoint(key, metadata.token))
|
|
105
|
+
return controlFailure("full_desktop_reopen_unavailable");
|
|
106
|
+
return new Promise(resolve => {
|
|
107
|
+
let settled = false, response = "";
|
|
108
|
+
const socket = net.createConnection(metadata.endpoint);
|
|
109
|
+
const finish = value => {
|
|
110
|
+
if (settled) return;
|
|
111
|
+
settled = true; clearTimeout(timer); socket.destroy(); resolve(value);
|
|
112
|
+
};
|
|
113
|
+
const timer = setTimeout(() => finish(controlFailure("full_desktop_reopen_timeout")), timeoutMs);
|
|
114
|
+
socket.setEncoding("utf8");
|
|
115
|
+
socket.once("connect", () => socket.write(JSON.stringify({
|
|
116
|
+
version: 1, command: "full.gui.open", controlToken: metadata.controlToken,
|
|
117
|
+
accountId, artifactVersion: version,
|
|
118
|
+
}) + "\n"));
|
|
119
|
+
socket.on("data", chunk => {
|
|
120
|
+
response += chunk;
|
|
121
|
+
if (Buffer.byteLength(response) > CONTROL_MAX_BYTES) return finish(controlFailure("full_invalid_desktop_reopen"));
|
|
122
|
+
if (!response.includes("\n")) return;
|
|
123
|
+
try {
|
|
124
|
+
const result = JSON.parse(response.trim());
|
|
125
|
+
if (result?.ok === true && typeof result.alreadyOpen === "boolean")
|
|
126
|
+
return finish({ ok: true, alreadyOpen: result.alreadyOpen });
|
|
127
|
+
if (result?.ok === false && /^full_[a-z0-9_]+$/.test(result.error ?? ""))
|
|
128
|
+
return finish(controlFailure(result.error));
|
|
129
|
+
} catch {}
|
|
130
|
+
finish(controlFailure("full_desktop_reopen_unavailable"));
|
|
131
|
+
});
|
|
132
|
+
socket.once("error", () => finish(controlFailure("full_desktop_reopen_unavailable")));
|
|
133
|
+
socket.once("end", () => finish(controlFailure("full_desktop_reopen_unavailable")));
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
87
137
|
function listen(server, endpoint) {
|
|
88
138
|
return new Promise((resolve, reject) => {
|
|
89
139
|
const onError = (error) => reject(error);
|
|
@@ -129,8 +179,17 @@ export async function acquireRunnerOwnership({
|
|
|
129
179
|
directory = configDir(),
|
|
130
180
|
startupGraceMs = DEFAULT_STARTUP_GRACE_MS,
|
|
131
181
|
probeTimeoutMs = DEFAULT_PROBE_TIMEOUT_MS,
|
|
182
|
+
desktopIdentity = null,
|
|
183
|
+
onOpenFullDesktop = null,
|
|
132
184
|
} = {}) {
|
|
133
185
|
if (!relayUrl || !agentId) throw new Error("Runner ownership requires relayUrl and agentId");
|
|
186
|
+
const desktop = onOpenFullDesktop === null ? null : {
|
|
187
|
+
accountId: desktopIdentity?.accountId, version: desktopIdentity?.version,
|
|
188
|
+
};
|
|
189
|
+
if (desktop && (typeof onOpenFullDesktop !== "function" || typeof desktop.accountId !== "string" ||
|
|
190
|
+
!accountIdPattern.test(desktop.accountId) || typeof desktop.version !== "string" ||
|
|
191
|
+
desktop.version.length > 64 || !versionPattern.test(desktop.version)))
|
|
192
|
+
throw new Error("Invalid desktop runner identity");
|
|
134
193
|
|
|
135
194
|
const key = ownershipKey(relayUrl, agentId);
|
|
136
195
|
const locksDir = path.join(directory, "runner-locks");
|
|
@@ -160,19 +219,71 @@ export async function acquireRunnerOwnership({
|
|
|
160
219
|
}
|
|
161
220
|
|
|
162
221
|
const token = randomUUID();
|
|
222
|
+
const controlToken = desktop ? randomBytes(32).toString("hex") : null;
|
|
163
223
|
const endpoint = socketEndpoint(key, token);
|
|
164
224
|
const metadata = {
|
|
165
225
|
version: 1,
|
|
166
226
|
pid: process.pid,
|
|
167
227
|
token,
|
|
228
|
+
...(controlToken ? { controlToken } : {}),
|
|
168
229
|
endpoint,
|
|
169
230
|
relayUrl: normalizeRelayUrl(relayUrl),
|
|
170
231
|
agentId: String(agentId),
|
|
171
232
|
createdAt: new Date().toISOString(),
|
|
172
233
|
};
|
|
173
|
-
const
|
|
234
|
+
const sockets = new Set();
|
|
235
|
+
let opening = null, releasing = false, controlWaiters = 0;
|
|
236
|
+
const server = net.createServer(socket => {
|
|
237
|
+
sockets.add(socket);
|
|
238
|
+
socket.once("close", () => sockets.delete(socket));
|
|
239
|
+
socket.on("error", () => {});
|
|
240
|
+
socket.setTimeout(1500, () => socket.destroy());
|
|
174
241
|
socket.setEncoding("utf8");
|
|
175
|
-
|
|
242
|
+
let input = "", handled = false;
|
|
243
|
+
socket.on("data", chunk => {
|
|
244
|
+
if (handled) return;
|
|
245
|
+
input += chunk;
|
|
246
|
+
if (Buffer.byteLength(input) > CONTROL_MAX_BYTES) {
|
|
247
|
+
handled = true; socket.end(JSON.stringify(controlFailure("full_invalid_desktop_reopen")) + "\n"); return;
|
|
248
|
+
}
|
|
249
|
+
if (!input.includes("\n")) return;
|
|
250
|
+
handled = true;
|
|
251
|
+
if (input.trim() === "PING") { socket.end(`OWNER ${token}\n`); return; }
|
|
252
|
+
const reply = value => { if (!socket.destroyed) socket.end(JSON.stringify(value) + "\n"); };
|
|
253
|
+
let request;
|
|
254
|
+
try { request = JSON.parse(input.trim()); } catch { reply(controlFailure("full_invalid_desktop_reopen")); return; }
|
|
255
|
+
const allowed = ["version", "command", "controlToken", "accountId", "artifactVersion"];
|
|
256
|
+
if (releasing || !desktop || !request || typeof request !== "object" || Array.isArray(request) ||
|
|
257
|
+
Object.keys(request).length !== allowed.length || Object.keys(request).some(key => !allowed.includes(key)) ||
|
|
258
|
+
request.version !== 1 || request.command !== "full.gui.open" ||
|
|
259
|
+
typeof request.controlToken !== "string" || !/^[a-f0-9]{64}$/.test(request.controlToken) ||
|
|
260
|
+
!timingSafeEqual(Buffer.from(request.controlToken), Buffer.from(controlToken)) ||
|
|
261
|
+
request.accountId !== desktop.accountId) {
|
|
262
|
+
reply(controlFailure("full_desktop_reopen_denied")); return;
|
|
263
|
+
}
|
|
264
|
+
if (request.artifactVersion !== desktop.version) {
|
|
265
|
+
reply(controlFailure("full_active_version_mismatch")); return;
|
|
266
|
+
}
|
|
267
|
+
if (controlWaiters >= 8) { reply(controlFailure("full_desktop_reopen_busy")); return; }
|
|
268
|
+
controlWaiters++;
|
|
269
|
+
socket.setTimeout(12000);
|
|
270
|
+
// Concurrent explicit reopen requests join one action; never start a
|
|
271
|
+
// second Core or permit the caller to change roots, version or scopes.
|
|
272
|
+
if (!opening) {
|
|
273
|
+
const pending = Promise.resolve().then(() => {
|
|
274
|
+
if (releasing) throw new Error("runner closing");
|
|
275
|
+
return onOpenFullDesktop();
|
|
276
|
+
});
|
|
277
|
+
opening = pending;
|
|
278
|
+
void pending.finally(() => { if (opening === pending) opening = null; }).catch(() => {});
|
|
279
|
+
}
|
|
280
|
+
void opening.then(result => {
|
|
281
|
+
if (typeof result?.alreadyOpen !== "boolean") throw new Error("invalid desktop response");
|
|
282
|
+
reply({ ok: true, alreadyOpen: result.alreadyOpen });
|
|
283
|
+
}).catch(error => reply(controlFailure(
|
|
284
|
+
typeof error?.code === "string" && /^full_[a-z0-9_]+$/.test(error.code)
|
|
285
|
+
? error.code : "full_desktop_reopen_unavailable"))).finally(() => { controlWaiters--; }).catch(() => {});
|
|
286
|
+
});
|
|
176
287
|
});
|
|
177
288
|
|
|
178
289
|
try {
|
|
@@ -200,6 +311,8 @@ export async function acquireRunnerOwnership({
|
|
|
200
311
|
async release() {
|
|
201
312
|
if (released) return;
|
|
202
313
|
released = true;
|
|
314
|
+
releasing = true;
|
|
315
|
+
for (const socket of sockets) socket.destroy();
|
|
203
316
|
await close(server);
|
|
204
317
|
removeSocket(endpoint);
|
|
205
318
|
if (readMetadata(lockDir)?.token === token) fs.rmSync(lockDir, { recursive: true, force: true });
|
package/cli/self-update.mjs
CHANGED
|
@@ -30,7 +30,7 @@ export function createUpgradeRelaunchSpec(options = {}, {
|
|
|
30
30
|
};
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
-
const args = uiArgs(options);
|
|
33
|
+
const args = [...(options.full === true ? ["--full", ...(options.headless === true ? ["--headless"] : [])] : []), ...uiArgs(options)];
|
|
34
34
|
const childEnv = {
|
|
35
35
|
...env,
|
|
36
36
|
[UPGRADE_LOOP_GUARD_ENV]: String(now + UPGRADE_LOOP_GUARD_MS),
|
package/cli/tui.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { humanizeToolCall } from "../agent/toolcall-summary.mjs";
|
|
2
|
+
import { activityCategory, activityIcon } from "../agent/toolcall-context.mjs";
|
|
2
3
|
|
|
3
4
|
const ESC = "\x1b[";
|
|
4
5
|
const RESET = "\x1b[0m";
|
|
@@ -284,6 +285,7 @@ function normalizeRelay(value) {
|
|
|
284
285
|
}
|
|
285
286
|
|
|
286
287
|
export function shouldUseTui(options = {}, stdout = process.stdout) {
|
|
288
|
+
if (options.full === true) return false;
|
|
287
289
|
if (options.tuiEnabled === false) return false;
|
|
288
290
|
if (options.tuiEnabled === true) return true;
|
|
289
291
|
return Boolean(stdout?.isTTY);
|
|
@@ -317,26 +319,6 @@ function cellPad(value, width) {
|
|
|
317
319
|
return clipped + " ".repeat(Math.max(0, width - terminalCellWidth(clipped)));
|
|
318
320
|
}
|
|
319
321
|
|
|
320
|
-
function activityCategory(item) {
|
|
321
|
-
if (item.category) return String(item.category);
|
|
322
|
-
const action = String(item.action || "");
|
|
323
|
-
if (action.startsWith("fs.")) return "Filesystem";
|
|
324
|
-
if (action.startsWith("terminal.")) return "Terminal";
|
|
325
|
-
if (action.startsWith("desktop.")) return "Desktop";
|
|
326
|
-
if (action.startsWith("learn")) return "Learn";
|
|
327
|
-
return "Agent";
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
function activityIcon(item) {
|
|
331
|
-
const action = String(item.action || "").toLowerCase();
|
|
332
|
-
const title = String(item.operation || item.summary || "").toLowerCase();
|
|
333
|
-
if (/search/.test(action) || /^(start|search)\b/.test(title)) return "🔎";
|
|
334
|
-
if (/(^|\.)(read|readmany|getcontent)(_|$|\.)/.test(action) || /^read\b/.test(title)) return "📖";
|
|
335
|
-
if (/(^|\.)(write|edit|move|mkdir|delete)(_|$|\.)/.test(action) || /^(write|edit|create|delete|move)\b/.test(title)) return "✏️";
|
|
336
|
-
if (activityCategory(item) === "Terminal") return "📟";
|
|
337
|
-
if (activityCategory(item) === "Filesystem") return "📁";
|
|
338
|
-
return "";
|
|
339
|
-
}
|
|
340
322
|
|
|
341
323
|
function shortActivityDetail(value, project) {
|
|
342
324
|
const normalized = String(value || "").replace(/\\/g, "/").replace(/\s+/g, " ").trim();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@anusornneal/chat-relay",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "2.1.0",
|
|
4
4
|
"description": "Zero-checkout remote MCP agent for ChatGPT with terminal, filesystem, process, multi-user, and multi-agent support.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -9,7 +9,9 @@
|
|
|
9
9
|
"files": [
|
|
10
10
|
"bin/",
|
|
11
11
|
"cli/",
|
|
12
|
+
"cli/full-release-default.json",
|
|
12
13
|
"agent/",
|
|
14
|
+
"packages/full-contracts/",
|
|
13
15
|
"README.md"
|
|
14
16
|
],
|
|
15
17
|
"engines": {
|
|
@@ -50,7 +52,7 @@
|
|
|
50
52
|
"test:dashboard": "node --test test/dashboard-ui-contract.test.mjs test/dashboard-theme.test.mjs && node test/dashboard-smoke.mjs",
|
|
51
53
|
"test:dashboard-timers": "node test/dashboard-timers.test.mjs",
|
|
52
54
|
"test:ops": "node test/ops-smoke.mjs",
|
|
53
|
-
"test:desktop": "node --test test/agent-desktop-adapter.test.mjs && node test/mcp-desktop-smoke.mjs",
|
|
55
|
+
"test:desktop": "node --test test/agent-desktop-adapter.test.mjs test/windows-desktop-runner.test.mjs && node test/mcp-desktop-smoke.mjs",
|
|
54
56
|
"test:device-management": "node test/device-management-smoke.mjs",
|
|
55
57
|
"test:submission": "node test/submission-smoke.mjs",
|
|
56
58
|
"test:agent-state": "node --experimental-strip-types --test test/agent-state.test.mjs test/reconnect-chaos.test.mjs",
|
|
@@ -64,7 +66,7 @@
|
|
|
64
66
|
"test:hardening": "npm run test:file-search && npm run test:batch-contract && npm run test:tool-efficiency && npm run test:terminal-perf && npm run test:tool-guidance && npm run test:tui && npm run test:config-security && npm run test:self-update && npm run test:budget && npm run test:worker-hotpath && node --test test/connection-generation.test.mjs && npm run test:agent-state && node test/heartbeat-ack-watchdog.test.mjs && npm run test:no-quota && npm run test:usage-storage && npm run test:learn && npm run test:learn-bootstrap && npm run test:soak",
|
|
65
67
|
"test:batch-contract": "node --test test/tool-contract-batch.test.mjs",
|
|
66
68
|
"test:tool-efficiency": "node --test --test-concurrency=1 test/tool-efficiency.test.mjs test/tool-efficiency-mcp.test.mjs",
|
|
67
|
-
"test:terminal-perf": "node --test test/terminal-perf.test.mjs test/terminal-wait.test.mjs",
|
|
69
|
+
"test:terminal-perf": "node --test test/terminal-perf.test.mjs test/terminal-wait.test.mjs test/terminal-retention.test.mjs test/terminal-capture-drain.test.mjs",
|
|
68
70
|
"test:tool-guidance": "node --test test/tool-error-guidance.test.mjs",
|
|
69
71
|
"verify:review": "node scripts/verify-review-artifacts.mjs",
|
|
70
72
|
"test:learn": "node test/learning-smoke.mjs && node test/project-alias-sqlite.test.mjs && node test/project-merge-mcp.test.mjs && node --test test/shared-learn.test.mjs test/shared-learn-ui.test.mjs && npm run test:learn-usage",
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// Conversation metadata is an attribution hint, never authorization.
|
|
2
|
+
// Only the already authorized Worker may construct the internal envelope.
|
|
3
|
+
const account=value=>typeof value==="string"&&/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value);
|
|
4
|
+
const activity=value=>typeof value==="string"&&/^act_[a-f0-9]{20}$/.test(value);
|
|
5
|
+
export function automaticSessionContext({accountId,activityId,reliableIdentity,scopes,action}={}){
|
|
6
|
+
if(reliableIdentity!==true||!account(accountId)||!activity(activityId)||
|
|
7
|
+
!Array.isArray(scopes)||!["read","write"].every(s=>scopes.includes("*")||scopes.includes(s))||
|
|
8
|
+
typeof action!=="string"||! /^(?:fs|terminal|git|desktop|process)\./.test(action))return undefined;
|
|
9
|
+
return {accountId,activityId};
|
|
10
|
+
}
|
|
11
|
+
export function validAutomaticSessionContext(value){
|
|
12
|
+
return !!value&&typeof value==="object"&&!Array.isArray(value)&&
|
|
13
|
+
Object.keys(value).length===2&&account(value.accountId)&&activity(value.activityId);
|
|
14
|
+
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// Small dependency-free boundary shared by Core, the optional Full runtime and its GUI.
|
|
2
|
+
export const FULL_API_VERSION = 1;
|
|
3
|
+
export const FULL_PACKAGE = "@anusornneal/chat-relay-mod-full";
|
|
4
|
+
export const FULL_LIMITS = Object.freeze({ frameBytes: 65536, controlTimeoutMs: 30000, eventCapacity: 256, capabilities: 64, idLength: 128 });
|
|
5
|
+
const ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
|
|
6
|
+
const VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-[0-9A-Za-z.-]+)?$/;
|
|
7
|
+
const CAPABILITY = /^full\.[a-z][a-z0-9.-]{0,95}$/;
|
|
8
|
+
const record = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
9
|
+
const validId = (v) => typeof v === "string" && ID.test(v);
|
|
10
|
+
const validVersion = (v) => typeof v === "string" && v.length <= 64 && VERSION.test(v);
|
|
11
|
+
const positiveInt = (v) => Number.isSafeInteger(v) && v > 0;
|
|
12
|
+
function requireContract(condition, code) {
|
|
13
|
+
if (!condition) throw new FullContractError(code);
|
|
14
|
+
}
|
|
15
|
+
export class FullContractError extends Error {
|
|
16
|
+
constructor(code) {
|
|
17
|
+
super(code);
|
|
18
|
+
this.name = "FullContractError";
|
|
19
|
+
this.code = code;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export function fullUnavailable() {
|
|
23
|
+
return { ok: false, error: "full_unavailable", message: "Full runtime is unavailable. No session-bound operation was executed." };
|
|
24
|
+
}
|
|
25
|
+
export function hasFullSessionRequest(value) {
|
|
26
|
+
// Presence, even with an invalid/null value, requires explicit validation;
|
|
27
|
+
// do not silently strip the field and execute an ordinary Core write.
|
|
28
|
+
return record(value) && Object.hasOwn(value, "taskSessionId");
|
|
29
|
+
}
|
|
30
|
+
function capabilityList(value) {
|
|
31
|
+
requireContract(Array.isArray(value) && value.length <= FULL_LIMITS.capabilities && value.every(v => typeof v === "string" && CAPABILITY.test(v)), "full_invalid_capabilities");
|
|
32
|
+
requireContract(new Set(value).size === value.length, "full_duplicate_capability");
|
|
33
|
+
return [...value];
|
|
34
|
+
}
|
|
35
|
+
export function parseManifest(input) {
|
|
36
|
+
requireContract(record(input) && input.packageName === FULL_PACKAGE, "full_invalid_package");
|
|
37
|
+
requireContract(input.apiVersion === FULL_API_VERSION, "full_api_incompatible");
|
|
38
|
+
requireContract(validVersion(input.version), "full_invalid_version");
|
|
39
|
+
requireContract(Array.isArray(input.coreVersions) && input.coreVersions.length > 0 && input.coreVersions.length <= 32 && input.coreVersions.every(validVersion) && new Set(input.coreVersions).size === input.coreVersions.length, "full_invalid_core_versions");
|
|
40
|
+
requireContract(["win32", "darwin", "linux"].includes(input.platform) && ["x64", "arm64"].includes(input.arch), "full_invalid_target");
|
|
41
|
+
requireContract(typeof input.sha256 === "string" && /^[a-f0-9]{64}$/.test(input.sha256) && positiveInt(input.sizeBytes), "full_invalid_artifact");
|
|
42
|
+
// Validation is NOT verification of digest, signature, trust, archive paths or installation.
|
|
43
|
+
return { packageName: FULL_PACKAGE, apiVersion: FULL_API_VERSION, version: input.version, coreVersions: [...input.coreVersions], platform: input.platform, arch: input.arch, sha256: input.sha256, sizeBytes: input.sizeBytes, capabilities: capabilityList(input.capabilities) };
|
|
44
|
+
}
|
|
45
|
+
export function negotiateManifest(input, { coreVersion, platform, arch, supportedCapabilities = [] } = {}) {
|
|
46
|
+
const manifest = parseManifest(input);
|
|
47
|
+
requireContract(manifest.coreVersions.includes(coreVersion), "full_core_incompatible");
|
|
48
|
+
requireContract(manifest.platform === platform && manifest.arch === arch, "full_target_incompatible");
|
|
49
|
+
const supported = new Set(capabilityList(supportedCapabilities));
|
|
50
|
+
return { manifest, capabilities: manifest.capabilities.filter(c => supported.has(c)) };
|
|
51
|
+
}
|
|
52
|
+
export function validateControlFrame(frame) {
|
|
53
|
+
requireContract(record(frame) && frame.apiVersion === FULL_API_VERSION && validId(frame.ownerEpoch) && validId(frame.requestId), "full_invalid_frame");
|
|
54
|
+
requireContract(["request", "response", "cancel"].includes(frame.kind), "full_invalid_frame_kind");
|
|
55
|
+
if (frame.kind === "request") {
|
|
56
|
+
requireContract(typeof frame.operation === "string" && CAPABILITY.test(frame.operation), "full_invalid_operation");
|
|
57
|
+
requireContract(positiveInt(frame.timeoutMs) && frame.timeoutMs <= FULL_LIMITS.controlTimeoutMs, "full_invalid_timeout");
|
|
58
|
+
if (hasFullSessionRequest(frame)) requireContract(validId(frame.taskSessionId), "full_invalid_session_id");
|
|
59
|
+
} else if (frame.kind === "response") {
|
|
60
|
+
requireContract(typeof frame.ok === "boolean" && (frame.ok || (typeof frame.error === "string" && /^full_[a-z0-9_]{1,80}$/.test(frame.error))), "full_invalid_response");
|
|
61
|
+
} else {
|
|
62
|
+
requireContract(validId(frame.targetRequestId) && frame.targetRequestId !== frame.requestId, "full_invalid_cancel_target");
|
|
63
|
+
}
|
|
64
|
+
// The transport must reject oversized frames BEFORE parsing. This check also bounds
|
|
65
|
+
// frames produced by clients. JSON-only data is required; no functions or handles.
|
|
66
|
+
let json;
|
|
67
|
+
try { json = JSON.stringify(frame); } catch { throw new FullContractError("full_invalid_frame"); }
|
|
68
|
+
requireContract(typeof json === "string" && new TextEncoder().encode(json).byteLength <= FULL_LIMITS.frameBytes, "full_frame_too_large");
|
|
69
|
+
return frame;
|
|
70
|
+
}
|
|
71
|
+
export function toolCorrelation(observability) {
|
|
72
|
+
if (!record(observability)) return {};
|
|
73
|
+
// Transport identifiers are correlation hints, never principals or authorization.
|
|
74
|
+
return {
|
|
75
|
+
...(validId(observability.activityId) ? { activityId: observability.activityId } : {}),
|
|
76
|
+
...(validId(observability.toolCallId) ? { toolCallId: observability.toolCallId } : {}),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
export function assertScopedOperation({ principal, session, taskSessionId, requiredScopes, targets = [], checkTarget } = {}) {
|
|
80
|
+
// principal, requiredScopes, targets and checkTarget are supplied by the trusted broker,
|
|
81
|
+
// not decoded from a caller frame. checkTarget must perform current canonical root checks.
|
|
82
|
+
requireContract(record(principal) && validId(principal.accountId) && validId(principal.agentId) && Array.isArray(principal.scopes), "full_unauthorized");
|
|
83
|
+
requireContract(record(session) && validId(taskSessionId) && session.taskSessionId === taskSessionId &&
|
|
84
|
+
session.accountId === principal.accountId && session.agentId === principal.agentId, "full_unauthorized");
|
|
85
|
+
requireContract(Array.isArray(requiredScopes) && requiredScopes.length > 0 && requiredScopes.every(scope => principal.scopes.includes(scope)), "full_unauthorized");
|
|
86
|
+
requireContract(Array.isArray(targets) && (!targets.length || (typeof checkTarget === "function" && targets.every(target => checkTarget(target) === true))), "full_unauthorized");
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
export function validateSessionIdentity(value) {
|
|
90
|
+
requireContract(record(value) && [value.taskSessionId, value.accountId, value.agentId].every(validId), "full_invalid_session");
|
|
91
|
+
return { taskSessionId: value.taskSessionId, accountId: value.accountId, agentId: value.agentId };
|
|
92
|
+
}
|
|
93
|
+
export function validateWorkspaceBinding(value) {
|
|
94
|
+
requireContract(record(value) && validId(value.workspaceId) && validId(value.taskSessionId) &&
|
|
95
|
+
["isolated", "shared", "main", "none"].includes(value.mode) &&
|
|
96
|
+
["git", "artifact", "desktop", "research", "read-only"].includes(value.workspaceKind) &&
|
|
97
|
+
["pending", "ready", "failed"].includes(value.state), "full_invalid_workspace_binding");
|
|
98
|
+
return { workspaceId: value.workspaceId, taskSessionId: value.taskSessionId, mode: value.mode, workspaceKind: value.workspaceKind, state: value.state };
|
|
99
|
+
}
|
|
100
|
+
export function validateResourceClaim(value) {
|
|
101
|
+
requireContract(record(value) && [value.resourceId, value.taskSessionId, value.ownerEpoch, value.attemptId].every(validId) &&
|
|
102
|
+
["read", "write", "exclusive"].includes(value.mode) && ["reserved", "quarantined", "released"].includes(value.state), "full_invalid_resource_claim");
|
|
103
|
+
return { resourceId: value.resourceId, taskSessionId: value.taskSessionId, ownerEpoch: value.ownerEpoch, attemptId: value.attemptId, mode: value.mode, state: value.state };
|
|
104
|
+
}
|
|
105
|
+
export function validateRevision(value) {
|
|
106
|
+
requireContract(record(value) && validId(value.workspaceId) && positiveInt(value.generation) &&
|
|
107
|
+
typeof value.fingerprint === "string" && /^sha256:[a-f0-9]{64}$/.test(value.fingerprint) &&
|
|
108
|
+
["complete", "partial", "unknown"].includes(value.coverage), "full_invalid_revision");
|
|
109
|
+
return { workspaceId: value.workspaceId, generation: value.generation, fingerprint: value.fingerprint, coverage: value.coverage };
|
|
110
|
+
}
|
|
111
|
+
export function validateEvidence(value) {
|
|
112
|
+
requireContract(record(value) && [value.evidenceId, value.taskSessionId, value.checkId].every(validId) &&
|
|
113
|
+
["automated", "manual", "static", "user-attested"].includes(value.kind) &&
|
|
114
|
+
["pass", "fail", "blocked", "not-run", "stale", "unknown"].includes(value.outcome) &&
|
|
115
|
+
typeof value.sourceRef === "string" && value.sourceRef.trim().length > 0 && value.sourceRef.length <= 2048 &&
|
|
116
|
+
typeof value.observedAt === "string" && Number.isFinite(Date.parse(value.observedAt)), "full_invalid_evidence");
|
|
117
|
+
// Structural validation does not prove evidence is authentic, current, or sufficient.
|
|
118
|
+
return { evidenceId: value.evidenceId, taskSessionId: value.taskSessionId, checkId: value.checkId,
|
|
119
|
+
revision: validateRevision(value.revision), kind: value.kind, outcome: value.outcome, sourceRef: value.sourceRef, observedAt: value.observedAt };
|
|
120
|
+
}
|
|
121
|
+
export function validateConsumerCursor(value) {
|
|
122
|
+
requireContract(record(value) && validId(value.consumerId) && validId(value.producerEpoch) &&
|
|
123
|
+
Number.isSafeInteger(value.sequence) && value.sequence >= 0, "full_invalid_cursor");
|
|
124
|
+
return { consumerId: value.consumerId, producerEpoch: value.producerEpoch, sequence: value.sequence };
|
|
125
|
+
}
|
|
126
|
+
export function newJob({ jobId, attemptId, ownerEpoch }) {
|
|
127
|
+
requireContract([jobId, attemptId, ownerEpoch].every(validId), "full_invalid_job");
|
|
128
|
+
return { jobId, attemptId, ownerEpoch, state: "accepted", lastSequence: 0 };
|
|
129
|
+
}
|
|
130
|
+
export function jobIsSettled(job) {
|
|
131
|
+
return ["exited","cancelled"].includes(job?.state)||(job?.state==="outcome-unknown"&&job.stopConfirmed===true);
|
|
132
|
+
}
|
|
133
|
+
export function applyJobEvent(job, event) {
|
|
134
|
+
// Only a trusted job producer may supply authoritative completion evidence.
|
|
135
|
+
if (!record(event) || event.jobId !== job.jobId || event.attemptId !== job.attemptId || event.ownerEpoch !== job.ownerEpoch ||
|
|
136
|
+
!positiveInt(event.sequence) || event.sequence <= job.lastSequence) return job;
|
|
137
|
+
if (jobIsSettled(job)) return job;
|
|
138
|
+
const allowed = {
|
|
139
|
+
accepted: ["running", "cancel-requested", "exited", "cancelled", "outcome-unknown"],
|
|
140
|
+
running: ["cancel-requested", "exited", "cancelled", "outcome-unknown"],
|
|
141
|
+
"cancel-requested": ["exited", "cancelled", "outcome-unknown"],
|
|
142
|
+
"outcome-unknown": ["exited", "cancelled", "outcome-unknown"],
|
|
143
|
+
};
|
|
144
|
+
if (!allowed[job.state]?.includes(event.state)) return job;
|
|
145
|
+
if (event.state === "exited" && (!(Number.isSafeInteger(event.exitCode) || (event.exitCode === null && validId(event.signal))) ||
|
|
146
|
+
(event.signal !== undefined && event.signal !== null && !validId(event.signal)))) return job;
|
|
147
|
+
if (event.state === "cancelled" && event.stopConfirmed !== true) return job;
|
|
148
|
+
// Private trusted producer proof may settle containment while the command
|
|
149
|
+
// result remains unknown. Ordinary unknown events still retain admission.
|
|
150
|
+
if (event.state === "outcome-unknown" && ((event.stopConfirmed !== undefined && event.stopConfirmed !== true) ||
|
|
151
|
+
(job.state === "outcome-unknown" && event.stopConfirmed !== true))) return job;
|
|
152
|
+
return { ...job, state: event.state, lastSequence: event.sequence,
|
|
153
|
+
...(event.state === "outcome-unknown" && event.stopConfirmed === true ? {stopConfirmed:true} : {}),
|
|
154
|
+
...(event.state === "exited" ? { exitCode: event.exitCode, ...(event.signal ? { signal: event.signal } : {}) } : {}) };
|
|
155
|
+
}
|
|
156
|
+
export function jobSucceeded(job) {
|
|
157
|
+
return job.state === "exited" && job.exitCode === 0 && !job.signal;
|
|
158
|
+
}
|
|
159
|
+
export async function acknowledgeAfterCommit(commit) {
|
|
160
|
+
requireContract(typeof commit === "function", "full_commit_required");
|
|
161
|
+
// The store owns the actual durability policy. Rejection is not ACK; no replay.
|
|
162
|
+
const result = await commit();
|
|
163
|
+
requireContract(record(result) && result.committed === true && validId(result.revision), "full_commit_failed");
|
|
164
|
+
return { acknowledged: true, revision: result.revision };
|
|
165
|
+
}
|
|
166
|
+
export function createEventBuffer({ producerEpoch, capacity = FULL_LIMITS.eventCapacity } = {}) {
|
|
167
|
+
requireContract(validId(producerEpoch) && positiveInt(capacity) && capacity <= FULL_LIMITS.eventCapacity, "full_invalid_event_buffer");
|
|
168
|
+
const entries = new Array(capacity);
|
|
169
|
+
let sequence = 0;
|
|
170
|
+
function append(event) {
|
|
171
|
+
requireContract(record(event) && ["tool.accepted", "tool.completed", "job.changed", "activity.progress"].includes(event.type), "full_invalid_event");
|
|
172
|
+
requireContract(validId(event.requestId) && typeof event.at === "string" && Number.isFinite(Date.parse(event.at)), "full_invalid_event");
|
|
173
|
+
// Copy selected fields, not arbitrary arguments, paths, command strings or output.
|
|
174
|
+
const value = { apiVersion: FULL_API_VERSION, producerEpoch, sequence: ++sequence, type: event.type, at: event.at, requestId: event.requestId, ...toolCorrelation(event) };
|
|
175
|
+
if (validId(event.action)) value.action = event.action;
|
|
176
|
+
if (typeof event.ok === "boolean") value.ok = event.ok;
|
|
177
|
+
if (Number.isFinite(event.durationMs) && event.durationMs >= 0) value.durationMs = event.durationMs;
|
|
178
|
+
if (validId(event.jobId)) value.jobId = event.jobId;
|
|
179
|
+
if (validId(event.taskSessionId)) value.taskSessionId = event.taskSessionId;
|
|
180
|
+
entries[(sequence - 1) % capacity] = Object.freeze(value);
|
|
181
|
+
return value;
|
|
182
|
+
}
|
|
183
|
+
function readAfter(cursor = { producerEpoch, sequence: 0 }) {
|
|
184
|
+
const oldest = Math.max(1, sequence - capacity + 1);
|
|
185
|
+
const valid = cursor?.producerEpoch === producerEpoch && Number.isSafeInteger(cursor.sequence) && cursor.sequence >= 0 && cursor.sequence <= sequence;
|
|
186
|
+
const gap = !valid || cursor.sequence < oldest - 1;
|
|
187
|
+
const start = gap ? oldest : Math.max(oldest, cursor.sequence + 1);
|
|
188
|
+
const events = [];
|
|
189
|
+
for (let i = start; i <= sequence; i++) events.push(entries[(i - 1) % capacity]);
|
|
190
|
+
return { gap, events, cursor: { producerEpoch, sequence } };
|
|
191
|
+
}
|
|
192
|
+
return { append, readAfter };
|
|
193
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// A small, content-free projection shared by Worker, relay and local monitor.
|
|
2
|
+
const scopes=new Set(["global","project","agent"]);
|
|
3
|
+
const kinds=new Set(["preference","response_style","work_style","coding_style","problem_solving","project_context","tool_pattern","workflow","correction","agent_context"]);
|
|
4
|
+
const count=value=>Number.isSafeInteger(value)&&value>=0&&value<=100?value:undefined;
|
|
5
|
+
const key=value=>typeof value==="string"&&/^[a-z0-9][a-z0-9_.:-]{0,79}$/.test(value)&&! /^(?:sk-|gh[pousr]_)/i.test(value)?value:null;
|
|
6
|
+
export const monitorAccountId=value=>typeof value==="string"&&/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/.test(value)?value:null;
|
|
7
|
+
export const monitorActivityId=value=>typeof value==="string"&&/^act_[a-f0-9]{20}$/.test(value)?value:null;
|
|
8
|
+
export function normalizeLearnMonitorMetadata(value){
|
|
9
|
+
if(!value||typeof value!=="object"||Array.isArray(value))return null;
|
|
10
|
+
const retrieved=count(value.retrieved);
|
|
11
|
+
if(retrieved!==undefined){
|
|
12
|
+
const items=[];
|
|
13
|
+
for(const item of (Array.isArray(value.items)?value.items:[]).slice(0,8)){
|
|
14
|
+
const name=key(item?.key);
|
|
15
|
+
if(name&&scopes.has(item.scope)&&kinds.has(item.kind))items.push({key:name,scope:item.scope,kind:item.kind});
|
|
16
|
+
}
|
|
17
|
+
return {retrieved,items:items.slice(0,retrieved)};
|
|
18
|
+
}
|
|
19
|
+
const evaluated=count(value.evaluated),applied=count(value.applied),verified=count(value.verified);
|
|
20
|
+
if(evaluated===undefined||applied===undefined||verified===undefined||applied>evaluated||verified>applied)return null;
|
|
21
|
+
return {evaluated,applied,verified};
|
|
22
|
+
}
|
|
23
|
+
export function learnMonitorMetadata(tool,body){
|
|
24
|
+
if(!body||typeof body!=="object")return null;
|
|
25
|
+
if(tool==="learn_usage_report")return normalizeLearnMonitorMetadata(body);
|
|
26
|
+
const items=tool==="learn_prepare"?body.preparedContext?.items:tool==="learn_get"?body.items:null;
|
|
27
|
+
return Array.isArray(items)?normalizeLearnMonitorMetadata({retrieved:Math.min(items.length,100),items}):null;
|
|
28
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
// Private native containment descriptors. Public callers never supply these.
|
|
2
|
+
// A protocol is an exact audited provider contract, not an extensible name.
|
|
3
|
+
const providers=Object.freeze({
|
|
4
|
+
win32:Object.freeze({protocol:"windows-job-guard-v1",magic:"RLYJOB1\0",guardBytes:78,helper:"relay-full-job.exe",identityScheme:"windows-filetime",containment:"windows-job-object",maxReason:2}),
|
|
5
|
+
linux:Object.freeze({protocol:"linux-pidns-guard-v1",magic:"RLYLNX1\0",guardBytes:160,helper:"relay-full-job",identityScheme:"linux-pidns-init-starttime",containment:"linux-pid-namespace",maxReason:3}),
|
|
6
|
+
});
|
|
7
|
+
export const NATIVE_RECOVERY_PROTOCOLS=Object.freeze(Object.values(providers).map(value=>value.protocol));
|
|
8
|
+
export function nativeJobPlatform(platform){return Object.hasOwn(providers,platform)?providers[platform]:null;}
|
|
9
|
+
export function validNativeRecovery(value){
|
|
10
|
+
return value!==null&&typeof value==="object"&&!Array.isArray(value)&&Object.hasOwn(value,"protocol")&&Object.hasOwn(value,"token")&&
|
|
11
|
+
NATIVE_RECOVERY_PROTOCOLS.includes(value.protocol)&&typeof value.token==="string"&&
|
|
12
|
+
/^[a-f0-9]{64}$/.test(value.token)&&Object.keys(value).length===2;
|
|
13
|
+
}
|