@anusornneal/chat-relay 1.8.0 → 2.0.1

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.
Files changed (54) hide show
  1. package/README.md +60 -0
  2. package/agent/activity-capture.mjs +165 -0
  3. package/agent/capability-scheduler.mjs +83 -6
  4. package/agent/file-manager.mjs +188 -77
  5. package/agent/fs-batch-preview.mjs +70 -0
  6. package/agent/full-bridge.mjs +53 -0
  7. package/agent/full-desktop-actions.mjs +124 -0
  8. package/agent/full-desktop-auth.mjs +53 -0
  9. package/agent/full-desktop-broker.mjs +308 -0
  10. package/agent/full-host.mjs +153 -0
  11. package/agent/full-job-broker.mjs +360 -0
  12. package/agent/full-native-job.mjs +205 -0
  13. package/agent/full-presentation-changes.mjs +191 -0
  14. package/agent/full-remote-diagnostics.mjs +129 -0
  15. package/agent/full-resources.mjs +343 -0
  16. package/agent/full-runtime-supervisor.mjs +67 -0
  17. package/agent/full-session-dispatch.mjs +167 -0
  18. package/agent/full-workspace-broker.mjs +290 -0
  19. package/agent/git-worktree-manager.mjs +170 -4
  20. package/agent/lifecycle.mjs +17 -0
  21. package/agent/local-agent.mjs +182 -33
  22. package/agent/local-usage.mjs +275 -0
  23. package/agent/monitor-activity.mjs +111 -0
  24. package/agent/presentation-redaction.mjs +10 -0
  25. package/agent/process-manager.mjs +32 -0
  26. package/agent/protocol.mjs +5 -1
  27. package/agent/terminal-manager.mjs +240 -29
  28. package/agent/terminal-output.mjs +136 -0
  29. package/agent/toolcall-context.mjs +35 -5
  30. package/agent/toolcall-summary.mjs +10 -0
  31. package/agent/windows-desktop-runner.mjs +65 -61
  32. package/agent/windows-desktop-worker.ps1 +33 -18
  33. package/agent/windows-powershell.mjs +51 -0
  34. package/cli/full-background.mjs +69 -0
  35. package/cli/full-launch.mjs +94 -0
  36. package/cli/full-prepare-child.mjs +48 -0
  37. package/cli/full-prepare.mjs +171 -0
  38. package/cli/full-release-default.json +4 -0
  39. package/cli/full-release-files.mjs +36 -0
  40. package/cli/full-release-official.mjs +48 -0
  41. package/cli/full-release-source.mjs +37 -0
  42. package/cli/index.mjs +8 -4
  43. package/cli/mod-cache.mjs +170 -0
  44. package/cli/mod-loader.mjs +67 -0
  45. package/cli/mod-manifest.mjs +63 -0
  46. package/cli/remote.mjs +172 -17
  47. package/cli/runner-ownership.mjs +116 -3
  48. package/cli/self-update.mjs +1 -1
  49. package/cli/tui.mjs +2 -20
  50. package/package.json +9 -6
  51. package/packages/full-contracts/index.mjs +193 -0
  52. package/packages/full-contracts/native-job.mjs +13 -0
  53. package/packages/full-contracts/package.json +7 -0
  54. package/packages/full-contracts/remote-session.mjs +239 -0
