@promptdriven/runtime-client 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +42 -2
  3. package/package.json +28 -4
  4. package/src/index.mjs +1 -0
  5. package/src/runtime/agent-ask.mjs +187 -0
  6. package/src/runtime/agent-chat.mjs +152 -0
  7. package/src/runtime/agent-coverage.mjs +97 -0
  8. package/src/runtime/agent-guide.mjs +152 -0
  9. package/src/runtime/agent-judge.mjs +71 -0
  10. package/src/runtime/agent-packet.mjs +62 -0
  11. package/src/runtime/agent-project.mjs +93 -0
  12. package/src/runtime/contract-refs.mjs +519 -0
  13. package/src/runtime/contracts.mjs +138 -0
  14. package/src/runtime/index.mjs +974 -0
  15. package/src/runtime/lint-call-preflight.mjs +19 -0
  16. package/src/runtime/lint-compatibility-display.mjs +62 -0
  17. package/src/runtime/live-local-bridge.mjs +178 -0
  18. package/src/runtime/live-local.mjs +181 -0
  19. package/src/runtime/product-composition.mjs +384 -0
  20. package/src/runtime/run-program.mjs +797 -0
  21. package/src/runtime/runtime-binding-plan.mjs +145 -0
  22. package/src/runtime/runtime-bindings.mjs +81 -0
  23. package/src/runtime/runtime-check-plan.mjs +411 -0
  24. package/src/runtime/runtime-client.mjs +8114 -0
  25. package/src/runtime/runtime-lint-receipt.mjs +25 -0
  26. package/src/runtime/runtime-markdown.mjs +215 -0
  27. package/src/runtime/runtime-outcome.mjs +468 -0
  28. package/src/runtime/runtime-output.mjs +752 -0
  29. package/src/runtime/runtime-preflight.mjs +3832 -0
  30. package/src/runtime/runtime-slots.mjs +462 -0
  31. package/src/runtime/runtime-workspace-migration.mjs +70 -0
  32. package/src/runtime/runtime-workspace.mjs +52 -0
  33. package/src/runtime/scenario-json.mjs +257 -0
  34. package/src/runtime/secret-redaction.mjs +54 -0
  35. package/src/runtime/try-doors.mjs +597 -0
  36. package/src/runtime/try-http.mjs +285 -0
  37. package/src/runtime/try-mcp.mjs +223 -0
  38. package/src/runtime/try-session.mjs +95 -0
  39. package/src/runtime/try-update-policy.mjs +43 -0
