@foundocs/foundocs-setup 0.5.0 → 0.5.2

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.
@@ -1,190 +0,0 @@
1
- import { readdir } from 'node:fs/promises';
2
- import { randomUUID } from 'node:crypto';
3
- import { join } from 'node:path';
4
- import { readJson, saveJson, privateDir } from './effect-storage.mjs';
5
- import { UUID, hash, validateBrief } from './effect-core.mjs';
6
-
7
- export const effectReads = new Set(['get_project_context', 'search_docs', 'explore_docs', 'get_doc', 'get_docs']);
8
- const evaluationTools = new Set(['report_retrieval_evaluation', 'report_retrieval_evaluations']);
9
- const reasons = new Set(['consent_required', 'missing_preparation', 'late_preparation', 'working_model_unavailable', 'unsupported_runner', 'runner_not_configured', 'isolation_unavailable', 'connection_unavailable', 'permission_denied', 'snapshot_unavailable', 'context_unavailable', 'budget_admission_denied', 'concurrency_limit', 'daily_run_limit', 'not_sampled', 'disabled', 'no_beneficial_retrieval', 'expired_preparation', 'duplicate_task', 'report_pending', 'local_failure', 'incomplete_evaluation']);
10
- const safeReason = e => reasons.has(e?.reason ?? e?.code?.toLowerCase()) ? (e.reason ?? e.code.toLowerCase()) : ['EACCES', 'EPERM'].includes(e?.code) ? 'permission_denied' : 'local_failure';
11
- const dataOf = r => r?.structuredContent ?? (() => { try { return JSON.parse(r?.content?.find(c => c.type === 'text')?.text); } catch { return null; } })();
12
- function retrievalIds(value, found = new Set()) {
13
- if (!value || typeof value !== 'object') return found;
14
- if (Array.isArray(value.retrievals)) for (const r of value.retrievals) if (UUID.test(r?.retrievalId)) found.add(r.retrievalId);
15
- for (const [key, child] of Object.entries(value)) if (key !== 'retrievals' && child && typeof child === 'object') retrievalIds(child, found);
16
- return found;
17
- }
18
- export function automaticTool(tool) {
19
- if (!effectReads.has(tool.name) && !evaluationTools.has(tool.name)) return tool;
20
- const properties = { ...tool.inputSchema.properties };
21
- if (effectReads.has(tool.name)) properties.effectTask = { type: 'object', additionalProperties: false,
22
- description: 'Local automatic measurement. First read: pre-exposure brief and current trusted host identity; following reads: same taskId only. Never reconstruct a brief after exposure. Source allowlist and consent come from installation, not this call.',
23
- required: ['taskId'], properties: { taskId: { type: 'string', format: 'uuid' },
24
- question: { type: 'string', minLength: 1, maxLength: 2000 }, knownContext: { type: 'string', maxLength: 4000 },
25
- criteria: { type: 'array', minItems: 1, maxItems: 10, items: { type: 'object', additionalProperties: false, required: ['id', 'description'], properties: { id: { type: 'string', maxLength: 80 }, description: { type: 'string', maxLength: 500 } } } },
26
- host: { type: 'object', additionalProperties: false, required: ['client', 'sessionId'], properties: { client: { type: 'string', enum: ['codex', 'claude_code'] }, sessionId: { type: 'string', format: 'uuid' }, transcriptPath: { type: 'string' } } },
27
- } };
28
- else {
29
- properties.effectTaskId = { type: 'string', format: 'uuid', description: 'Same automatic information task identity.' };
30
- properties.effectTaskComplete = { type: 'boolean', description: 'True only on the final evaluation after ALL information reads and evaluations for this question. The installer starts at most one comparison automatically, after saved consent. Do not issue measure run.' };
31
- }
32
- return { ...tool, description: tool.description + ' Installed automatic measurement accepts local task metadata; no shell prepare/run is needed.', inputSchema: { ...tool.inputSchema, properties },
33
- annotations: { ...tool.annotations, readOnlyHint: false, openWorldHint: true } };
34
- }
35
-
36
- /** Serializes calls for this bridge; persistent coordinator locks prevent duplicate probes across bridges/restarts. */
37
- export class AutomaticMeasurement {
38
- constructor({ projectId, remote, factory, store, warn = () => {} }) { Object.assign(this, { projectId, remote, factory, store, warn }); this.queue = Promise.resolve(); this.jobs = new Set(); }
39
- call(params) {
40
- const next = this.queue.then(() => this.handle(params));
41
- this.queue = next.catch(() => {}); return next;
42
- }
43
- async recover() {
44
- for (const state of await this.store.list?.() ?? []) {
45
- if (state.diagnostic) {
46
- try { await this.remote('report_effect_diagnostic', state.diagnostic); state.diagnostic = null; await this.store.save(state); }
47
- catch { this.warn('Foundocs measurement status is pending; no inference was repeated.'); }
48
- }
49
- if (!state.closed || state.settled || !state.preparationId) continue;
50
- try {
51
- const { coordinator } = await this.factory({ recovery: true });
52
- const result = await coordinator.flush(state.taskId);
53
- if (result.reason === 'coordinator_active') continue;
54
- if (result.status === 'report_pending') {
55
- await this.diagnostic(state, 'failed', 'report_pending');
56
- continue;
57
- }
58
- state.settled = true;
59
- if (['reported', 'already_reported'].includes(result.status)) {
60
- const failed = result.result && result.result.status !== 'completed';
61
- await this.diagnostic(state, failed ? 'failed' : 'completed', failed ? 'local_failure' : null);
62
- }
63
- else await this.diagnostic(state, 'failed', result.status === 'nothing_pending' ? 'local_failure' : safeReason(result));
64
- } catch { this.warn('Foundocs measurement recovery pending; no inference was repeated.'); }
65
- }
66
- }
67
- async diagnostic(state, status, reason = null) {
68
- state.sequence = (state.sequence ?? 0) + 1;
69
- state.diagnostic = { requestId: randomUUID(), taskId: state.taskId, sequence: state.sequence, status, reason };
70
- try { await this.store.save(state); } catch { this.warn('Foundocs measurement status could not be saved locally.'); }
71
- try { await this.remote('report_effect_diagnostic', state.diagnostic); state.diagnostic = null; await this.store.save(state); }
72
- catch { this.warn('Foundocs measurement status could not be delivered; local status retained.'); }
73
- }
74
- async handle(params) {
75
- const { effectTask, effectTaskId, effectTaskComplete, ...args } = params.arguments ?? {};
76
- const forward = () => this.remote(params.name, args, true);
77
- if (args.project_id !== this.projectId) {
78
- if (effectTask || effectTaskId || effectTaskComplete) throw new Error('Automatic measurement project mismatch');
79
- return forward();
80
- }
81
- if (effectReads.has(params.name)) {
82
- // Explicit legacy tracking stays under its existing coordinator. Never attach two tasks.
83
- if (!effectTask) return forward();
84
- const taskId = effectTask?.taskId ?? (UUID.test(args.taskId ?? '') ? args.taskId : UUID.test(args.readId ?? '') ? args.readId : randomUUID());
85
- if (!UUID.test(taskId) || (args.taskId && args.taskId !== taskId) || (effectTask && args.effectPreparationId)) throw new Error('Conflicting measurement task');
86
- let state;
87
- try { state = await this.store.load(taskId); }
88
- catch (e) {
89
- args.taskId = taskId;
90
- try { await this.remote('report_effect_diagnostic', { requestId: randomUUID(), taskId, sequence: 0, status: 'skipped', reason: safeReason(e) }); } catch { this.warn('Foundocs measurement storage unavailable.'); }
91
- return forward();
92
- }
93
- if (!state) {
94
- state = { taskId, retrievals: [], evaluated: [], exposed: false, closed: false, expiresAt: new Date(Date.now() + 86400000).toISOString() };
95
- // Persist before preparation; a crash must never create a new baseline after exposure.
96
- try { await this.store.save(state); }
97
- catch (e) {
98
- args.taskId = taskId;
99
- try { await this.remote('report_effect_diagnostic', { requestId: randomUUID(), taskId, sequence: 0, status: 'skipped', reason: safeReason(e) }); } catch { this.warn('Foundocs measurement storage unavailable.'); }
100
- return forward();
101
- }
102
- try {
103
- const policy = await this.remote('get_effect_measurement_policy', {});
104
- if (!policy.enabled) state.skipped = 'disabled';
105
- else if (!effectTask?.question || !effectTask?.criteria) state.skipped = 'missing_preparation';
106
- else {
107
- const brief = { taskId, question: effectTask.question, knownContext: effectTask.knownContext ?? '', criteria: effectTask.criteria };
108
- validateBrief(brief); state.briefHash = hash(brief);
109
- const { coordinator, config } = await this.factory();
110
- if (!config?.enabled) state.skipped = 'consent_required';
111
- else {
112
- const result = await coordinator.prepare({ policy, brief, allowlist: config.allowlist, excludePaths: config.excludePaths, host: effectTask.host });
113
- if (result.status === 'prepared') { state.preparationId = result.effectPreparationId; state.consentHash = hash(config); }
114
- else state.skipped = safeReason(result);
115
- }
116
- }
117
- } catch (e) { state.skipped = safeReason(e); }
118
- await this.diagnostic(state, state.preparationId ? 'prepared' : 'skipped', state.preparationId ? null : state.skipped);
119
- } else if (effectTask?.question && state.briefHash !== hash({ taskId, question: effectTask.question, knownContext: effectTask.knownContext ?? '', criteria: effectTask.criteria })) {
120
- throw new Error('Do not change a frozen information task');
121
- }
122
- if (!state.preparationId && !state.skipped) state.skipped = 'missing_preparation'; // interrupted preparation stays unmeasured
123
- if (state.closed && effectTask) throw new Error('Information task is closed; never add later context or relabel the same question.');
124
- if (state.closed || Date.parse(state.expiresAt) <= Date.now()) {
125
- // Continue ordinary reads, but never silently add post-completion context to an existing sample.
126
- delete args.effectPreparationId; args.taskId = taskId;
127
- return forward();
128
- }
129
- args.taskId = taskId;
130
- if (state.preparationId) args.effectPreparationId = state.preparationId;
131
- // Mark exposure before the remote request: a lost reply must not re-prepare.
132
- state.exposed = true;
133
- try { await this.store.save(state); }
134
- catch (e) { delete args.effectPreparationId; await this.diagnostic(state, 'skipped', safeReason(e)); return forward(); }
135
- const result = await forward(), body = dataOf(result);
136
- if (body?.ok) {
137
- state.retrievals = [...new Set([...state.retrievals, ...retrievalIds(body.data)])];
138
- try { await this.store.save(state); } catch { this.warn('Foundocs retrieval tracking could not be saved; no extra reads were requested.'); }
139
- }
140
- return result;
141
- }
142
- const isBatch = params.name === 'report_retrieval_evaluations';
143
- if (isBatch && effectTaskId && args.taskId !== effectTaskId) throw new Error('Conflicting measurement task');
144
- const result = await forward();
145
- if (!evaluationTools.has(params.name) || !effectTaskId || !dataOf(result)?.ok) return result;
146
- if (!UUID.test(effectTaskId)) return result;
147
- let state;
148
- try { state = await this.store.load(effectTaskId); } catch { this.warn('Foundocs evaluation tracking unavailable.'); return result; }
149
- if (!state || state.closed) return result;
150
- const submitted = isBatch ? args.items : [args];
151
- const tracked = submitted.filter(item => state.retrievals.includes(item.retrievalId));
152
- if (!tracked.length) return result;
153
- state.evaluated = [...new Set([...state.evaluated, ...tracked.map(item => item.retrievalId)])];
154
- if (tracked.some(item => item.verdict === 'beneficial')) state.beneficial = true;
155
- try { await this.store.save(state); } catch { this.warn('Foundocs evaluation tracking could not be saved; no comparison started.'); return result; }
156
- if (!effectTaskComplete) return result;
157
- if (state.retrievals.some(id => !state.evaluated.includes(id))) {
158
- await this.diagnostic(state, 'skipped', 'incomplete_evaluation'); return result;
159
- }
160
- state.closed = true;
161
- try { await this.store.save(state); } catch { this.warn('Foundocs task closure could not be saved; no comparison started.'); return result; }
162
- if (!state.preparationId || !state.beneficial) { state.settled = true; await this.diagnostic(state, 'skipped', state.skipped ?? 'no_beneficial_retrieval'); return result; }
163
- // No long-running model call inside the MCP response timeout. The bridge owns and settles the task.
164
- const job = this.run(state).catch(() => this.warn('Foundocs automatic measurement failed; ordinary work continues.'));
165
- this.jobs.add(job); void job.finally(() => this.jobs.delete(job));
166
- return result;
167
- }
168
- async run(state) {
169
- try {
170
- const { coordinator, config } = await this.factory();
171
- if (!config?.enabled || state.consentHash !== hash(config)) { state.settled = true; await this.diagnostic(state, 'skipped', 'consent_required'); return; }
172
- await this.diagnostic(state, 'running');
173
- const result = await coordinator.run({ taskId: state.taskId, retrievalIds: state.retrievals });
174
- state.settled = !['report_pending'].includes(result.status);
175
- if (result.status === 'reported' || result.status === 'already_reported') {
176
- const failed = result.result && result.result.status !== 'completed';
177
- await this.diagnostic(state, failed ? 'failed' : 'completed', failed ? 'local_failure' : null);
178
- } else await this.diagnostic(state, result.status === 'report_pending' ? 'failed' : 'skipped', result.status === 'report_pending' ? 'report_pending' : safeReason(result));
179
- } catch (e) { await this.diagnostic(state, 'failed', safeReason(e)); }
180
- }
181
- async drain() { await this.queue; await Promise.allSettled([...this.jobs]); }
182
- }
183
- export function automaticStore(base) {
184
- const path = taskId => { if (!UUID.test(taskId)) throw new Error('Invalid task'); return join(base, taskId, 'automatic.json'); };
185
- return {
186
- async list() { await privateDir(base); const result = []; for (const id of await readdir(base)) if (UUID.test(id)) { const state = await this.load(id); if (state) result.push(state); } return result; },
187
- async load(taskId) { try { return await readJson(path(taskId)); } catch (e) { if (e.code === 'ENOENT') return null; throw e; } },
188
- async save(state) { await privateDir(join(base, state.taskId)); await saveJson(path(state.taskId), state); },
189
- };
190
- }
@@ -1,31 +0,0 @@
1
- import { join } from 'node:path';
2
- import { readJson, saveJson } from './effect-storage.mjs';
3
- import { EffectError } from './effect-core.mjs';
4
- export function validateAutomaticConsent(input) {
5
- if (input?.enabled === false && Object.keys(input).length === 1) return { enabled: false };
6
- if (!input || input.enabled !== true || input.consentVersion !== 1 || input.shareProjectDataWithWorkingModel !== true || input.additionalModelUsage !== true) throw new EffectError('consent_required');
7
- const paths = value => Array.isArray(value) && value.length > 0 && value.length <= 100 && value.every(p => typeof p === 'string' && p.length <= 500 && p !== '.' && !p.startsWith('/') && !p.includes('\\') && !p.split('/').some(s => !s || s === '..' || s === '.'));
8
- if (!paths(input.allowlist) || !Array.isArray(input.excludePaths) || (input.excludePaths.length && !paths(input.excludePaths))) throw new EffectError('snapshot_unavailable');
9
- return { enabled: true, consentVersion: 1, shareProjectDataWithWorkingModel: true, additionalModelUsage: true, allowlist: input.allowlist, excludePaths: input.excludePaths };
10
- }
11
- export async function saveAutomaticConsent(directory, input) {
12
- const config = validateAutomaticConsent(input);
13
- await saveJson(join(directory, 'measurement-consent.json'), { ...config, acceptedAt: new Date().toISOString() });
14
- return { status: config.enabled ? 'consent_saved' : 'disabled', hostPermissions: 'unchanged', reconnectRequired: false };
15
- }
16
- export async function readAutomaticConsent(directory) {
17
- try { const value = await readJson(join(directory, 'measurement-consent.json')); return validateAutomaticConsent(value.enabled ? value : { enabled: false }); }
18
- catch (e) { if (e.code === 'ENOENT') return { enabled: false }; throw e; }
19
- }
20
-
21
- /** Readiness is a non-inference check, not proof that a later provider request will succeed. */
22
- export async function automaticReadiness({ config, checkCli, checkConnection, identify }) {
23
- const issues = [];
24
- if (!config.enabled) issues.push('consent_required');
25
- try { await checkCli(); } catch { issues.push('unsupported_runner'); }
26
- try { await checkConnection(); } catch { issues.push('connection_unavailable'); }
27
- try { if ((await identify()).status !== 'identified') issues.push('working_model_unavailable'); }
28
- catch { issues.push('working_model_unavailable'); }
29
- return { config, ready: issues.length === 0, issues, hostPermissions: 'unchanged', inferenceExecuted: false,
30
- note: 'Checks installation storage, supported CLI/login, current model metadata and Foundocs connectivity. Host approval and provider inference permissions remain independent.' };
31
- }
@@ -1,86 +0,0 @@
1
- import { open, realpath, readdir } from 'node:fs/promises';
2
- import { constants } from 'node:fs';
3
- import { basename, isAbsolute, relative, join } from 'node:path';
4
- import { UUID } from './effect-core.mjs';
5
-
6
- const exactModel = /^claude-(haiku|sonnet|opus)-\d+(?:-\d+)*$/;
7
- const maxTail = 1024 * 1024;
8
- const within = (root, path) => { const r = relative(root, path); return r === '' || (!r.startsWith('..') && !isAbsolute(r)); };
9
-
10
- /** Read only model metadata from the current host transcript; never return/persist conversation text. */
11
- export async function workingSessionModel(host, root, now = Date.now()) {
12
- if (host?.client === 'codex' || (!host && process.env.CODEX_THREAD_ID)) return codexSessionModel(host ?? { client: 'codex', sessionId: process.env.CODEX_THREAD_ID }, root, now);
13
- if (!host || host.client !== 'claude_code') return { status: 'skipped', reason: host?.client ? 'unsupported_runner' : 'working_model_unavailable' };
14
- if (typeof host.sessionId !== 'string' || !UUID.test(host.sessionId) || typeof host.transcriptPath !== 'string' || !isAbsolute(host.transcriptPath) || basename(host.transcriptPath) !== `${host.sessionId}.jsonl`) return { status: 'skipped', reason: 'working_model_unavailable' };
15
- let file;
16
- try {
17
- file = await open(host.transcriptPath, constants.O_RDONLY | constants.O_NOFOLLOW);
18
- const stat = await file.stat();
19
- if (!stat.isFile() || now - stat.mtimeMs > 5 * 60_000 || stat.mtimeMs > now + 60_000) throw new Error();
20
- const start = Math.max(0, stat.size - maxTail), buffer = Buffer.alloc(Math.min(stat.size, maxTail));
21
- const { bytesRead } = await file.read(buffer, 0, buffer.length, start);
22
- const lines = buffer.subarray(0, bytesRead).toString('utf8').split('\n');
23
- if (start) lines.shift(); // Never parse a truncated leading record.
24
- for (const line of lines.reverse()) {
25
- if (!line.trim()) continue;
26
- let event; try { event = JSON.parse(line); } catch { throw new Error(); } // An incomplete latest record must not select an older model.
27
- if (event.type !== 'assistant' || event.isSidechain || event.parent_tool_use_id) continue;
28
- // Stop at the latest assistant record; never fall back to an older/different model.
29
- if (event.sessionId !== host.sessionId || typeof event.cwd !== 'string' || !within(await realpath(root), await realpath(event.cwd))) throw new Error();
30
- const timestamp = Date.parse(event.timestamp);
31
- if (!Number.isFinite(timestamp) || now - timestamp > 5 * 60_000 || timestamp > now + 60_000 || !exactModel.test(event.message?.model ?? '')) throw new Error();
32
- return { status: 'identified', model: event.message.model, modelSource: 'working_session' };
33
- }
34
- } catch { /* Missing, stale, inaccessible or unsupported metadata never chooses a default. */ }
35
- finally { await file?.close(); }
36
- return { status: 'skipped', reason: 'working_model_unavailable' };
37
- }
38
-
39
-
40
- /** Resolve only this host's exact thread ID, never another thread's contents. */
41
- export async function codexSessionModel(host, root, now = Date.now(), env = process.env) {
42
- if (!UUID.test(host.sessionId ?? '') || (env.CODEX_THREAD_ID && env.CODEX_THREAD_ID !== host.sessionId)) return { status: 'skipped', reason: 'working_model_unavailable' };
43
- let file;
44
- try {
45
- let path = host.transcriptPath;
46
- if (!path) {
47
- const base = join(env.CODEX_HOME || join(env.HOME, '.codex'), 'sessions');
48
- const matches = [];
49
- async function find(dir, depth = 0) {
50
- for (const entry of await readdir(dir, { withFileTypes: true })) {
51
- if (entry.isDirectory() && depth < 3 && /^\d{2,4}$/.test(entry.name)) await find(join(dir, entry.name), depth + 1);
52
- else if (entry.isFile() && entry.name.endsWith(`-${host.sessionId}.jsonl`)) matches.push(join(dir, entry.name));
53
- }
54
- }
55
- await find(base); if (matches.length !== 1) throw new Error(); path = matches[0];
56
- }
57
- if (typeof path !== 'string' || !isAbsolute(path) || !basename(path).endsWith(`-${host.sessionId}.jsonl`)) throw new Error();
58
- file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
59
- const stat = await file.stat();
60
- if (!stat.isFile() || now - stat.mtimeMs > 5 * 60_000 || stat.mtimeMs > now + 60_000) throw new Error();
61
- // Identity is in the first record. A long active Codex turn can emit several
62
- // MiB after turn_context; inspect a bounded 16 MiB tail, returning metadata only.
63
- const head = Buffer.alloc(Math.min(stat.size, 64 * 1024)); await file.read(head, 0, head.length, 0);
64
- const meta = JSON.parse(head.toString('utf8').split('\n')[0]);
65
- if (meta.type !== 'session_meta' || meta.payload.id !== host.sessionId || meta.payload.model_provider !== 'openai') throw new Error();
66
- const canonicalRoot = await realpath(root);
67
- if (!within(canonicalRoot, await realpath(meta.payload.cwd))) throw new Error();
68
- const start = Math.max(0, stat.size - 16 * maxTail), buffer = Buffer.alloc(Math.min(stat.size, 16 * maxTail));
69
- const { bytesRead } = await file.read(buffer, 0, buffer.length, start);
70
- const lines = buffer.subarray(0, bytesRead).toString('utf8').split('\n'); if (start) lines.shift();
71
- for (const line of lines.reverse()) {
72
- if (!line.trim()) continue;
73
- const event = JSON.parse(line);
74
- if (event.type !== 'turn_context') continue;
75
- const p = event.payload;
76
- if (!within(canonicalRoot, await realpath(p.cwd)) || !/^gpt-\d[\w.-]{0,150}$/.test(p.model) || /(?:latest|auto)$/.test(p.model)) throw new Error();
77
- const timestamp = Date.parse(event.timestamp);
78
- if (!Number.isFinite(timestamp) || timestamp > now + 60_000) throw new Error();
79
- // A long active turn can outlive five minutes. Freshness is the current
80
- // transcript's mtime; never select an older turn after malformed metadata.
81
- return { status: 'identified', model: p.model, modelSource: 'working_session', runner: 'codex_read_tools_v1', ...(typeof p.effort === 'string' && ['none','minimal','low','medium','high','xhigh','max','ultra'].includes(p.effort) ? { reasoningEffort: p.effort } : {}) };
82
- }
83
- } catch { /* Never infer a model from config/defaults or another thread. */ }
84
- finally { await file?.close(); }
85
- return { status: 'skipped', reason: 'working_model_unavailable' };
86
- }
@@ -1,28 +0,0 @@
1
- import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
2
- import { readCredential } from './auth.mjs';
3
- import { EffectError } from './effect-core.mjs';
4
- export async function connectEffectRemote(manifest) {
5
- const url = new URL(manifest.mcpUrl);
6
- const key = await readCredential(manifest.credentialPath, manifest.projectId, manifest.workspaceId);
7
- const client = new Client({ name: 'foundocs-effect-coordinator', version: '1' });
8
- const transport = new StreamableHTTPClientTransport(url, {
9
- requestInit: { headers: { Authorization: `Bearer ${key}` } },
10
- fetch: (target, init) => {
11
- if (new URL(typeof target === 'string' || target instanceof URL ? target : target.url).origin !== url.origin) throw new EffectError('origin_changed');
12
- return fetch(target, { ...init, redirect: 'error', signal: init?.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(5000)]) : AbortSignal.timeout(5000) });
13
- },
14
- });
15
- try { await client.connect(transport, { timeout: 5000 }); await client.listTools(); } catch { await client.close().catch(() => {}); throw new EffectError('connection_unavailable'); }
16
- return {
17
- close: () => client.close(),
18
- async call(name, args) {
19
- let result;
20
- try { result = await client.callTool({ name, arguments: { ...args, project_id: manifest.projectId } }, undefined, { timeout: 5000 }); }
21
- catch { throw new EffectError('transport_uncertain', 'Request outcome is uncertain; no inference will be repeated.', true); }
22
- const body = result.structuredContent ?? (() => { try { return JSON.parse(result.content?.find(c => c.type === 'text')?.text); } catch { return null; } })();
23
- if (!body || typeof body.ok !== 'boolean') throw new EffectError('invalid_response', 'Request outcome is uncertain.', true);
24
- if (!body.ok || result.isError) throw new EffectError(body.error?.code ?? 'request_failed', 'Server rejected the measurement request.');
25
- return body.data;
26
- },
27
- };
28
- }
package/src/effect.mjs DELETED
@@ -1,209 +0,0 @@
1
- import { join, dirname, isAbsolute } from 'node:path';
2
- import { readFile, rm, realpath } from 'node:fs/promises';
3
- import { randomUUID } from 'node:crypto';
4
- import { loadInstallation } from './setup.mjs';
5
- import { validateInstallation } from './runtime.mjs';
6
- import { RUNNER, CLI_VERSION, UUID, EffectError, hash, missingObservation, normalizeProbe, toolPolicy, validateBrief } from './effect-core.mjs';
7
- import { privateDir, readJson, saveJson, cleanExpired, purgeRaw, freezeSnapshot, copySnapshot } from './effect-storage.mjs';
8
- import { capabilities, runProbe } from './effect-runner.mjs';
9
- import { workingSessionModel } from './effect-host.mjs';
10
- import { CODEX_RUNNER, CODEX_VERSION, codexCapabilities, codexToolPolicy } from './effect-codex.mjs';
11
- import { connectEffectRemote } from './effect-remote.mjs';
12
-
13
- export async function measurementInstallation(rootPath, options = {}) {
14
- if (!isAbsolute(rootPath)) throw new EffectError('invalid_root');
15
- const { root, directory, manifest } = await loadInstallation(rootPath, options);
16
- // Exact governing file; no ancestor/alternate config fallback.
17
- const config = JSON.parse(await readFile(join(root, 'foundocs.json'), 'utf8'));
18
- if (config.project_id !== manifest.projectId) throw new EffectError('project_mismatch');
19
- await validateInstallation(root, directory, manifest);
20
- return { root, base: join(directory, 'effects'), manifest };
21
- }
22
- // Unobserved crash: finite upper allowance for two timeout/grace windows, never renewed by recovery.
23
- export const crashSettlementDeadline = (policy, now = Date.now()) => new Date(now + 2 * (policy.perProbeTimeoutMs + 5000) + 86400000).toISOString();
24
-
25
- export class EffectCoordinator {
26
- constructor({ root, base, remote, probe = runProbe, check = options => options?.runner === CODEX_RUNNER ? codexCapabilities() : capabilities(), identify = workingSessionModel }) { Object.assign(this, { root, base, remote, probe, check, identify }); }
27
- async initialize() { await cleanExpired(this.base); }
28
- path(taskId) { if (!UUID.test(taskId)) throw new EffectError('invalid_task_id'); return join(this.base, taskId); }
29
- async state(taskId) {
30
- const dir = this.path(taskId); await privateDir(dir);
31
- const s = await readJson(join(dir, 'state.json'));
32
- if (Date.parse(s.settlementExpiresAt ?? s.expiresAt) <= Date.now()) throw new EffectError('expired_preparation');
33
- return s;
34
- }
35
- async prepare({ policy, brief, allowlist, excludePaths = [], host }) {
36
- // Host fetched policy exactly once, before any exposure. OFF must not inspect/spawn CLI.
37
- if (policy?.enabled === false) return { status: 'skipped', reason: 'disabled' };
38
- if (policy?.enabled !== true || ![RUNNER, CODEX_RUNNER].includes(policy.runner)) return { status: 'skipped', reason: 'unsupported_runner' };
39
- const workingModel = await this.identify(host, this.root);
40
- if (workingModel.status !== 'identified') return workingModel;
41
- const runner = workingModel.runner ?? RUNNER;
42
- validateBrief(brief);
43
- const dir = this.path(brief.taskId); await privateDir(dir);
44
- let state = await readJson(join(dir, 'state.json')).catch(e => { if (e.code !== 'ENOENT') throw e; return null; });
45
- if (state) {
46
- if (state.workingModel?.model !== workingModel.model || state.workingModel?.modelSource !== 'working_session' || (state.policy.runner ?? RUNNER) !== runner || state.workingModel?.reasoningEffort !== workingModel.reasoningEffort) throw new EffectError('task_conflict');
47
- if (state.briefSha256 !== hash(brief) || state.sourceSelectionHash !== hash({ allowlist, excludePaths })) throw new EffectError('task_conflict');
48
- if (Date.parse(state.expiresAt) <= Date.now()) throw new EffectError('expired_preparation');
49
- if (state.prepared) return { status: 'prepared', ...state.prepared, effectPreparationId: state.prepared.id };
50
- if (!state.prepareInput) throw new EffectError('incomplete_preparation', 'A prior snapshot attempt was interrupted. Do not recreate this task after exposure.');
51
- } else {
52
- let runnerVersion;
53
- try { runnerVersion = await this.check({ runner }); } catch (e) { if (e.code === 'unsupported_runner') return { status: 'skipped', reason: e.code }; throw e; }
54
- state = { taskId: brief.taskId, criterionIds: brief.criteria.map(c => c.id), brief, briefSha256: hash(brief), sourceSelectionHash: hash({ allowlist, excludePaths }), policy: { ...policy, runner, model: workingModel.model }, workingModel, runnerVersion, expiresAt: new Date(Date.now() + 86400000).toISOString() };
55
- await saveJson(join(dir, 'state.json'), state, true);
56
- state.snapshot = await freezeSnapshot(this.root, join(dir, 'snapshot'), allowlist, excludePaths);
57
- state.prepareInput = { requestId: randomUUID(), brief, briefSha256: state.briefSha256, snapshot: state.snapshot, runner, runnerVersion, model: workingModel.model, modelSource: workingModel.modelSource };
58
- await saveJson(join(dir, 'state.json'), state);
59
- }
60
- state.prepared = await this.remote.call('prepare_effect_measurement', state.prepareInput);
61
- state.expiresAt = state.prepared.expiresAt;
62
- await saveJson(join(dir, 'state.json'), state);
63
- return { status: 'prepared', ...state.prepared, effectPreparationId: state.prepared.id };
64
- }
65
- baseProbe(state, arm) {
66
- return { arm, status: 'not_started', runner: state.policy.runner, runnerVersion: state.runnerVersion, provider: state.policy.runner === CODEX_RUNNER ? 'openai' : 'anthropic', model: state.policy.model, tokenUnit: 'provider_input_output_tokens', briefSha256: state.briefSha256, snapshotSha256: state.snapshot.sha256, criteriaSha256: hash(state.brief.criteria), toolPolicySha256: hash(state.policy.runner === CODEX_RUNNER ? codexToolPolicy({ ...state.policy, reasoningEffort: state.workingModel.reasoningEffort }) : toolPolicy(state.policy)), protocolVersion: 1, contextSha256: arm === 'with_foundocs' ? state.reservation.deliveredContextSha256 : null, isolationVerified: false, evidenceVerified: false, startedAt: null, finishedAt: null, observation: missingObservation(), output: null };
67
- }
68
- async flush(taskId) {
69
- const dir = this.path(taskId); const state = await this.state(taskId);
70
- const outbox = await readJson(join(dir, 'outbox.json')).catch(e => { if (e.code !== 'ENOENT') throw e; return null; });
71
- if (!outbox) {
72
- const receipt = await readJson(join(dir, 'receipt.json')).catch(e => { if (e.code !== 'ENOENT') throw e; return null; });
73
- if (receipt) return { status: 'already_reported', requestId: receipt.requestId, result: receipt.result };
74
- if (state.reservation && state.probes) {
75
- const owner = await readJson(join(dir, 'run-lock.json'));
76
- let alive = true; try { process.kill(owner.pid, 0); } catch (error) { if (error.code === 'ESRCH') alive = false; }
77
- if (alive) return { status: 'report_pending', reason: 'coordinator_active' };
78
- state.recovered = true;
79
- for (const probe of Object.values(state.probes)) if (probe.startedAt && !probe.finishedAt) { probe.status = 'failed'; probe.finishedAt = new Date().toISOString(); }
80
- return this.report(state, dir);
81
- }
82
- return { status: 'nothing_pending' };
83
- }
84
- if (outbox.rejected) return { status: 'report_rejected', reason: outbox.rejected };
85
- try {
86
- const result = await this.remote.call('report_effect_measurement', outbox.payload);
87
- await saveJson(join(dir, 'receipt.json'), { reportedAt: new Date().toISOString(), requestId: outbox.payload.requestId, result });
88
- await rm(join(dir, 'outbox.json'));
89
- // Raw sources/context/brief are no longer needed after settlement.
90
- await rm(join(dir, 'snapshot'), { recursive: true, force: true });
91
- for (const arm of ['with_foundocs', 'without_foundocs']) await rm(join(dir, arm), { recursive: true, force: true });
92
- return { status: 'reported', result };
93
- } catch (e) {
94
- if (!e.uncertain) { outbox.rejected = e.code ?? 'request_failed'; await saveJson(join(dir, 'outbox.json'), outbox); return { status: 'report_rejected', reason: outbox.rejected }; }
95
- return { status: 'report_pending', reason: 'transport_uncertain' };
96
- }
97
- }
98
- async report(state, dir) {
99
- const payload = { requestId: randomUUID(), runId: state.reservation.runId, leaseToken: state.reservation.leaseToken, withFoundocs: normalizeProbe(state.probes.with_foundocs, { criteria: state.criterionIds.map(id => ({ id })) }), withoutFoundocs: normalizeProbe(state.probes.without_foundocs, { criteria: state.criterionIds.map(id => ({ id })) }) };
100
- if (Buffer.byteLength(JSON.stringify(payload)) > 96 * 1024) throw new EffectError('report_too_large');
101
- // This outbox has report fields only: never snapshot bytes, delivered context, API keys or raw transcript.
102
- if (!state.recovered) state.settlementExpiresAt = new Date(Math.max(Date.now(), ...Object.values(state.probes).map(p => Date.parse(p.finishedAt ?? p.startedAt)).filter(Number.isFinite)) + 86400000).toISOString();
103
- await saveJson(join(dir, 'state.json'), state);
104
- await saveJson(join(dir, 'outbox.json'), { payload }, true);
105
- return this.flush(state.taskId);
106
- }
107
- async run({ taskId, retrievalIds }) {
108
- if (!Array.isArray(retrievalIds) || !retrievalIds.every(v => UUID.test(v))) throw new EffectError('invalid_retrieval_ids');
109
- const dir = this.path(taskId); let state = await this.state(taskId);
110
- if (!state.prepared) throw new EffectError('missing_preparation');
111
- if (state.policy.enabled !== true) return { status: 'skipped', reason: 'disabled' };
112
- if (state.workingModel?.modelSource !== 'working_session') return { status: 'skipped', reason: 'working_model_unavailable' };
113
- const receipt = await readJson(join(dir, 'receipt.json')).catch(e => { if (e.code !== 'ENOENT') throw e; return null; });
114
- if (receipt) return { status: 'already_reported', requestId: receipt.requestId, result: receipt.result };
115
- const lock = join(dir, 'run-lock.json');
116
- try { await saveJson(lock, { pid: process.pid, attemptId: randomUUID() }, true); }
117
- catch (e) {
118
- if (e.code !== 'EEXIST') throw e;
119
- const owner = await readJson(lock);
120
- let alive = true; try { process.kill(owner.pid, 0); } catch (error) { if (error.code === 'ESRCH') alive = false; }
121
- // Existing owner (or PID reuse) is conservatively treated as active.
122
- if (alive) return { status: 'skipped', reason: 'duplicate_task' };
123
- const pending = await this.flush(taskId);
124
- if (pending.status !== 'nothing_pending') return pending;
125
- if (state.reservation && state.probes) {
126
- state.recovered = true;
127
- for (const p of Object.values(state.probes)) if (p.startedAt && !p.finishedAt) { p.status = 'failed'; p.finishedAt = new Date().toISOString(); }
128
- return this.report(state, dir);
129
- }
130
- return { status: 'skipped', reason: 'duplicate_task' }; // Never recreate an uncertain reservation/spawn.
131
- }
132
- const controller = new AbortController();
133
- const abort = () => controller.abort();
134
- process.once('SIGINT', abort); process.once('SIGTERM', abort);
135
- let purging = Promise.resolve();
136
- const expiration = setTimeout(() => { controller.abort(); purging = purgeRaw(dir, state); }, Math.max(1, Date.parse(state.expiresAt) - Date.now()));
137
- let stopped = false;
138
- try {
139
- if (state.rawExpired) throw new EffectError('expired_preparation');
140
- const version = await this.check({ runner: state.policy.runner });
141
- if (version !== state.runnerVersion || version !== (state.policy.runner === CODEX_RUNNER ? CODEX_VERSION : CLI_VERSION)) throw new EffectError('unsupported_runner');
142
- const { sha256: ignored, ...manifest } = state.snapshot;
143
- if (hash(manifest) !== state.snapshot.sha256 || hash(state.brief) !== state.briefSha256) throw new EffectError('unsafe_snapshot');
144
- state.reserveInput = { requestId: randomUUID(), preparationId: state.prepared.id, retrievalIds: [...new Set(retrievalIds)] };
145
- await saveJson(join(dir, 'state.json'), state);
146
- const reserved = await this.remote.call('reserve_effect_measurement', state.reserveInput);
147
- if (reserved.status !== 'reserved') return reserved;
148
- state.reservation = reserved.reservation;
149
- if (state.reservation.policy.revision !== state.prepared.policyRevision || hash(state.reservation.policy) !== hash(state.policy)) throw new EffectError('policy_changed');
150
- state.probes = Object.fromEntries(['with_foundocs', 'without_foundocs'].map(arm => [arm, this.baseProbe(state, arm)]));
151
- state.settlementExpiresAt = crashSettlementDeadline(state.policy);
152
- await saveJson(join(dir, 'state.json'), state);
153
- const control = async (action, arm, probe) => {
154
- const args = { requestId: randomUUID(), runId: state.reservation.runId, leaseToken: state.reservation.leaseToken, policyRevision: state.policy.revision, action, ...(arm ? { arm } : {}), ...(probe ? { probe } : {}) };
155
- if (action === 'start_arm') { state.lastStart = args; await saveJson(join(dir, 'state.json'), state); }
156
- try { const result = await this.remote.call('control_effect_measurement', args); if (result.action !== 'continue' || result.policyRevision !== state.policy.revision) stopped = true; }
157
- catch { stopped = true; }
158
- return !stopped;
159
- };
160
- const first = state.reservation.firstArm;
161
- if (!['with_foundocs', 'without_foundocs'].includes(first)) throw new EffectError('invalid_response');
162
- for (const arm of [first, first === 'with_foundocs' ? 'without_foundocs' : 'with_foundocs']) {
163
- if (stopped || controller.signal.aborted) break;
164
- const cwd = join(dir, arm);
165
- await copySnapshot(join(dir, 'snapshot'), cwd, state.snapshot);
166
- // Durable consumed marker BEFORE start_arm request: even a lost grant must not re-spawn.
167
- await saveJson(join(dir, `${arm}.consumed.json`), { consumedAt: new Date().toISOString() }, true);
168
- if (!(await control('start_arm', arm)) || controller.signal.aborted) break;
169
- const probe = state.probes[arm]; probe.startedAt = new Date().toISOString(); probe.status = 'failed';
170
- await saveJson(join(dir, 'state.json'), state);
171
- state.probes[arm] = await this.probe({ cwd, brief: state.brief, snapshot: state.snapshot, context: arm === 'with_foundocs' ? state.reservation.deliveredContext : [], policy: { ...state.policy, ...(state.workingModel.reasoningEffort ? { reasoningEffort: state.workingModel.reasoningEffort } : {}) }, probe, signal: controller.signal, heartbeat: () => control('heartbeat'), observe: async observation => { probe.observation = observation; state.settlementExpiresAt = crashSettlementDeadline(state.policy); await saveJson(join(dir, 'state.json'), state); } });
172
- state.probes[arm] = normalizeProbe(state.probes[arm], { criteria: state.criterionIds.map(id => ({ id })) });
173
- await saveJson(join(dir, 'state.json'), state);
174
- if (!(await control('heartbeat', undefined, state.probes[arm]))) break;
175
- }
176
- await purging;
177
- return await this.report(state, dir);
178
- } catch (e) {
179
- if (state.reservation && state.probes) {
180
- for (const p of Object.values(state.probes)) if (p.startedAt && !p.finishedAt) { p.status = 'failed'; p.finishedAt = new Date().toISOString(); }
181
- await purging;
182
- return await this.report(state, dir);
183
- }
184
- throw e;
185
- } finally { clearTimeout(expiration); process.removeListener('SIGINT', abort); process.removeListener('SIGTERM', abort); }
186
- }
187
- }
188
- export async function measure(action, rootPath, input) {
189
- const installation = await measurementInstallation(rootPath);
190
- await cleanExpired(installation.base);
191
- if (action === 'configure' || action === 'status') {
192
- const { saveAutomaticConsent, readAutomaticConsent, automaticReadiness } = await import('./effect-config.mjs');
193
- if (action === 'configure') return saveAutomaticConsent(dirname(installation.base), input);
194
- return automaticReadiness({ config: await readAutomaticConsent(dirname(installation.base)),
195
- checkCli: () => installation.manifest.client === 'codex' ? codexCapabilities() : capabilities(),
196
- identify: () => workingSessionModel(input.host, installation.root),
197
- checkConnection: async () => { const remote = await connectEffectRemote(installation.manifest); try { await remote.call('get_effect_measurement_policy', {}); } finally { await remote.close(); } },
198
- });
199
- }
200
- if (action === 'prepare' && input.policy?.enabled === false) return { status: 'skipped', reason: 'disabled' };
201
- const remote = await connectEffectRemote(installation.manifest);
202
- try {
203
- const coordinator = new EffectCoordinator({ ...installation, remote });
204
- if (action === 'prepare') return await coordinator.prepare(input);
205
- if (action === 'run') return await coordinator.run(input);
206
- if (action === 'flush') return await coordinator.flush(input.taskId);
207
- throw new EffectError('invalid_command');
208
- } finally { await remote.close(); }
209
- }