@@ -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,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
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "name": "@anusornneal/chat-relay-full-contracts",
3
+ "version": "1.0.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "exports": "./index.mjs"
7
+ }
@@ -0,0 +1,239 @@
1
+ import {FullContractError,FULL_LIMITS} from "./index.mjs";
2
+
3
+ const ID=/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}$/;
4
+ const AGENT=/^[a-z0-9_-]{1,64}$/;
5
+ const id=value=>typeof value==="string"&&ID.test(value);
6
+ const record=value=>value!==null&&typeof value==="object"&&!Array.isArray(value);
7
+ const require=(condition,code)=>{if(!condition)throw new FullContractError(code);};
8
+ const exact=(value,fields)=>record(value)&&Object.keys(value).every(key=>fields.includes(key));
9
+ const relativePath=relative=>typeof relative==="string"&&relative.length>0&&relative.length<=512&&relative.split("/").every(part=>part.length>0&&part!=="."&&part!==".."&&![".git",".workspace",".relay-workspace-owner.json"].includes(part.toLowerCase())&&!/[\\:\u0000-\u001f]/.test(part)&&!/[. ]$/.test(part)&&!/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(part));
10
+ const descriptors={
11
+ "full.session.ensure":{fields:["intent","taskSessionId","idempotencyKey","title","projectKey"],write:true},
12
+ "full.session.list":{fields:["after","limit"]},
13
+ "full.session.snapshot":{fields:["taskSessionId","consumerId","cursor"],session:true},
14
+ "full.session.acknowledge":{fields:["taskSessionId","consumerId","cursor","revision"],session:true},
15
+ "full.task.checkpoint":{fields:["taskSessionId","expectedRevision","facts"],session:true,write:true},
16
+ "full.task.plan":{fields:["taskSessionId","expectedRevision","steps","reason"],session:true,write:true},
17
+ "full.task.phase":{fields:["taskSessionId","expectedRevision","phase"],session:true,write:true},
18
+ "full.task.narrative":{fields:["taskSessionId","expectedRevision","stepId","state","note"],session:true,write:true},
19
+ "full.task.status":{fields:["taskSessionId","expectedRevision","status"],session:true,write:true},
20
+ "full.workspace.ensure":{fields:["taskSessionId","kind","mode","repoPath","sharedPath","baseRef","artifactRoot"],session:true,write:true},
21
+ "full.workspace.read":{fields:["taskSessionId","relativePath","relativePaths"],session:true},
22
+ "full.workspace.edit":{fields:["taskSessionId","operations"],session:true,write:true},
23
+ "full.intelligence.refresh":{fields:["taskSessionId","queries","readPaths","taskContext"],session:true,write:true},
24
+ "full.intelligence.search":{fields:["taskSessionId","query","limit","cursor"],session:true},
25
+ "full.intelligence.symbols":{fields:["taskSessionId","query","limit","cursor"],session:true},
26
+ "full.intelligence.dependencies":{fields:["taskSessionId","files","direction","depth"],session:true},
27
+ "full.intelligence.impact":{fields:["taskSessionId","baseGeneration","proposedPaths","proposedSymbolIds","mandatoryChecks"],session:true},
28
+ "full.intelligence.context":{fields:["taskSessionId","consumerId","phase","query","budgetBytes","requirements","learn","cursor","refresh"],session:true},
29
+ "full.intelligence.acknowledge":{fields:["taskSessionId","consumerId","deliveryId"],session:true},
30
+ "full.job.start":{fields:["taskSessionId","idempotencyKey","command","timeoutMs","verificationCheckId","waitMs"],session:true,terminal:true,write:true},
31
+ "full.job.status":{fields:["taskSessionId","jobId"],session:true},
32
+ "full.job.read":{fields:["taskSessionId","jobId","afterSeq","waitMs"],session:true,terminal:true},
33
+ "full.job.cancel":{fields:["taskSessionId","jobId"],session:true,terminal:true,write:true},
34
+ "full.job.reconcile":{fields:["taskSessionId","jobId"],session:true,terminal:true,write:true},
35
+ "full.verification.plan":{fields:["taskSessionId","expectedRevision","requirements","checks","risk","knownImplementationComplete","staticReviewComplete"],session:true,write:true},
36
+ "full.verification.record":{fields:["taskSessionId","expectedRevision","jobId"],session:true,write:true},
37
+ "full.verification.assess":{fields:["taskSessionId"],session:true},
38
+ "full.diagnostics.snapshot":{fields:["taskSessionId","cursor"],session:true},
39
+ "full.diagnostics.mode":{fields:["taskSessionId","mode","durationMs","confirmed"],session:true,write:true},
40
+ "full.diagnostics.export":{fields:["taskSessionId","confirmed"],session:true},
41
+ "full.desktop.windows":{fields:["taskSessionId","limit"],session:true,desktopRead:true},
42
+ "full.desktop.step":{fields:["taskSessionId","idempotencyKey","actions","settleMs"],session:true,write:true,desktopControl:true},
43
+ "full.session.export":{fields:["taskSessionId","confirmed","cursor"],session:true},
44
+ "full.session.delete":{fields:["taskSessionId","confirmed","expectedRevision"],session:true,write:true}
45
+ };
46
+ export const REMOTE_FULL_OPERATIONS=Object.freeze(Object.keys(descriptors));
47
+ // Additive optional operations must not change the baseline required of older
48
+ // verified full.sessions providers during Core startup.
49
+ export const REMOTE_SESSION_LIFECYCLE_OPERATIONS=Object.freeze(["full.session.export","full.session.delete"]);
50
+ export const REMOTE_SESSION_OPERATIONS=Object.freeze(REMOTE_FULL_OPERATIONS.filter(op=>(op.startsWith("full.session.")||op.startsWith("full.task."))&&!REMOTE_SESSION_LIFECYCLE_OPERATIONS.includes(op)));
51
+ export const REMOTE_WORKSPACE_OPERATIONS=Object.freeze(REMOTE_FULL_OPERATIONS.filter(op=>op.startsWith("full.workspace.")));
52
+ export const REMOTE_INTELLIGENCE_OPERATIONS=Object.freeze(REMOTE_FULL_OPERATIONS.filter(op=>op.startsWith("full.intelligence.")));
53
+ export const REMOTE_JOB_OPERATIONS=Object.freeze(REMOTE_FULL_OPERATIONS.filter(op=>op.startsWith("full.job.")));
54
+ export const REMOTE_DESKTOP_OPERATIONS=Object.freeze(REMOTE_FULL_OPERATIONS.filter(op=>op.startsWith("full.desktop.")));
55
+ export const DESKTOP_BROKER_OPERATION="full.internal.desktop.run";
56
+ export const VERIFICATION_ASSESS_OPERATION="full.internal.verification.assess";
57
+ export const DIAGNOSTICS_OPERATION="full.diagnostics.snapshot";
58
+ export const REMOTE_DIAGNOSTICS_OPERATIONS=Object.freeze(REMOTE_FULL_OPERATIONS.filter(op=>op.startsWith("full.diagnostics.")));
59
+ export const JOB_BROKER_OPERATION="full.internal.jobs.run";
60
+ export const RESOURCE_HEALTH_OPERATION="full.internal.resources.health";
61
+ export const INTELLIGENCE_BROKER_OPERATION="full.internal.intelligence.run";
62
+ export const WORKSPACE_BROKER_OPERATIONS=Object.freeze(["full.internal.workspace.snapshot","full.internal.workspace.set"]);
63
+ // Private inherited IPC only. This is deliberately absent from remote operations.
64
+ export const PRESENTATION_WORKSPACE_OPERATION="full.internal.presentation.workspace";
65
+ export const EDIT_BROKER_OPERATION="full.internal.workspace.edit";
66
+ export const ISOLATION_BROKER_OPERATION="full.internal.workspace.set-isolated";
67
+ export const ARTIFACT_BROKER_OPERATION="full.internal.workspace.set-artifact";
68
+ export const REMOTE_FULL_CAPABILITIES=Object.freeze(["full.host","full.sessions","full.sessions.lifecycle","full.workspace.readonly","full.workspace.read-batch","full.workspace.isolated","full.workspace.artifacts","full.workspace.edit","full.intelligence","full.intelligence.batch","full.intelligence.task-context","full.intelligence.task-context.expand","full.jobs","full.jobs.recovery","full.jobs.wait","full.verification","full.diagnostics","full.desktop"]);
69
+
70
+ /** Public request contains data only. It cannot choose an authority, a job,
71
+ * an evidence producer, an arbitrary absolute read target or host capability. */
72
+ export function parseRemoteFullRequest(value){
73
+ require(exact(value,["operation","input"])&&typeof value.operation==="string"&&Object.hasOwn(descriptors,value.operation),"full_capability_unavailable");
74
+ const {operation}=value,descriptor=descriptors[operation];
75
+ const input=record(value.input)?{...value.input}:value.input;
76
+ require(exact(input,descriptor.fields),"full_invalid_remote_input");
77
+ if(descriptor.session||Object.hasOwn(input,"taskSessionId"))require(id(input.taskSessionId),"full_invalid_session_id");
78
+ if(operation==="full.session.ensure"){
79
+ require(["create","ensure","resume","new-attempt"].includes(input.intent)&&id(input.idempotencyKey),"full_invalid_intent");
80
+ if(["resume","new-attempt"].includes(input.intent))require(id(input.taskSessionId),"full_invalid_session_id");
81
+ if(input.intent==="create")require(!Object.hasOwn(input,"taskSessionId"),"full_invalid_session_id");
82
+ }
83
+ if(operation==="full.session.export"){
84
+ require(input.confirmed===true,"full_export_confirmation_required");
85
+ if(Object.hasOwn(input,"cursor"))require(typeof input.cursor==="string"&&input.cursor.length>=1&&input.cursor.length<=512&&/^[A-Za-z0-9_-]+$/.test(input.cursor),"full_invalid_cursor");
86
+ }
87
+ if(operation==="full.session.delete")require(input.confirmed===true,"full_delete_confirmation_required");
88
+ if(operation.startsWith("full.task.")||operation==="full.session.delete")require(Number.isSafeInteger(input.expectedRevision)&&input.expectedRevision>=1,"full_revision_required");
89
+ if(operation==="full.session.acknowledge")require(id(input.consumerId)&&Number.isSafeInteger(input.revision)&&input.revision>=1,"full_invalid_cursor");
90
+ if(Object.hasOwn(input,"consumerId"))require(id(input.consumerId),"full_invalid_identifier");
91
+ if(operation==="full.task.plan")require(Array.isArray(input.steps)&&input.steps.length<=32&&input.steps.every(step=>exact(step,["stepId","title"])),"full_invalid_task_step");
92
+ if(operation==="full.task.checkpoint")require(exact(input.facts,["requirements","decisions","changedFiles","outcomes","blockers","summary","nextSteps"]),"full_invalid_checkpoint_field");
93
+ if(operation==="full.workspace.ensure"){
94
+ require(["git","artifact","research","desktop","read-only"].includes(input.kind),"full_invalid_workspace_kind");
95
+ const has=key=>Object.hasOwn(input,key);
96
+ const boundedPath=value=>typeof value==="string"&&value.length>0&&value.length<=512&&!/[\u0000-\u001f]/.test(value);
97
+ if(input.kind==="git"){
98
+ require(!has("artifactRoot"),"full_invalid_workspace_mode");
99
+ input.mode=input.mode===undefined?"isolated":input.mode;
100
+ require(["isolated","main","shared"].includes(input.mode),"full_invalid_workspace_mode");
101
+ require(!has("baseRef")||(input.mode==="isolated"&&typeof input.baseRef==="string"&&input.baseRef.length>0&&input.baseRef.length<=256&&!/[\u0000\r\n]/.test(input.baseRef)),"full_invalid_workspace_base");
102
+ require(boundedPath(input.repoPath),"full_invalid_resource_path");
103
+ require(input.mode==="shared"?boundedPath(input.sharedPath):!has("sharedPath"),"full_invalid_resource_path");
104
+ }else if(input.kind==="artifact"){
105
+ input.mode=input.mode===undefined?"isolated":input.mode;
106
+ require(input.mode==="isolated"&&!has("repoPath")&&!has("sharedPath")&&!has("baseRef"),"full_invalid_workspace_mode");
107
+ require(boundedPath(input.artifactRoot),"full_invalid_resource_path");
108
+ }else require(!has("repoPath")&&!has("sharedPath")&&!has("baseRef")&&!has("artifactRoot")&&(!has("mode")||input.mode==="none"),"full_invalid_workspace_mode");
109
+ }
110
+ if(operation==="full.workspace.read"){
111
+ const multi=Object.hasOwn(input,"relativePaths");
112
+ require(multi?!Object.hasOwn(input,"relativePath")&&Array.isArray(input.relativePaths)&&input.relativePaths.length>=1&&input.relativePaths.length<=4&&input.relativePaths.every(relativePath)&&new Set(input.relativePaths.map(p=>p.toLowerCase())).size===input.relativePaths.length:relativePath(input.relativePath),"full_invalid_resource_path");
113
+ }
114
+ if(operation==="full.workspace.edit"){
115
+ const ops=input.operations;
116
+ require(Array.isArray(ops)&&ops.length>=1&&ops.length<=8,"full_invalid_edit_batch");
117
+ for(const op of ops){
118
+ require(record(op)&&relativePath(op.relativePath),"full_invalid_resource_path");
119
+ if(op.op==="create")require(exact(op,["op","relativePath","content"])&&typeof op.content==="string"&&op.content.isWellFormed()&&!op.content.includes("\u0000"),"full_invalid_edit_batch");
120
+ else require(op.op==="edit"&&exact(op,["op","relativePath","edits"])&&Array.isArray(op.edits)&&op.edits.length>=1&&op.edits.length<=20&&op.edits.every(e=>exact(e,["oldText","newText","expectedReplacements"])&&typeof e.oldText==="string"&&e.oldText.length>0&&e.oldText.isWellFormed()&&typeof e.newText==="string"&&e.newText.isWellFormed()&&!e.oldText.includes("\u0000")&&!e.newText.includes("\u0000")&&(e.expectedReplacements===undefined||Number.isSafeInteger(e.expectedReplacements)&&e.expectedReplacements>=1&&e.expectedReplacements<=100)),"full_invalid_edit_batch");
121
+ }
122
+ require(new TextEncoder().encode(JSON.stringify(ops)).byteLength<=44000,"full_frame_too_large");
123
+ }
124
+ if(operation==="full.intelligence.refresh"){
125
+ if(Object.hasOwn(input,"taskContext")){
126
+ const context=input.taskContext;
127
+ require(exact(context,["consumerId","phase","query","requirements","learn","budgetBytes","detail"]),"full_invalid_task_context");
128
+ require(context.detail===undefined||["compact","expanded"].includes(context.detail),"full_invalid_task_context");
129
+ require(id(context.consumerId)&&typeof context.query==="string"&&context.query.trim().length>0&&context.query.length<=512&&context.query.isWellFormed(),"full_invalid_task_context");
130
+ require(context.phase===undefined||["prepare","read","execute","verify","complete","review","implement","test","resume"].includes(context.phase),"full_invalid_task_context");
131
+ require(context.budgetBytes===undefined||Number.isSafeInteger(context.budgetBytes)&&context.budgetBytes>=4096&&context.budgetBytes<=16000,"full_invalid_task_context");
132
+ require(context.requirements===undefined||Array.isArray(context.requirements)&&context.requirements.length<=32&&context.requirements.every(v=>typeof v==="string"&&v.length<=512&&v.isWellFormed()),"full_invalid_task_context");
133
+ require(context.learn===undefined||Array.isArray(context.learn)&&context.learn.length<=8&&context.learn.every(m=>exact(m,["memoryId","revision","content"])&&id(m.memoryId)&&typeof m.content==="string"&&m.content.length<=2048&&m.content.isWellFormed()&&(m.revision===undefined||typeof m.revision==="string"&&m.revision.length<=128)),"full_invalid_task_context");
134
+ require(new TextEncoder().encode(JSON.stringify(context)).byteLength<=24000,"full_invalid_task_context");
135
+ }
136
+ if(Object.hasOwn(input,"queries")){
137
+ require(Array.isArray(input.queries)&&input.queries.length>=1&&input.queries.length<=4,"full_invalid_query_batch");
138
+ for(const query of input.queries){
139
+ require(record(query)&&["search","symbols","dependencies"].includes(query.kind),"full_invalid_query_batch");
140
+ const fields=query.kind==="dependencies"?["kind","files","direction","depth"]:["kind","query","limit"];
141
+ require(exact(query,fields),"full_invalid_query_batch");
142
+ const {kind,...options}=query;
143
+ // Share the standalone query checks without allowing nested authority,
144
+ // cursors, refreshes or effectful operations inside a retrieval batch.
145
+ parseRemoteFullRequest({operation:"full.intelligence."+kind,input:{taskSessionId:input.taskSessionId,...options}});
146
+ }
147
+ }
148
+ if(Object.hasOwn(input,"readPaths")){
149
+ require(Array.isArray(input.readPaths)&&input.readPaths.length>=1&&input.readPaths.length<=4&&input.readPaths.every(relativePath),"full_invalid_resource_path");
150
+ require(new Set(input.readPaths.map(p=>p.toLowerCase())).size===input.readPaths.length,"full_invalid_query_batch");
151
+ }
152
+ }
153
+ if(operation==="full.intelligence.search"||operation==="full.intelligence.symbols"){
154
+ require(typeof input.query==="string"&&input.query.trim().length>0&&input.query.length<=(operation.endsWith("symbols")?128:256),"full_invalid_index_query");
155
+ require(input.limit===undefined||Number.isSafeInteger(input.limit)&&input.limit>=1&&input.limit<=10,"full_invalid_page");
156
+ }
157
+ if(operation==="full.intelligence.dependencies"){
158
+ require(Array.isArray(input.files)&&input.files.length>=1&&input.files.length<=8&&input.files.every(p=>typeof p==="string"&&p.length>0&&p.length<=512&&!p.startsWith("/")&&!/[\\:\u0000-\u001f]/.test(p)&&p.split("/").every(x=>x&&x!=="."&&x!=="..")),"full_invalid_graph_roots");
159
+ require(input.direction===undefined||["consumers","dependencies"].includes(input.direction),"full_invalid_graph_direction");
160
+ require(input.depth===undefined||Number.isSafeInteger(input.depth)&&input.depth>=1&&input.depth<=4,"full_invalid_graph_depth");
161
+ }
162
+ if(operation==="full.intelligence.impact"){
163
+ require(input.baseGeneration===undefined||Number.isSafeInteger(input.baseGeneration)&&input.baseGeneration>=1,"full_invalid_revision");
164
+ for(const key of ["proposedPaths","proposedSymbolIds","mandatoryChecks"])
165
+ require(input[key]===undefined||Array.isArray(input[key])&&input[key].length<=32&&input[key].every(v=>typeof v==="string"&&v.length>0&&v.length<=512),"full_invalid_impact_input");
166
+ }
167
+ if(operation==="full.intelligence.context"||operation==="full.intelligence.acknowledge")require(id(input.consumerId),"full_invalid_identifier");
168
+ if(operation==="full.intelligence.context")require(input.budgetBytes===undefined||Number.isSafeInteger(input.budgetBytes)&&input.budgetBytes>=4096&&input.budgetBytes<=32000,"full_context_invalid_budget_or_query");
169
+ if(operation==="full.intelligence.acknowledge")require(id(input.deliveryId),"full_invalid_identifier");
170
+ if(operation==="full.verification.plan"||operation==="full.verification.record")require(Number.isSafeInteger(input.expectedRevision)&&input.expectedRevision>=1,"full_revision_required");
171
+ if(operation==="full.verification.plan"){
172
+ require(Array.isArray(input.requirements)&&input.requirements.length>=1&&input.requirements.length<=16&&input.requirements.every(r=>exact(r,["requirementId","title"])&&id(r.requirementId)&&typeof r.title==="string"&&r.title.trim()&&r.title.length<=256),"full_invalid_verification_plan");
173
+ require(Array.isArray(input.checks)&&input.checks.length>=1&&input.checks.length<=8,"full_invalid_verification_plan");
174
+ for(const c of input.checks){
175
+ require(exact(c,["checkId","title","requirementIds","mandatory","command","timeoutMs","paths"])&&id(c.checkId)&&typeof c.title==="string"&&c.title.trim()&&c.title.length<=128&&Array.isArray(c.requirementIds)&&c.requirementIds.length>=1&&c.requirementIds.length<=8&&c.requirementIds.every(id)&&typeof c.mandatory==="boolean","full_invalid_verification_check");
176
+ require(typeof c.command==="string"&&c.command.trim()&&c.command.length<=4000&&!c.command.includes("\u0000"),"full_invalid_job_request");
177
+ require(c.timeoutMs===undefined||Number.isSafeInteger(c.timeoutMs)&&c.timeoutMs>=1000&&c.timeoutMs<=1800000,"full_invalid_timeout");
178
+ require(Array.isArray(c.paths)&&c.paths.length>=1&&c.paths.length<=6&&c.paths.every(p=>relativePath(p)&&p.length<=100)&&new Set(c.paths.map(p=>p.toLowerCase())).size===c.paths.length,"full_verification_input_limit");
179
+ }
180
+ require(new Set(input.checks.flatMap(c=>c.paths)).size<=12,"full_verification_input_limit");
181
+ require(input.risk===undefined||["trivial","low","normal","high"].includes(input.risk),"full_invalid_verification_plan");
182
+ require(["knownImplementationComplete","staticReviewComplete"].every(k=>input[k]===undefined||typeof input[k]==="boolean"),"full_invalid_verification_plan");
183
+ }
184
+ if(operation==="full.verification.record")require(id(input.jobId),"full_invalid_job");
185
+ if(operation===DIAGNOSTICS_OPERATION&&input.cursor!==undefined)require(exact(input.cursor,["epoch","sequence","sourceGaps"])&&id(input.cursor.epoch)&&Number.isSafeInteger(input.cursor.sequence)&&input.cursor.sequence>=0&&Number.isSafeInteger(input.cursor.sourceGaps)&&input.cursor.sourceGaps>=0,"full_invalid_cursor");
186
+ if(operation==="full.diagnostics.mode"){
187
+ require(["normal","debug","profile"].includes(input.mode),"full_invalid_diagnostic_mode");
188
+ require(input.mode==="normal"?(input.confirmed===undefined||typeof input.confirmed==="boolean"):input.confirmed===true,"full_diagnostic_confirmation_required");
189
+ require(input.durationMs===undefined||Number.isSafeInteger(input.durationMs)&&input.durationMs>=100&&input.durationMs<=1800000,"full_invalid_timeout");
190
+ }
191
+ if(operation==="full.diagnostics.export")require(input.confirmed===true,"full_diagnostic_confirmation_required");
192
+ if(operation==="full.desktop.windows")require(input.limit===undefined||Number.isSafeInteger(input.limit)&&input.limit>=1&&input.limit<=32,"full_invalid_page");
193
+ if(operation==="full.desktop.step"){
194
+ require(id(input.idempotencyKey)&&Array.isArray(input.actions)&&input.actions.length>=1&&input.actions.length<=20,"full_invalid_desktop_step");
195
+ require(input.settleMs===undefined||Number.isSafeInteger(input.settleMs)&&input.settleMs>=0&&input.settleMs<=1000,"full_invalid_desktop_step");
196
+ let wait=0,bytes=0;
197
+ for(const action of input.actions){
198
+ require(record(action),"full_invalid_desktop_step");
199
+ if(action.type==="click")require(exact(action,["type","x","y","button","clicks"])&&[action.x,action.y].every(n=>Number.isSafeInteger(n)&&Math.abs(n)<=1000000)&&(action.button===undefined||["left","right","middle"].includes(action.button))&&(action.clicks===undefined||action.clicks===1||action.clicks===2),"full_invalid_desktop_step");
200
+ else if(action.type==="text"){
201
+ require(exact(action,["type","text"])&&typeof action.text==="string"&&action.text.length>0&&action.text.length<=8192&&action.text.isWellFormed()&&!action.text.includes("\u0000"),"full_invalid_desktop_step");
202
+ bytes+=new TextEncoder().encode(action.text).byteLength;
203
+ }else if(action.type==="key")require(exact(action,["type","key","ctrl","alt","shift","win"])&&typeof action.key==="string"&&/^(?:[A-Za-z0-9]|Enter|Tab|Escape|Backspace|Delete|Arrow(?:Left|Up|Right|Down)|Home|End|PageUp|PageDown|Space|F(?:[1-9]|1[0-2]))$/.test(action.key)&&["ctrl","alt","shift","win"].every(k=>action[k]===undefined||typeof action[k]==="boolean"),"full_invalid_desktop_step");
204
+ else if(action.type==="wait"){require(exact(action,["type","ms"])&&Number.isSafeInteger(action.ms)&&action.ms>=0&&action.ms<=2000,"full_invalid_desktop_step");wait+=action.ms;}
205
+ else throw new FullContractError("full_invalid_desktop_step");
206
+ }
207
+ require(wait<=2000&&bytes<=16384,"full_invalid_desktop_step");
208
+ }
209
+ if(operation==="full.job.start"){
210
+ require(id(input.idempotencyKey)&&typeof input.command==="string"&&input.command.trim().length>0&&input.command.length<=4000&&!input.command.includes("\u0000"),"full_invalid_job_request");
211
+ require(input.verificationCheckId===undefined||id(input.verificationCheckId),"full_invalid_verification_check");
212
+ input.timeoutMs=input.timeoutMs===undefined?120000:input.timeoutMs;
213
+ require(Number.isSafeInteger(input.timeoutMs)&&input.timeoutMs>=1000&&input.timeoutMs<=1800000,"full_invalid_timeout");
214
+ }else if(REMOTE_JOB_OPERATIONS.includes(operation)){
215
+ require(id(input.jobId),"full_invalid_job");
216
+ if(operation==="full.job.read")require(input.afterSeq===undefined||Number.isSafeInteger(input.afterSeq)&&input.afterSeq>=0,"full_invalid_cursor");
217
+ }
218
+ if((operation==="full.job.start"||operation==="full.job.read")&&Object.hasOwn(input,"waitMs"))
219
+ require(Number.isSafeInteger(input.waitMs)&&input.waitMs>=0&&input.waitMs<=8000,"full_invalid_wait");
220
+ let encoded;try{encoded=JSON.stringify(input);}catch{throw new FullContractError("full_invalid_remote_input");}
221
+ require(typeof encoded==="string"&&new TextEncoder().encode(encoded).byteLength<=FULL_LIMITS.frameBytes-4096,"full_frame_too_large");
222
+ return {operation,input:JSON.parse(encoded),requiredScopes:operation==="full.workspace.ensure"&&input.kind==="git"&&input.mode==="isolated"?["read","write","terminal"]:["read",...(descriptor.write?["write"]:[]),...(descriptor.terminal?["terminal"]:[]),...(descriptor.desktopRead?["desktop_read"]:[]),...(descriptor.desktopControl?["desktop_control"]:[])]};
223
+ }
224
+ /** Trusted Worker only, AFTER selecting an explicit agent and checking all
225
+ * required ACL scopes. The public /relay route never accepts full.invoke. */
226
+ export function createAuthorizedFullInvocation(request,{accountId,agentId}){
227
+ const parsed=parseRemoteFullRequest(request);
228
+ require(id(accountId)&&typeof agentId==="string"&&AGENT.test(agentId),"full_unauthorized");
229
+ return {action:"full.invoke",operation:parsed.operation,input:parsed.input,principal:{accountId,agentId,scopes:parsed.requiredScopes}};
230
+ }
231
+ /** Defense in depth at the agent and supervised child. No wildcard grants,
232
+ * extra fields or foreign agent identities in an internal invocation. */
233
+ export function parseAuthorizedFullInvocation(value,agentId){
234
+ require(exact(value,["action","operation","input","principal"])&&value.action==="full.invoke","full_unauthorized");
235
+ const parsed=parseRemoteFullRequest({operation:value.operation,input:value.input});
236
+ const p=value.principal;
237
+ require(exact(p,["accountId","agentId","scopes"])&&id(p.accountId)&&p.agentId===agentId&&AGENT.test(agentId)&&Array.isArray(p.scopes)&&p.scopes.length===parsed.requiredScopes.length&&parsed.requiredScopes.every(scope=>p.scopes.includes(scope)),"full_unauthorized");
238
+ return {...parsed,principal:{accountId:p.accountId,agentId,scopes:parsed.requiredScopes}};
239
+ }