@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
package/LICENSE
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
Copyright 2025 Prompt Driven, Inc.
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
4
|
+
|
|
5
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
6
|
+
|
|
7
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,43 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @promptdriven/runtime-client
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`@promptdriven/runtime-client` is the standalone JavaScript client package for the PDD Runtime service. It powers prompt checking, linting, interactive simulation, shared contract checks, and MCP tools for the [PDD CLI](https://github.com/promptdriven/pdd) and other Node.js hosts.
|
|
4
|
+
|
|
5
|
+
## Requirements
|
|
6
|
+
|
|
7
|
+
- Node.js `>=22.16.0`
|
|
8
|
+
- Zero runtime npm dependencies (pure Node.js built-ins)
|
|
9
|
+
|
|
10
|
+
## Installation
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm install @promptdriven/runtime-client
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Package Exports
|
|
17
|
+
|
|
18
|
+
- Root entry (`@promptdriven/runtime-client` -> `./src/index.mjs`):
|
|
19
|
+
- **Commands:** `check`, `lint`, `read`, `retry`, `local`, `simulate`, `jobs`, `health`, `mcp`, `contracts`
|
|
20
|
+
- **Readers & Utilities:** `format`, `source`, `saved`, `workspace`, `render`, `exactValue`, `causeText`, `cleanText`, `observeTryCall`, `failedCheckCount`, `providerText`, `evaluateCheckBudget`, `estimateCheckCalls`, `parsePromptFrontmatter`, `promptMarkdownTargets`, `version`
|
|
21
|
+
- **Scoped Slice Loaders:** `runtimeAgentPacketSlice`, `runtimeCheckPlanSlice`, `runtimeClientSlice`, `runtimeOutcomeSlice`, `runtimeOutputSlice`, `runtimePreflightSlice`, `runtimeScenarioJsonSlice`, `runtimeWorkspaceSlice`
|
|
22
|
+
- Subpath exports (`@promptdriven/runtime-client/*` -> `./src/runtime/*`):
|
|
23
|
+
- All 31 Runtime client modules (`./*` -> `./src/runtime/*`) are exported directly as subpaths.
|
|
24
|
+
|
|
25
|
+
## Host `ports` Contract
|
|
26
|
+
|
|
27
|
+
`@promptdriven/runtime-client` imports zero files outside `src/runtime/`. Host applications pass environment streams and host-specific capabilities through `input` and `ports`:
|
|
28
|
+
|
|
29
|
+
- **Streams & Environment:** `stdout`, `stderr`, `env`, `fetch`, `gh`, `now`, `sleep`
|
|
30
|
+
- **Caller Metadata:** `client.version`, `client.commands` (`{ test, lint, simulate }`), `workflow.base_sha`
|
|
31
|
+
- **Selection & Exit Codes:** `isStoryPath`, `hasAcceptance`, `expectedTestPath`, `matchTests`, `orphanSummary`, `selectTests`, `whyNoTests`, `exitFor`, `exitCodeFor`
|
|
32
|
+
- **Secret Redaction:** `redaction` (`{ remember, redact, known }`)
|
|
33
|
+
- **Host Extensions (when applicable):**
|
|
34
|
+
- Ownership & hygiene: `headerPrompts`, `isTestOwnedPath`, `promptClaims`, `resolveOwners`
|
|
35
|
+
- Workflow & native evidence: `evidenceEligibility`, `allRuns`, `workflowBaseSha`, `assessNativeEvidence`, `usableResult`, `resultLines`
|
|
36
|
+
- Interactive simulation & approvals: `loadAgentDefinitions`, `discoverAgents`, `runAgentProcess`, `askAgent`, `lineReader`, `askApproval`, `approvePromptText`, `readApprovalPolicy`, `readPromptApprovals`, `recordPromptApproval`
|
|
37
|
+
- Visual & product checks: `lintSvgLayouts`, `compareScreen`, `formatScreenComparison`, `parseProductDocuments`, `parseProductWorldWriters`
|
|
38
|
+
|
|
39
|
+
## Environment Variables & Local State
|
|
40
|
+
|
|
41
|
+
- `PDD_RUNTIME_URL`: Runtime server origin (defaults to `DEFAULT_RUNTIME_URL` in `src/runtime/runtime-client.mjs`).
|
|
42
|
+
- `PDD_STATE_DIR`: Local state directory for batches, active slots, and cached login metadata.
|
|
43
|
+
- `.pdd/cache/test/`: Per-repository Story check cache (`stories.json` and `lastfailed.json`).
|
package/package.json
CHANGED
|
@@ -1,6 +1,30 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@promptdriven/runtime-client",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "PDD Runtime Client (@promptdriven/runtime-client)",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.mjs",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./src/index.mjs",
|
|
9
|
+
"./*": "./src/runtime/*"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"src",
|
|
13
|
+
"!src/runtime-seam.mjs"
|
|
14
|
+
],
|
|
15
|
+
"publishConfig": {
|
|
16
|
+
"access": "public"
|
|
17
|
+
},
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "https://github.com/promptdriven/runtime-client.git"
|
|
21
|
+
},
|
|
22
|
+
"scripts": {
|
|
23
|
+
"test": "node --import ./test/helpers/test-home.mjs --test test/runtime-package/*.test.mjs"
|
|
24
|
+
},
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=22.16.0"
|
|
27
|
+
},
|
|
28
|
+
"homepage": "https://github.com/promptdriven/pdd",
|
|
29
|
+
"license": "MIT"
|
|
30
|
+
}
|
package/src/index.mjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './runtime/index.mjs';
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// Generated from prompts/cli/agent-ask.prompt.md (sha256: 69f7563df2b19a37af55ce4af2778710044fc1477906a8a93e054ec24094bd14).
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { mkdtempSync, writeFileSync, readFileSync, readSync, readdirSync, rmSync, chmodSync, mkdirSync, lstatSync, openSync, fstatSync, closeSync, fchmodSync, statSync, constants } from 'node:fs';
|
|
4
|
+
import { homedir, tmpdir } from 'node:os';
|
|
5
|
+
import { join, dirname } from 'node:path';
|
|
6
|
+
import { loadRuntimeWorkspace } from './runtime-workspace.mjs';
|
|
7
|
+
import { buildAgentInput } from './agent-packet.mjs';
|
|
8
|
+
import { checkInput } from './runtime-preflight.mjs';
|
|
9
|
+
const AGENTS = [['codex','Codex'],['claude','Claude'],['gemini','Gemini']];
|
|
10
|
+
const SECRET = /token|password|secret|api[_-]?key|authorization|cookie|credential/i;
|
|
11
|
+
const object = x => x !== null && typeof x === 'object' && !Array.isArray(x);
|
|
12
|
+
const fail = (state, message) => ({say:message,fill:null,error:{state,message}});
|
|
13
|
+
const unboundPortError = message => Object.assign(new Error(message), { unboundPort: true });
|
|
14
|
+
const MESSAGES = {signed_out:'This agent is signed out. Sign in at your terminal, or choose another agent.',quota:'This agent has reached its usage limit. Choose another agent or try later.',not_installed:'This agent is not installed. Choose another agent.'};
|
|
15
|
+
function stateOf(text) { return /rate.?limit|usage.?limit|quota|credits|capacity/i.test(text)?'quota':/not logged|not signed|sign.?in|login required|unauthorized|authentication/i.test(text)?'signed_out':'error'; }
|
|
16
|
+
function scrub(value,env) {
|
|
17
|
+
const values=Object.entries(env).filter(([k,v])=>SECRET.test(k)&&typeof v==='string'&&v.length>0).map(([,v])=>v);
|
|
18
|
+
const clean=x=>{
|
|
19
|
+
if(typeof x==='string'){for(const v of values)x=x.split(v).join('[redacted]');return x.replace(/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g,'[redacted]').replace(/\b(?:gh[pousr]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]{12,})\b/g,'[redacted]').replace(/Bearer\s+\S+/gi,'Bearer [redacted]').replace(/\b(token|password|secret|api[_-]?key|authorization|cookie|credential)["']?\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;]+)/gi,'$1=[redacted]').replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gi,'$1[redacted]@');}
|
|
20
|
+
if(Array.isArray(x))return x.map(clean);
|
|
21
|
+
if(object(x))return Object.fromEntries(Object.entries(x).map(([k,v])=>[k,SECRET.test(k)?'[redacted]':clean(v)]));
|
|
22
|
+
return x;
|
|
23
|
+
};return clean(value);
|
|
24
|
+
}
|
|
25
|
+
function diagnostic(text,env) {
|
|
26
|
+
return scrub(String(text??''),env).replace(/\x1b\[[0-?]*[ -/]*[@-~]/g,'').replace(/[\x00-\x08\x0b-\x1f\x7f]/g,'');
|
|
27
|
+
}
|
|
28
|
+
function logDiagnostic(agent,text,env) {
|
|
29
|
+
if(!env.HOME)return null;
|
|
30
|
+
const folder=join(env.HOME,'.pdd','runtime'),file=join(folder,'agent-chat.log');let fd;
|
|
31
|
+
try{
|
|
32
|
+
for(const dir of [join(env.HOME,'.pdd'),folder]){try{mkdirSync(dir,{mode:0o700});}catch(e){if(e.code!=='EEXIST')throw e;}const st=lstatSync(dir);if(!st.isDirectory()||st.isSymbolicLink())throw Error('Unsafe log directory');}
|
|
33
|
+
fd=openSync(file,constants.O_WRONLY|constants.O_APPEND|constants.O_CREAT|constants.O_NOFOLLOW|constants.O_NONBLOCK,0o600);if(!fstatSync(fd).isFile())throw Error('Unsafe log');fchmodSync(fd,0o600);
|
|
34
|
+
writeFileSync(fd,`[${new Date().toISOString()}] ${agent}\n${diagnostic(text,env)}\n`);return file;
|
|
35
|
+
}catch{return null;}finally{if(fd!==undefined)closeSync(fd);}
|
|
36
|
+
}
|
|
37
|
+
function failedInvocation(agent,text,env,state=stateOf(text),name=AGENTS.find(([id])=>id===agent)?.[1]??'Agent') {
|
|
38
|
+
const line=diagnostic(text,env).split(/\r?\n/).map(x=>x.trim()).find(Boolean)?.slice(0,500)||'The CLI exited without an error message.';
|
|
39
|
+
const log=logDiagnostic(name,text,env),prefix=state==='error'?`${name} could not start`:MESSAGES[state];
|
|
40
|
+
return fail(state,`${prefix}${state==='error'?': ': ' '}${line}. ${log?`Details: ${log}`:'Local diagnostic log unavailable.'}`);
|
|
41
|
+
}
|
|
42
|
+
function unknownFeature(answer,args) {
|
|
43
|
+
if(stateOf(answer.stderr+' '+answer.stdout)!=='error')return null;
|
|
44
|
+
const text=answer.stderr||answer.stdout;
|
|
45
|
+
const first=text.split(/\r?\n/).map(x=>x.trim()).find(Boolean)??'';
|
|
46
|
+
if(answer.stdout?.trim()||! /^(?:error loading config|configuration error|error:\s*(?:unknown|unrecognized|unsupported)\s+feature)/i.test(first))return null;
|
|
47
|
+
const match=text.match(/(?:unknown|unrecognized|unsupported)\s+feature(?:\s+(?:flag|key))?\s*[:=]?\s*[`"']?(?:features\.)?([a-z][a-z0-9_]*)/i);
|
|
48
|
+
const flag=match&&`features.${match[1]}=false`;
|
|
49
|
+
return flag&&args.includes(flag)?flag:null;
|
|
50
|
+
}
|
|
51
|
+
function geminiCapabilityError(help) {
|
|
52
|
+
if(help.code!==0)return 'Gemini Try read-only capability discovery failed (--help).';
|
|
53
|
+
const missing=['--approval-mode','--admin-policy','--extensions','--allowed-mcp-server-names','--output-format'].find(flag=>!help.stdout.includes(flag));
|
|
54
|
+
return missing?`Gemini Try read-only mode requires ${missing}; update Gemini CLI.`:null;
|
|
55
|
+
}
|
|
56
|
+
function claudeCapabilities(help) {
|
|
57
|
+
if(!help||help.code!==0||typeof help.stdout!=='string')return {mode:null,excludeDynamic:false};
|
|
58
|
+
const text=help.stdout;
|
|
59
|
+
const mode=/(?:^|\s)--system-prompt(?:-file|\[-file\])(?:\s|<|=|,|\.|$)/m.test(text)?'file':/(?:^|\s)--system-prompt(?:\s|<|=|$)/m.test(text)?'arg':null;
|
|
60
|
+
return {mode,excludeDynamic:/(?:^|\s)--exclude-dynamic-system-prompt-sections(?:\s|$)/m.test(text)};
|
|
61
|
+
}
|
|
62
|
+
function splitClaudeInput(input) {
|
|
63
|
+
const marker='\n\nDATA\n',index=input.indexOf(marker),header=input.slice(0,index),data=JSON.parse(input.slice(index+marker.length));
|
|
64
|
+
const staticData={productRules:data.productRules,ways:data.ways,project:data.project,criteria:data.criteria};
|
|
65
|
+
const turnData={conversation:data.conversation,coverage:data.coverage,progress:data.progress,try:data.try,message:data.message,changed:data.changed};
|
|
66
|
+
return {systemPrompt:`${header}\nDATA\n${JSON.stringify(staticData)}`,turnInput:JSON.stringify(turnData)};
|
|
67
|
+
}
|
|
68
|
+
function claudeSystemPromptFile(text) {
|
|
69
|
+
const folder=mkdtempSync(join(tmpdir(),'pdd-agent-claude-'));chmodSync(folder,0o700);
|
|
70
|
+
try{const file=join(folder,'system-prompt.txt');writeFileSync(file,text,{mode:0o600});return {file,cleanup:()=>rmSync(folder,{recursive:true,force:true})};}catch(e){rmSync(folder,{recursive:true,force:true});throw e;}
|
|
71
|
+
}
|
|
72
|
+
function parseJsonc(text) {
|
|
73
|
+
const src=text.charCodeAt(0)===0xfeff?text.slice(1):text;let out='',inStr=false;
|
|
74
|
+
for(let i=0;i<src.length;i++){
|
|
75
|
+
const ch=src[i];
|
|
76
|
+
if(inStr){out+=ch;if(ch==='\\'&&i+1<src.length)out+=src[++i];else if(ch==='"')inStr=false;}
|
|
77
|
+
else if(ch==='"'){inStr=true;out+=ch;}
|
|
78
|
+
else if(ch==='/'&&src[i+1]==='/'){i+=2;while(i<src.length&&src[i]!=='\n'&&src[i]!=='\r')i++;i--;}
|
|
79
|
+
else if(ch==='/'&&src[i+1]==='*'){const end=src.indexOf('*/',i+2);if(end===-1)throw new SyntaxError('Unterminated comment');i=end+1;}
|
|
80
|
+
else out+=ch;
|
|
81
|
+
}
|
|
82
|
+
let clean='';inStr=false;
|
|
83
|
+
for(let i=0;i<out.length;i++){
|
|
84
|
+
const ch=out[i];
|
|
85
|
+
if(inStr){clean+=ch;if(ch==='\\'&&i+1<out.length)clean+=out[++i];else if(ch==='"')inStr=false;}
|
|
86
|
+
else if(ch==='"'){inStr=true;clean+=ch;}
|
|
87
|
+
else if(ch===','){let j=i+1;while(j<out.length&&(out[j]===' '||out[j]==='\t'||out[j]==='\n'||out[j]==='\r'))j++;if(out[j]!=='}'&&out[j]!==']')clean+=ch;}
|
|
88
|
+
else clean+=ch;
|
|
89
|
+
}
|
|
90
|
+
return JSON.parse(clean);
|
|
91
|
+
}
|
|
92
|
+
function geminiMcpSentinel(cwd,env,existing,defaultsPath) {
|
|
93
|
+
const configured=new Set(object(existing?.mcpServers)?Object.keys(existing.mcpServers):[]),failed=existing?.mcpServers!==undefined&&!object(existing.mcpServers)?[Buffer.from('system:mcpServers')]:[];
|
|
94
|
+
const effectiveCwd=cwd??process.cwd(),home=env.HOME||homedir(),files=[...new Set([defaultsPath,...(env.GEMINI_CLI_HOME?[join(env.GEMINI_CLI_HOME,'settings.json'),join(env.GEMINI_CLI_HOME,'.gemini','settings.json')]:[]),home?join(home,'.gemini','settings.json'):null,effectiveCwd?join(effectiveCwd,'.gemini','settings.json'):null].filter(Boolean))];
|
|
95
|
+
for(const file of files){
|
|
96
|
+
try{lstatSync(file);}catch(e){if(e.code==='ENOENT'||e.code==='ENOTDIR')continue;failed.push(Buffer.from(`${file}:${e.code||e.message}`));continue;}
|
|
97
|
+
let fd,raw=null;
|
|
98
|
+
try{
|
|
99
|
+
const st=statSync(file);if(!st.isFile()||st.size>1048576)throw new Error('invalid_target');
|
|
100
|
+
fd=openSync(file,'r');const fst=fstatSync(fd);if(!fst.isFile()||fst.size>1048576)throw new Error('invalid_target');
|
|
101
|
+
const buf=Buffer.alloc(fst.size+1);let n=0;while(n<buf.length){const got=readSync(fd,buf,n,buf.length-n,n);if(!got)break;n+=got;}
|
|
102
|
+
if(n>1048576)throw new Error('too_large');raw=buf.subarray(0,n);
|
|
103
|
+
const doc=parseJsonc(raw.toString('utf8'));if(!object(doc)||(doc.mcpServers!==undefined&&!object(doc.mcpServers)))throw new Error('invalid_json');
|
|
104
|
+
if(doc.mcpServers)for(const key of Object.keys(doc.mcpServers))configured.add(key);
|
|
105
|
+
}catch(e){
|
|
106
|
+
failed.push(raw??Buffer.from(`${file}:${e.code||e.message}`));
|
|
107
|
+
if(raw)for(const [tok] of raw.toString('utf8').matchAll(/pdd-disabled-[0-9A-Za-z_-]*/g))configured.add(tok);
|
|
108
|
+
}finally{if(fd!==undefined)try{closeSync(fd);}catch{}}
|
|
109
|
+
}
|
|
110
|
+
if(!failed.length&&!configured.has('pdd-disabled-none'))return 'pdd-disabled-none';
|
|
111
|
+
let salt=0,sentinel;
|
|
112
|
+
do{const h=createHash('sha256');h.update([...configured].sort().join('\0')+'\0');for(const chunk of failed){h.update(chunk);h.update('\0');}h.update(String(salt++));sentinel=`pdd-disabled-${h.digest('hex').slice(0,16)}`;}while(configured.has(sentinel)||failed.some(b=>b.includes(sentinel)));
|
|
113
|
+
return sentinel;
|
|
114
|
+
}
|
|
115
|
+
function geminiOverlay(env,cwd) {
|
|
116
|
+
const systemDir=process.platform==='darwin'?'/Library/Application Support/GeminiCli':process.platform==='win32'?'C:\\ProgramData\\gemini-cli':'/etc/gemini-cli';
|
|
117
|
+
try{if(readdirSync(join(systemDir,'policies')).some(name=>name.endsWith('.toml')))throw new Error('Gemini system policy prevents the private deny-all policy.');}catch(e){if(e.code!=='ENOENT')throw e;}
|
|
118
|
+
const original=env.GEMINI_CLI_SYSTEM_SETTINGS_PATH||join(systemDir,'settings.json'),defaultsPath=env.GEMINI_CLI_SYSTEM_DEFAULTS_PATH||join(dirname(original),'system-defaults.json');let existing={};
|
|
119
|
+
try{const bytes=readFileSync(original);if(bytes.length>1048576)throw new Error('Settings too large');existing=parseJsonc(bytes.toString('utf8'));if(!object(existing))throw new Error('Invalid settings');}catch(e){if(e.code!=='ENOENT')throw e;}
|
|
120
|
+
const mcpSentinel=geminiMcpSentinel(cwd,env,existing,defaultsPath);
|
|
121
|
+
const config={...existing,tools:{...existing.tools,core:[],allowed:[],discoveryCommand:'',callCommand:''},hooksConfig:{...existing.hooksConfig,enabled:false},admin:{...existing.admin,mcp:{...existing.admin?.mcp,enabled:false},extensions:{...existing.admin?.extensions,enabled:false},skills:{...existing.admin?.skills,enabled:false}},general:{...existing.general,enableAutoUpdate:false,enableAutoUpdateNotification:false,plan:{...existing.general?.plan,enabled:false,modelRouting:false}}};
|
|
122
|
+
const folder=mkdtempSync(join(tmpdir(),'pdd-agent-gemini-'));chmodSync(folder,0o700);
|
|
123
|
+
try{const settings=join(folder,'settings.json'),policy=join(folder,'deny.toml');writeFileSync(settings,JSON.stringify(config),{mode:0o600});writeFileSync(policy,'[[rule]]\ntoolName = "*"\ndecision = "deny"\npriority = 999\n',{mode:0o600});return {env:{...env,GEMINI_CLI_SYSTEM_SETTINGS_PATH:settings,GEMINI_CLI_SYSTEM_DEFAULTS_PATH:defaultsPath},policy,mcpSentinel,cleanup:()=>rmSync(folder,{recursive:true,force:true})};}catch(e){rmSync(folder,{recursive:true,force:true});throw e;}
|
|
124
|
+
}
|
|
125
|
+
function references(x){return Array.isArray(x)?x.some(references):object(x)&&(Object.hasOwn(x,'$step_result')||Object.values(x).some(references));}
|
|
126
|
+
function validFill(fill,entries){
|
|
127
|
+
if(fill===null)return true;
|
|
128
|
+
if(!object(fill)||Object.keys(fill).sort().join(',')!=='entry,input'||!object(fill.input)||references(fill.input))return false;
|
|
129
|
+
const entry=entries.find(e=>e.entry===fill.entry);if(!entry)return false;
|
|
130
|
+
const result=checkInput(fill.input,entry.input_schema,0);return !result.refusals.length&&!result.warnings.length;
|
|
131
|
+
}
|
|
132
|
+
export async function askAgent({agent,definition,cwd,env=process.env,context={},entries=[],supportsApply=false,supportsRun=false,workspace,signal,run,timeoutMs=120000}={}, ports={}) {
|
|
133
|
+
if((workspace??(cwd?loadRuntimeWorkspace({root:cwd}):null))?.configured)return fail('error','Bounded agent connection is unavailable: native tool and automatic context controls cannot establish packet-only context.');
|
|
134
|
+
const command=definition?.command??agent,name=definition?.name??AGENTS.find(([id])=>id===agent)?.[1];
|
|
135
|
+
agent=definition?.kind??agent;env={...env,...definition?.env};
|
|
136
|
+
if(!AGENTS.some(([id])=>id===agent))return fail('error','Choose Codex, Claude or Gemini.');
|
|
137
|
+
if(signal?.aborted)return fail('error','The agent request was cancelled.');
|
|
138
|
+
const runPort=run??ports.run??ports.runAgentProcess??ports.agents?.run;
|
|
139
|
+
if(typeof runPort!=='function')throw unboundPortError('Agent process port (run / agents.run) is not bound.');
|
|
140
|
+
try{
|
|
141
|
+
const safe=scrub({context,entries},env);
|
|
142
|
+
const input=buildAgentInput({context:safe.context,entries:safe.entries,supportsApply,supportsRun});
|
|
143
|
+
const opts={cwd,env,input,signal,timeoutMs,maxBytes:131072};
|
|
144
|
+
let args,overlay,claudePrompt,answer;
|
|
145
|
+
try{
|
|
146
|
+
if(agent==='gemini'){const detail=geminiCapabilityError(await runPort(command,['--help'],{cwd,env,signal,timeoutMs:10000,maxBytes:131072}));if(detail)return fail('error',detail);overlay=geminiOverlay(env,cwd);opts.env=overlay.env;}
|
|
147
|
+
if(agent==='codex'){
|
|
148
|
+
args=['exec','--sandbox','read-only','--ephemeral','--color','never','--ignore-rules','-c','approval_policy="never"','-c','web_search="disabled"','-c','mcp_servers={}'];
|
|
149
|
+
for(const feature of ['hooks','plugins','apps','browser_use','browser_use_external','browser_use_full_cdp_access','computer_use','multi_agent','multi_agent_v2','shell_tool','unified_exec','code_mode','code_mode_host'])args.push('-c',`features.${feature}=false`);
|
|
150
|
+
args.push('-');
|
|
151
|
+
}else if(agent==='gemini')args=['--extensions','none','--allowed-mcp-server-names',overlay.mcpSentinel,'-p','Answer the supplied Try question as strict JSON.','--approval-mode','default','--admin-policy',overlay.policy,'--output-format','json'];
|
|
152
|
+
else{
|
|
153
|
+
const caps=claudeCapabilities(await runPort(command,['--help'],{cwd,env,signal,timeoutMs:10000,maxBytes:131072}));
|
|
154
|
+
args=['-p','--safe-mode','--tools','Read,Grep,Glob','--permission-mode','plan','--permission-prompts','none','--strict-mcp-config','--no-chrome','--no-session-persistence'];
|
|
155
|
+
if(caps.excludeDynamic)args.push('--exclude-dynamic-system-prompt-sections');
|
|
156
|
+
if(caps.mode){const split=splitClaudeInput(input);opts.input=split.turnInput;if(caps.mode==='file'){claudePrompt=claudeSystemPromptFile(split.systemPrompt);args.push('--system-prompt-file',claudePrompt.file);}else args.push('--system-prompt',split.systemPrompt);}
|
|
157
|
+
args.push('--output-format','json');
|
|
158
|
+
}
|
|
159
|
+
answer=await runPort(command,args,opts);
|
|
160
|
+
if(agent==='codex'&&answer.code!==0){const flag=unknownFeature(answer,args);if(flag){logDiagnostic(name,answer.stderr||answer.stdout,env);const index=args.indexOf(flag);args.splice(index-1,2);answer=await runPort(command,args,opts);}}
|
|
161
|
+
}finally{overlay?.cleanup();claudePrompt?.cleanup();}
|
|
162
|
+
if(answer.code!==0)return failedInvocation(agent,answer.stderr||answer.stdout,env,stateOf(answer.stdout+' '+answer.stderr),name);
|
|
163
|
+
let parsed=JSON.parse(answer.stdout);
|
|
164
|
+
// Claude's JSON transport wraps the textual final answer; it is not the chat schema.
|
|
165
|
+
if(agent==='claude'&&object(parsed)&&typeof parsed.result==='string'){
|
|
166
|
+
if(parsed.is_error)return failedInvocation(agent,parsed.result,env,stateOf(parsed.result),name);parsed=JSON.parse(parsed.result);
|
|
167
|
+
}
|
|
168
|
+
if(agent==='gemini'&&object(parsed)&&typeof parsed.response==='string')parsed=JSON.parse(parsed.response);
|
|
169
|
+
if(!object(parsed)||Object.keys(parsed).some(key=>!['say','fill','apply','criterion','expect','save','next','run'].includes(key))||typeof parsed.say!=='string'||!parsed.say.trim())return fail('error','The agent returned an invalid answer. No fields were applied.');
|
|
170
|
+
const clean=scrub(parsed,env),result={say:clean.say,fill:null};
|
|
171
|
+
const fillValid=validFill(clean.fill??null,entries);
|
|
172
|
+
if(fillValid)result.fill=clean.fill??null;
|
|
173
|
+
if(typeof clean.apply==='boolean'&&fillValid&&(result.fill!==null||!clean.apply))result.apply=clean.apply;
|
|
174
|
+
if(typeof clean.run==='boolean'&&supportsRun&&supportsApply&&['chat','own','walk'].includes(context.requestKind??'chat')&&(!clean.run||(result.apply===true&&result.fill!==null)))result.run=clean.run;
|
|
175
|
+
const known=new Set((Array.isArray(context.criteria)?context.criteria:[]).map(c=>c.id));
|
|
176
|
+
if(clean.criterion===null||known.has(clean.criterion))result.criterion=clean.criterion;
|
|
177
|
+
if(clean.next===null)result.next=null;
|
|
178
|
+
else if(object(clean.next)&&Object.keys(clean.next).sort().join(',')==='criterion,text'&&typeof clean.next.text==='string'&&clean.next.text.trim()&&clean.next.text.length<=200&&(clean.next.criterion===null||known.has(clean.next.criterion)))result.next=clean.next;
|
|
179
|
+
const pointer=path=>typeof path==='string'&&path.length<=256&&(path===''||(path.startsWith('/')&&!/~(?:[^01]|$)/.test(path)));
|
|
180
|
+
const checks=(list,expected)=>Array.isArray(list)&&list.length>0&&list.length<=32&&list.every(c=>object(c)&&Object.keys(c).sort().join(',')===(expected?'path,target,value':'path,target')&&['result','world'].includes(c.target)&&pointer(c.path)&&(!expected||!references(c.value)));
|
|
181
|
+
if(clean.expect===null)result.expect=null;
|
|
182
|
+
else if(result.fill&&object(clean.expect)&&Object.keys(clean.expect).sort().join(',')==='checks,text'&&typeof clean.expect.text==='string'&&clean.expect.text.trim()&&clean.expect.text.length<=500&&checks(clean.expect.checks,true)&&Buffer.byteLength(JSON.stringify(clean.expect))<=16384)result.expect=clean.expect;
|
|
183
|
+
if(clean.save===null)result.save=null;
|
|
184
|
+
else if(object(clean.save)&&Object.keys(clean.save).sort().join(',')==='checks,criterion,name'&&typeof clean.save.name==='string'&&clean.save.name.trim()&&clean.save.name.length<=100&&(clean.save.criterion===null||known.has(clean.save.criterion))&&checks(clean.save.checks,false))result.save=clean.save;
|
|
185
|
+
return result;
|
|
186
|
+
}catch(e){if(e?.unboundPort)throw e;if(e instanceof SyntaxError)return fail('error','The agent returned invalid JSON. No fields were applied.');const state=e.code==='ENOENT'?'not_installed':'error';return failedInvocation(agent,e.stderr||e.message,env,state,name);}
|
|
187
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import {loadRuntimeWorkspace} from './runtime-workspace.mjs';
|
|
2
|
+
import {captureSource} from './runtime-preflight.mjs';
|
|
3
|
+
// Generated from prompts/cli/agent-chat.prompt.md (sha256: 88ccfc9a9fca1ffaae42fc354f414d00ae2934babe472ecd09c8d4325b1060ec).
|
|
4
|
+
import {createTryGuide} from './agent-guide.mjs';
|
|
5
|
+
import {askAgent} from './agent-ask.mjs';
|
|
6
|
+
import {cleanText} from './runtime-output.mjs';
|
|
7
|
+
const object=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
|
|
8
|
+
const unboundPortError=message=>Object.assign(new Error(message),{unboundPort:true});
|
|
9
|
+
const FEATURES=['apply','progress','run_events','expect','save','run'];
|
|
10
|
+
const ready=a=>['ready','available'].includes(a?.state);
|
|
11
|
+
const write=(context,text)=>context.ports.stderr.write(`${cleanText(text,context.secrets)}\n`);
|
|
12
|
+
const json=body=>({method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});
|
|
13
|
+
const good=reply=>reply?.status>=200&&reply.status<300&&object(reply.json);
|
|
14
|
+
// Why a relay request failed, for the terminal: the network cause, else the server's message, else the HTTP status.
|
|
15
|
+
const why=reply=>reply?.unreachable??cleanText(reply?.json?.error?.message??reply?.why??(reply?.status?`HTTP ${reply.status}`:'no answer'));
|
|
16
|
+
function scrub(value,secrets){
|
|
17
|
+
if(typeof value==='string'){for(const secret of secrets??[])if(secret)value=value.split(secret).join('[redacted]');return value.replace(/\b(?:gh[pousr]_[A-Za-z0-9_]+|github_pat_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]{12,})\b/g,'[redacted]').replace(/Bearer\s+\S+/gi,'Bearer [redacted]');}
|
|
18
|
+
if(Array.isArray(value))return value.map(v=>scrub(v,secrets));
|
|
19
|
+
if(object(value))return Object.fromEntries(Object.entries(value).map(([k,v])=>[k,/token|password|secret|api[_-]?key|authorization|cookie|credential/i.test(k)?'[redacted]':scrub(v,secrets)]));
|
|
20
|
+
return value;
|
|
21
|
+
}
|
|
22
|
+
export async function createAgentBridge(context,test,tryId,options={},link,seamPorts={}){
|
|
23
|
+
const mergeDefined=(base={},override={})=>{const out={...base};for(const [k,v] of Object.entries(override??{}))if(v!==undefined)out[k]=v;return out;};
|
|
24
|
+
const mergedPorts=mergeDefined(seamPorts,context.ports);
|
|
25
|
+
const workspace=loadRuntimeWorkspace({root:context.root});
|
|
26
|
+
if(workspace.configured){(mergedPorts.captureSource??((r,o)=>captureSource(r,o,mergedPorts)))(context.root,{tests:[test.path]});throw Error('Bounded agent connection is unavailable: native controls cannot establish packet-only context.');}
|
|
27
|
+
const guideBase=mergeDefined(seamPorts.guidePorts,context.ports?.guidePorts);
|
|
28
|
+
const ports={...mergedPorts,guidePorts:mergeDefined({redaction:context.ports?.redaction??seamPorts.redaction,redactSecrets:context.ports?.redactSecrets??seamPorts.redactSecrets,evidenceEligibility:context.ports?.evidenceEligibility??context.ports?.readEvidenceEligibility??seamPorts.evidenceEligibility??seamPorts.readEvidenceEligibility,isStoryPath:mergedPorts.isStoryPath,hasAcceptance:mergedPorts.hasAcceptance,matchTests:mergedPorts.matchTests,orphanSummary:mergedPorts.orphanSummary,captureSource:mergedPorts.captureSource,readAgentScenarios:mergedPorts.readAgentScenarios},guideBase)};
|
|
29
|
+
const loadDefinitions=context.ports?.loadAgentDefinitions??context.ports?.agents?.loadDefinitions??seamPorts.loadAgentDefinitions??seamPorts.agents?.loadDefinitions;
|
|
30
|
+
if(!context.agentDefinitions&&typeof loadDefinitions!=='function')throw unboundPortError('Agent configuration port (loadAgentDefinitions) is not bound.');
|
|
31
|
+
const definitions=context.agentDefinitions??loadDefinitions({cwd:context.root,env:ports.env});
|
|
32
|
+
if(!definitions.length)throw Error('No agents are configured. Add an agent or enable defaults in agents.json.');
|
|
33
|
+
const discover=context.ports?.discoverAgents??context.ports?.agents?.list??seamPorts.discoverAgents??seamPorts.agents?.list;
|
|
34
|
+
const runPort=context.ports?.runAgentProcess??context.ports?.agents?.run??seamPorts.runAgentProcess??seamPorts.agents?.run;
|
|
35
|
+
const ask=context.ports?.askAgent??context.ports?.agents?.ask??seamPorts.askAgent??seamPorts.agents?.ask??(typeof runPort==='function'?input=>askAgent(input,{run:runPort}):undefined);
|
|
36
|
+
if(typeof discover!=='function'||typeof ask!=='function')throw unboundPortError('Agent adapter ports (discoverAgents, askAgent) are not bound.');
|
|
37
|
+
const known=id=>definitions.some(d=>d.id===id),byChoice=value=>definitions.find(d=>d.name===value)??definitions.find(d=>['codex','claude','gemini'].includes(d.id)&&d.id===value);
|
|
38
|
+
const explicit=options['--agent']!==undefined?byChoice(options['--agent']):null;
|
|
39
|
+
if(options['--agent']!==undefined&&!explicit)throw Error('Unknown agent name. Choose a name from agents.json or an enabled default.');
|
|
40
|
+
const {root,store,runtime}=context,prefix=`/v1/try/${tryId}`,bridge_id=ports.randomUUID();
|
|
41
|
+
write(context,'Connecting your agent to the Try page…');
|
|
42
|
+
const modelReply=await runtime.send(`${prefix}/model`,{method:'GET'},30000);
|
|
43
|
+
if(modelReply.status===404){write(context,'This interpreter does not support Ask your agent yet. The ordinary Try link remains available.');return null;}
|
|
44
|
+
if(!good(modelReply)||!Array.isArray(modelReply.json.entries))throw Error(`Could not read the owner’s Try model for agent chat (${why(modelReply)}). Run pdd simulate again.`);
|
|
45
|
+
const model=modelReply.json,entries=model.entries.filter(e=>typeof e.entry_path==='string'&&typeof e.operation==='string'&&object(e.input_schema))
|
|
46
|
+
.map(e=>({entry:`${e.entry_path}#${e.operation}`,prompt_path:e.entry_path,operation:e.operation,input_schema:e.input_schema,...Object.fromEntries(['label','name','cli','http'].filter(k=>Object.hasOwn(e,k)).map(k=>[k,e[k]]))}));
|
|
47
|
+
const discovered=await discover({cwd:root,env:ports.env,definitions});
|
|
48
|
+
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
|
+
let choice=(explicit??byChoice(store.repo(root).agent_choice))?.id;
|
|
50
|
+
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,saved=store.repo(root);if(saved.agent_choice!==name)store.saveRepo(root,{...saved,agent_choice:name});};
|
|
52
|
+
const connected=await runtime.send(`${prefix}/agent/connect`,json({bridge_id,agents,selected:choice,features:FEATURES}),30000);
|
|
53
|
+
if(connected.status===404){write(context,'This interpreter does not support Ask your agent yet. The ordinary Try link remains available.');return null;}
|
|
54
|
+
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
|
+
remember(choice);
|
|
56
|
+
const features=Array.isArray(connected.json.features)?connected.json.features.slice(0,32).filter(x=>FEATURES.includes(x)):[];
|
|
57
|
+
const secretName=/token|password|secret|api[_-]?key|authorization|cookie|credential/i;
|
|
58
|
+
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))];
|
|
59
|
+
const guide=createTryGuide({root,env:ports.env,model,test,features,secrets,ports:ports.guidePorts});
|
|
60
|
+
const onSaved=record=>guide.saved(record);context.onAgentCaseSaved=onSaved;
|
|
61
|
+
const ownerUrl=new URL(link);ownerUrl.hash=`agent=${connected.json.browser_key}`;
|
|
62
|
+
let closed=false,task=null,tickTask=null,failed=false,unboundError=null;const seen=new Set(),controller=new AbortController();
|
|
63
|
+
const stop=()=>controller.abort();context.signal?.addEventListener('abort',stop,{once:true});
|
|
64
|
+
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);
|
|
66
|
+
try{await (context.agentFinalSend??runtime.send.bind(runtime))(`${prefix}/agent/disconnect`,json({bridge_id}),5000);}catch{}
|
|
67
|
+
}
|
|
68
|
+
async function answer(message){
|
|
69
|
+
const agent=agents.find(a=>a.id===message.agent),name=agent?.name??'Your agent',turn=guide.prepare(message);let result,asked=false;
|
|
70
|
+
if(turn.fast)result=turn.fast;
|
|
71
|
+
else if(!ready(agent))result={say:agent?.state==='signed_out'?`${agent.name} is signed out. Sign in at your terminal, or switch to another agent.`:agent?.state==='quota'?`${agent.name} has reached its usage limit. Switch to another agent.`:`${agent?.name??'This agent'} is not available. Choose an installed agent.`,fill:null};
|
|
72
|
+
else {asked=true;write(context,`${name} is answering a question from the Try page…`);result=await ask({agent:agent.id,definition:definitions.find(d=>d.id===agent.id),cwd:root,env:ports.env,entries,signal:controller.signal,supportsApply:features.includes('apply'),supportsRun:features.includes('run'),context:turn.context});}
|
|
73
|
+
if(controller.signal.aborted)return;
|
|
74
|
+
if(turn.fast)write(context,'PDD checked the run against the local test cases.');
|
|
75
|
+
else write(context,result.error||!ready(agent)?`${name} could not answer: ${result.error?.message??result.say}`:`${name} answered.${result.fill?' It proposed input for the form.':''}`);
|
|
76
|
+
if(result.error)agents=agents.map(a=>a.id===message.agent?{...a,state:result.error.state,detail:result.error.message}:a);
|
|
77
|
+
else if(asked&&agent)agents=agents.map(a=>a.id===message.agent?{...a,state:'ready',detail:undefined}:a);
|
|
78
|
+
const decorated=guide.decorate(result),safe=guide.wire(decorated);
|
|
79
|
+
const reply=await runtime.send(`${prefix}/agent/reply`,json({bridge_id,message_id:message.id,...safe,agents:scrub(agents,secrets)}),30000);
|
|
80
|
+
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
|
+
else guide.delivered(message,decorated);
|
|
82
|
+
}
|
|
83
|
+
async function run(onTick){
|
|
84
|
+
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.`);
|
|
85
|
+
try{while(!closed&&!controller.signal.aborted&&!context.interrupted){
|
|
86
|
+
const before=ports.now();const poll=await runtime.send(`${prefix}/agent/poll?bridge_id=${bridge_id}`,{method:'GET'},25000);
|
|
87
|
+
if(controller.signal.aborted||context.interrupted)break;
|
|
88
|
+
if(!good(poll)||poll.json.connected!==true){failed=true;write(context,'Your agent connection ended. Run pdd simulate again to reconnect.');break;}
|
|
89
|
+
remember(poll.json.selected);
|
|
90
|
+
const message=poll.json.message;
|
|
91
|
+
if(message!==null&&message!==undefined){
|
|
92
|
+
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;}
|
|
93
|
+
if(!seen.has(message.id)){
|
|
94
|
+
if(task){failed=true;write(context,'Another agent message arrived while one was running. Reconnect with pdd simulate.');break;}
|
|
95
|
+
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
|
+
}
|
|
97
|
+
}
|
|
98
|
+
if(onTick&&!tickTask)tickTask=Promise.resolve().then(onTick).then(keep=>{if(keep===false)stop();}).catch(err=>{if(err?.unboundPort)unboundError=err;else{failed=true;write(context,'Saved Try updates could not be read. Reconnect with pdd simulate.');}stop();}).finally(()=>{tickTask=null;});
|
|
99
|
+
if(ports.now()-before<1000)await ports.sleep(1000,controller.signal);
|
|
100
|
+
}}finally{await close();await task;await tickTask;}
|
|
101
|
+
if(unboundError)throw unboundError;
|
|
102
|
+
return failed?5:0;
|
|
103
|
+
}
|
|
104
|
+
return{url:ownerUrl.href,run,close};
|
|
105
|
+
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// Generated from prompts/cli/agent-coverage.prompt.md (sha256: 0b965a159573795ed2298532748378aff66e76d0dc270441918792658790a0c1).
|
|
2
|
+
import {basename} from 'node:path';
|
|
3
|
+
const object=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
|
|
4
|
+
function clip(value,max=160){let text='',bytes=0;for(const c of String(value??'').replace(/[\u0000-\u001f\u007f-\u009f]/g,' ')){const n=Buffer.byteLength(c);if(bytes+n>max)break;text+=c;bytes+=n;}return text;}
|
|
5
|
+
const id=e=>typeof e?.entry==='string'?e.entry:typeof e?.entry_path==='string'&&typeof e?.operation==='string'?`${e.entry_path}#${e.operation}`:'';
|
|
6
|
+
const slug=path=>basename(path,'.md');
|
|
7
|
+
const states=new Set(['pass','fail','differs','tried','todo']);
|
|
8
|
+
const first=input=>Array.isArray(input?.argv)&&input.argv.every(x=>typeof x==='string')?(input.argv[0]??''):null;
|
|
9
|
+
const MARK={pass:'✓',fail:'✗',differs:'~',tried:'~',todo:'·'};
|
|
10
|
+
const escaped=text=>text.replace(/[.*+?^${}()|[\]\\]/g,'\\$&');
|
|
11
|
+
export function createCoverage({scenarios=[],model={},productRules=[]}={}){
|
|
12
|
+
let incomplete=scenarios.incomplete===true;
|
|
13
|
+
model=object(model)?model:{};scenarios=Array.isArray(scenarios)?scenarios:[];
|
|
14
|
+
const entries=new Map(),stories=new Map(),commands=new Map(),endpoints=new Map(),screens=new Map();
|
|
15
|
+
const admitted=Array.isArray(model.entries)?model.entries:[];
|
|
16
|
+
if(admitted.length>64)incomplete=true;
|
|
17
|
+
for(const e of admitted.slice(0,64)){const key=id(e);if(key)entries.set(key,e);}
|
|
18
|
+
const keyFor=(entry,word)=>JSON.stringify([entry,word]);
|
|
19
|
+
const addCommand=(entry,word)=>{
|
|
20
|
+
if(typeof word!=='string'||Buffer.byteLength(word)>120||/[\u0000-\u001f\u007f-\u009f]/.test(word)){incomplete=true;return;}
|
|
21
|
+
const key=keyFor(entry,word);if(commands.has(key))return;
|
|
22
|
+
if(commands.size>=64){incomplete=true;return;}
|
|
23
|
+
const e=entries.get(entry),name=clip(e?.name||basename(entry.split('#')[0]).split('.')[0],64);
|
|
24
|
+
commands.set(key,{entry,command:word,label:clip(`${name} ${word||'(default)'}`),tried:false});
|
|
25
|
+
};
|
|
26
|
+
const cli=new Set();
|
|
27
|
+
for(const [entry,e] of entries){
|
|
28
|
+
if(e.cli===true||e.convention==='cli'||e.input_schema?.properties?.argv||(Array.isArray(e.conventions)&&e.conventions.some(c=>c?.convention==='cli')))cli.add(entry);
|
|
29
|
+
const title=e.input_schema?.title;
|
|
30
|
+
const match=typeof title==='string'?/^HTTP\s+([A-Z]+)\s+(\/\S*)$/i.exec(title):null;
|
|
31
|
+
const method=match?.[1]??e.http?.method,path=match?.[2]??e.http?.path;
|
|
32
|
+
if(typeof method==='string'&&typeof path==='string'&&path.startsWith('/'))endpoints.set(entry,{entry,label:clip(`${method.toUpperCase()} ${path}`),tried:false});
|
|
33
|
+
}
|
|
34
|
+
const storyFor=path=>{
|
|
35
|
+
if(typeof path!=='string'||!path)return null;
|
|
36
|
+
if(!stories.has(path)){if(stories.size>=64){incomplete=true;return null;}stories.set(path,{path:clip(path,256),title:slug(path),criteria:new Map(),references:new Set()});}
|
|
37
|
+
return stories.get(path);
|
|
38
|
+
};
|
|
39
|
+
const addCriteria=(story,list)=>{
|
|
40
|
+
if(!story||!Array.isArray(list))return;
|
|
41
|
+
for(const criterion of list){if(typeof criterion?.id!=='string'||!criterion.id||criterion.id.length>64)continue;if(!story.criteria.has(criterion.id)&&story.criteria.size>=64){incomplete=true;continue;}story.criteria.set(criterion.id,{id:criterion.id});}
|
|
42
|
+
};
|
|
43
|
+
if(scenarios.length>128)incomplete=true;
|
|
44
|
+
for(const scenario of scenarios.slice(0,128)){
|
|
45
|
+
const doc=scenario?.doc;if(!object(doc))continue;
|
|
46
|
+
const story=storyFor(doc.story_path);addCriteria(story,doc.criteria);
|
|
47
|
+
const steps=Array.isArray(doc.steps)?doc.steps:[];
|
|
48
|
+
for(const step of steps){const entry=id(step);if(story&&entry)story.references.add(entry);if(cli.has(entry)){const word=first(step.input);if(word!==null)addCommand(entry,word);}}
|
|
49
|
+
}
|
|
50
|
+
const modelStories=Array.isArray(model.stories)?model.stories:Object.values(object(model.stories)?model.stories:{});
|
|
51
|
+
for(const source of modelStories){const story=storyFor(source?.path);if(!story)continue;if(typeof source.title==='string')story.title=clip(source.title);addCriteria(story,source.criteria);}
|
|
52
|
+
for(const binding of Array.isArray(model.criterion_bindings)?model.criterion_bindings:[]){const story=storyFor(binding?.story_path);const entry=id(binding);if(story&&entry)story.references.add(entry);}
|
|
53
|
+
for(const example of Array.isArray(model.examples)?model.examples:[]){const entry=id(example);if(cli.has(entry)){const word=first(example.input);if(word!==null)addCommand(entry,word);}}
|
|
54
|
+
for(const [entry,e] of entries){
|
|
55
|
+
if(!cli.has(entry))continue;
|
|
56
|
+
const path=entry.split('#')[0];
|
|
57
|
+
for(const rule of Array.isArray(productRules)?productRules:[]){
|
|
58
|
+
if(rule?.path!==path||typeof rule.text!=='string')continue;
|
|
59
|
+
const program=clip(e.name||rule.text.match(/\bUsage:\s*([A-Za-z][\w.-]*)/i)?.[1]||basename(path).split('.')[0],64);
|
|
60
|
+
const pattern=new RegExp('(?:`|^\\s*(?:[-*]\\s*)?(?:Usage:\\s*)?)'+escaped(program)+'\\s+([A-Za-z][A-Za-z0-9_-]*|--[a-z][a-z-]*)','gmi');
|
|
61
|
+
for(const match of rule.text.matchAll(pattern))addCommand(entry,match[1]);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
for(const entry of cli)if(![...commands.values()].some(x=>x.entry===entry)){incomplete=true;if(commands.size>=64)continue;commands.set(keyFor(entry,null),{entry,command:null,label:clip(`${entries.get(entry)?.name||'CLI'} (commands unknown)`),tried:false});}
|
|
65
|
+
const screenSources=[...(Array.isArray(model.screen_sources)?model.screen_sources:[]),...(Array.isArray(model.app_map?.screens)?model.app_map.screens:[])];
|
|
66
|
+
for(const source of screenSources){if(typeof source?.id!=='string'||!source.id)continue;if(screens.size>=64&&!screens.has(source.id)){incomplete=true;continue;}screens.set(source.id,{id:clip(source.id,128),label:clip(source.name||source.title||source.id),tried:false});}
|
|
67
|
+
if(model.app_map===true&&!screens.size)incomplete=true;
|
|
68
|
+
function record(run){
|
|
69
|
+
if(!object(run))return;
|
|
70
|
+
const entry=run.entry;
|
|
71
|
+
if(endpoints.has(entry))endpoints.get(entry).tried=true;
|
|
72
|
+
if(cli.has(entry)){const unknown=commands.get(keyFor(entry,null));if(unknown)unknown.tried=true;const word=first(run.input);if(word!==null&&commands.has(keyFor(entry,word)))commands.get(keyFor(entry,word)).tried=true;}
|
|
73
|
+
const ids=[run.screen,...(Array.isArray(run.screens)?run.screens:[])];
|
|
74
|
+
for(const screen of ids)if(typeof screen==='string'&&screens.has(screen))screens.get(screen).tried=true;
|
|
75
|
+
}
|
|
76
|
+
function snapshot({progressByStory={},ownCases=[]}={}){
|
|
77
|
+
progressByStory=progressByStory instanceof Map||object(progressByStory)?progressByStory:{};ownCases=Array.isArray(ownCases)?ownCases:[];
|
|
78
|
+
const projected=[];
|
|
79
|
+
for(const story of stories.values()){
|
|
80
|
+
const raw=progressByStory instanceof Map?(progressByStory.get(story.path)??progressByStory.get(slug(story.path))):(progressByStory[story.path]??progressByStory[slug(story.path)]);
|
|
81
|
+
const list=Array.isArray(raw)?raw:Array.isArray(raw?.items)?raw.items:[];
|
|
82
|
+
const progress=new Map(list.filter(x=>typeof x?.id==='string').map(x=>[x.id,states.has(x.state)?x.state:'todo']));
|
|
83
|
+
const criteria=[...story.criteria.keys()].map(id=>({id,state:progress.get(id)??'todo'}));
|
|
84
|
+
const runnable=story.references.size>0&&[...story.references].every(entry=>entries.has(entry));
|
|
85
|
+
projected.push({path:story.path,title:story.title,runnable,needsOwnTry:runnable?null:`pdd simulate ${slug(story.path)}`,criteria,passed:criteria.filter(x=>x.state==='pass').length,total:criteria.length});
|
|
86
|
+
}
|
|
87
|
+
const own=(Array.isArray(ownCases)?ownCases:[]).slice(0,64).map(item=>({name:clip(item?.name||'Own case'),state:item?.saved===true||item?.state==='saved'?'saved':item?.matched===true||['match','matched'].includes(item?.state)?'matched':item?.state==='differs'?'differs':'pending'}));
|
|
88
|
+
const allCli=[...commands.values()].map(x=>({...x})),http=[...endpoints.values()].map(x=>({...x})),allScreens=[...screens.values()].map(x=>({...x}));
|
|
89
|
+
const known=projected.length+allCli.length+http.length+allScreens.length>0;
|
|
90
|
+
const fullyTried=known&&!incomplete&&ownCases.length<=64&&projected.every(s=>s.runnable&&s.criteria.every(c=>c.state==='pass'))&&[...allCli,...http,...allScreens].every(x=>x.tried)&&own.every(x=>['matched','saved'].includes(x.state));
|
|
91
|
+
const total=projected.reduce((n,s)=>n+s.total,0),passed=projected.reduce((n,s)=>n+s.passed,0);
|
|
92
|
+
const line=`Coverage: ${passed}/${total} criteria pass · ${[...allCli,...http,...allScreens].filter(x=>x.tried).length}/${allCli.length+http.length+allScreens.length} surfaces tried${fullyTried?' · fully tried':''}${incomplete?' · inventory incomplete':''}`;
|
|
93
|
+
const lines=[line,...projected.map(s=>`${s.title}: ${s.runnable?`${s.passed}/${s.total} pass ${s.criteria.map(c=>c.id+MARK[c.state]).join(' ')}`:'needs its own Try: '+s.needsOwnTry}`),`CLI: ${allCli.map(x=>x.label+(x.tried?' ✓':' ·')).join(', ')||'none'}`,`HTTP: ${http.map(x=>x.label+(x.tried?' ✓':' ·')).join(', ')||'none'}`,`Screens: ${allScreens.map(x=>x.label+(x.tried?' ✓':' ·')).join(', ')||(model.app_map===true?'unknown (inventory incomplete)':'none')}`,`Own cases: ${own.map(x=>x.name+' ('+x.state+')').join(', ')||'none yet'}`];
|
|
94
|
+
return{stories:projected,cli:allCli,http,screens:allScreens,ownCases:own,fullyTried,line,text:clip(lines.join('\n'),1024)};
|
|
95
|
+
}
|
|
96
|
+
return{record,snapshot};
|
|
97
|
+
}
|