@promptdriven/runtime-client 1.0.0 → 1.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/runtime/agent-chat.mjs +55 -8
- package/src/runtime/index.mjs +41 -1
- package/src/runtime/live-local-bridge.mjs +178 -0
- package/src/runtime/live-local.mjs +181 -0
- package/src/runtime/run-program.mjs +798 -0
- package/src/runtime/runtime-bindings.mjs +28 -18
- package/src/runtime/runtime-check-plan.mjs +19 -27
- package/src/runtime/runtime-check-reconcile.mjs +328 -0
- package/src/runtime/runtime-client.mjs +2797 -345
- package/src/runtime/runtime-outcome.mjs +66 -2
- package/src/runtime/runtime-output.mjs +202 -15
- package/src/runtime/runtime-preflight.mjs +994 -87
- package/src/runtime/runtime-slots.mjs +75 -4
- package/src/runtime/runtime-stream.mjs +125 -0
- package/src/runtime/scenario-json.mjs +167 -1
- package/src/runtime/secret-redaction.mjs +3 -2
- package/src/runtime/try-doors.mjs +426 -59
- package/src/runtime/try-http.mjs +49 -15
- package/src/runtime/try-update-policy.mjs +43 -0
package/package.json
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import {loadRuntimeWorkspace} from './runtime-workspace.mjs';
|
|
2
2
|
import {captureSource} from './runtime-preflight.mjs';
|
|
3
|
-
// Generated from prompts/cli/agent-chat.prompt.md (sha256:
|
|
3
|
+
// Generated from prompts/cli/agent-chat.prompt.md (sha256: 5c30e8797dcab312c52f5b1b9b3b83e78b937d01ee8202a30a4aaad0b833285d).
|
|
4
4
|
import {createTryGuide} from './agent-guide.mjs';
|
|
5
5
|
import {askAgent} from './agent-ask.mjs';
|
|
6
|
+
import {advanceTryUpdates} from './try-update-policy.mjs';
|
|
7
|
+
import {tryRetryDelay,withRepositoryRunLock} from './runtime-client.mjs';
|
|
6
8
|
import {cleanText} from './runtime-output.mjs';
|
|
7
9
|
const object=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
|
|
8
10
|
const unboundPortError=message=>Object.assign(new Error(message),{unboundPort:true});
|
|
@@ -48,11 +50,14 @@ export async function createAgentBridge(context,test,tryId,options={},link,seamP
|
|
|
48
50
|
let agents=definitions.map(d=>{const found=discovered.find(a=>a.id===d.id);return{id:d.id,name:d.name,state:found?.state??'error',...(typeof found?.detail==='string'?{detail:found.detail}:{})};});
|
|
49
51
|
let choice=(explicit??byChoice(store.repo(root).agent_choice))?.id;
|
|
50
52
|
if(!known(choice)||(!explicit&&agents.find(a=>a.id===choice)?.state==='not_installed'))choice=agents.find(ready)?.id??agents.find(a=>a.state!=='not_installed')?.id??definitions[0].id;
|
|
51
|
-
const remember=id=>{if(!known(id))return;choice=id;const name=definitions.find(d=>d.id===id).name,
|
|
53
|
+
const remember=async id=>{if(!known(id))return;choice=id;const name=definitions.find(d=>d.id===id).name;if(typeof store.updateRepo==='function')await store.updateRepo(root,current=>current.agent_choice===name?undefined:{...current,agent_choice:name});else{const current=store.repo(root);if(current.agent_choice!==name)store.saveRepo(root,{...current,agent_choice:name});}};
|
|
52
54
|
const connected=await runtime.send(`${prefix}/agent/connect`,json({bridge_id,agents,selected:choice,features:FEATURES}),30000);
|
|
53
55
|
if(connected.status===404){write(context,'This interpreter does not support Ask your agent yet. The ordinary Try link remains available.');return null;}
|
|
54
56
|
if(!good(connected)||connected.json.bridge_id!==bridge_id||connected.json.connected!==true||!/^[A-Za-z0-9_-]{43,128}$/.test(connected.json.browser_key??''))throw Error(`Could not connect your agent to this Try (${why(connected)}). Run pdd simulate again.`);
|
|
55
|
-
|
|
57
|
+
const watchMs=Number.isSafeInteger(ports.watchMs)&&ports.watchMs>0?ports.watchMs:5000;
|
|
58
|
+
let policy=advanceTryUpdates({state:null,event:{kind:'connect',advertised:Object.hasOwn(connected.json,'update_revisions'),revisions:connected.json.update_revisions??null},now:ports.now(),watchMs});
|
|
59
|
+
if(policy.error){try{await (context.agentFinalSend??runtime.send.bind(runtime))(`${prefix}/agent/disconnect`,json({bridge_id}),5000);}catch{}throw Error('The server sent invalid-update-revisions. Reconnect with pdd simulate.');}
|
|
60
|
+
await remember(choice);
|
|
56
61
|
const features=Array.isArray(connected.json.features)?connected.json.features.slice(0,32).filter(x=>FEATURES.includes(x)):[];
|
|
57
62
|
const secretName=/token|password|secret|api[_-]?key|authorization|cookie|credential/i;
|
|
58
63
|
const secrets=[...(context.secrets??[]),...Object.entries(ports.env??{}).filter(([k,v])=>secretName.test(k)&&typeof v==='string'&&v).map(([,v])=>v),...definitions.flatMap(d=>Object.entries(d.env??{}).filter(([k,v])=>secretName.test(k)&&typeof v==='string'&&v).map(([,v])=>v))];
|
|
@@ -60,9 +65,11 @@ export async function createAgentBridge(context,test,tryId,options={},link,seamP
|
|
|
60
65
|
const onSaved=record=>guide.saved(record);context.onAgentCaseSaved=onSaved;
|
|
61
66
|
const ownerUrl=new URL(link);ownerUrl.hash=`agent=${connected.json.browser_key}`;
|
|
62
67
|
let closed=false,task=null,tickTask=null,failed=false,unboundError=null;const seen=new Set(),controller=new AbortController();
|
|
63
|
-
|
|
68
|
+
let structured=false,wakeCollection=()=>{};
|
|
69
|
+
const advance=event=>(policy=advanceTryUpdates({state:policy.state,event,now:ports.now(),watchMs}));
|
|
70
|
+
const stop=()=>{controller.abort();wakeCollection();};context.signal?.addEventListener('abort',stop,{once:true});
|
|
64
71
|
if(context.signal?.aborted)stop();
|
|
65
|
-
async function close(){if(closed)return;closed=true;stop();guide.close();if(context.onAgentCaseSaved===onSaved)delete context.onAgentCaseSaved;context.onAgentChatClose?.();context.signal?.removeEventListener('abort',stop);
|
|
72
|
+
async function close(){if(closed)return;closed=true;advance({kind:'end'});stop();guide.close();if(context.onAgentCaseSaved===onSaved)delete context.onAgentCaseSaved;context.onAgentChatClose?.();context.signal?.removeEventListener('abort',stop);
|
|
66
73
|
try{await (context.agentFinalSend??runtime.send.bind(runtime))(`${prefix}/agent/disconnect`,json({bridge_id}),5000);}catch{}
|
|
67
74
|
}
|
|
68
75
|
async function answer(message){
|
|
@@ -80,13 +87,53 @@ export async function createAgentBridge(context,test,tryId,options={},link,seamP
|
|
|
80
87
|
if(!good(reply)||reply.json.ok!==true){failed=true;write(context,'Your agent reply could not be delivered. It will not be run again. Reconnect with pdd simulate.');stop();}
|
|
81
88
|
else guide.delivered(message,decorated);
|
|
82
89
|
}
|
|
90
|
+
async function collect(onTick){
|
|
91
|
+
try {
|
|
92
|
+
while(!closed&&!controller.signal.aborted&&!context.interrupted){
|
|
93
|
+
const plan=advance({kind:'plan'});
|
|
94
|
+
if(plan.read.length||plan.postApprovals){
|
|
95
|
+
const result=await onTick({read:plan.read,targets:Object.fromEntries(plan.read.map(key=>[key,plan.state[key].target])),postApprovals:plan.postApprovals,signal:controller.signal});
|
|
96
|
+
if(controller.signal.aborted)break;
|
|
97
|
+
if(result===false){stop();break;}
|
|
98
|
+
if(object(result)&&object(result.categories)){
|
|
99
|
+
structured=true;
|
|
100
|
+
for(const category of plan.read){const completion=result.categories[category]??{outcome:'retry',retryMs:5000};advance({kind:'complete',category,...completion});}
|
|
101
|
+
if(result.delivery)advance({kind:'delivery',...result.delivery});
|
|
102
|
+
}else{
|
|
103
|
+
// Existing Boolean callbacks have no category acknowledgement contract.
|
|
104
|
+
structured=false;policy.state={...policy.state,mode:'legacy'};
|
|
105
|
+
for(const category of plan.read)advance({kind:'complete',category,outcome:'success',retryMs:0});
|
|
106
|
+
}
|
|
107
|
+
if(policy.state.mode==='ended'){stop();break;}
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
const deadlines=[];
|
|
111
|
+
for(const key of ['tests','approvals']){const item=policy.state[key];if(!item.missing&&item.target===null&&(policy.state.mode==='legacy'||item.desired>item.acknowledged))deadlines.push(Math.max(item.retryAt,policy.state.mode==='legacy'?item.nextAt:0));}
|
|
112
|
+
if(policy.state.deliveryPending&&!policy.state.deliveryInFlight)deadlines.push(policy.state.deliveryRetryAt);
|
|
113
|
+
let wake;const changed=new Promise(resolve=>{wake=resolve;wakeCollection=resolve;});
|
|
114
|
+
const delay=new AbortController(),abort=()=>delay.abort();controller.signal.addEventListener('abort',abort,{once:true});
|
|
115
|
+
try{if(controller.signal.aborted)break;if(deadlines.length)await Promise.race([changed,ports.sleep(Math.max(0,Math.min(...deadlines)-ports.now()),delay.signal)]);else await changed;}
|
|
116
|
+
finally{delay.abort();controller.signal.removeEventListener('abort',abort);if(wakeCollection===wake)wakeCollection=()=>{};}
|
|
117
|
+
}
|
|
118
|
+
}catch(err){if(controller.signal.aborted)return;if(err?.unboundPort)unboundError=err;else{failed=true;write(context,`Saved Try updates could not be read (${err?.message??'collection failed'}). Reconnect with pdd simulate.`);}stop();}
|
|
119
|
+
}
|
|
83
120
|
async function run(onTick){
|
|
84
121
|
write(context,`Ask your agent is connected (${agents.find(a=>a.id===choice)?.name??choice}). Keep this window open for Ask your agent; Ctrl-C disconnects the chat and keeps the Try open.`);
|
|
122
|
+
if(onTick)tickTask=collect(onTick);
|
|
85
123
|
try{while(!closed&&!controller.signal.aborted&&!context.interrupted){
|
|
86
|
-
const before=ports.now();const
|
|
124
|
+
const before=ports.now();const params=new URLSearchParams({bridge_id});
|
|
125
|
+
if(onTick&&structured&&policy.pollRevisions)for(const category of ['tests','approvals'])if(policy.pollRevisions[category]!==null)params.set(`${category}_revision`,String(policy.pollRevisions[category]));
|
|
126
|
+
const poll=await runtime.send(`${prefix}/agent/poll?${params}`,{method:'GET',signal:controller.signal},25000);
|
|
87
127
|
if(controller.signal.aborted||context.interrupted)break;
|
|
128
|
+
if(poll.status===429){await ports.sleep(tryRetryDelay(poll),controller.signal);continue;}
|
|
88
129
|
if(!good(poll)||poll.json.connected!==true){failed=true;write(context,'Your agent connection ended. Run pdd simulate again to reconnect.');break;}
|
|
89
|
-
|
|
130
|
+
const legacyCallback=policy.state.mode==='legacy'&&Object.hasOwn(connected.json,'update_revisions');
|
|
131
|
+
if(legacyCallback)policy.state={...policy.state,mode:'notifications'};
|
|
132
|
+
const notice=advance({kind:'notice',revisions:poll.json.update_revisions??null});
|
|
133
|
+
if(notice.error){failed=true;write(context,'The server sent invalid-update-revisions. Reconnect with pdd simulate.');break;}
|
|
134
|
+
if(legacyCallback)policy={...policy,state:{...policy.state,mode:'legacy'},pollRevisions:null};
|
|
135
|
+
wakeCollection();
|
|
136
|
+
await remember(poll.json.selected);
|
|
90
137
|
const message=poll.json.message;
|
|
91
138
|
if(message!==null&&message!==undefined){
|
|
92
139
|
if(!object(message)||typeof message.id!=='string'||message.id.length>128||typeof message.text!=='string'||message.text.length>8000||!known(message.agent)||(message.kind!==undefined&&!['chat','run','walk','own'].includes(message.kind))){failed=true;write(context,'The server sent an invalid agent message. Reconnect with pdd simulate.');break;}
|
|
@@ -95,7 +142,7 @@ export async function createAgentBridge(context,test,tryId,options={},link,seamP
|
|
|
95
142
|
seen.add(message.id);task=answer(message).catch(()=>{failed=true;write(context,'Your agent could not finish this message. It will not be run again.');stop();}).finally(()=>{task=null;});
|
|
96
143
|
}
|
|
97
144
|
}
|
|
98
|
-
|
|
145
|
+
|
|
99
146
|
if(ports.now()-before<1000)await ports.sleep(1000,controller.signal);
|
|
100
147
|
}}finally{await close();await task;await tickTask;}
|
|
101
148
|
if(unboundError)throw unboundError;
|
package/src/runtime/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Generated from prompts/cli/runtime-entry.prompt.md (sha256:
|
|
1
|
+
// Generated from prompts/cli/runtime-entry.prompt.md (sha256: 4dfc22f130b60bcad7f0d180c951547c6d50efd298ef310434f12dc1f974a010).
|
|
2
2
|
import { createRequire } from 'node:module';
|
|
3
3
|
import { isDeepStrictEqual } from 'node:util';
|
|
4
4
|
|
|
@@ -529,6 +529,21 @@ export async function runCheck(input, ports) {
|
|
|
529
529
|
return run(input, ports);
|
|
530
530
|
}
|
|
531
531
|
|
|
532
|
+
export async function runProgram(input = {}, ports) {
|
|
533
|
+
const { runProgram: execute } = await import('./run-program.mjs');
|
|
534
|
+
return execute(input, ports);
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
export async function run(input = {}, ports) {
|
|
538
|
+
return runProgram(input, ports);
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
let programModule;
|
|
542
|
+
function programPolicy() { return programModule ??= req('./run-program.mjs'); }
|
|
543
|
+
export function prepareProgramInvocation(input) { return programPolicy().prepareProgramInvocation(input); }
|
|
544
|
+
export function planProgramSession(input) { return programPolicy().planProgramSession(input); }
|
|
545
|
+
export function planProgramCase(input) { return programPolicy().planProgramCase(input); }
|
|
546
|
+
|
|
532
547
|
export async function runTry(input, ports) {
|
|
533
548
|
const { runTry: run } = await import('./runtime-client.mjs');
|
|
534
549
|
return run(input, ports);
|
|
@@ -549,6 +564,15 @@ export async function observeTryCall(input, ports) {
|
|
|
549
564
|
return observe(input, ports);
|
|
550
565
|
}
|
|
551
566
|
|
|
567
|
+
let checkReconcileModule;
|
|
568
|
+
function checkReconcileSlice() { return checkReconcileModule ??= req('./runtime-check-reconcile.mjs'); }
|
|
569
|
+
export function projectCheckReconciliation(input) { return checkReconcileSlice().projectCheckReconciliation(input); }
|
|
570
|
+
|
|
571
|
+
export async function reconcileCheckReceipt(input, ports) {
|
|
572
|
+
const { reconcileCheckReceipt: reconcile } = await import('./runtime-client.mjs');
|
|
573
|
+
return reconcile(input, ports);
|
|
574
|
+
}
|
|
575
|
+
|
|
552
576
|
export async function askAgent(input, ports) {
|
|
553
577
|
const { askAgent: ask } = await import('./agent-ask.mjs');
|
|
554
578
|
return ask(input, ports);
|
|
@@ -941,3 +965,19 @@ export function estimateCheckCalls(...args) {
|
|
|
941
965
|
export function evaluateCheckBudget(...args) {
|
|
942
966
|
return runtimeCheckPlanSlice().evaluateCheckBudget(...args);
|
|
943
967
|
}
|
|
968
|
+
|
|
969
|
+
export async function executeLocalCommand(input, ports) {
|
|
970
|
+
return (await import('./live-local.mjs')).executeLocalCommand(input, ports);
|
|
971
|
+
}
|
|
972
|
+
export function validateLocalManifest(manifest) {
|
|
973
|
+
return req('./live-local.mjs').validateLocalManifest(manifest);
|
|
974
|
+
}
|
|
975
|
+
export function compileLocalManifest(config, options) {
|
|
976
|
+
return req('./live-local.mjs').compileLocalManifest(config, options);
|
|
977
|
+
}
|
|
978
|
+
export function validateLocalRequest(manifest, request) {
|
|
979
|
+
return req('./live-local.mjs').validateLocalRequest(manifest, request);
|
|
980
|
+
}
|
|
981
|
+
export async function createLocalCommandBridge(input, ports) {
|
|
982
|
+
return (await import('./live-local-bridge.mjs')).createLocalCommandBridge(input, ports);
|
|
983
|
+
}
|
|
@@ -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
|
+
}
|