gdp-wired 0.50.3 → 0.50.4
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 +4 -0
- package/dist/core/agent-consult/cli.d.ts +2 -0
- package/dist/core/agent-consult/cli.js +19 -0
- package/dist/core/agent-consult/protocol.d.ts +93 -0
- package/dist/core/agent-consult/protocol.js +154 -0
- package/dist/core/agent-consult/service.d.ts +435 -0
- package/dist/core/agent-consult/service.js +84 -0
- package/dist/core/agent-consult/session.d.ts +13 -0
- package/dist/core/agent-consult/session.js +163 -0
- package/dist/core/agent-consult/source-service.d.ts +83 -0
- package/dist/core/agent-consult/source-service.js +51 -0
- package/dist/core/agent-consult/tsconfig.json +5 -0
- package/dist/core/agent-consult/worker.d.ts +1 -0
- package/dist/core/agent-consult/worker.js +17 -0
- package/dist/core/agent-consult/workspace.d.ts +27 -0
- package/dist/core/agent-consult/workspace.js +66 -0
- package/dist/core/agent-consult.d.ts +8 -0
- package/dist/core/agent-consult.js +6 -0
- package/dist/core/cli.d.ts +5 -0
- package/dist/core/cli.js +118 -49
- package/docs/agent-consult-workspace-check.md +118 -0
- package/docs/agent-consult.md +151 -0
- package/examples/agent-consult.json +22 -0
- package/package.json +11 -3
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { parseRequest, Refusal, toolNames, toolDescriptions, inputSchema } from "./protocol.js";
|
|
4
|
+
import { configureRoots } from "./workspace.js";
|
|
5
|
+
export function createConsultation(options = {}) {
|
|
6
|
+
const roots = configureRoots(options.workspaceRoots);
|
|
7
|
+
const records = new Map();
|
|
8
|
+
let cancelActive;
|
|
9
|
+
let closed = false;
|
|
10
|
+
let queue = Promise.resolve();
|
|
11
|
+
const refusal = (code, message, fix) => ({ schema: 'gdp-wired/agent-tool/v1', ok: false, refusal: { code, message, fix }, explanation: `${message} Fix: ${fix}` });
|
|
12
|
+
const result = (value) => ({ content: [{ type: 'text', text: JSON.stringify(value) }], structuredContent: value, isError: value.ok === false });
|
|
13
|
+
function runWorker(tool, args, signal) {
|
|
14
|
+
return new Promise((resolve, reject) => {
|
|
15
|
+
if (closed || signal?.aborted) {
|
|
16
|
+
reject(new Refusal('cancelled', 'Create a new session or retry without an aborted signal.', 'Consultation was cancelled.'));
|
|
17
|
+
return;
|
|
18
|
+
}
|
|
19
|
+
const input = JSON.stringify({ tool, args, ...(tool === 'check' ? { roots } : {}) });
|
|
20
|
+
if (Buffer.byteLength(input) > 131072) {
|
|
21
|
+
reject(new Refusal('input-budget-exceeded', 'Reduce the request to128KiB.', 'Worker input exceeds128KiB.'));
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
const worker = import.meta.url.endsWith('.ts') ? './worker.ts' : './worker.js';
|
|
25
|
+
const child = spawn(process.execPath, [fileURLToPath(new URL(worker, import.meta.url))], { stdio: ['pipe', 'pipe', 'pipe'], env: { PATH: process.env.PATH, HOME: process.env.HOME, TMPDIR: process.env.TMPDIR, LANG: 'C.UTF-8', GDP_WORK_FULL: '1', GDP_WORK_W: '500000' } });
|
|
26
|
+
let out = '', err = '', failure;
|
|
27
|
+
// Wait for close before releasing the session queue: no overlap/orphan on cancellation.
|
|
28
|
+
const fail = (e) => { if (failure)
|
|
29
|
+
return; failure = e; child.kill('SIGTERM'); };
|
|
30
|
+
const cancel = () => fail(new Refusal('cancelled', 'Retry in an open session with a fresh signal.', 'Consultation was cancelled; no conclusion is available.'));
|
|
31
|
+
cancelActive = cancel;
|
|
32
|
+
signal?.addEventListener('abort', cancel, { once: true });
|
|
33
|
+
if (signal?.aborted)
|
|
34
|
+
cancel();
|
|
35
|
+
child.stdout.on('data', (x) => { out += x.toString(); if (Buffer.byteLength(out) > 262144)
|
|
36
|
+
fail(new Error('worker output exceeds256KiB')); });
|
|
37
|
+
child.stderr.on('data', (x) => { if (err.length < 8192)
|
|
38
|
+
err += x.toString().slice(0, 8192 - err.length); });
|
|
39
|
+
child.on('error', fail);
|
|
40
|
+
child.on('close', code => { cancelActive = undefined; signal?.removeEventListener('abort', cancel); if (failure) {
|
|
41
|
+
reject(failure);
|
|
42
|
+
return;
|
|
43
|
+
} if (code !== 0) {
|
|
44
|
+
reject(new Error(`worker exited (${code}): ${err}`));
|
|
45
|
+
return;
|
|
46
|
+
} try {
|
|
47
|
+
const v = JSON.parse(out);
|
|
48
|
+
if (!v || typeof v.ok !== 'boolean' || v.schema !== 'gdp-wired/agent-tool/v1')
|
|
49
|
+
throw Error('invalid worker envelope');
|
|
50
|
+
resolve(v);
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
reject(new Error(`worker failed (${code}): ${err || 'invalid JSON'}`));
|
|
54
|
+
} });
|
|
55
|
+
child.stdin.on('error', fail);
|
|
56
|
+
child.stdin.end(input);
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
async function dispatch(request, signal) {
|
|
60
|
+
if (!request || typeof request !== 'object' || Array.isArray(request))
|
|
61
|
+
return { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid Request' } };
|
|
62
|
+
const q = request, id = q.id;
|
|
63
|
+
if (id !== undefined && id !== null && typeof id !== 'string' && (typeof id !== 'number' || !Number.isFinite(id)))
|
|
64
|
+
return { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid request id' } };
|
|
65
|
+
if (q.jsonrpc !== '2.0' || typeof q.method !== 'string')
|
|
66
|
+
return { jsonrpc: '2.0', id: id ?? null, error: { code: -32600, message: 'Invalid Request' } };
|
|
67
|
+
if (id === undefined)
|
|
68
|
+
return null;
|
|
69
|
+
const respond = (r) => ({ jsonrpc: '2.0', id, result: r });
|
|
70
|
+
if (q.method === 'initialize')
|
|
71
|
+
return respond({ protocolVersion: '2024-11-05', capabilities: { tools: { listChanged: false } }, serverInfo: { name: 'gdp-wired-agent-consult', version: '1.0.0' }, instructions: roots.length ? 'Scalar rule tools plus explicit trusted-workspace check. Workspace check executes project code/imports; not an OS sandbox. Only server-configured roots authorize files. Counted-work profile provisional; external runtime is not counted. Cancellation/exhaustion are not conclusions.' : 'Data-only scalar natural rule consultation by default. Workspace check disabled: no server roots. Checked model proofs only; counted-work profile provisional. Cancellation/exhaustion are not conclusions.' });
|
|
72
|
+
if (q.method === 'ping')
|
|
73
|
+
return respond({});
|
|
74
|
+
if (q.method === 'tools/list')
|
|
75
|
+
return respond({ tools: toolNames.map(name => ({ name, description: toolDescriptions[name], inputSchema: inputSchema(name) })) });
|
|
76
|
+
if (q.method !== 'tools/call')
|
|
77
|
+
return { jsonrpc: '2.0', id, error: { code: -32601, message: 'Method not found' } };
|
|
78
|
+
const params = q.params, tool = params?.name, args = params?.arguments;
|
|
79
|
+
try {
|
|
80
|
+
if (closed || signal?.aborted)
|
|
81
|
+
throw new Refusal('cancelled', 'Use an open session and a fresh signal.', 'Consultation was cancelled.');
|
|
82
|
+
const parsed = parseRequest(tool, args);
|
|
83
|
+
if (parsed.tool === 'check' && !roots.length)
|
|
84
|
+
throw new Refusal('workspace-unconfigured', 'Configure trusted workspaceRoots on the server; callers cannot grant roots.', 'File checking is disabled by default.');
|
|
85
|
+
if (parsed.tool === 'status') {
|
|
86
|
+
const key = parsed.unit + '@' + parsed.revision, known = records.get(key);
|
|
87
|
+
if (!known)
|
|
88
|
+
return respond(result({ ...refusal('missing-evidence', 'No local checked evidence exists for this exact unit/revision.', 'Call prove/check_change on the same rule and laws first; native labels require separately validated runtime evidence.'), tool: 'status', subject: { unit: parsed.unit, revision: parsed.revision }, label: 'not adequate' }));
|
|
89
|
+
const proven = known.proven === true && known.checked === true;
|
|
90
|
+
return respond(result({ schema: 'gdp-wired/agent-tool/v1', tool: 'status', ok: true, subject: { unit: known.unit, revision: known.revision }, label: proven ? 'proven' : 'not adequate', result: { proven: known.proven, checked: known.checked, laws: known.laws, nativeLabel: null, assumptions: known.assumptions ?? null, source: 'local isolated existing-kernel proof receipt' }, explanation: `${known.unit}: ${proven ? 'all requested laws were proven and checked' : 'one or more requested laws remain unproven or unchecked'}. No conformance or harness-checked evidence is available; a supplied label is never accepted.`, budget: { apiCalls: 0, work: { numerator: '0', denominator: '1' } } }));
|
|
91
|
+
}
|
|
92
|
+
const value = await runWorker(parsed.tool, args, signal);
|
|
93
|
+
if (closed || signal?.aborted)
|
|
94
|
+
throw new Refusal('cancelled', 'Retry in an open session with a fresh signal.', 'Consultation was cancelled; no evidence was retained.');
|
|
95
|
+
if (Array.isArray(value.statusEvidence))
|
|
96
|
+
for (const raw of value.statusEvidence) {
|
|
97
|
+
const s = raw;
|
|
98
|
+
if (typeof s.unit !== 'string' || typeof s.revision !== 'string' || !/^[a-f0-9]{64}$/.test(s.revision) || typeof s.proven !== 'boolean' || typeof s.checked !== 'boolean' || !Array.isArray(s.laws))
|
|
99
|
+
continue;
|
|
100
|
+
const key = s.unit + '@' + s.revision, old = records.get(key);
|
|
101
|
+
if (!old || !old.proven || s.proven && s.checked)
|
|
102
|
+
records.set(key, s);
|
|
103
|
+
while (records.size > 256)
|
|
104
|
+
records.delete(records.keys().next().value);
|
|
105
|
+
}
|
|
106
|
+
delete value.statusEvidence;
|
|
107
|
+
return respond(result(value));
|
|
108
|
+
}
|
|
109
|
+
catch (e) {
|
|
110
|
+
return respond(result(e instanceof Refusal ? refusal(e.code, e.message, e.fix) : refusal('worker-failure', e instanceof Error ? e.message : String(e), 'Inspect stderr and retry the supported scalar request with counted budgets; do not infer a proof.')));
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
function handle(request, options = {}) {
|
|
114
|
+
const next = queue.then(() => dispatch(request, options.signal));
|
|
115
|
+
queue = next.catch(() => undefined);
|
|
116
|
+
return next;
|
|
117
|
+
}
|
|
118
|
+
function close() { closed = true; records.clear(); cancelActive?.(); return queue.then(() => undefined); }
|
|
119
|
+
async function call(tool, args, options = {}) {
|
|
120
|
+
const response = await handle({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: tool, arguments: args } }, options);
|
|
121
|
+
return response.result.structuredContent;
|
|
122
|
+
}
|
|
123
|
+
return { handle, call, close };
|
|
124
|
+
}
|
|
125
|
+
export async function serveStdio(options = {}) {
|
|
126
|
+
const session = createConsultation(options);
|
|
127
|
+
const stop = () => { void session.close(); process.exitCode = 1; process.stdin.destroy(); };
|
|
128
|
+
process.on('SIGTERM', stop);
|
|
129
|
+
process.on('SIGINT', stop);
|
|
130
|
+
try {
|
|
131
|
+
let pending = '';
|
|
132
|
+
for await (const chunk of process.stdin) {
|
|
133
|
+
pending += chunk.toString();
|
|
134
|
+
if (Buffer.byteLength(pending) > 131072 && !pending.includes('\n'))
|
|
135
|
+
throw new Error('MCP request exceeds128KiB');
|
|
136
|
+
let split;
|
|
137
|
+
while ((split = pending.indexOf('\n')) >= 0) {
|
|
138
|
+
const line = pending.slice(0, split);
|
|
139
|
+
pending = pending.slice(split + 1);
|
|
140
|
+
if (!line.trim())
|
|
141
|
+
continue;
|
|
142
|
+
let response;
|
|
143
|
+
try {
|
|
144
|
+
if (Buffer.byteLength(line) > 131072)
|
|
145
|
+
throw Error('request too large');
|
|
146
|
+
response = await session.handle(JSON.parse(line));
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
response = { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error or request exceeds128KiB' } };
|
|
150
|
+
}
|
|
151
|
+
if (response)
|
|
152
|
+
process.stdout.write(JSON.stringify(response) + '\n');
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
if (pending.trim())
|
|
156
|
+
process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Incomplete JSON line' } }) + '\n');
|
|
157
|
+
}
|
|
158
|
+
finally {
|
|
159
|
+
await session.close();
|
|
160
|
+
process.removeListener('SIGTERM', stop);
|
|
161
|
+
process.removeListener('SIGINT', stop);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { type WorkspaceRoot } from './workspace.js';
|
|
2
|
+
export declare function executeSource(args: unknown, roots: readonly WorkspaceRoot[]): Promise<{
|
|
3
|
+
assumptions: {
|
|
4
|
+
scope: string;
|
|
5
|
+
workspaceTrust: string;
|
|
6
|
+
supported: string[];
|
|
7
|
+
unsupported: string[];
|
|
8
|
+
};
|
|
9
|
+
budget: {
|
|
10
|
+
limits: import("./protocol.ts").Budget | null;
|
|
11
|
+
apiCalls: number;
|
|
12
|
+
work: Readonly<{
|
|
13
|
+
numerator: string;
|
|
14
|
+
denominator: string;
|
|
15
|
+
}>;
|
|
16
|
+
counters: {
|
|
17
|
+
[k: string]: string;
|
|
18
|
+
};
|
|
19
|
+
profile: "raw-work-v1";
|
|
20
|
+
provisional: boolean;
|
|
21
|
+
coverage: {
|
|
22
|
+
counted: string;
|
|
23
|
+
notCounted: string[];
|
|
24
|
+
apiCalls: string;
|
|
25
|
+
sourceBytesPerFile: number;
|
|
26
|
+
projectConfig: string;
|
|
27
|
+
clock: string;
|
|
28
|
+
};
|
|
29
|
+
};
|
|
30
|
+
reason?: string | undefined;
|
|
31
|
+
schema: string;
|
|
32
|
+
tool: string;
|
|
33
|
+
ok: boolean;
|
|
34
|
+
label: string;
|
|
35
|
+
subject: {
|
|
36
|
+
file: string;
|
|
37
|
+
root: string;
|
|
38
|
+
revision: string;
|
|
39
|
+
sources: {
|
|
40
|
+
[k: string]: {
|
|
41
|
+
hash: string;
|
|
42
|
+
dev: number;
|
|
43
|
+
ino: number;
|
|
44
|
+
size: number;
|
|
45
|
+
};
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
result: {
|
|
49
|
+
rules: import("../cli.ts").RuleOut[];
|
|
50
|
+
};
|
|
51
|
+
} | {
|
|
52
|
+
label: string;
|
|
53
|
+
budget: {
|
|
54
|
+
limits: import("./protocol.ts").Budget | null;
|
|
55
|
+
apiCalls: number;
|
|
56
|
+
work: Readonly<{
|
|
57
|
+
numerator: string;
|
|
58
|
+
denominator: string;
|
|
59
|
+
}>;
|
|
60
|
+
counters: {
|
|
61
|
+
[k: string]: string;
|
|
62
|
+
};
|
|
63
|
+
profile: "raw-work-v1";
|
|
64
|
+
provisional: boolean;
|
|
65
|
+
coverage: {
|
|
66
|
+
counted: string;
|
|
67
|
+
notCounted: string[];
|
|
68
|
+
apiCalls: string;
|
|
69
|
+
sourceBytesPerFile: number;
|
|
70
|
+
projectConfig: string;
|
|
71
|
+
clock: string;
|
|
72
|
+
};
|
|
73
|
+
};
|
|
74
|
+
schema: string;
|
|
75
|
+
tool: string;
|
|
76
|
+
ok: boolean;
|
|
77
|
+
refusal: {
|
|
78
|
+
code: string;
|
|
79
|
+
message: string;
|
|
80
|
+
fix: string;
|
|
81
|
+
};
|
|
82
|
+
explanation: string;
|
|
83
|
+
}>;
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { prepareFileCheck } from "../cli.js";
|
|
2
|
+
import { withBudget } from "../../kernel/prove.js";
|
|
3
|
+
import { completeWorkProfile } from "../work-profile.js";
|
|
4
|
+
import { workLedger } from "../work-admission.js";
|
|
5
|
+
import { exactRaw, workFromExact, workSub } from "../work-amount.js";
|
|
6
|
+
import { parseRequest, refuse, Refusal, wireJSON } from "./protocol.js";
|
|
7
|
+
import { failure } from "./service.js";
|
|
8
|
+
import { sourceGuard } from "./workspace.js";
|
|
9
|
+
// Module initialization only; this does not parse/load any workspace source.
|
|
10
|
+
export async function executeSource(args, roots) {
|
|
11
|
+
const run = await prepareFileCheck();
|
|
12
|
+
const before = workLedger.snapshot();
|
|
13
|
+
let calls = 0, sticky;
|
|
14
|
+
let limits;
|
|
15
|
+
const budget = () => { const after = workLedger.snapshot(); return { limits: limits ?? null, apiCalls: calls, work: exactRaw(workSub(workFromExact(after.actual), workFromExact(before.actual))), counters: Object.fromEntries(Object.entries(after.counters).map(([k, v]) => [k, String(BigInt(v) - BigInt(before.counters[k]))])), profile: completeWorkProfile.id, provisional: true, coverage: { counted: 'Existing engine work sinks during synchronous extraction, law parsing, proofs, replay and proposals under one root budget and sticky refusal boundary.', notCounted: ['module initialization', 'filesystem bytes/identity/hash operations', 'external interpreter runtime and project code execution', 'unmetered frontend parsing operations'], apiCalls: 'Each extraction and each top-level proof/step/liveness/two-run invocation. Internal engine subcalls are covered by counted work, not separate API calls.', sourceBytesPerFile: 131072, projectConfig: 'disabled in initial workspace profile; no ancestor discovery or project interpreter overrides', clock: 'counted logical telemetry and finite proposal candidate cap; no wall stop in the CLI proposal driver' } }; };
|
|
16
|
+
try {
|
|
17
|
+
const q = parseRequest('check', args);
|
|
18
|
+
limits = q.budget;
|
|
19
|
+
if (!completeWorkProfile.enabled)
|
|
20
|
+
refuse('counted-profile-required', 'Start source workers with GDP_WORK_FULL=1 before engine imports.', 'Counted profile is disabled.');
|
|
21
|
+
const invoke = (f) => { if (sticky)
|
|
22
|
+
throw sticky; if (calls >= q.budget.apiCalls) {
|
|
23
|
+
sticky = new Refusal('api-budget-exceeded', 'Increase budget.apiCalls or check fewer entries/laws.', 'Source engine API allowance exhausted.');
|
|
24
|
+
throw sticky;
|
|
25
|
+
} calls++; return f(); };
|
|
26
|
+
return withBudget(q.budget.work, () => workLedger.withCapacityRefusalBoundary(() => {
|
|
27
|
+
const source = sourceGuard(roots, q.file);
|
|
28
|
+
let rules;
|
|
29
|
+
try {
|
|
30
|
+
rules = run(source.file, source.root, { invoke, candidates: q.budget.candidates }, source.guard);
|
|
31
|
+
}
|
|
32
|
+
catch (e) {
|
|
33
|
+
if (e instanceof Refusal)
|
|
34
|
+
throw e;
|
|
35
|
+
refuse('source-engine-refused', 'Inspect the exact extractor reason; use supported Python/plain TypeScript with explicit law comments.', e instanceof Error ? e.message : String(e));
|
|
36
|
+
}
|
|
37
|
+
if (sticky)
|
|
38
|
+
throw sticky;
|
|
39
|
+
const receipt = source.receipt();
|
|
40
|
+
const laws = rules.flatMap(r => r.laws);
|
|
41
|
+
const label = rules.length > 0 && rules.every(r => r.ok) && laws.length > 0 && laws.every(l => l.verdict === 'proven') ? 'proven' : laws.some(l => l.verdict === 'broken' && l.run?.length) ? 'broken' : 'unknown';
|
|
42
|
+
const output = { schema: 'gdp-wired/agent-tool/v1', tool: 'check', ok: true, label, subject: receipt, result: { rules }, ...(label === 'unknown' ? { reason: 'No complete checked proof set, no stated laws, or a source/law was refused; inspect rule refusals and law reasons.' } : {}), assumptions: { scope: 'Existing CLI file extraction, model proof and native replay behavior; not an OS sandbox or a proof of every possible runtime behavior.', workspaceTrust: 'Server-configured roots explicitly authorize runtime/project code execution, imports and dependencies. Mutable hostile workspaces require external OS isolation.', supported: ['Python', 'plain TypeScript/JavaScript'], unsupported: ['Effect', 'XState', 'other CLI languages', 'project gdp configuration overrides'] }, budget: budget() };
|
|
43
|
+
// Serialization validation is inside the sticky boundary too. A caught refusal cannot escape as proof.
|
|
44
|
+
wireJSON(output);
|
|
45
|
+
return output;
|
|
46
|
+
}));
|
|
47
|
+
}
|
|
48
|
+
catch (e) {
|
|
49
|
+
return { ...failure('check', e), label: 'unknown', budget: budget() };
|
|
50
|
+
}
|
|
51
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { execute, failure } from "./service.js";
|
|
2
|
+
import { wireJSON } from "./protocol.js";
|
|
3
|
+
let data = '';
|
|
4
|
+
try {
|
|
5
|
+
for await (const chunk of process.stdin) {
|
|
6
|
+
data += chunk.toString();
|
|
7
|
+
if (Buffer.byteLength(data) > 131072)
|
|
8
|
+
throw Error('worker input exceeds128KiB');
|
|
9
|
+
}
|
|
10
|
+
const request = JSON.parse(data);
|
|
11
|
+
const value = request.tool === 'check' ? await (await import("./source-service.js")).executeSource(request.args, request.roots ?? []) : execute(request.tool, request.args);
|
|
12
|
+
process.stdout.write(wireJSON(value) + '\n');
|
|
13
|
+
}
|
|
14
|
+
catch (e) {
|
|
15
|
+
process.stdout.write(wireJSON(failure('worker', e)) + '\n');
|
|
16
|
+
process.exitCode = 1;
|
|
17
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export type WorkspaceRoot = Readonly<{
|
|
2
|
+
path: string;
|
|
3
|
+
dev: number;
|
|
4
|
+
ino: number;
|
|
5
|
+
}>;
|
|
6
|
+
export type ConsultationOptions = {
|
|
7
|
+
workspaceRoots?: readonly string[];
|
|
8
|
+
};
|
|
9
|
+
export declare function configureRoots(paths?: readonly string[]): readonly WorkspaceRoot[];
|
|
10
|
+
export declare function sourceGuard(roots: readonly WorkspaceRoot[], file: string): {
|
|
11
|
+
file: string;
|
|
12
|
+
root: string;
|
|
13
|
+
guard: (candidate: string) => void;
|
|
14
|
+
receipt: () => {
|
|
15
|
+
file: string;
|
|
16
|
+
root: string;
|
|
17
|
+
revision: string;
|
|
18
|
+
sources: {
|
|
19
|
+
[k: string]: {
|
|
20
|
+
hash: string;
|
|
21
|
+
dev: number;
|
|
22
|
+
ino: number;
|
|
23
|
+
size: number;
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
};
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { realpathSync, statSync, openSync, fstatSync, readFileSync, closeSync, constants } from 'node:fs';
|
|
2
|
+
import { isAbsolute, relative, sep, extname } from 'node:path';
|
|
3
|
+
import { digest, refuse } from "./protocol.js";
|
|
4
|
+
const inside = (root, file) => { const r = relative(root, file); return r !== '' && !isAbsolute(r) && r !== '..' && !r.startsWith('..' + sep); };
|
|
5
|
+
// Called once by the server, never with tool arguments. Freeze authority before any request.
|
|
6
|
+
export function configureRoots(paths = []) {
|
|
7
|
+
if (paths.length > 16)
|
|
8
|
+
throw new Error('At most16 server workspace roots are supported');
|
|
9
|
+
return Object.freeze(paths.map(p => { if (!isAbsolute(p) || p.includes('\0'))
|
|
10
|
+
throw new Error('Workspace roots must be absolute local directories'); const path = realpathSync(p), s = statSync(path); if (!s.isDirectory())
|
|
11
|
+
throw new Error('Workspace root must be a directory'); return Object.freeze({ path, dev: s.dev, ino: s.ino }); }));
|
|
12
|
+
}
|
|
13
|
+
export function sourceGuard(roots, file) {
|
|
14
|
+
if (!roots.length)
|
|
15
|
+
refuse('workspace-unconfigured', 'Configure trusted workspaceRoots on the server; callers cannot grant roots.', 'File checking is disabled by default.');
|
|
16
|
+
if (!isAbsolute(file) || /^[a-z][a-z0-9+.-]*:/i.test(file) || file.split(/[\\/]/).includes('..'))
|
|
17
|
+
refuse('invalid-file', 'Supply an absolute local file without traversal or URL syntax.', 'Not a supported workspace path.');
|
|
18
|
+
const captures = new Map();
|
|
19
|
+
const bindings = new Map();
|
|
20
|
+
let root;
|
|
21
|
+
const guard = (candidate) => {
|
|
22
|
+
let canonical;
|
|
23
|
+
try {
|
|
24
|
+
canonical = realpathSync(candidate);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
refuse('file-unavailable', 'Use an existing readable regular file.', 'Cannot resolve workspace file.');
|
|
28
|
+
}
|
|
29
|
+
if (bindings.has(candidate) && bindings.get(candidate) !== canonical)
|
|
30
|
+
refuse('source-changed', 'Retry after symlink replacements have stopped.', 'Source path resolved to a different file during the request.');
|
|
31
|
+
bindings.set(candidate, canonical);
|
|
32
|
+
const selected = root ?? roots.find(r => inside(r.path, canonical));
|
|
33
|
+
if (!selected || !inside(selected.path, canonical))
|
|
34
|
+
refuse('outside-workspace', 'Move the file/dependency under a server-configured root.', 'Resolved file escapes its authorized workspace.');
|
|
35
|
+
const rs = statSync(selected.path);
|
|
36
|
+
if (realpathSync(selected.path) !== selected.path || rs.dev !== selected.dev || rs.ino !== selected.ino)
|
|
37
|
+
refuse('workspace-changed', 'Restart the server after reviewing the configured directory.', 'Workspace root identity changed.');
|
|
38
|
+
root = selected;
|
|
39
|
+
const fd = openSync(canonical, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
40
|
+
try {
|
|
41
|
+
const s = fstatSync(fd);
|
|
42
|
+
if (!s.isFile())
|
|
43
|
+
refuse('not-regular-file', 'Supply a regular source file, not a directory/device.', 'Target is not a regular file.');
|
|
44
|
+
if (s.size > 131072)
|
|
45
|
+
refuse('source-budget-exceeded', 'Split the source into files at most128KiB.', 'Source exceeds128KiB.');
|
|
46
|
+
const bytes = readFileSync(fd);
|
|
47
|
+
if (bytes.length > 131072)
|
|
48
|
+
refuse('source-budget-exceeded', 'Split the source into files at most128KiB.', 'Source grew past128KiB.');
|
|
49
|
+
const capture = { hash: digest(bytes.toString('base64')), dev: s.dev, ino: s.ino, size: bytes.length }, prior = captures.get(canonical);
|
|
50
|
+
if (prior && digest(prior) !== digest(capture))
|
|
51
|
+
refuse('source-changed', 'Retry after edits and file replacements have stopped.', 'Checked source identity/content changed during the request.');
|
|
52
|
+
if (realpathSync(candidate) !== canonical)
|
|
53
|
+
refuse('source-changed', 'Retry in a stable trusted workspace.', 'Source symlink changed during authorization.');
|
|
54
|
+
captures.set(canonical, capture);
|
|
55
|
+
}
|
|
56
|
+
finally {
|
|
57
|
+
closeSync(fd);
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
guard(file);
|
|
61
|
+
const canonical = realpathSync(file);
|
|
62
|
+
if (!['.py', '.ts', '.mts', '.tsx', '.js', '.mjs'].includes(extname(canonical)))
|
|
63
|
+
refuse('unsupported-source-language', 'Use Python or plain TypeScript/JavaScript; async-only Effect/XState and other CLI languages are not yet supported.', 'Unsupported workspace source language.');
|
|
64
|
+
return { file: canonical, root: root.path, guard, receipt: () => { guard(file); for (const p of captures.keys())
|
|
65
|
+
guard(p); const sources = Object.fromEntries(captures); return { file: canonical, root: root.path, revision: digest(sources), sources }; } };
|
|
66
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** Counted consultation; data-only by default. Explicit server roots opt into source execution.
|
|
2
|
+
* Each session owns a bounded evidence registry and serial isolated workers.
|
|
3
|
+
* close()/AbortSignal cancel work, never turn cancellation into a verdict.
|
|
4
|
+
*/
|
|
5
|
+
export { createConsultation, serveStdio } from './agent-consult/session.js';
|
|
6
|
+
export { parseRequest, revision, inputSchema, toolNames, toolDescriptions, Refusal } from './agent-consult/protocol.js';
|
|
7
|
+
export type { Tool, Unit, Budget, Request, Json } from './agent-consult/protocol.js';
|
|
8
|
+
export type { ConsultationOptions } from './agent-consult/workspace.js';
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Counted consultation; data-only by default. Explicit server roots opt into source execution.
|
|
2
|
+
* Each session owns a bounded evidence registry and serial isolated workers.
|
|
3
|
+
* close()/AbortSignal cancel work, never turn cancellation into a verdict.
|
|
4
|
+
*/
|
|
5
|
+
export { createConsultation, serveStdio } from "./agent-consult/session.js";
|
|
6
|
+
export { parseRequest, revision, inputSchema, toolNames, toolDescriptions, Refusal } from "./agent-consult/protocol.js";
|
package/dist/core/cli.d.ts
CHANGED
|
@@ -5,6 +5,10 @@ import { type Verdict } from './dsl.js';
|
|
|
5
5
|
import type { TranslationFields } from './source-check.js';
|
|
6
6
|
import { type SearchTerminationFields } from './search-termination.js';
|
|
7
7
|
import { type LawText } from './laws.js';
|
|
8
|
+
type SyncControl = {
|
|
9
|
+
invoke: <T>(f: () => T) => T;
|
|
10
|
+
candidates: number;
|
|
11
|
+
};
|
|
8
12
|
export declare const colors: (env: Record<string, string | undefined>, tty: boolean, json?: boolean) => boolean;
|
|
9
13
|
export type Opts = {
|
|
10
14
|
entry?: string;
|
|
@@ -89,6 +93,7 @@ type Scoped = LawText & {
|
|
|
89
93
|
};
|
|
90
94
|
export declare function scoped(file: string): Scoped[];
|
|
91
95
|
export declare function checkTarget(t: Target, o: Opts): Promise<RuleOut[]>;
|
|
96
|
+
export declare function prepareFileCheck(): Promise<(file: string, root: string, control: SyncControl, guard: (file: string) => void) => RuleOut[]>;
|
|
92
97
|
export declare function runOf(x: Extraction, run: NonNullable<Verdict['run']>): string[];
|
|
93
98
|
export declare const proposedLaws: (x: Extraction, lang: Lang, ms?: number) => {
|
|
94
99
|
shown: LawOut[];
|