@@ -0,0 +1,19 @@
1
+ // Generated from prompts/cli/lint-call-preflight.prompt.md.
2
+ // The Runtime supplies all costs. Association gates display only, never paid admission.
3
+ export function describeCallPreflight({ test, preflight, context, sourceSha256, requestedCap }) {
4
+ const trusted = preflight && context && context.source_sha256 === sourceSha256
5
+ && /^[a-f0-9]{40}$/.test(context.engine_build ?? '')
6
+ && context.selected_cap === requestedCap && preflight.selected_cap === requestedCap;
7
+ const quantity = value => value ?? 'unknown';
8
+ const lines = [trusted
9
+ ? `Call preflight (${test}): ${preflight.status}; structural catalog estimate ${quantity(preflight.estimated_calls)} calls; selected cap ${preflight.selected_cap ?? 'not selected'}; complete ${preflight.complete}.`
10
+ : `Call preflight (${test}): unavailable; no estimate or cap-fit claim.`];
11
+ if (trusted) for (const step of preflight.steps ?? []) lines.push(
12
+ ` Step ${step.step_id} (${step.entry_path} :: ${step.operation}): catalog ${quantity(step.catalog_calls)}; cumulative ${quantity(step.cumulative_catalog_calls)}; external resources ${step.has_external_resources}.`);
13
+ lines.push(context
14
+ ? ` Source ${context.source_sha256}; engine ${context.engine_build}; configured maximum ${context.max_cap}.`
15
+ : ' Source and engine identity unavailable.');
16
+ if (trusted && preflight.status === 'warning') lines.push(' Warning: the structural estimate exceeds the selected cap; the cap is unchanged.');
17
+ lines.push(' Advisory only: no guarantee of actual calls or completion; resource continuations are not included. Lint uses 0 AI calls.');
18
+ return { text: lines.join('\n') };
19
+ }
@@ -0,0 +1,62 @@
1
+ // Generated from prompts/cli/lint-compatibility-display.prompt.md (sha256: 73f366ec3d5c86902ce432f5037b2af34a29d67e30ae388bff28d361707d2cb8).
2
+
3
+ const countText = (count, singular) => count === 1 ? `1 ${singular}` : `${count} ${singular}s`;
4
+ const nonblank = value => typeof value === 'string' && value.trim().length > 0;
5
+ const distinct = values => [...new Set(values)];
6
+
7
+ export function describeCompatibility({ label, compatibility, clientAdvice = null, details = false }) {
8
+ if (details) {
9
+ const lines = [`Compatibility (${label}): ${JSON.stringify(compatibility, null, 2)}`];
10
+ if (clientAdvice !== null && clientAdvice !== undefined) lines.push(` Client advice: ${JSON.stringify(clientAdvice)}`);
11
+ return { text: lines.join('\n') };
12
+ }
13
+ const reported = compatibility?.reported;
14
+ const structured = reported !== null && typeof reported === 'object' && !Array.isArray(reported)
15
+ && Array.isArray(reported.operations) && Array.isArray(reported.edges);
16
+ let summary;
17
+ if (structured) {
18
+ const items = [...reported.operations, ...reported.edges];
19
+ const stepCount = countText(distinct(items.map(item => item.selection.step_id)).length, 'step');
20
+ const opCount = countText(reported.operations.length, 'operation');
21
+ const edgeCount = countText(reported.edges.length, 'edge');
22
+ const execModes = items.length ? distinct(items.map(item => item.execution_mode)).join(', ') : 'none';
23
+ const resModes = items.length ? distinct(items.map(item => item.resource_mode)).join(', ') : 'none';
24
+ const engine = reported.engine_build === 'unknown' ? 'unknown' : String(reported.engine_build ?? '').slice(0, 12);
25
+ summary = `Compatibility (${label}): ${compatibility.state} (association ${compatibility.association}); ${stepCount} (${opCount}, ${edgeCount}); execution ${execModes}; resources ${resModes}; complete ${reported.complete}; engine ${engine}`;
26
+ if (nonblank(compatibility.issue)) summary += `; issue ${compatibility.issue}`;
27
+ const nonSupported = distinct(items.filter(item => item.verdict !== 'supported').map(item => item.reason_code));
28
+ if (nonSupported.length > 0) summary += `; non-supported: ${nonSupported.join(', ')}`;
29
+ summary += '.';
30
+ } else {
31
+ summary = `Compatibility (${label}): ${compatibility.state} (association ${compatibility.association})`;
32
+ if (typeof reported?.complete === 'boolean') summary += `; complete ${reported.complete}`;
33
+ if (typeof reported?.engine_build === 'string' && reported.engine_build.length > 0) {
34
+ summary += `; engine ${reported.engine_build === 'unknown' ? 'unknown' : reported.engine_build.slice(0, 12)}`;
35
+ }
36
+ if (nonblank(compatibility.issue)) summary += `; issue ${compatibility.issue}`;
37
+ summary += '.';
38
+ }
39
+ const lines = [summary];
40
+ if (clientAdvice !== null && clientAdvice !== undefined) {
41
+ lines.push(` Client advice (${clientAdvice.owner}): ${clientAdvice.next_step}`);
42
+ }
43
+ return { text: lines.join('\n') };
44
+ }
45
+
46
+ export function describeLintDiagnostics({ problems, localOnly = false }) {
47
+ if (!problems.length) return { text: '' };
48
+ const blocking = problems.filter(item => item.severity !== 'warning');
49
+ const advisories = problems.filter(item => item.severity === 'warning');
50
+ const lines = [];
51
+ const emitGroup = (heading, items) => {
52
+ if (!items.length) return;
53
+ lines.push(heading);
54
+ for (const item of items) {
55
+ lines.push(` ${[item.code, item.path, item.section, item.message].filter(Boolean).join(' ')}`);
56
+ if (nonblank(item.hint)) lines.push(` ${item.hint}`);
57
+ }
58
+ };
59
+ emitGroup(localOnly ? 'Local lint problems:' : 'Lint problems (from the PDD interpreter):', blocking);
60
+ emitGroup(localOnly ? 'Local lint advisories:' : 'Lint advisories (from the PDD interpreter):', advisories);
61
+ return { text: lines.join('\n') };
62
+ }
@@ -0,0 +1,178 @@
1
+ // Generated from prompts/cli/live-local-bridge.prompt.md (sha256: 66d676e2e7d255f95f7b361c5f256a652f8add9380c0a9174e62b35165c82f44).
2
+ // Owned by prompts/cli/live-local-bridge.prompt.md.
3
+ import {createHash} from 'node:crypto';
4
+ import {executeLocalCommand, validateLocalManifest, validateLocalRequest} from './live-local.mjs';
5
+ import {rememberSecrets, redactSecrets} from './secret-redaction.mjs';
6
+ const PROTOCOL='prompt-runtime.local-commands.v1', CAPABILITY='execute-command-v1';
7
+ function fail(code='live-local-bridge-refused') { throw Object.assign(new Error(code),{code}); }
8
+ function bound(object,name) { if(typeof object?.[name]!=='function')throw Object.assign(new Error(`Live-local port ${name} is not bound.`),{unboundPort:true});return object[name].bind(object); }
9
+ const shape=(value,keys)=>value&&typeof value==='object'&&!Array.isArray(value)&&Object.keys(value).length===keys.length&&keys.every(k=>Object.hasOwn(value,k));
10
+ const clone = value => JSON.parse(JSON.stringify(value));
11
+ function freeze(value) { if(value&&typeof value==='object'){for(const child of Object.values(value))freeze(child);Object.freeze(value);}return value; }
12
+ const id = value => typeof value==='string' && /^[A-Za-z0-9_-]{1,512}$/.test(value);
13
+ const canonical=value=>value&&typeof value==='object'?Array.isArray(value)?value.map(canonical):Object.fromEntries(Object.keys(value).sort().map(k=>[k,canonical(value[k])])):value;
14
+ const hex = value => createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');
15
+ export async function createLocalCommandBridge(input,ports={}) {
16
+ const host=ports.liveLocal;
17
+ for(const name of ['readManifest','execute','confirm','randomUUID','sleep','redact','resolveExecutable','environment'])bound(host,name);
18
+ bound(host?.journal,'read');bound(host?.journal,'write');bound(ports,'request');bound(ports,'owner');
19
+ const waitMs=input?.wait_ms??0;
20
+ if(!input||!['check','try'].includes(input.kind)||!input.identity?.login||typeof input.root!=='string'||typeof input.origin!=='string'||typeof input.allow_writes!=='boolean'||typeof host.terminal!=='boolean'||!Number.isSafeInteger(waitMs)||waitMs<0||waitMs>20000)fail();
21
+ rememberSecrets(input.identity.token);
22
+ for(const c of input.manifest?.commands??[])for(const value of [c.stdin?.literal,...(c.argv??[]).map(v=>v.literal).filter(v=>v!==undefined)])if(typeof value==='string'&&redactSecrets(value)!==value)fail('live-local-sensitive-manifest');
23
+ const manifest=freeze(clone(validateLocalManifest(input.manifest)));
24
+ const owner=input.identity.login, client_id=host.randomUUID();if(!id(client_id))fail();
25
+ const binding_ids=[...new Set(manifest.commands.map(c=>c.binding_id))].sort(), executables=[...new Set(manifest.commands.map(c=>c.executable))].sort();
26
+ const controller=new AbortController(), jobs=new Set(), records=new Map(), active=new Set();
27
+ let closed=false, servicePromise=null, failure=null;
28
+ const ownerCheck = () => { if(ports.owner()!==owner)fail('live-local-owner-changed'); };
29
+ const request = async(method,path,body) => {
30
+ ownerCheck();const response=await ports.request({method,path,...(body===undefined?{}:{body})});ownerCheck();
31
+ if(!response||response.status!==200||!response.json||typeof response.json!=='object')fail('live-local-transport-failed');return response.json;
32
+ };
33
+ const registration={schema_version:PROTOCOL,capability:CAPABILITY,client_id,binding_ids,executables};
34
+ const checkRegistration = (r,previous) => { if(!shape(r,['schema_version','capability','client_id','registration_id','epoch'])||r.schema_version!==PROTOCOL||r.capability!==CAPABILITY||r.client_id!==client_id||!id(r.registration_id)||!Number.isSafeInteger(r.epoch)||r.epoch<1||previous&&(r.registration_id!==previous.registration_id||r.epoch!==previous.epoch))fail('live-local-registration-invalid');return r; };
35
+ const registered=checkRegistration(await request('POST','/v1/local-commands/registrations',registration));
36
+ const pause=async ms=>{
37
+ try { await host.sleep(ms,controller.signal); }
38
+ catch(error) { if(!controller.signal.aborted)throw error; }
39
+ };
40
+ // Keep owner authority alive while a potentially slow source upload is pending.
41
+ const heartbeat=(async()=>{
42
+ try {
43
+ while(!closed&&!controller.signal.aborted){
44
+ await pause(5000);
45
+ if(closed||controller.signal.aborted)break;
46
+ checkRegistration(await request('POST','/v1/local-commands/registrations',registration),registered);
47
+ }
48
+ } catch(error){failure=error;controller.abort();}
49
+ })();
50
+ const resource_setup=freeze({schema_version:'prompt-runtime.hosted-resource-setup.v1',selection:clone(manifest.selection),local_bindings:manifest.commands.map(c=>{
51
+ const {parameters,binding_id,resource,operation,...fields}=c;
52
+ return {binding_id,resource,operation,configuration:{schema_version:'prompt-runtime.local-command-binding.v1',...fields,resource,operation,access:c.access??'read'}};
53
+ }),registration_id:registered.registration_id});
54
+ const base = job => `/v1/${input.kind}/${encodeURIComponent(job)}/local-commands`;
55
+ const connect = async job => {
56
+ if(failure)throw failure;
57
+ if(closed||controller.signal.aborted||!id(job))fail();
58
+ const r=await request('POST',`${base(job)}/connect`,{schema_version:PROTOCOL,capability:CAPABILITY,client_id,binding_ids});
59
+ if(!shape(r,['schema_version','capability','client_id','epoch'])||r.schema_version!==PROTOCOL||r.capability!==CAPABILITY||r.client_id!==client_id||r.epoch!==registered.epoch)fail('live-local-registration-invalid');jobs.add(job);
60
+ };
61
+ const event=async(job,rid,action,result) => {
62
+ const answer=await request('POST',`${base(job)}/${encodeURIComponent(rid)}/events`,{session_id:job,client_id,epoch:registered.epoch,request_id:rid,action,...(result===undefined?{}:{result})});
63
+ if(!shape(answer,['request_id','state','dispatch_permitted','request','outcome','result'])||answer.request_id!==rid||!['queued','claimed','dispatched','cancel_requested','completed','failed','cancelled','unknown'].includes(answer.state)||typeof answer.dispatch_permitted!=='boolean')fail('live-local-response-invalid');return answer;
64
+ };
65
+ const save=async(key,value) => { await host.journal.write(key,value);records.set(key,value); };
66
+ const serve=async(job,rid) => {
67
+ const key=hex([owner,input.origin,input.source_sha256??null,job,rid]);
68
+ const association=hex([owner,input.origin,input.source_sha256??null,hex(resource_setup),client_id,registered.epoch,job,rid]);
69
+ const old=records.get(key)??await host.journal.read(key);
70
+ if(old) {
71
+ if(old.scope!==key||old.association!==association||old.request_id!==rid)fail('live-local-journal-conflict');
72
+ if(old.result)await event(job,rid,'reply',old.result);
73
+ return;
74
+ }
75
+ const polled=await event(job,rid,'poll');
76
+ if(!['queued','claimed'].includes(polled.state)||polled.dispatch_permitted||!polled.request||polled.request.request_id!==rid)fail('live-local-response-invalid');
77
+ const wire=polled.request;
78
+ const identity={scope:key,association,request_hash:hex(wire),request_id:rid,attempt_id:wire.attempt_id,call_id:wire.call_id,state:'permission-unknown'};
79
+ let permitted=false;
80
+ const deliver=async result => {
81
+ await save(key,{...identity,state:'result',result});
82
+ const answer=await event(job,rid,'reply',result);
83
+ if(!['completed','failed','unknown'].includes(answer.state)||hex(answer.result)!==hex(result))fail('live-local-response-invalid');
84
+ return {accepted:true};
85
+ };
86
+ try {
87
+ validateLocalRequest(manifest,wire);
88
+ // Persist uncertainty before asking for a one-use permit. Never replay it.
89
+ await save(key,identity);
90
+ const executed=await executeLocalCommand({mode:'live-local',manifest_json:JSON.stringify(manifest),request_json:JSON.stringify(wire),allow_writes:input.allow_writes,terminal:host.terminal},{
91
+ runner:{execute:async()=>{
92
+ ownerCheck();if(closed||controller.signal.aborted)fail();
93
+ const resolvedExecutable=await host.resolveExecutable({executable:wire.argv[0]});
94
+ if(typeof resolvedExecutable!=='string'||!resolvedExecutable.startsWith('/'))fail('live-local-executable-unavailable');
95
+ const environment=await host.environment({names:wire.environment});
96
+ if(!environment||typeof environment!=='object'||Array.isArray(environment))fail();
97
+ rememberSecrets(input.identity.token,...Object.values(environment).filter(v=>typeof v==='string'));
98
+ ownerCheck();if(closed||controller.signal.aborted)fail();
99
+ const started=await event(job,rid,'started');
100
+ if(started.state!=='dispatched'||started.dispatch_permitted!==true||started.request!==null||started.outcome!==null||started.result!==null)fail('live-local-permit-unavailable');
101
+ permitted=true;
102
+ await save(key,{...identity,state:'launched'});
103
+ ownerCheck();if(closed||controller.signal.aborted)fail();
104
+ return host.execute({request:wire,resolvedExecutable,environment,root:input.root,signal:controller.signal});
105
+ }},
106
+ consent:{confirm:args=>host.confirm({...args,signal:controller.signal})},
107
+ redaction:{redact:async args=>{const result=await host.redact(args);if(typeof result?.text!=='string')fail();return {text:redactSecrets(result.text)};}},
108
+ delivery:{reply:async({result_json})=>deliver(JSON.parse(result_json))}
109
+ });
110
+ if(typeof ports.onReceipt==='function'){try{await ports.onReceipt(Object.fromEntries(Object.entries(executed.receipt).map(([key,value])=>[key,redactSecrets(value)])));}catch{}}
111
+ } catch(error) {
112
+ if(records.get(key)?.result)throw error;
113
+ const status=error.code==='live-local-redaction-failed'?'sensitive-output':permitted?'unknown':'unavailable';
114
+ const reason=status==='sensitive-output'?'output-suppressed':permitted?'outcome-lost':'policy-refused';
115
+ // A lost started response has unknown authority. Keep its journal fuse.
116
+ if(!permitted&&records.has(key)&&!['live-local-write-denied','live-local-policy-refused'].includes(error.code))throw error;
117
+ await deliver({request_id:rid,attempt_id:wire.attempt_id,call_id:wire.call_id,status,outcome:null,reason});
118
+ }
119
+ };
120
+ const loop=async signal => {
121
+ const stop=()=>controller.abort();signal?.addEventListener('abort',stop,{once:true});if(signal?.aborted)stop();
122
+ try {
123
+ while(!closed&&!controller.signal.aborted) {
124
+ checkRegistration(await request('POST','/v1/local-commands/registrations',registration),registered);
125
+ if(closed||controller.signal.aborted)break;
126
+ for(const job of [...jobs]) {
127
+ ownerCheck();const read=await ports.request({method:'GET',path:`/v1/runs/${encodeURIComponent(job)}`});ownerCheck();
128
+ if(read.status!==200||read.json?.id!==job||read.json?.command!==input.kind)fail('live-local-job-unverified');
129
+ const answer=read.json;
130
+ if(input.kind==='check'&&!['queued','running'].includes(answer.state)||input.kind==='try'&&(['failed','refused','unknown','not_run'].includes(answer.state)||['stopped','stopping','unknown'].includes(answer.result?.session?.state))) { jobs.delete(job);controller.abort();continue; }
131
+ if(closed||controller.signal.aborted)break;
132
+ await connect(job);
133
+ if(closed||controller.signal.aborted)break;
134
+ let pendingResponse;
135
+ try {
136
+ ownerCheck();
137
+ pendingResponse=await ports.request({method:'GET',path:`${base(job)}/pending?client_id=${encodeURIComponent(client_id)}&epoch=${registered.epoch}${waitMs>0?`&wait_ms=${waitMs}`:''}`,signal:controller.signal});
138
+ ownerCheck();
139
+ } catch(error) {
140
+ if(error?.code==='live-local-owner-changed')throw error;
141
+ if(!closed&&!controller.signal.aborted)throw error;
142
+ break;
143
+ }
144
+ if(closed||controller.signal.aborted)break;
145
+ if(!pendingResponse||pendingResponse.status!==200||!pendingResponse.json||typeof pendingResponse.json!=='object')fail('live-local-transport-failed');
146
+ const pending=pendingResponse.json;
147
+ if(!shape(pending,['request_ids'])||!Array.isArray(pending.request_ids)||pending.request_ids.length>16||!pending.request_ids.every(id)||new Set(pending.request_ids).size!==pending.request_ids.length)fail('live-local-response-invalid');
148
+ for(const rid of pending.request_ids) {
149
+ if(closed||controller.signal.aborted)break;
150
+ const k=job+':'+rid;if(active.has(k))continue;active.add(k);
151
+ const task=serve(job,rid).catch(error=>{failure=error;controller.abort();}).finally(()=>active.delete(k));
152
+ active.add(task);task.finally(()=>active.delete(task));
153
+ }
154
+ }
155
+ if(input.kind==='check'&&!jobs.size)break;
156
+ if(input.kind==='try'&&!jobs.size)break;
157
+ await pause(waitMs>0?50:1000);
158
+ if(failure)throw failure;
159
+ }
160
+ controller.abort();await heartbeat;
161
+ await Promise.all([...active].filter(v=>v instanceof Promise));if(failure)throw failure;
162
+ } finally { signal?.removeEventListener('abort',stop);controller.abort(); }
163
+ };
164
+ const service=signal=>servicePromise??=(loop(signal));
165
+ let closing;
166
+ const close=()=>closing??=(async()=>{
167
+ closed=true;controller.abort();
168
+ for(const job of jobs) {
169
+ if(input.kind!=='try')continue;
170
+ try { ownerCheck();await ports.request({method:'DELETE',path:`/v1/try/${encodeURIComponent(job)}`,body:undefined}); } catch {}
171
+ }
172
+ try { await request('POST',`/v1/local-commands/registrations/${encodeURIComponent(registered.registration_id)}/revoke`,{}); } catch {}
173
+ await heartbeat;
174
+ await servicePromise?.catch(()=>{});
175
+ await Promise.all([...active].filter(v=>v instanceof Promise));
176
+ })();
177
+ return {resource_setup,connect,service,close};
178
+ }
@@ -0,0 +1,181 @@
1
+ // Generated from prompts/cli/live-local.prompt.md (sha256: c9d09e7fb36a2a2c9ca7c7fc289fa26027783c6b4b0164dd5cae51ffb88073a2).
2
+ // Owned by prompts/cli/live-local.prompt.md.
3
+ const manifestError = () => fail('live-local-manifest-invalid');
4
+ function fail(code) { throw Object.assign(new Error(code), {code}); }
5
+ const object = v => v !== null && typeof v === 'object' && !Array.isArray(v) && [Object.prototype,null].includes(Object.getPrototypeOf(v));
6
+ function shape(v, required, optional = []) { return object(v) && required.every(k => Object.hasOwn(v,k)) && Object.keys(v).every(k => [...required,...optional].includes(k)); }
7
+ const text = (v, max = 512) => typeof v === 'string' && v.length > 0 && v.length <= max && !/[\u0000\uD800-\uDFFF]/u.test(v);
8
+ const bytes = v => Buffer.byteLength(v,'utf8');
9
+ const string = v => typeof v === 'string' && !/\0|[\uD800-\uDFFF]/u.test(v);
10
+ const integer = (v,min,max) => Number.isSafeInteger(v) && v >= min && v <= max;
11
+ const envName = v => typeof v === 'string' && /^[A-Z][A-Z0-9_]{0,127}$/.test(v);
12
+ const unique = values => new Set(values).size === values.length;
13
+ const cwdSafe = v => text(v,4096) && !v.startsWith('/') && !v.includes('\\') && v.split('/').every(x=>x && x !== '..');
14
+ const forbidden = /^(?:sh|bash|dash|zsh|fish|cmd|powershell|pwsh|node|nodejs|python[0-9.]*|perl|ruby|php|lua|deno|bun|eval|exec|env|printenv|sudo|doas|xargs)(?:\.exe)?$/i;
15
+ const commandKeys = ['binding_id','resource','operation','executable','argv','parameters','stdin','cwd','environment','timeout_ms','stdout_limit_bytes','stderr_limit_bytes'];
16
+ const requestKeys = ['schema_version','request_id','run_id','action_id','attempt_id','call_id','graph_id','edge_id','resource','operation','binding_id','access','argv','stdin','cwd','environment','timeout_ms','stdout_limit_bytes','stderr_limit_bytes'];
17
+ const outcomeKeys = ['stdout','stderr','exit_code','timed_out','stdout_truncated','stderr_truncated'];
18
+
19
+ // JSON.parse alone silently accepts duplicate keys. Scan every object first.
20
+ export function parseLocalJson(raw, code = 'live-local-policy-refused') {
21
+ if (typeof raw !== 'string' || raw.length > 2097152) fail(code);
22
+ let i = 0;
23
+ const ws = () => { while (/\s/.test(raw[i] ?? '') && i < raw.length) i++; };
24
+ const str = () => { const start=i++; while (i<raw.length) { if(raw[i]==='\\') { i+=2;continue; } if(raw[i++]==='"')return JSON.parse(raw.slice(start,i)); } throw Error(); };
25
+ const value = () => {
26
+ ws();
27
+ if(raw[i]==='{') { i++;ws();const seen=new Set(); if(raw[i]==='}') { i++;return; } for(;;) { ws();if(raw[i]!=='"')throw Error();const key=str();if(seen.has(key))throw Error();seen.add(key);ws();if(raw[i++]!==':')throw Error();value();ws();const c=raw[i++];if(c==='}')return;if(c!==',')throw Error(); } }
28
+ if(raw[i]==='[') { i++;ws();if(raw[i]===']'){i++;return;}for(;;){value();ws();const c=raw[i++];if(c===']')return;if(c!==',')throw Error();} }
29
+ if(raw[i]==='"'){str();return;}const m=/^(?:true|false|null|-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)/.exec(raw.slice(i));if(!m)throw Error();i+=m[0].length;
30
+ };
31
+ try { value();ws();if(i!==raw.length)throw Error();return JSON.parse(raw); } catch { fail(code); }
32
+ }
33
+ function limits(c) { return integer(c.timeout_ms,1,120000) && integer(c.stdout_limit_bytes,0,65536) && integer(c.stderr_limit_bytes,0,65536); }
34
+ function parameter(p) {
35
+ if(!shape(p,['name','type'],['enum','pattern','maxLength','minimum','maximum']) || !text(p.name) || !['string','integer','boolean'].includes(p.type))return false;
36
+ const valid = v => p.type==='integer' ? Number.isSafeInteger(v) : typeof v===p.type && (p.type!=='string'||string(v));
37
+ if(p.enum!==undefined && (!Array.isArray(p.enum)||!p.enum.length||!p.enum.every(valid)||!unique(p.enum)))return false;
38
+ if(p.type==='string') {
39
+ if(p.minimum!==undefined||p.maximum!==undefined||p.enum===undefined&&p.pattern===undefined&&p.maxLength===undefined)return false;
40
+ if(p.maxLength!==undefined&&!integer(p.maxLength,0,8192))return false;
41
+ if(p.pattern!==undefined) { if(typeof p.pattern!=='string'||p.pattern.length>512)return false;try { new RegExp(p.pattern,'u'); } catch{return false;} }
42
+ } else if(p.pattern!==undefined||p.maxLength!==undefined)return false;
43
+ if(p.type!=='integer'&&(p.minimum!==undefined||p.maximum!==undefined))return false;
44
+ if(p.minimum!==undefined&&!Number.isSafeInteger(p.minimum)||p.maximum!==undefined&&!Number.isSafeInteger(p.maximum)||p.minimum!==undefined&&p.maximum!==undefined&&p.minimum>p.maximum)return false;
45
+ return true;
46
+ }
47
+ function credentialDump(c) {
48
+ const args=c.argv.map(v=>v.literal ?? '').join(' ').toLowerCase();
49
+ return /^(?:cat|head|tail|less|more|strings|base64|xxd|od)(?:\.exe)?$/i.test(c.executable) && /(?:credentials?|tokens?|secrets?|\.ssh|\.aws|hosts\.yml|\.env|config\/gh)/i.test(args)
50
+ || /^gh(?:\.exe)?$/i.test(c.executable)&&/^(?:auth (?:token|status.*--show-token)|api.*(?:authorizations|applications\/.*token))/.test(args)
51
+ || /^git(?:\.exe)?$/i.test(c.executable)&&/(?:^|\s)credential(?:-[a-z-]+)?\s+(?:fill|get)(?:\s|$)|(?:^|\s)config\s+.*(?:credential|token|password|secret|extraheader)/.test(args)
52
+ || /^aws(?:\.exe)?$/i.test(c.executable)&&/(?:^|\s)configure\s+(?:export-credentials|get)(?:\s|$)/.test(args)
53
+ || /^gcloud(?:\.exe)?$/i.test(c.executable)&&/(?:^|\s)auth\s+(?:application-default\s+)?print-(?:access-token|identity-token)(?:\s|$)/.test(args)
54
+ || /^kubectl(?:\.exe)?$/i.test(c.executable)&&/(?:^|\s)config\s+view(?:\s|$)/.test(args)&&args.includes('--raw')
55
+ || /(?:^|\s)(?:--show-token|--show-secrets|--print-credentials)(?:\s|$)/.test(args);
56
+ }
57
+ export function validateLocalManifest(m) {
58
+ if(!shape(m,['schema_version','selection','commands'])||m.schema_version!=='pdd.live-local-manifest.v1'||!shape(m.selection,['schema_version','resources'])||m.selection.schema_version!=='prompt-runtime.resource-selection.v2'||!Array.isArray(m.selection.resources)||m.selection.resources.length>128||!Array.isArray(m.commands)||!m.commands.length||m.commands.length>512)manifestError();
59
+ const names=new Set(), identities=new Set(), pairs=new Set();
60
+ for(const r of m.selection.resources) {
61
+ if(!shape(r,['resource','mode','location','binding_id'])||!text(r.resource)||!text(r.binding_id)||names.has(r.resource)||!(['fake:simulation','real:local'].includes(`${r.mode}:${r.location}`)))manifestError();names.add(r.resource);
62
+ }
63
+ for(const c of m.commands) {
64
+ if(!shape(c,commandKeys,['access'])||!['binding_id','resource','operation'].every(k=>text(c[k]))||!['read','write'].includes(c.access??'read')||typeof c.executable!=='string'||!(/^[A-Za-z0-9][A-Za-z0-9_.+-]{0,127}$/).test(c.executable)||forbidden.test(c.executable)||!limits(c)||!cwdSafe(c.cwd)||!shape(c.stdin,['literal'])||!string(c.stdin.literal)||bytes(c.stdin.literal)>131072||!Array.isArray(c.environment)||c.environment.length>64||!c.environment.every(envName)||!unique(c.environment)||!Array.isArray(c.parameters)||c.parameters.length>127||!c.parameters.every(parameter)||!unique(c.parameters.map(p=>p.name))||!Array.isArray(c.argv)||c.argv.length>127)manifestError();
65
+ const selected=m.selection.resources.find(r=>r.resource===c.resource);
66
+ if(!selected||selected.mode!=='real'||selected.location!=='local'||selected.binding_id!==c.binding_id)manifestError();
67
+ const id=JSON.stringify([c.binding_id,c.resource,c.operation]), pair=JSON.stringify([c.resource,c.operation]);
68
+ if(identities.has(id)||pairs.has(pair))manifestError();identities.add(id);pairs.add(pair);
69
+ const used=[];
70
+ for(const a of c.argv) {
71
+ if(shape(a,['literal'])) { if(!string(a.literal)||bytes(a.literal)>8192)manifestError(); }
72
+ else if(shape(a,['argument'])&&c.parameters.some(p=>p.name===a.argument))used.push(a.argument);
73
+ else manifestError();
74
+ }
75
+ if(!unique(used)||used.length!==c.parameters.length||credentialDump(c))manifestError();
76
+ }
77
+ if(m.selection.resources.some(r=>r.mode==='real'&&!m.commands.some(c=>c.resource===r.resource)))manifestError();
78
+ return m;
79
+ }
80
+ export function compileLocalManifest(config, options = {}) {
81
+ if(!object(config))manifestError();
82
+ if(config.schema_version==='pdd.live-local-manifest.v1')return validateLocalManifest(config);
83
+ if(!shape(config,['commands'],['schema_version','simulated_resources'])||(config.schema_version!==undefined&&config.schema_version!=='pdd.local-commands.v1')||!object(config.commands)||!Object.keys(config.commands).length)manifestError();
84
+ const simInput=[...(config.simulated_resources??[]),...(options?.simulatedResources??[])];
85
+ if(config.simulated_resources!==undefined&&!Array.isArray(config.simulated_resources)||!simInput.every(v=>text(v)))manifestError();
86
+ const bindingsByResource=new Map(), commands=[];
87
+ for(const [qualified,spec] of Object.entries(config.commands)) {
88
+ const dot=qualified.indexOf('.');
89
+ if(dot<=0||dot===qualified.length-1)manifestError();
90
+ const resource=qualified.slice(0,dot), operation=qualified.slice(dot+1);
91
+ const entry=Array.isArray(spec)?{cmd:spec}:spec;
92
+ if(!object(entry)||!Object.keys(entry).every(k=>['cmd','argv','access','binding_id','cwd','env','environment','stdin','timeout_ms','stdout_limit_bytes','stderr_limit_bytes','params'].includes(k)))manifestError();
93
+ const tokens=entry.cmd??entry.argv;
94
+ if(!Array.isArray(tokens)||!tokens.length||!tokens.every(string))manifestError();
95
+ const executable=tokens[0];
96
+ if(executable.includes('{')||executable.includes('}'))manifestError();
97
+ if(!bindingsByResource.has(resource))bindingsByResource.set(resource,undefined);
98
+ if(entry.binding_id!==undefined) {
99
+ if(!text(entry.binding_id))manifestError();
100
+ const existing=bindingsByResource.get(resource);
101
+ if(existing!==undefined&&existing!==entry.binding_id)manifestError();
102
+ bindingsByResource.set(resource,entry.binding_id);
103
+ }
104
+ const paramOverrides=entry.params??{};
105
+ if(!object(paramOverrides))manifestError();
106
+ const argv=[], paramNames=[];
107
+ for(const token of tokens.slice(1)) {
108
+ const m=/^\{([A-Za-z_][A-Za-z0-9_-]{0,127})\}$/.exec(token);
109
+ if(m) { argv.push({argument:m[1]});paramNames.push(m[1]); }
110
+ else if(token.includes('{')||token.includes('}'))manifestError();
111
+ else argv.push({literal:token});
112
+ }
113
+ if(Object.keys(paramOverrides).some(k=>!paramNames.includes(k)))manifestError();
114
+ const parameters=paramNames.map(name=>{
115
+ const raw=paramOverrides[name];
116
+ if(raw!==undefined&&!object(raw))manifestError();
117
+ const base={name,type:'string',...(raw??{})};
118
+ if(base.type==='string'&&base.enum===undefined&&base.pattern===undefined&&base.maxLength===undefined)base.maxLength=512;
119
+ return base;
120
+ });
121
+ const envList=entry.environment??entry.env??[];
122
+ const stdinVal=typeof entry.stdin==='string'?{literal:entry.stdin}:(entry.stdin??{literal:''});
123
+ commands.push({
124
+ binding_id:'',resource,operation,access:entry.access??'read',executable,argv,parameters,
125
+ stdin:stdinVal,cwd:entry.cwd??'.',environment:envList,
126
+ timeout_ms:entry.timeout_ms??30000,
127
+ stdout_limit_bytes:entry.stdout_limit_bytes??16384,
128
+ stderr_limit_bytes:entry.stderr_limit_bytes??16384,
129
+ });
130
+ }
131
+ for(const [resource,explicit] of bindingsByResource)bindingsByResource.set(resource,explicit??`local-${resource}`);
132
+ for(const command of commands)command.binding_id=bindingsByResource.get(command.resource);
133
+ const resources=[...bindingsByResource.entries()].map(([resource,binding_id])=>({resource,mode:'real',location:'local',binding_id}));
134
+ for(const sim of [...new Set(simInput)]) {
135
+ if(!bindingsByResource.has(sim))resources.push({resource:sim,mode:'fake',location:'simulation',binding_id:`sim-${sim}`});
136
+ }
137
+ return validateLocalManifest({schema_version:'pdd.live-local-manifest.v1',selection:{schema_version:'prompt-runtime.resource-selection.v2',resources},commands});
138
+ }
139
+ function matchesParameter(p,v) {
140
+ let value=v;
141
+ if(p.type==='integer') { if(!/^-?(?:0|[1-9][0-9]*)$/.test(v))return false;value=Number(v);if(!Number.isSafeInteger(value)||String(value)!==v)return false; }
142
+ else if(p.type==='boolean') { if(!['true','false'].includes(v))return false;value=v==='true'; }
143
+ else if(!string(v)||v.startsWith('-')||v.includes('\\')||v.split('/').includes('..')||v.startsWith('/'))return false;
144
+ return (p.enum===undefined||p.enum.includes(value)) && (p.pattern===undefined||new RegExp(p.pattern,'u').test(value)) && (p.maxLength===undefined||value.length<=p.maxLength) && (p.minimum===undefined||value>=p.minimum) && (p.maximum===undefined||value<=p.maximum);
145
+ }
146
+ export function validateLocalRequest(manifest,r) {
147
+ validateLocalManifest(manifest);
148
+ if(!shape(r,requestKeys)||r.schema_version!=='prompt-runtime.local-command-request.v1'||!['request_id','run_id','action_id','attempt_id','call_id','graph_id','edge_id','resource','operation','binding_id'].every(k=>text(r[k]))||!['read','write'].includes(r.access)||!Array.isArray(r.argv)||!r.argv.length||r.argv.length>128||!r.argv.every(v=>string(v)&&bytes(v)<=8192)||r.argv.reduce((n,v)=>n+bytes(v),0)>65536||!string(r.stdin)||bytes(r.stdin)>131072||!cwdSafe(r.cwd)||!Array.isArray(r.environment)||r.environment.length>64||!r.environment.every(envName)||!unique(r.environment)||!limits(r))fail('live-local-policy-refused');
149
+ const c=manifest.commands.find(c=>c.binding_id===r.binding_id&&c.resource===r.resource&&c.operation===r.operation);
150
+ if(!c||r.access!==(c.access??'read')||r.argv[0]!==c.executable||r.argv.length!==c.argv.length+1||r.stdin!==c.stdin.literal||r.cwd!==c.cwd||JSON.stringify(r.environment)!==JSON.stringify(c.environment)||['timeout_ms','stdout_limit_bytes','stderr_limit_bytes'].some(k=>r[k]!==c[k]))fail('live-local-policy-refused');
151
+ for(let i=0;i<c.argv.length;i++) { const a=c.argv[i];if(a.literal!==undefined?r.argv[i+1]!==a.literal:!matchesParameter(c.parameters.find(p=>p.name===a.argument),r.argv[i+1]))fail('live-local-policy-refused'); }
152
+ return r;
153
+ }
154
+ function port(ports,group,name) { const fn=ports?.[group]?.[name];if(typeof fn!=='function')throw Object.assign(new Error(`Live-local port ${group}.${name} is not bound.`),{unboundPort:true});return fn.bind(ports[group]); }
155
+ export function truncateLocalText(value,limit) { const encoded=Buffer.from(value,'utf8');if(encoded.length<=limit)return {text:value,truncated:false};let end=limit;while(end>0&&(encoded[end]&0xc0)===0x80)end--;return {text:encoded.subarray(0,end).toString('utf8'),truncated:true}; }
156
+ export async function executeLocalCommand(input,ports={}) {
157
+ if(input?.mode==='simulated')return {status:'simulated',private_report:false,receipt:null,outcome:null};
158
+ if(!shape(input,['mode','manifest_json','request_json','allow_writes','terminal'])||input.mode!=='live-local'||typeof input.allow_writes!=='boolean'||typeof input.terminal!=='boolean')fail('live-local-policy-refused');
159
+ const manifest=validateLocalManifest(parseLocalJson(input.manifest_json,'live-local-manifest-invalid'));
160
+ const request=validateLocalRequest(manifest,parseLocalJson(input.request_json));
161
+ const run=port(ports,'runner','execute'),redact=port(ports,'redaction','redact'),reply=port(ports,'delivery','reply');
162
+ if(request.access==='write') {
163
+ if(!input.allow_writes||!input.terminal)fail('live-local-write-denied');
164
+ const confirmation=await port(ports,'consent','confirm')({binding_id:request.binding_id,executable:request.argv[0],argv:request.argv});
165
+ if(!shape(confirmation,['confirmed'])||confirmation.confirmed!==true)fail('live-local-write-denied');
166
+ }
167
+ let outcome;
168
+ try { outcome=await run({request_json:JSON.stringify(request)}); } catch(error) { if(error?.unboundPort)throw error;fail('live-local-outcome-unknown'); }
169
+ if(!shape(outcome,outcomeKeys)||!string(outcome.stdout)||!string(outcome.stderr)||typeof outcome.timed_out!=='boolean'||!['stdout_truncated','stderr_truncated'].every(k=>typeof outcome[k]==='boolean')||!(outcome.timed_out?outcome.exit_code===null:integer(outcome.exit_code,-2147483648,2147483647))||bytes(outcome.stdout)>1048576||bytes(outcome.stderr)>1048576)fail('live-local-outcome-unknown');
170
+ outcome={...outcome};
171
+ try {
172
+ for(const stream of ['stdout','stderr']) {
173
+ const safe=await redact({text:outcome[stream]});if(!shape(safe,['text'])||!string(safe.text))throw Error();
174
+ const cut=truncateLocalText(safe.text,request[`${stream}_limit_bytes`]);outcome[stream]=cut.text;outcome[`${stream}_truncated`] ||= cut.truncated;
175
+ }
176
+ } catch { fail('live-local-redaction-failed'); }
177
+ const status=outcome.timed_out?'timed_out':'completed';
178
+ const result={request_id:request.request_id,attempt_id:request.attempt_id,call_id:request.call_id,status,outcome};
179
+ try { const accepted=await reply({result_json:JSON.stringify(result)});if(!shape(accepted,['accepted'])||accepted.accepted!==true)throw Error(); } catch { fail('live-local-outcome-unknown'); }
180
+ return {status,private_report:true,receipt:{request_id:request.request_id,call_id:request.call_id,status},outcome};
181
+ }