@promptdriven/runtime-client 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +7 -0
- package/README.md +42 -2
- package/package.json +28 -4
- package/src/index.mjs +1 -0
- package/src/runtime/agent-ask.mjs +187 -0
- package/src/runtime/agent-chat.mjs +105 -0
- package/src/runtime/agent-coverage.mjs +97 -0
- package/src/runtime/agent-guide.mjs +152 -0
- package/src/runtime/agent-judge.mjs +71 -0
- package/src/runtime/agent-packet.mjs +62 -0
- package/src/runtime/agent-project.mjs +93 -0
- package/src/runtime/contract-refs.mjs +519 -0
- package/src/runtime/contracts.mjs +138 -0
- package/src/runtime/index.mjs +943 -0
- package/src/runtime/lint-call-preflight.mjs +19 -0
- package/src/runtime/lint-compatibility-display.mjs +62 -0
- package/src/runtime/product-composition.mjs +384 -0
- package/src/runtime/runtime-binding-plan.mjs +145 -0
- package/src/runtime/runtime-bindings.mjs +71 -0
- package/src/runtime/runtime-check-plan.mjs +411 -0
- package/src/runtime/runtime-client.mjs +6323 -0
- package/src/runtime/runtime-lint-receipt.mjs +25 -0
- package/src/runtime/runtime-markdown.mjs +215 -0
- package/src/runtime/runtime-outcome.mjs +407 -0
- package/src/runtime/runtime-output.mjs +714 -0
- package/src/runtime/runtime-preflight.mjs +3118 -0
- package/src/runtime/runtime-slots.mjs +391 -0
- package/src/runtime/runtime-workspace-migration.mjs +70 -0
- package/src/runtime/runtime-workspace.mjs +52 -0
- package/src/runtime/scenario-json.mjs +91 -0
- package/src/runtime/secret-redaction.mjs +53 -0
- package/src/runtime/try-doors.mjs +231 -0
- package/src/runtime/try-http.mjs +259 -0
- package/src/runtime/try-mcp.mjs +223 -0
- package/src/runtime/try-session.mjs +95 -0
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
// Generated from prompts/cli/try-mcp.prompt.md (sha256: f005492d96bf72699f50571513cd90416a70c422a79c079a79bb54e3ce7471f9).
|
|
2
|
+
import { createInterface } from 'node:readline';
|
|
3
|
+
import { readTryOwner, observeTryCall, runDoorCall, saveDoorCase, applyPendingCaseWithHandoff } from './runtime-client.mjs';
|
|
4
|
+
import { createRunJudge } from './agent-judge.mjs';
|
|
5
|
+
|
|
6
|
+
const object = x => x !== null && typeof x === 'object' && !Array.isArray(x);
|
|
7
|
+
const text = x => typeof x === 'string' && x.length > 0;
|
|
8
|
+
const validSha256 = x => typeof x === 'string' && /^[0-9a-f]{64}$/i.test(x) ? x.toLowerCase() : null;
|
|
9
|
+
const validEngineSha = x => typeof x === 'string' && /^[0-9a-f]{8,40}$/i.test(x) ? x.toLowerCase() : null;
|
|
10
|
+
const validCommit = x => typeof x === 'string' && x.length > 0 ? x : null;
|
|
11
|
+
const schema = (properties, required = []) => ({
|
|
12
|
+
type: 'object',
|
|
13
|
+
properties: { story: { type: 'string' }, ...properties },
|
|
14
|
+
...(required.length ? { required } : {}),
|
|
15
|
+
additionalProperties: false,
|
|
16
|
+
});
|
|
17
|
+
const tools = [
|
|
18
|
+
['try_open', 'Open or reuse the current repo and Story Try, or pass try_id to bind only an existing running simulation without opening or reopening one. Returns its entries, data and budget. No prompt approval.', { try_id: { type: 'string' } }, false],
|
|
19
|
+
['try_state', 'Read current Try data, entries and schemas, Story criteria, test inputs, runs, budget and progress. Opens a missing Try only when try_id is omitted.', { try_id: { type: 'string' } }, false],
|
|
20
|
+
['try_run', 'Run one action on the Try, spending its existing AI call budget. Pass try_id to require that exact running Try without opening or reopening one. Use entry and input, or exact CLI argv. Declared entry errors return structured error outcomes; every run appears on the Try page.', { try_id: { type: 'string' }, entry: { type: 'string' }, input: { type: 'object', additionalProperties: true }, argv: { type: 'array', items: { type: 'string' } } }, false],
|
|
21
|
+
['try_observe', 'Read call state and session state for run_id on try_id without opening, reopening, recovering or replaying a run. Works while the session is running, paused or stopped.', { try_id: { type: 'string' }, run_id: { type: 'string' } }, true, ['try_id', 'run_id']],
|
|
22
|
+
['try_check', 'Compare a confirmed run with the Story tests, with honest limits and first differences. No AI calls.', { try_id: { type: 'string' }, run_id: { type: 'string' } }, true],
|
|
23
|
+
['try_save_case', 'Save a confirmed run as an exact observed-result case. Or apply a retained pending_id with closed_editor_for: obtain the person’s actual confirmation that this exact original test is closed and handed over until apply finishes; generic tool approval is insufficient. Review its expectation and starting data; saving does not approve correctness.', { try_id: { type: 'string' }, run_id: { type: 'string' }, criterion_id: { type: 'string' }, name: { type: 'string' }, pending_id: { type: 'string', pattern: '^[0-9a-f]{64}\\.[0-9a-f]{64}$' }, closed_editor_for: { type: 'string', minLength: 1 } }, false],
|
|
24
|
+
].map(([name, description, properties, readOnlyHint, required]) => ({ name, description, inputSchema: schema(properties, required), annotations: { readOnlyHint, destructiveHint: false, idempotentHint: name !== 'try_run', openWorldHint: false } }));
|
|
25
|
+
|
|
26
|
+
function validate(name, args) {
|
|
27
|
+
const tool = tools.find(tool => tool.name === name);
|
|
28
|
+
if (!tool) throw new Error(`Unknown tool ${name}.`);
|
|
29
|
+
if (!object(args)) throw new Error('Tool arguments must be an object.');
|
|
30
|
+
for (const key of tool.inputSchema.required ?? []) {
|
|
31
|
+
if (!Object.hasOwn(args, key)) throw new Error(`Missing required argument ${key}.`);
|
|
32
|
+
}
|
|
33
|
+
for (const [key, value] of Object.entries(args)) {
|
|
34
|
+
const property = tool.inputSchema.properties[key];
|
|
35
|
+
if (!property) throw new Error(`Unknown argument ${key}.`);
|
|
36
|
+
if (property.type === 'string' && !text(value) || property.type === 'object' && !object(value)
|
|
37
|
+
|| property.type === 'array' && (!Array.isArray(value) || !value.every(x => typeof x === 'string'))) throw new Error(`Invalid ${key}.`);
|
|
38
|
+
}
|
|
39
|
+
if (name === 'try_run') {
|
|
40
|
+
if (Object.hasOwn(args, 'argv')) {
|
|
41
|
+
if (Object.hasOwn(args, 'entry') || Object.hasOwn(args, 'input')) throw new Error('Choose argv, or entry and input.');
|
|
42
|
+
} else if (!text(args.entry) || !object(args.input)) throw new Error('Give entry and input, or argv.');
|
|
43
|
+
}
|
|
44
|
+
if(name==='try_save_case'&&(Object.hasOwn(args,'pending_id')||Object.hasOwn(args,'closed_editor_for'))){
|
|
45
|
+
if(!text(args.pending_id)||!text(args.closed_editor_for))throw new Error('Give both pending_id and closed_editor_for for retained-case application.');
|
|
46
|
+
if(!/^[a-f0-9]{64}\.[a-f0-9]{64}$/.test(args.pending_id))throw new Error('Invalid pending_id.');
|
|
47
|
+
if(['story','try_id','run_id','criterion_id','name'].some(key=>Object.hasOwn(args,key)))throw new Error('Pending application accepts only pending_id and closed_editor_for.');
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function recordedCaseNote({scope,covered,total}){
|
|
52
|
+
const prefix=scope==='original-story'?`Recorded case; covers ${covered} of ${total} Story criteria.${total>1?' Complete coverage before pdd test.':''}`
|
|
53
|
+
:scope==='retained-scenario'?`Recorded case; references ${covered} of ${total} retained scenario criteria. Whole-Story coverage is unavailable. Complete coverage before pdd test.`
|
|
54
|
+
:'Recorded case; criterion coverage is unavailable. Complete coverage before pdd test.';
|
|
55
|
+
return prefix+' This records observed output; review its expectation and saved-data setup before replaying.';
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function createTryTools({ cwd = process.cwd(), words = [], env } = {}, ports = {}) {
|
|
59
|
+
const dependencies = {
|
|
60
|
+
...ports,
|
|
61
|
+
readTryOwner: ports.readTryOwner ?? readTryOwner,
|
|
62
|
+
observeTryCall: ports.observeTryCall ?? observeTryCall,
|
|
63
|
+
runDoorCall: ports.runDoorCall ?? runDoorCall,
|
|
64
|
+
saveDoorCase: ports.saveDoorCase ?? saveDoorCase,
|
|
65
|
+
applyPendingCaseWithHandoff: ports.applyPendingCaseWithHandoff ?? applyPendingCaseWithHandoff,
|
|
66
|
+
};
|
|
67
|
+
const runtimePorts = { ...ports, env: env ?? ports.env ?? process.env, stdout: ports.stderr ?? process.stderr, stderr: ports.stderr ?? process.stderr };
|
|
68
|
+
const sessions = new Map();
|
|
69
|
+
let queue = Promise.resolve();
|
|
70
|
+
async function invoke(name, args) {
|
|
71
|
+
validate(name, args);
|
|
72
|
+
if(name==='try_save_case'&&Object.hasOwn(args,'pending_id')){
|
|
73
|
+
const outcome=await dependencies.applyPendingCaseWithHandoff({cwd,pendingId:args.pending_id,handoff:{kind:'closed-editor',testPath:args.closed_editor_for},signal:runtimePorts.signal},runtimePorts);
|
|
74
|
+
if(outcome.kind!=='case'||outcome.result.state!=='committed')throw new Error(outcome.message);
|
|
75
|
+
return{pending_id:args.pending_id,result:outcome.message,note:recordedCaseNote(outcome.coverage)};
|
|
76
|
+
}
|
|
77
|
+
if (name === 'try_observe') {
|
|
78
|
+
return await dependencies.observeTryCall({ cwd, story: args.story ?? words[0], tryId: args.try_id, runId: args.run_id }, runtimePorts);
|
|
79
|
+
}
|
|
80
|
+
const owner = await dependencies.readTryOwner({ cwd, story: args.story ?? words[0], ...(args.try_id ? { tryId: args.try_id } : {}) }, runtimePorts);
|
|
81
|
+
const key = `${owner.root}:${owner.record.id}`;
|
|
82
|
+
let session = sessions.get(key);
|
|
83
|
+
if (!session) {
|
|
84
|
+
session = { judge: createRunJudge({ scenario: owner.test.doc }), runs: [], unknown: false };
|
|
85
|
+
sessions.set(key, session);
|
|
86
|
+
}
|
|
87
|
+
const { judge, runs } = session;
|
|
88
|
+
if (name === 'try_open' || name === 'try_state') return {
|
|
89
|
+
story: owner.test.title, story_path: owner.test.storyPath, try_id: owner.record.id,
|
|
90
|
+
source_sha256: validSha256(owner.model?.source_sha256) ?? validSha256(owner.source_sha256) ?? validSha256(owner.record?.source_sha256) ?? null,
|
|
91
|
+
engine_sha: validEngineSha(owner.model?.engine_sha) ?? validEngineSha(owner.engine_sha) ?? validEngineSha(owner.record?.engine_sha) ?? null,
|
|
92
|
+
server_commit: validCommit(owner.model?.server_commit) ?? validCommit(owner.server_commit) ?? validCommit(owner.record?.server_commit) ?? null,
|
|
93
|
+
criteria: owner.test.doc.criteria, test_inputs: judge.bindings(),
|
|
94
|
+
entries: owner.model.entries.map(e => ({ ...e, entry: `${e.entry_path}#${e.operation}` })),
|
|
95
|
+
data_now: owner.data ?? null, ...(owner.data_error ? { data_error: owner.data_error } : {}),
|
|
96
|
+
runs: runs.map(({ saved, ...run }) => run), calls: owner.model.calls ?? null, actions: owner.actions ?? null,
|
|
97
|
+
progress: judge.snapshot(), ...(session.unknown ? { warning: 'A run has an unknown outcome. Do not repeat it automatically.' } : {}),
|
|
98
|
+
};
|
|
99
|
+
if (name === 'try_run') {
|
|
100
|
+
if (session.unknown) throw new Error('A prior run has an unknown outcome. Inspect the Try page before starting another run; do not repeat it automatically.');
|
|
101
|
+
let entry, input;
|
|
102
|
+
if (Object.hasOwn(args, 'argv')) {
|
|
103
|
+
const cli = owner.model.entries.filter(e => e.cli === true);
|
|
104
|
+
if (cli.length !== 1) throw new Error('This Try needs exactly one CLI entry for argv. Choose an explicit entry and input from try_state.');
|
|
105
|
+
entry = cli[0]; input = { argv: args.argv };
|
|
106
|
+
} else {
|
|
107
|
+
entry = owner.model.entries.find(e => `${e.entry_path}#${e.operation}` === args.entry);
|
|
108
|
+
input = args.input;
|
|
109
|
+
}
|
|
110
|
+
if (!entry) throw new Error('Unknown entry. Read try_state for admitted entries.');
|
|
111
|
+
const started = Date.now();
|
|
112
|
+
let answer;
|
|
113
|
+
try {
|
|
114
|
+
answer = await dependencies.runDoorCall({ root: owner.root, originalPath:owner.test.path, origin: owner.record.origin, sessionId: owner.record.id,
|
|
115
|
+
login: owner.record.login, prompt: entry.entry_path, operation: entry.operation, callCap: owner.model.calls?.cap ?? null,
|
|
116
|
+
existingOnly: Boolean(args.try_id), declaredErrors: Array.isArray(entry.errors) ? entry.errors : [] }, input, runtimePorts);
|
|
117
|
+
} catch (error) {
|
|
118
|
+
// The door owns dispatch/recovery. Conservatively block a second mutation when its outcome is unconfirmed.
|
|
119
|
+
if (error.unknownOutcome === true) session.unknown = true;
|
|
120
|
+
throw error;
|
|
121
|
+
}
|
|
122
|
+
const isProgramError = answer.error !== undefined && answer.error !== null;
|
|
123
|
+
const run = { id: answer.id, ...(answer.actionId !== undefined ? { action_id: answer.actionId } : {}),
|
|
124
|
+
...(answer.replayed !== undefined ? { replayed: Boolean(answer.replayed) } : {}),
|
|
125
|
+
entry: `${entry.entry_path}#${entry.operation}`, input,
|
|
126
|
+
...(answer.inputWorld !== undefined ? { world_before: answer.inputWorld } : {}),
|
|
127
|
+
...(isProgramError ? { error: answer.error } : { result: answer.result, error: null }),
|
|
128
|
+
...(answer.world !== undefined ? { world_after: answer.world } : {}), lossless: true };
|
|
129
|
+
runs.push(run);
|
|
130
|
+
return { run_id: run.id, action_id: answer.actionId ?? null, replayed: Boolean(answer.replayed),
|
|
131
|
+
result: isProgramError ? null : run.result, error: isProgramError ? run.error : null,
|
|
132
|
+
data_before: run.world_before ?? null, data_after: run.world_after ?? null,
|
|
133
|
+
...(answer.inputWorld === undefined || answer.world === undefined ? { data_warning: 'The interpreter did not supply both run world snapshots; world checks may be unavailable.' } : {}),
|
|
134
|
+
usage: answer.usage ?? null, seconds: Math.round((Date.now() - started) / 100) / 10 };
|
|
135
|
+
}
|
|
136
|
+
const run = args.run_id ? runs.find(run => run.id === args.run_id) : runs.at(-1);
|
|
137
|
+
if (!run) throw new Error('No matching confirmed run. Use try_run first.');
|
|
138
|
+
if (name === 'try_check') return { run_id: run.id, verdict: judge.record(run), progress: judge.snapshot() };
|
|
139
|
+
if (run.saved) return { run_id: run.id, already_saved: true, result: run.saved };
|
|
140
|
+
const criteria = owner.test.doc.criteria ?? [];
|
|
141
|
+
const tied = [...new Set(owner.test.doc.steps.filter(step => `${step.entry_path}#${step.operation}` === run.entry).flatMap(step => (step.checks ?? []).map(check => check.criterion_id)))];
|
|
142
|
+
const criterion = args.criterion_id ?? (tied.length === 1 ? tied[0] : undefined);
|
|
143
|
+
if (!criteria.some(item => item.id === criterion)) throw new Error(`Choose criterion_id from: ${criteria.map(item => item.id).join(', ')}.`);
|
|
144
|
+
if (!object(run.world_before)) throw new Error('The interpreter did not provide a confirmed starting world. This run cannot be saved safely.');
|
|
145
|
+
const separator = run.entry.lastIndexOf('#');
|
|
146
|
+
const step = run.error && typeof run.error.code === 'string'
|
|
147
|
+
? { step_id: `try-${run.id}`, entry_path: run.entry.slice(0, separator), operation: run.entry.slice(separator + 1), input: run.input,
|
|
148
|
+
expected_error: run.error.code, checks: [{ criterion_id: criterion, target: 'error', path: '/code', op: 'equals', value: run.error.code }] }
|
|
149
|
+
: { step_id: `try-${run.id}`, entry_path: run.entry.slice(0, separator), operation: run.entry.slice(separator + 1), input: run.input,
|
|
150
|
+
checks: [{ criterion_id: criterion, target: 'result', path: '', op: 'equals', value: run.result }] };
|
|
151
|
+
const result = dependencies.saveDoorCase(owner.root, { id: run.id, name: args.name ?? 'Recorded Try tool run', story_path: owner.test.storyPath, original_path: owner.test.path,
|
|
152
|
+
test: { schema_version: 'prompt-runtime.program-scenario.v1', story_path: owner.test.storyPath, criteria, initial_world: run.world_before, simulation: owner.test.doc.simulation ?? {}, context: owner.test.doc.context ?? [],
|
|
153
|
+
steps: [step] } }, { ...runtimePorts, ports: runtimePorts, isolated: true });
|
|
154
|
+
if (!result.startsWith('added ') && !result.startsWith('already saved ')) throw new Error(result);
|
|
155
|
+
run.saved = result;
|
|
156
|
+
return { run_id: run.id, result, note: recordedCaseNote({scope:'original-story',covered:1,total:criteria.length}) };
|
|
157
|
+
}
|
|
158
|
+
return { call(name, args = {}) { const result = queue.then(() => invoke(name, args)); queue = result.catch(() => {}); return result; } };
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export async function runMcp({ cwd = process.cwd(), words = [], env, client } = {}, ports = {}) {
|
|
162
|
+
const serverVersion = typeof client?.version === 'string' && client.version ? client.version : typeof ports.clientVersion === 'string' && ports.clientVersion ? ports.clientVersion : '0.0.0';
|
|
163
|
+
const stdin = ports.stdin ?? process.stdin, stdout = ports.stdout ?? process.stdout, stderr = ports.stderr ?? process.stderr;
|
|
164
|
+
const service = createTryTools({ cwd, words, env }, ports), replay = new Map();
|
|
165
|
+
const send = message => stdout.write(`${JSON.stringify(message)}\n`);
|
|
166
|
+
const error = (id, code, message) => ({ jsonrpc: '2.0', id, error: { code, message } });
|
|
167
|
+
const validId = id => id === null || typeof id === 'string' || typeof id === 'number' && Number.isFinite(id);
|
|
168
|
+
async function respond(msg) {
|
|
169
|
+
const id = msg.id;
|
|
170
|
+
if (msg.method === 'initialize') {
|
|
171
|
+
if (!object(msg.params) || typeof msg.params.protocolVersion !== 'string' || !object(msg.params.capabilities) || !object(msg.params.clientInfo)) return error(id, -32602, 'Invalid initialize parameters');
|
|
172
|
+
const versions = ['2025-06-18', '2025-03-26', '2024-11-05'];
|
|
173
|
+
return { jsonrpc: '2.0', id, result: { protocolVersion: versions.includes(msg.params.protocolVersion) ? msg.params.protocolVersion : versions[0], capabilities: { tools: {} }, serverInfo: { name: 'pdd-try', version: serverVersion } } };
|
|
174
|
+
}
|
|
175
|
+
if (msg.method === 'ping' || msg.method === 'tools/list') {
|
|
176
|
+
if (msg.params !== undefined && !object(msg.params)) return error(id, -32602, 'Parameters must be an object');
|
|
177
|
+
return { jsonrpc: '2.0', id, result: msg.method === 'ping' ? {} : { tools } };
|
|
178
|
+
}
|
|
179
|
+
if (msg.method !== 'tools/call') return error(id, -32601, 'Method not found');
|
|
180
|
+
if (!object(msg.params) || !text(msg.params.name) || msg.params.arguments !== undefined && !object(msg.params.arguments)) return error(id, -32602, 'Invalid tools/call parameters');
|
|
181
|
+
const token = msg.params._meta?.progressToken;
|
|
182
|
+
let progress = 0;
|
|
183
|
+
const tick = () => {
|
|
184
|
+
stderr.write(`pdd mcp: ${msg.params.name} is still working…\n`);
|
|
185
|
+
if (typeof token === 'string' || typeof token === 'number') send({ jsonrpc: '2.0', method: 'notifications/progress', params: { progressToken: token, progress: ++progress, message: `${msg.params.name} is still working` } });
|
|
186
|
+
};
|
|
187
|
+
const timer = setInterval(tick, ports.progressMs ?? 10_000);
|
|
188
|
+
timer.unref?.();
|
|
189
|
+
try {
|
|
190
|
+
const value = await service.call(msg.params.name, msg.params.arguments ?? {});
|
|
191
|
+
return { jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: JSON.stringify(value) }], structuredContent: value } };
|
|
192
|
+
} catch (e) {
|
|
193
|
+
return { jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: String(e.message || 'The Try tool failed.') }], isError: true } };
|
|
194
|
+
} finally { clearInterval(timer); }
|
|
195
|
+
}
|
|
196
|
+
const pending = new Set();
|
|
197
|
+
const input = createInterface({ input: stdin, crlfDelay: Infinity });
|
|
198
|
+
for await (const line of input) {
|
|
199
|
+
if (Buffer.byteLength(line) > 1_048_576) { send(error(null, -32600, 'Request exceeds 1 MiB')); continue; }
|
|
200
|
+
let msg;
|
|
201
|
+
try { msg = JSON.parse(line); } catch { send(error(null, -32700, 'Parse error')); continue; }
|
|
202
|
+
if (!object(msg) || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string' || Object.hasOwn(msg, 'id') && !validId(msg.id)) { send(error(null, -32600, 'Invalid Request')); continue; }
|
|
203
|
+
if (!Object.hasOwn(msg, 'id')) continue;
|
|
204
|
+
const key = `${typeof msg.id}:${msg.id}`, signature = JSON.stringify(msg);
|
|
205
|
+
const prior = replay.get(key);
|
|
206
|
+
if (prior) {
|
|
207
|
+
if (prior.signature !== signature) send(error(msg.id, -32600, 'Request ID already used for a different request'));
|
|
208
|
+
else { const task = prior.answer.then(send); pending.add(task); task.finally(() => pending.delete(task)); }
|
|
209
|
+
continue;
|
|
210
|
+
}
|
|
211
|
+
const answer = respond(msg).catch(() => error(msg.id, -32603, 'Internal error'));
|
|
212
|
+
const record = { signature, answer, settled: false };
|
|
213
|
+
replay.set(key, record);
|
|
214
|
+
// Keep pending IDs until completion and a bounded recent replay window afterwards.
|
|
215
|
+
const task = answer.then(send).finally(() => {
|
|
216
|
+
pending.delete(task); record.settled = true;
|
|
217
|
+
if (replay.size > 1024) for (const [old, cached] of replay) { if (old !== key && cached.settled) { replay.delete(old); break; } }
|
|
218
|
+
});
|
|
219
|
+
pending.add(task);
|
|
220
|
+
}
|
|
221
|
+
await Promise.all(pending);
|
|
222
|
+
return 0;
|
|
223
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// Generated from prompts/cli/try-session.prompt.md (sha256: 0201646679c184b9c28af44b93264b1602c8ab0a700e7ad394f3fdd362edae57).
|
|
2
|
+
|
|
3
|
+
function fail(code, message = code) {
|
|
4
|
+
const error = new Error(message);
|
|
5
|
+
error.code = code;
|
|
6
|
+
throw error;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function bindExistingTry({ try_id, story, records, drift, model }) {
|
|
10
|
+
const hits = records.filter(record => record.id === try_id);
|
|
11
|
+
if (hits.length !== 1) fail('try-not-found', `No open Try with ID "${try_id}". No new Try was opened.`);
|
|
12
|
+
const record = hits[0];
|
|
13
|
+
if (story !== undefined && story !== '' && ![record.story, record.story_path, record.test_path, record.test_name].includes(story)) {
|
|
14
|
+
fail('story-mismatch', `Try "${try_id}" belongs to "${record.story_path}", not "${story}".`);
|
|
15
|
+
}
|
|
16
|
+
if (drift !== null) fail('source-drift', drift || 'The Story or prompt changed since this Try started.');
|
|
17
|
+
if (model.status !== 200) {
|
|
18
|
+
fail('session-not-running', `Try "${try_id}" is not running (HTTP ${model.status}${model.error_code ? `: ${model.error_code}` : ''}). No new Try or reopen was sent.`);
|
|
19
|
+
}
|
|
20
|
+
if (record.max_calls !== null && model.cap !== null && record.max_calls !== model.cap) {
|
|
21
|
+
fail('cap-mismatch', `Try "${try_id}" reported call cap ${model.cap} instead of pinned cap ${record.max_calls}.`);
|
|
22
|
+
}
|
|
23
|
+
return {
|
|
24
|
+
try_id: record.id,
|
|
25
|
+
test_path: record.test_path,
|
|
26
|
+
story_path: record.story_path,
|
|
27
|
+
source_sha256: record.source_sha256,
|
|
28
|
+
engine_sha: record.engine_sha,
|
|
29
|
+
server_commit: record.server_commit,
|
|
30
|
+
cap: model.cap !== null ? model.cap : record.max_calls,
|
|
31
|
+
remaining: model.remaining,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function projectTryCall({ request_id, declared_errors, state, has_program_result, usage_calls, report }) {
|
|
36
|
+
if (state === 'queued' || state === 'running' || state === 'unknown') {
|
|
37
|
+
fail('unknown-outcome', 'The command result is unknown. Do not repeat it automatically.');
|
|
38
|
+
}
|
|
39
|
+
if (state === 'passed') {
|
|
40
|
+
if (!has_program_result) fail('unknown-outcome', 'The command result is unknown. Do not repeat it automatically.');
|
|
41
|
+
return {
|
|
42
|
+
outcome: 'result',
|
|
43
|
+
run_id: request_id,
|
|
44
|
+
action_id: report !== null ? report.action_id : null,
|
|
45
|
+
error_code: null,
|
|
46
|
+
replayed: report !== null ? Boolean(report.replayed) : false,
|
|
47
|
+
calls: usage_calls,
|
|
48
|
+
remaining_calls: report !== null ? report.remaining_calls : null,
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
if ((state === 'failed' || state === 'refused') && report !== null && report.verdict === 'failed' && report.error_code !== null && declared_errors.includes(report.error_code)) {
|
|
52
|
+
return {
|
|
53
|
+
outcome: 'program_error',
|
|
54
|
+
run_id: request_id,
|
|
55
|
+
action_id: report.action_id,
|
|
56
|
+
error_code: report.error_code,
|
|
57
|
+
replayed: Boolean(report.replayed),
|
|
58
|
+
calls: usage_calls,
|
|
59
|
+
remaining_calls: report.remaining_calls,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
fail('call-refused', 'The interpreter refused the command.');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function projectTryObservation({ try_id, run_id, status, body }) {
|
|
66
|
+
if (status === 404) fail('run-not-found', `No call "${run_id}" was found on Try "${try_id}".`);
|
|
67
|
+
if (status === 410) fail('result-expired', `Call "${run_id}" on Try "${try_id}" has expired.`);
|
|
68
|
+
if (status !== 200 || body === null || body.session_id !== try_id || body.request_id !== run_id) {
|
|
69
|
+
fail('observation-unavailable', `Observation for call "${run_id}" on Try "${try_id}" is unavailable${status ? ` (HTTP ${status})` : ''}.`);
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
try_id: body.session_id,
|
|
73
|
+
run_id: body.request_id,
|
|
74
|
+
action_id: body.action_id,
|
|
75
|
+
state: body.state,
|
|
76
|
+
session_state: body.session_state,
|
|
77
|
+
terminal: body.state === 'passed' || body.state === 'failed' || body.state === 'refused',
|
|
78
|
+
unknown_outcome: body.state === 'unknown',
|
|
79
|
+
source_sha256: body.source_sha256,
|
|
80
|
+
server_commit: body.server_commit,
|
|
81
|
+
engine_sha: body.engine_sha,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function selectTryToStop({ selector, records }) {
|
|
86
|
+
if (selector === undefined || selector === '') {
|
|
87
|
+
if (records.length === 0) fail('stop-not-found', 'No open Try in this repository.');
|
|
88
|
+
if (records.length > 1) fail('stop-ambiguous', 'Name the Try to stop.');
|
|
89
|
+
return { id: records[0].id, test_path: records[0].test_path, story_path: records[0].story_path };
|
|
90
|
+
}
|
|
91
|
+
const hits = records.filter(record => [record.id, record.story_path, record.story, record.test_path, record.test_name].includes(selector));
|
|
92
|
+
if (hits.length === 0) fail('stop-not-found', `No open Try for "${selector}".`);
|
|
93
|
+
if (hits.length > 1) fail('stop-ambiguous', `More than one open Try matches "${selector}".`);
|
|
94
|
+
return { id: hits[0].id, test_path: hits[0].test_path, story_path: hits[0].story_path };
|
|
95
|
+
}
|