dal-code 1.0.42 → 1.0.44
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/CHANGELOG.md +16 -0
- package/dist/core/agent-session.js +9 -9
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/types.d.ts +19 -0
- package/dist/core/permissions/tool-policy.d.ts +2 -1
- package/dist/core/permissions/tool-policy.js +1 -1
- package/dist/core/sandbox/shell-sandbox.js +7 -5
- package/dist/core/tool-denial.d.ts +13 -0
- package/dist/core/tool-denial.js +1 -0
- package/dist/core/tools/bash.d.ts +1 -0
- package/dist/core/tools/bash.js +14 -14
- package/dist/core/tools/index.d.ts +1 -1
- package/dist/core/tools/index.js +1 -1
- package/dist/dal/manifest.js +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.js +1 -1
- package/dist/main.js +3 -3
- package/dist/modes/rpc/approvals.js +1 -0
- package/dist/modes/rpc/message-meta.js +1 -0
- package/dist/modes/rpc/rpc-client.d.ts +15 -1
- package/dist/modes/rpc/rpc-client.js +3 -3
- package/dist/modes/rpc/rpc-mode.js +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +55 -1
- package/dist/node_modules/@dalcode/dal-advisor/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-awake/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-bridge/src/index.js +1 -1
- package/dist/node_modules/@dalcode/dal-capabilities/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-compat/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-dap/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-goal/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-guard/src/index.js +2 -1
- package/dist/node_modules/@dalcode/dal-guard/src/workspace.js +2 -2
- package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-interactive/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-learn/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +2 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.js +1 -1
- package/dist/node_modules/@dalcode/dal-plugins/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-recall/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-remote/LICENSE +21 -0
- package/dist/node_modules/@dalcode/dal-remote/package.json +32 -0
- package/dist/node_modules/@dalcode/dal-remote/src/cli.js +15 -0
- package/dist/node_modules/@dalcode/dal-remote/src/index.js +1 -0
- package/dist/node_modules/@dalcode/dal-remote/src/install.js +8 -0
- package/dist/node_modules/@dalcode/dal-remote/src/paths.js +1 -0
- package/dist/node_modules/@dalcode/dal-remote/src/processes.js +2 -0
- package/dist/node_modules/@dalcode/dal-remote/src/service.js +8 -0
- package/dist/node_modules/@dalcode/dal-remote/src/spec.js +1 -0
- package/dist/node_modules/@dalcode/dal-review/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-rewind/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-router/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-rtk/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-statusline/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-structured/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-subagent/src/background.js +8 -8
- package/dist/node_modules/@dalcode/dal-subagent/src/index.js +20 -20
- package/dist/node_modules/@dalcode/dal-subagent/src/progress.js +1 -0
- package/dist/node_modules/@dalcode/dal-telemetry/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-terminal/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-tool-catalog/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-usage/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-web/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-workflow/package.json +2 -2
- package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
- package/dist/node_modules/@earendil-works/chord/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/agent-loop.js +1 -1
- package/dist/node_modules/@earendil-works/pi-agent-core/dist/types.d.ts +1 -0
- package/dist/node_modules/@earendil-works/pi-agent-core/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-client/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-codemode/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-coding-agent/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-mcp/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-server/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
package/dist/main.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Ke=Object.defineProperty;var
|
|
1
|
+
var Ke=Object.defineProperty;var u=(e,t)=>Ke(e,"name",{value:t,configurable:!0});import{createInterface as $e}from"node:readline";import{modelsAreEqual as We}from"@earendil-works/pi-ai";import d from"chalk";import{normalizeSessionName as qe,parseArgs as ue,printHelp as Ue,reclaimBooleanFlagMessages as Ve}from"./cli/args.js";import{checkProviderAuth as ze,createAuthCheckModelRuntime as Ye,getProviderCredential as Ge}from"./cli/auth-check.js";import{AuthCommandError as K,getAuthCommandName as Je,getAuthCommandUsage as Qe,isAuthCommandHelp as Xe,parseAuthCommand as Ze,printAuthCommandHelp as et,validateAuthCommandArgs as tt}from"./cli/auth-command.js";import{resolveCredentialForPrint as ot}from"./cli/credential-print.js";import{processFileArguments as st}from"./cli/file-processor.js";import{buildInitialMessage as fe}from"./cli/initial-message.js";import{listModels as nt}from"./cli/list-models.js";import{createProjectTrustContext as it}from"./cli/project-trust.js";import{selectSession as rt}from"./cli/session-picker.js";import{shouldRunFirstTimeSetup as at,showFirstTimeSetup as lt,showStartupSelector as ct}from"./cli/startup-ui.js";import{APP_NAME as pe,ENV_SESSION_DIR as dt,expandTildePath as mt,getAgentDir as ut,getPackageDir as ft,VERSION as pt}from"./config.js";import{createAgentSessionRuntime as gt}from"./core/agent-session-runtime.js";import{createAgentSessionFromServices as ht,createAgentSessionServices as vt}from"./core/agent-session-services.js";import{formatNoModelsAvailableMessage as xt}from"./core/auth-guidance.js";import{AuthStorage as wt,ReadOnlyAuthStorage as St}from"./core/auth-storage.js";import{exportFromFile as yt}from"./core/export-html/index.js";import{applyHttpProxySettings as ge,configureHttpDispatcher as he}from"./core/http-dispatcher.js";import{resolveCliModel as Tt,resolveModelScope as Pt}from"./core/model-resolver.js";import{ModelRuntime as Mt}from"./core/model-runtime.js";import{restoreStdout as kt,takeOverStdout as Ct}from"./core/output-guard.js";import{resolveProjectTrusted as It}from"./core/project-trust.js";import{formatMissingSessionCwdPrompt as At,getMissingSessionCwdIssue as bt,MissingSessionCwdError as Et}from"./core/session-cwd.js";import{assertValidSessionId as Rt,SessionManager as g}from"./core/session-manager.js";import{collectSettingsDiagnostics as ve,deduplicateDiagnostics as xe}from"./core/settings-diagnostics.js";import{SettingsManager as $}from"./core/settings-manager.js";import{printTimings as I,resetTimings as Ft,time as h}from"./core/timings.js";import{hasTrustRequiringProjectResources as we,ProjectTrustStore as Lt}from"./core/trust-manager.js";import{applyDalEnvApiKeyPolicy as _t,applyDalSystemProxyFallback as jt,dalBuiltinExtensionPaths as Ot}from"./dal/builtins.js";import{markHostExtensionPaths as Dt}from"./dal/host-extensions.js";import{fill as f,t as c}from"./dal/i18n.js";import{installDalShellSafetyNet as Nt}from"./dal/safety-net.js";import{builtInExtensions as Ht}from"./extensions/index.js";import{loadMcpCommand as Bt}from"./extensions/mcp/cli.lazy.js";import{runMigrations as Kt,showDeprecationWarnings as $t}from"./migrations.js";import{InteractiveMode as Wt,runAcpMode as qt,runPrintMode as Ut,runRpcMode as Vt}from"./modes/index.js";import{initTheme as zt,stopThemeWatcher as W}from"./modes/interactive/theme/theme.js";import{cleanupManagedInstall as Yt,handleConfigCommand as Gt,handlePackageCommand as Jt}from"./package-manager-cli.js";import{isTruthyEnvFlag as Se}from"./utils/offline.js";import{isLocalPath as Qt,normalizePath as Xt,resolvePath as ye}from"./utils/paths.js";import{cleanupWindowsSelfUpdateQuarantine as Zt}from"./utils/windows-self-update.js";const eo=u(()=>f(c("\u63D0\u793A\uFF1A\u53EF\u4EE5\u7528\u300C{app} -ne\u300D\u5728\u4E0D\u52A0\u8F7D\u6269\u5C55\u7684\u60C5\u51B5\u4E0B\u542F\u52A8\u3002"),{app:pe}),"extensionLoadFailureHint");async function to(){if(!process.stdin.isTTY)return new Promise(e=>{let t="";process.stdin.setEncoding("utf8"),process.stdin.on("data",s=>{t+=s}),process.stdin.on("end",()=>{e(t.trim()||void 0)}),process.stdin.resume()})}u(to,"readPipedStdin");function q(e){for(const t of e){const s=t.type==="error"?d.red:t.type==="warning"?d.yellow:d.dim,l=t.type==="error"?f(c("\u9519\u8BEF\uFF1A{message}"),{message:t.message}):t.type==="warning"?f(c("\u8B66\u544A\uFF1A{message}"),{message:t.message}):t.message;console.error(s(l))}}u(q,"reportDiagnostics");function oo(e,t,s){return e.mode==="rpc"?"rpc":e.mode==="acp"?"acp":e.mode==="json"?"json":e.print||!t||!s?"print":"interactive"}u(oo,"resolveAppMode");function so(e){return e==="json"?"json":"text"}u(so,"toPrintOutputMode");function no(e){return!e.print&&e.mode===void 0&&(e.help===!0||e.listModels!==void 0)}u(no,"isPlainRuntimeMetadataCommand");async function io(e){if(Xe(e))return et(),!0;let t;try{t=Ze(e)}catch(l){const n=l instanceof K?l.message:c("\u65E0\u6CD5\u89E3\u6790 auth \u547D\u4EE4");return console.error(d.red(f(c("\u9519\u8BEF\uFF1A{message}"),{message:n}))),process.exitCode=1,!0}if(!t)return!1;const s=ue(t.args);if(s.unknownFlags.size>0){const l=s.unknownFlags.keys().next().value;return console.error(d.red(f(c("\u300C{command}\u300D\u4E0D\u652F\u6301\u9009\u9879 --{option}\u3002"),{option:String(l),command:Je(t.kind)}))),console.error(d.dim(f(c("\u8BF7\u67E5\u770B\u300C{app} --help\u300D\u6216\u300C{usage}\u300D\u3002"),{app:pe,usage:Qe(t.kind)}))),process.exitCode=1,!0}try{if(s.diagnostics.length>0)throw new K(s.diagnostics.map(o=>o.message).join(`
|
|
2
2
|
`));if(t.kind!=="check"){const o=AbortSignal.timeout(15e3),r=await Mt.create({allowModelNetwork:!1,signal:o}),P=await ot(s,r,t.kind,t.minExpiryMs,o);return process.stdout.write(`${P}
|
|
3
|
-
`),!0}const l=tt(s,t.kind);let n,a;try{const o=t.noRefresh?new wt
|
|
4
|
-
`),process.exitCode=n.status==="ready"?0:n.status==="not_ready"?1:2}catch(l){const n=l instanceof K?l.message:c("\u65E0\u6CD5\u83B7\u53D6\u51ED\u636E");console.error(d.red(f(c("\u9519\u8BEF\uFF1A{message}"),{message:n}))),process.exitCode=t.kind==="check"?2:1}return!0}m(io,"runAuthCommand");async function ro(e,t){if(e.fileArgs.length===0)return fe({parsed:e,stdinContent:t});const{text:s,images:l}=await st(e.fileArgs,{autoResizeImages:!1});return fe({parsed:e,fileText:s,fileImages:l,stdinContent:t})}m(ro,"prepareInitialMessage");function U(e,t,s){const l=g.findById(t,e,s);return l?{type:"local",path:l}:void 0}m(U,"findLocalSessionByExactId");async function Te(e,t,s){if(e.includes("/")||e.includes("\\")||e.endsWith(".jsonl"))return{type:"path",path:ye(e,t)};const l=U(e,t,s);if(l)return l;const a=(await g.list(t,s)).find(r=>r.id.startsWith(e));if(a)return{type:"local",path:a.path};const p=await g.listAll(s),o=p.find(r=>r.id===e)??p.find(r=>r.id.startsWith(e));return o?{type:"global",path:o.path,cwd:o.cwd}:{type:"not_found",arg:e}}m(Te,"resolveSessionPath");async function ao(e){return new Promise(t=>{const s=$e({input:process.stdin,output:process.stdout});s.question(`${e} [y/N] `,l=>{s.close(),t(l.toLowerCase()==="y"||l.toLowerCase()==="yes")})})}m(ao,"promptConfirm");function lo(e){if(!e.fork)return;const t=[e.session?"--session":void 0,e.continue?"--continue":void 0,e.resume?"--resume":void 0,e.noSession?"--no-session":void 0].filter(s=>s!==void 0);t.length>0&&(console.error(d.red(f(c("\u9519\u8BEF\uFF1A--fork \u4E0D\u80FD\u548C {flags} \u540C\u65F6\u4F7F\u7528"),{flags:t.join(", ")}))),process.exit(1))}m(lo,"validateForkFlags");function co(e){if(e.sessionId===void 0)return;const t=[e.session?"--session":void 0,e.continue?"--continue":void 0,e.resume?"--resume":void 0].filter(s=>s!==void 0);t.length>0&&(console.error(d.red(f(c("\u9519\u8BEF\uFF1A--session-id \u4E0D\u80FD\u548C {flags} \u540C\u65F6\u4F7F\u7528"),{flags:t.join(", ")}))),process.exit(1));try{Ft(e.sessionId)}catch(s){const l=s instanceof Error?s.message:String(s);console.error(d.red(f(c("\u9519\u8BEF\uFF1A{message}"),{message:l}))),process.exit(1)}}m(co,"validateSessionIdFlags");function mo(e,t){try{return g.open(e,t)}catch(s){const l=s instanceof Error?s.message:String(s);console.error(d.red(f(c("\u9519\u8BEF\uFF1A{message}"),{message:l}))),process.exit(1)}}m(mo,"openSessionOrExit");function Pe(e,t,s,l){try{return g.forkFrom(e,t,s,{id:l})}catch(n){const a=n instanceof Error?n.message:String(n);console.error(d.red(f(c("\u9519\u8BEF\uFF1A{message}"),{message:a}))),process.exit(1)}}m(Pe,"forkSessionOrExit");async function uo(e,t,s,l){if(e.noSession||e.help||e.listModels!==void 0)return g.inMemory(t,e.sessionId!==void 0?{id:e.sessionId}:void 0);if(e.fork){e.sessionId&&U(e.sessionId,t,s)&&(console.error(d.red(f(c("ID \u4E3A\u300C{id}\u300D\u7684\u4F1A\u8BDD\u5DF2\u7ECF\u5B58\u5728"),{id:e.sessionId}))),process.exit(1));const n=await Te(e.fork,t,s);switch(n.type){case"path":case"local":case"global":return Pe(n.path,t,s,e.sessionId);case"not_found":console.error(d.red(f(c("\u6CA1\u6709\u627E\u5230\u5339\u914D\u300C{session}\u300D\u7684\u4F1A\u8BDD"),{session:n.arg}))),process.exit(1)}}if(e.session){const n=await Te(e.session,t,s);switch(n.type){case"path":case"local":return mo(n.path,s);case"global":return console.log(d.yellow(f(c("\u5728\u53E6\u4E00\u4E2A\u9879\u76EE\u91CC\u627E\u5230\u4E86\u8FD9\u4E2A\u4F1A\u8BDD\uFF1A{cwd}"),{cwd:n.cwd}))),await ao(c("\u8981\u628A\u8FD9\u4E2A\u4F1A\u8BDD\u5206\u53C9\u5230\u5F53\u524D\u76EE\u5F55\u5417\uFF1F"))||(console.log(d.dim(c("\u5DF2\u53D6\u6D88\u3002"))),process.exit(0)),Pe(n.path,t,s);case"not_found":console.error(d.red(f(c("\u6CA1\u6709\u627E\u5230\u5339\u914D\u300C{session}\u300D\u7684\u4F1A\u8BDD"),{session:n.arg}))),process.exit(1)}}if(e.resume)try{const n=await rt((a,p)=>g.list(t,s,a,p),(a,p)=>g.listAll(s,a,p),l);return n||(console.log(d.dim(c("\u6CA1\u6709\u9009\u62E9\u4F1A\u8BDD"))),process.exit(0)),g.open(n,s)}finally{W()}if(e.continue)return g.continueRecent(t,s);if(e.sessionId){const n=U(e.sessionId,t,s);if(e.newSession)return n&&(console.error(d.red(f(c("ID \u4E3A\u300C{id}\u300D\u7684\u4F1A\u8BDD\u5DF2\u7ECF\u5B58\u5728"),{id:e.sessionId}))),process.exit(1)),g.create(t,s,{id:e.sessionId});if(n)return g.open(n.path,s);console.error(d.yellow(f(c("\u8B66\u544A\uFF1A\u5F53\u524D\u9879\u76EE\u91CC\u6CA1\u6709 ID \u4E3A\u300C{id}\u300D\u7684\u4F1A\u8BDD\uFF0C\u5C06\u7528\u8FD9\u4E2A ID \u65B0\u5EFA\u4E00\u4E2A\u4F1A\u8BDD\u3002"),{id:e.sessionId})))}return g.create(t,s,{id:e.sessionId})}m(uo,"createSessionManager");function fo(e,t,s,l,n){const a={},p=[];let o=!1;if(e.provider&&!e.model&&p.push({type:"error",message:`--provider requires --model (for example: --provider ${e.provider} --model <pattern>)`}),e.model){const r=Tt({cliProvider:e.provider,cliModel:e.model,cliThinking:e.thinking,modelRuntime:l});r.warning&&p.push({type:"warning",message:r.warning}),r.error&&p.push({type:"error",message:r.error}),r.model&&(a.model=r.model,!e.thinking&&r.thinkingLevel&&(a.thinkingLevel=r.thinkingLevel,o=!0))}if(!a.model&&t.length>0&&!s){const r=n.getDefaultProvider(),P=n.getDefaultModel(),A=r&&P?l.getModel(r,P):void 0,w=A?t.find(x=>We(x.model,A)):void 0;w?(a.model=w.model,!e.thinking&&w.thinkingLevel&&(a.thinkingLevel=w.thinkingLevel)):(a.model=t[0].model,!e.thinking&&t[0].thinkingLevel&&(a.thinkingLevel=t[0].thinkingLevel))}return e.thinking&&(a.thinkingLevel=e.thinking),t.length>0&&(a.scopedModels=t.map(r=>({model:r.model,thinkingLevel:r.thinkingLevel}))),e.noTools?a.noTools="all":e.noBuiltinTools&&(a.noTools="builtin"),e.tools&&(a.tools=[...e.tools]),e.excludeTools&&(a.excludeTools=[...e.excludeTools]),a.sandbox={defaultLevel:"workspace-write",...e.sandbox?{level:e.sandbox}:{},...e.sandboxAllowDomains?{allowedDomains:[...e.sandboxAllowDomains]}:{}},a.defaultActiveTools=["read","bash","edit","write","process"],{options:a,cliThinkingFromModel:o,diagnostics:p}}m(fo,"buildSessionOptions");function L(e,t){return t?.map(s=>Qt(s)?ye(s,e):s)}m(L,"resolveCliPaths");async function po(e,t){return ct(t,At(e),[{label:"Continue",value:e.fallbackCwd},{label:"Cancel",value:void 0}])}m(po,"promptForMissingSessionCwd");async function is(e,t){Rt();const s=[...Ht,...t?.extensionFactories??[]],l=e.includes("--offline")||we(process.env.PI_OFFLINE);if(l&&(process.env.PI_OFFLINE="1",process.env.PI_SKIP_VERSION_CHECK="1",process.env.DAL_SKIP_VERSION_CHECK="1"),await io(e))return;process.platform==="win32"&&Zt(ft()),Yt();const n=process.cwd(),a=ut(),p=$.create(n,a,{projectTrusted:!1});if(ge(p.getGlobalSettings().httpProxy),jt(),_t(),Dt(),he(),await Jt(e,{extensionFactories:s})){const i=process.exitCode??0;if(process.platform==="win32"&&i===0&&e[0]==="update")return;process.exit(i);return}if(await Gt(e,{extensionFactories:s}))return;if(e[0]==="mcp"){const{runMcpCommand:i}=await Bt();process.exitCode=await i(e.slice(1),{cwd:n,agentDir:a});return}const o=ue(e);if(o.diagnostics.length>0){for(const i of o.diagnostics){const u=i.type==="error"?d.red:d.yellow;console.error(u(f(i.type==="error"?c("\u9519\u8BEF\uFF1A{message}"):c("\u8B66\u544A\uFF1A{message}"),{message:i.message})))}o.diagnostics.some(i=>i.type==="error")&&process.exit(1)}if(h("parseArgs"),o.version&&(console.log(pt),process.exit(0)),o.export){let i;try{const u=o.messages.length>0?o.messages[0]:void 0;i=await yt(o.export,u)}catch(u){const E=u instanceof Error?u.message:c("\u5BFC\u51FA\u4F1A\u8BDD\u5931\u8D25");console.error(d.red(f(c("\u9519\u8BEF\uFF1A{message}"),{message:E}))),process.exit(1)}console.log(f(c("\u5DF2\u5BFC\u51FA\u5230\uFF1A{path}"),{path:i})),process.exit(0)}let r=oo(o,process.stdin.isTTY,process.stdout.isTTY);r!=="interactive"&&!no(o)&&Ct(),(o.mode==="rpc"||o.mode==="acp")&&o.fileArgs.length>0&&(console.error(d.red(f(c("\u9519\u8BEF\uFF1A{mode} \u6A21\u5F0F\u4E0D\u652F\u6301 @\u6587\u4EF6 \u53C2\u6570"),{mode:o.mode.toUpperCase()}))),process.exit(1)),lo(o),co(o);const{migratedAuthProviders:A,deprecationWarnings:w}=Kt(n);h("runMigrations");const x=$.create(n,a),_=ve(x);r==="interactive"&&!o.help&&o.listModels===void 0&&at()&&(await lt(x),h("firstTimeSetup")),r==="interactive"&&o.useTheme!==void 0&&x.applyOverrides({theme:o.useTheme});const V=process.env[dt],z=(o.sessionDir?Xt(o.sessionDir):void 0)??(V?mt(V):void 0)??x.getSessionDir();let y=await uo(o,n,z,x);const b=bt(y,n);if(b)if(r==="interactive"){const i=await po(b,x);i||process.exit(0),y=g.open(b.sessionFile,z,i)}else console.error(d.red(new Et(b).message)),process.exit(1);if(o.name!==void 0){const i=qe(o.name);i===void 0&&(console.error(d.red(c("\u9519\u8BEF\uFF1A--name \u7684\u503C\u4E0D\u80FD\u4E3A\u7A7A"))),process.exit(1)),y.appendSessionInfo(i)}h("createSessionManager");const Y=new Lt(a),G=y.getCwd(),Me=o.projectTrustOverride===void 0&&!Se(G)?G:void 0,J=o.help||o.listModels!==void 0?"print":r,Q=new Map,X=L(n,o.extensions)??[];Nt(X);const ke=[...Ot(),...X],Ce=L(n,o.skills),Ie=L(n,o.promptTemplates),Ae=L(n,o.themes),be=m(async({cwd:i,agentDir:u,sessionManager:E,sessionStartEvent:ie,projectTrustContext:Le})=>{const re=ie===void 0,ae=[],le=Q.get(i),ce=Se(i),de=o.projectTrustOverride===void 0&&le===void 0&&ce,_e=de?!1:le??o.projectTrustOverride??(!ce||Y.get(i)===!0),je=$.create(i,u,{projectTrusted:_e}),F=await vt({cwd:i,agentDir:u,settingsManager:je,modelRuntimeSignal:AbortSignal.timeout(15e3),extensionFlagValues:o.unknownFlags,resourceLoaderReloadOptions:de?{resolveProjectTrust:m(async({extensionsResult:C})=>{const T=await It({cwd:i,trustStore:Y,trustOverride:o.projectTrustOverride,defaultProjectTrust:x.getDefaultProjectTrust(),extensionsResult:C,projectTrustContext:Le??it({cwd:i,mode:re?J:r,settingsManager:x,hasUI:re&&J==="interactive"}),onExtensionError:m(Be=>ae.push({type:"warning",message:Be}),"onExtensionError")});return Q.set(i,T),T},"resolveProjectTrust")}:void 0,resourceLoaderOptions:{additionalExtensionPaths:ke,additionalSkillPaths:Ce,additionalPromptTemplatePaths:Ie,additionalThemePaths:Ae,noExtensions:o.noExtensions,disabledBuiltinExtensions:o.noMcp?["mcp"]:void 0,noSkills:o.noSkills,noPromptTemplates:o.noPromptTemplates,noThemes:o.noThemes,noContextFiles:o.noContextFiles,systemPrompt:o.systemPrompt,appendSystemPrompt:o.appendSystemPrompt,extensionFactories:s}}),{settingsManager:D,modelRuntime:H,resourceLoader:me}=F,R=[...ae,...F.diagnostics,...ve(D),...me.getExtensions().errors.map(({path:C,error:T})=>({type:"error",message:`Failed to load extension "${C}": ${T}`})),...(me.getExtensions().warnings??[]).map(({path:C,warning:T})=>({type:"warning",message:`Extension package "${C}": ${T}`}))],B=o.models??D.getEnabledModels(),Oe=B&&B.length>0?await Pt(B,H,{signal:AbortSignal.timeout(15e3)}):[],{options:v,cliThinkingFromModel:Ne,diagnostics:De}=fo(o,Oe,E.buildSessionContext().messages.length>0,H,D);R.push(...De),o.apiKey&&(v.model?await H.setRuntimeApiKey(v.model.provider,o.apiKey):R.push({type:"error",message:c("\u4F7F\u7528 --api-key \u65F6\u9700\u8981\u901A\u8FC7 --model\u3001--provider/--model \u6216 --models \u6307\u5B9A\u6A21\u578B")}));const M=await ht({services:F,sessionManager:E,sessionStartEvent:ie,model:v.model,thinkingLevel:v.thinkingLevel,scopedModels:v.scopedModels,tools:v.tools,excludeTools:v.excludeTools,noTools:v.noTools,customTools:v.customTools,sandbox:v.sandbox,defaultActiveTools:v.defaultActiveTools}),He=o.thinking!==void 0||Ne;M.session.model&&He&&M.session.setThinkingLevel(M.session.thinkingLevel);const k=M.session.getSandboxStatus();return k&&k.level!=="off"&&!k.enforced&&R.push({type:"warning",message:f(c("\u547D\u4EE4\u6C99\u7BB1\u4E0D\u53EF\u7528\uFF08{level}\uFF09\uFF1A{reason} shell \u547D\u4EE4\u4F1A\u88AB\u62D2\u7EDD\uFF1B\u786E\u5B9A\u4E0D\u8981\u6C99\u7BB1\u8BF7\u7528 --sandbox off\u3002"),{level:k.level,reason:k.unavailableReason??""})}),{...M,services:F,diagnostics:R}},"createRuntime");h("createRuntime");const S=await gt(be,{cwd:y.getCwd(),agentDir:a,sessionManager:y});h("createAgentSessionRuntime");const{services:Ee,session:Fe,modelFallbackMessage:Re}=S,{settingsManager:j,modelRuntime:Z,resourceLoader:ee}=Ee;if(Ve(o,new Set(ee.getExtensions().extensions.flatMap(i=>[...i.flags].filter(([,u])=>u.type==="boolean").map(([u])=>u)))),ge(j.getGlobalSettings().httpProxy),he(j.getHttpIdleTimeoutMs()),o.help){q(_);const i=ee.getExtensions().extensions.flatMap(u=>Array.from(u.flags.values()));Ue(i),process.exit(0)}if(o.listModels!==void 0){q(xe([..._,...S.diagnostics]));const i=typeof o.listModels=="string"?o.listModels:void 0;await nt(Z,i,AbortSignal.timeout(15e3)),process.exit(0)}let O;r!=="rpc"&&r!=="acp"&&(O=await to(),O!==void 0&&r==="interactive"&&(r="print")),h("readPipedStdin");const{initialMessage:N,initialImages:te}=await ro(o,O);h("prepareInitialMessage"),zt(j.getTheme(),r==="interactive"),h("initTheme"),r==="interactive"&&w.length>0&&await $t(w),h("resolveModelScope");const oe=xe([..._,...S.diagnostics]),se=S.diagnostics.some(i=>i.type==="error");(r!=="interactive"||se)&&q(oe),se&&(S.diagnostics.some(i=>i.message.includes("Failed to load extension"))&&console.error(d.yellow(eo())),process.exit(1)),h("createAgentSession"),r!=="interactive"&&!Fe.model&&(console.error(d.red(xt())),process.exit(1));const ne=we(process.env.PI_STARTUP_BENCHMARK);if(ne&&r!=="interactive"&&(console.error(d.red(c("\u9519\u8BEF\uFF1API_STARTUP_BENCHMARK \u53EA\u652F\u6301\u4EA4\u4E92\u6A21\u5F0F"))),process.exit(1)),!l&&(r==="rpc"||r==="acp")){const i=new AbortController,u=setTimeout(()=>i.abort(),15e3);Z.refresh({signal:i.signal}).catch(()=>{}).finally(()=>clearTimeout(u))}if(r==="rpc")I(),await Vt(S);else if(r==="acp")I(),await qt(S);else if(r==="interactive"){const i=new Wt(S,{migratedProviders:A,startupDiagnostics:oe,modelFallbackMessage:Re,autoTrustOnReloadCwd:Me,initialMessage:N,initialImages:te,initialMessages:o.messages,verbose:o.verbose,tuiMode:o.tuiMode,initialThemeSetting:o.useTheme});if(ne){await i.init(),h("interactiveMode.init"),await new Promise(u=>setTimeout(u,150)),i.stop(),W(),I(),process.stdout.writableLength>0&&await new Promise(u=>process.stdout.once("drain",u)),process.stderr.writableLength>0&&await new Promise(u=>process.stderr.once("drain",u));return}I(),await i.run()}else{if(I(),!N&&o.messages.length===0){console.error(d.red(c('\u9519\u8BEF\uFF1A\u6CA1\u6709\u8981\u53D1\u7ED9\u52A9\u624B\u7684\u5185\u5BB9\u3002\u7528\u6CD5\uFF1Adal -p "\u4EFB\u52A1"\uFF0C\u6216\u901A\u8FC7\u6807\u51C6\u8F93\u5165\u4F20\u5165\u3002'))),await S.dispose(),process.exitCode=1;return}const i=await Ut(S,{mode:so(r),messages:o.messages,initialMessage:N,initialImages:te});W(),kt(),i!==0&&(process.exitCode=i);return}}m(is,"main");export{uo as createSessionManager,is as main};
|
|
3
|
+
`),!0}const l=tt(s,t.kind);let n,a;try{const o=t.noRefresh?new St:wt.create(),r=await Ye(o);n=await ze(s,r,{refresh:!t.noRefresh}),t.credentials&&n.status==="ready"&&(a=await Ge(n.provider,r,o,{refresh:!t.noRefresh}),a||(n={status:"not_ready",provider:n.provider,reason:"credential_not_available"}))}catch{n={status:"invalid",provider:l.provider??l.model,reason:"invalid_state"}}const p=t.json?JSON.stringify({...n,...a?{credentials:a}:{}}):a??n.status;process.stdout.write(`${p}
|
|
4
|
+
`),process.exitCode=n.status==="ready"?0:n.status==="not_ready"?1:2}catch(l){const n=l instanceof K?l.message:c("\u65E0\u6CD5\u83B7\u53D6\u51ED\u636E");console.error(d.red(f(c("\u9519\u8BEF\uFF1A{message}"),{message:n}))),process.exitCode=t.kind==="check"?2:1}return!0}u(io,"runAuthCommand");async function ro(e,t){if(e.fileArgs.length===0)return fe({parsed:e,stdinContent:t});const{text:s,images:l}=await st(e.fileArgs,{autoResizeImages:!1});return fe({parsed:e,fileText:s,fileImages:l,stdinContent:t})}u(ro,"prepareInitialMessage");function U(e,t,s){const l=g.findById(t,e,s);return l?{type:"local",path:l}:void 0}u(U,"findLocalSessionByExactId");async function Te(e,t,s){if(e.includes("/")||e.includes("\\")||e.endsWith(".jsonl"))return{type:"path",path:ye(e,t)};const l=U(e,t,s);if(l)return l;const a=(await g.list(t,s)).find(r=>r.id.startsWith(e));if(a)return{type:"local",path:a.path};const p=await g.listAll(s),o=p.find(r=>r.id===e)??p.find(r=>r.id.startsWith(e));return o?{type:"global",path:o.path,cwd:o.cwd}:{type:"not_found",arg:e}}u(Te,"resolveSessionPath");async function ao(e){return new Promise(t=>{const s=$e({input:process.stdin,output:process.stdout});s.question(`${e} [y/N] `,l=>{s.close(),t(l.toLowerCase()==="y"||l.toLowerCase()==="yes")})})}u(ao,"promptConfirm");function lo(e){if(!e.fork)return;const t=[e.session?"--session":void 0,e.continue?"--continue":void 0,e.resume?"--resume":void 0,e.noSession?"--no-session":void 0].filter(s=>s!==void 0);t.length>0&&(console.error(d.red(f(c("\u9519\u8BEF\uFF1A--fork \u4E0D\u80FD\u548C {flags} \u540C\u65F6\u4F7F\u7528"),{flags:t.join(", ")}))),process.exit(1))}u(lo,"validateForkFlags");function co(e){if(e.sessionId===void 0)return;const t=[e.session?"--session":void 0,e.continue?"--continue":void 0,e.resume?"--resume":void 0].filter(s=>s!==void 0);t.length>0&&(console.error(d.red(f(c("\u9519\u8BEF\uFF1A--session-id \u4E0D\u80FD\u548C {flags} \u540C\u65F6\u4F7F\u7528"),{flags:t.join(", ")}))),process.exit(1));try{Rt(e.sessionId)}catch(s){const l=s instanceof Error?s.message:String(s);console.error(d.red(f(c("\u9519\u8BEF\uFF1A{message}"),{message:l}))),process.exit(1)}}u(co,"validateSessionIdFlags");function mo(e,t){try{return g.open(e,t)}catch(s){const l=s instanceof Error?s.message:String(s);console.error(d.red(f(c("\u9519\u8BEF\uFF1A{message}"),{message:l}))),process.exit(1)}}u(mo,"openSessionOrExit");function Pe(e,t,s,l){try{return g.forkFrom(e,t,s,{id:l})}catch(n){const a=n instanceof Error?n.message:String(n);console.error(d.red(f(c("\u9519\u8BEF\uFF1A{message}"),{message:a}))),process.exit(1)}}u(Pe,"forkSessionOrExit");async function uo(e,t,s,l){if(e.noSession||e.help||e.listModels!==void 0)return g.inMemory(t,e.sessionId!==void 0?{id:e.sessionId}:void 0);if(e.fork){e.sessionId&&U(e.sessionId,t,s)&&(console.error(d.red(f(c("ID \u4E3A\u300C{id}\u300D\u7684\u4F1A\u8BDD\u5DF2\u7ECF\u5B58\u5728"),{id:e.sessionId}))),process.exit(1));const n=await Te(e.fork,t,s);switch(n.type){case"path":case"local":case"global":return Pe(n.path,t,s,e.sessionId);case"not_found":console.error(d.red(f(c("\u6CA1\u6709\u627E\u5230\u5339\u914D\u300C{session}\u300D\u7684\u4F1A\u8BDD"),{session:n.arg}))),process.exit(1)}}if(e.session){const n=await Te(e.session,t,s);switch(n.type){case"path":case"local":return mo(n.path,s);case"global":return console.log(d.yellow(f(c("\u5728\u53E6\u4E00\u4E2A\u9879\u76EE\u91CC\u627E\u5230\u4E86\u8FD9\u4E2A\u4F1A\u8BDD\uFF1A{cwd}"),{cwd:n.cwd}))),await ao(c("\u8981\u628A\u8FD9\u4E2A\u4F1A\u8BDD\u5206\u53C9\u5230\u5F53\u524D\u76EE\u5F55\u5417\uFF1F"))||(console.log(d.dim(c("\u5DF2\u53D6\u6D88\u3002"))),process.exit(0)),Pe(n.path,t,s);case"not_found":console.error(d.red(f(c("\u6CA1\u6709\u627E\u5230\u5339\u914D\u300C{session}\u300D\u7684\u4F1A\u8BDD"),{session:n.arg}))),process.exit(1)}}if(e.resume)try{const n=await rt((a,p)=>g.list(t,s,a,p),(a,p)=>g.listAll(s,a,p),l);return n||(console.log(d.dim(c("\u6CA1\u6709\u9009\u62E9\u4F1A\u8BDD"))),process.exit(0)),g.open(n,s)}finally{W()}if(e.continue)return g.continueRecent(t,s);if(e.sessionId){const n=U(e.sessionId,t,s);if(e.newSession)return n&&(console.error(d.red(f(c("ID \u4E3A\u300C{id}\u300D\u7684\u4F1A\u8BDD\u5DF2\u7ECF\u5B58\u5728"),{id:e.sessionId}))),process.exit(1)),g.create(t,s,{id:e.sessionId});if(n)return g.open(n.path,s);console.error(d.yellow(f(c("\u8B66\u544A\uFF1A\u5F53\u524D\u9879\u76EE\u91CC\u6CA1\u6709 ID \u4E3A\u300C{id}\u300D\u7684\u4F1A\u8BDD\uFF0C\u5C06\u7528\u8FD9\u4E2A ID \u65B0\u5EFA\u4E00\u4E2A\u4F1A\u8BDD\u3002"),{id:e.sessionId})))}return g.create(t,s,{id:e.sessionId})}u(uo,"createSessionManager");function fo(e,t,s,l,n){const a={},p=[];let o=!1;if(e.provider&&!e.model&&p.push({type:"error",message:`--provider requires --model (for example: --provider ${e.provider} --model <pattern>)`}),e.model){const r=Tt({cliProvider:e.provider,cliModel:e.model,cliThinking:e.thinking,modelRuntime:l});r.warning&&p.push({type:"warning",message:r.warning}),r.error&&p.push({type:"error",message:r.error}),r.model&&(a.model=r.model,!e.thinking&&r.thinkingLevel&&(a.thinkingLevel=r.thinkingLevel,o=!0))}if(!a.model&&t.length>0&&!s){const r=n.getDefaultProvider(),P=n.getDefaultModel(),A=r&&P?l.getModel(r,P):void 0,S=A?t.find(x=>We(x.model,A)):void 0;S?(a.model=S.model,!e.thinking&&S.thinkingLevel&&(a.thinkingLevel=S.thinkingLevel)):(a.model=t[0].model,!e.thinking&&t[0].thinkingLevel&&(a.thinkingLevel=t[0].thinkingLevel))}return e.thinking&&(a.thinkingLevel=e.thinking),t.length>0&&(a.scopedModels=t.map(r=>({model:r.model,thinkingLevel:r.thinkingLevel}))),e.noTools?a.noTools="all":e.noBuiltinTools&&(a.noTools="builtin"),e.tools&&(a.tools=[...e.tools]),e.excludeTools&&(a.excludeTools=[...e.excludeTools]),a.sandbox={defaultLevel:"workspace-write",...e.sandbox?{level:e.sandbox}:{},...e.sandboxAllowDomains?{allowedDomains:[...e.sandboxAllowDomains]}:{}},a.defaultActiveTools=["read","bash","edit","write","process"],{options:a,cliThinkingFromModel:o,diagnostics:p}}u(fo,"buildSessionOptions");function L(e,t){return t?.map(s=>Qt(s)?ye(s,e):s)}u(L,"resolveCliPaths");async function po(e,t){return ct(t,At(e),[{label:"Continue",value:e.fallbackCwd},{label:"Cancel",value:void 0}])}u(po,"promptForMissingSessionCwd");async function is(e,t){Ft();const s=[...Ht,...t?.extensionFactories??[]],l=e.includes("--offline")||Se(process.env.PI_OFFLINE);if(l&&(process.env.PI_OFFLINE="1",process.env.PI_SKIP_VERSION_CHECK="1",process.env.DAL_SKIP_VERSION_CHECK="1"),await io(e))return;process.platform==="win32"&&Zt(ft()),Yt();const n=process.cwd(),a=ut(),p=$.create(n,a,{projectTrusted:!1});if(ge(p.getGlobalSettings().httpProxy),jt(),_t(),Nt(),he(),await Jt(e,{extensionFactories:s})){const i=process.exitCode??0;if(process.platform==="win32"&&i===0&&e[0]==="update")return;process.exit(i);return}if(await Gt(e,{extensionFactories:s}))return;if(e[0]==="remote"){const{defaultRemoteDeps:i,runRemoteCommand:m}=await import("@dalcode/dal-remote/cli");process.exitCode=await m(e.slice(1),i(a));return}if(e[0]==="mcp"){const{runMcpCommand:i}=await Bt();process.exitCode=await i(e.slice(1),{cwd:n,agentDir:a});return}const o=ue(e);if(o.diagnostics.length>0){for(const i of o.diagnostics){const m=i.type==="error"?d.red:d.yellow;console.error(m(f(i.type==="error"?c("\u9519\u8BEF\uFF1A{message}"):c("\u8B66\u544A\uFF1A{message}"),{message:i.message})))}o.diagnostics.some(i=>i.type==="error")&&process.exit(1)}if(h("parseArgs"),o.version&&(console.log(pt),process.exit(0)),o.export){let i;try{const m=o.messages.length>0?o.messages[0]:void 0;i=await yt(o.export,m)}catch(m){const E=m instanceof Error?m.message:c("\u5BFC\u51FA\u4F1A\u8BDD\u5931\u8D25");console.error(d.red(f(c("\u9519\u8BEF\uFF1A{message}"),{message:E}))),process.exit(1)}console.log(f(c("\u5DF2\u5BFC\u51FA\u5230\uFF1A{path}"),{path:i})),process.exit(0)}let r=oo(o,process.stdin.isTTY,process.stdout.isTTY);r!=="interactive"&&!no(o)&&Ct(),(o.mode==="rpc"||o.mode==="acp")&&o.fileArgs.length>0&&(console.error(d.red(f(c("\u9519\u8BEF\uFF1A{mode} \u6A21\u5F0F\u4E0D\u652F\u6301 @\u6587\u4EF6 \u53C2\u6570"),{mode:o.mode.toUpperCase()}))),process.exit(1)),lo(o),co(o);const{migratedAuthProviders:A,deprecationWarnings:S}=Kt(n);h("runMigrations");const x=$.create(n,a),_=ve(x);r==="interactive"&&!o.help&&o.listModels===void 0&&at()&&(await lt(x),h("firstTimeSetup")),r==="interactive"&&o.useTheme!==void 0&&x.applyOverrides({theme:o.useTheme});const V=process.env[dt],z=(o.sessionDir?Xt(o.sessionDir):void 0)??(V?mt(V):void 0)??x.getSessionDir();let y=await uo(o,n,z,x);const b=bt(y,n);if(b)if(r==="interactive"){const i=await po(b,x);i||process.exit(0),y=g.open(b.sessionFile,z,i)}else console.error(d.red(new Et(b).message)),process.exit(1);if(o.name!==void 0){const i=qe(o.name);i===void 0&&(console.error(d.red(c("\u9519\u8BEF\uFF1A--name \u7684\u503C\u4E0D\u80FD\u4E3A\u7A7A"))),process.exit(1)),y.appendSessionInfo(i)}h("createSessionManager");const Y=new Lt(a),G=y.getCwd(),Me=o.projectTrustOverride===void 0&&!we(G)?G:void 0,J=o.help||o.listModels!==void 0?"print":r,Q=new Map,X=L(n,o.extensions)??[];Dt(X);const ke=[...Ot(),...X],Ce=L(n,o.skills),Ie=L(n,o.promptTemplates),Ae=L(n,o.themes),be=u(async({cwd:i,agentDir:m,sessionManager:E,sessionStartEvent:ie,projectTrustContext:Le})=>{const re=ie===void 0,ae=[],le=Q.get(i),ce=we(i),de=o.projectTrustOverride===void 0&&le===void 0&&ce,_e=de?!1:le??o.projectTrustOverride??(!ce||Y.get(i)===!0),je=$.create(i,m,{projectTrusted:_e}),R=await vt({cwd:i,agentDir:m,settingsManager:je,modelRuntimeSignal:AbortSignal.timeout(15e3),extensionFlagValues:o.unknownFlags,resourceLoaderReloadOptions:de?{resolveProjectTrust:u(async({extensionsResult:C})=>{const T=await It({cwd:i,trustStore:Y,trustOverride:o.projectTrustOverride,defaultProjectTrust:x.getDefaultProjectTrust(),extensionsResult:C,projectTrustContext:Le??it({cwd:i,mode:re?J:r,settingsManager:x,hasUI:re&&J==="interactive"}),onExtensionError:u(Be=>ae.push({type:"warning",message:Be}),"onExtensionError")});return Q.set(i,T),T},"resolveProjectTrust")}:void 0,resourceLoaderOptions:{additionalExtensionPaths:ke,additionalSkillPaths:Ce,additionalPromptTemplatePaths:Ie,additionalThemePaths:Ae,noExtensions:o.noExtensions,disabledBuiltinExtensions:o.noMcp?["mcp"]:void 0,noSkills:o.noSkills,noPromptTemplates:o.noPromptTemplates,noThemes:o.noThemes,noContextFiles:o.noContextFiles,systemPrompt:o.systemPrompt,appendSystemPrompt:o.appendSystemPrompt,extensionFactories:s}}),{settingsManager:N,modelRuntime:H,resourceLoader:me}=R,F=[...ae,...R.diagnostics,...ve(N),...me.getExtensions().errors.map(({path:C,error:T})=>({type:"error",message:`Failed to load extension "${C}": ${T}`})),...(me.getExtensions().warnings??[]).map(({path:C,warning:T})=>({type:"warning",message:`Extension package "${C}": ${T}`}))],B=o.models??N.getEnabledModels(),Oe=B&&B.length>0?await Pt(B,H,{signal:AbortSignal.timeout(15e3)}):[],{options:v,cliThinkingFromModel:De,diagnostics:Ne}=fo(o,Oe,E.buildSessionContext().messages.length>0,H,N);F.push(...Ne),o.apiKey&&(v.model?await H.setRuntimeApiKey(v.model.provider,o.apiKey):F.push({type:"error",message:c("\u4F7F\u7528 --api-key \u65F6\u9700\u8981\u901A\u8FC7 --model\u3001--provider/--model \u6216 --models \u6307\u5B9A\u6A21\u578B")}));const M=await ht({services:R,sessionManager:E,sessionStartEvent:ie,model:v.model,thinkingLevel:v.thinkingLevel,scopedModels:v.scopedModels,tools:v.tools,excludeTools:v.excludeTools,noTools:v.noTools,customTools:v.customTools,sandbox:v.sandbox,defaultActiveTools:v.defaultActiveTools}),He=o.thinking!==void 0||De;M.session.model&&He&&M.session.setThinkingLevel(M.session.thinkingLevel);const k=M.session.getSandboxStatus();return k&&k.level!=="off"&&!k.enforced&&F.push({type:"warning",message:f(c("\u547D\u4EE4\u6C99\u7BB1\u4E0D\u53EF\u7528\uFF08{level}\uFF09\uFF1A{reason} shell \u547D\u4EE4\u4F1A\u88AB\u62D2\u7EDD\uFF1B\u786E\u5B9A\u4E0D\u8981\u6C99\u7BB1\u8BF7\u7528 --sandbox off\u3002"),{level:k.level,reason:k.unavailableReason??""})}),{...M,services:R,diagnostics:F}},"createRuntime");h("createRuntime");const w=await gt(be,{cwd:y.getCwd(),agentDir:a,sessionManager:y});h("createAgentSessionRuntime");const{services:Ee,session:Re,modelFallbackMessage:Fe}=w,{settingsManager:j,modelRuntime:Z,resourceLoader:ee}=Ee;if(Ve(o,new Set(ee.getExtensions().extensions.flatMap(i=>[...i.flags].filter(([,m])=>m.type==="boolean").map(([m])=>m)))),ge(j.getGlobalSettings().httpProxy),he(j.getHttpIdleTimeoutMs()),o.help){q(_);const i=ee.getExtensions().extensions.flatMap(m=>Array.from(m.flags.values()));Ue(i),process.exit(0)}if(o.listModels!==void 0){q(xe([..._,...w.diagnostics]));const i=typeof o.listModels=="string"?o.listModels:void 0;await nt(Z,i,AbortSignal.timeout(15e3)),process.exit(0)}let O;r!=="rpc"&&r!=="acp"&&(O=await to(),O!==void 0&&r==="interactive"&&(r="print")),h("readPipedStdin");const{initialMessage:D,initialImages:te}=await ro(o,O);h("prepareInitialMessage"),zt(j.getTheme(),r==="interactive"),h("initTheme"),r==="interactive"&&S.length>0&&await $t(S),h("resolveModelScope");const oe=xe([..._,...w.diagnostics]),se=w.diagnostics.some(i=>i.type==="error");(r!=="interactive"||se)&&q(oe),se&&(w.diagnostics.some(i=>i.message.includes("Failed to load extension"))&&console.error(d.yellow(eo())),process.exit(1)),h("createAgentSession"),r!=="interactive"&&!Re.model&&(console.error(d.red(xt())),process.exit(1));const ne=Se(process.env.PI_STARTUP_BENCHMARK);if(ne&&r!=="interactive"&&(console.error(d.red(c("\u9519\u8BEF\uFF1API_STARTUP_BENCHMARK \u53EA\u652F\u6301\u4EA4\u4E92\u6A21\u5F0F"))),process.exit(1)),!l&&(r==="rpc"||r==="acp")){const i=new AbortController,m=setTimeout(()=>i.abort(),15e3);Z.refresh({signal:i.signal}).catch(()=>{}).finally(()=>clearTimeout(m))}if(r==="rpc")I(),await Vt(w);else if(r==="acp")I(),await qt(w);else if(r==="interactive"){const i=new Wt(w,{migratedProviders:A,startupDiagnostics:oe,modelFallbackMessage:Fe,autoTrustOnReloadCwd:Me,initialMessage:D,initialImages:te,initialMessages:o.messages,verbose:o.verbose,tuiMode:o.tuiMode,initialThemeSetting:o.useTheme});if(ne){await i.init(),h("interactiveMode.init"),await new Promise(m=>setTimeout(m,150)),i.stop(),W(),I(),process.stdout.writableLength>0&&await new Promise(m=>process.stdout.once("drain",m)),process.stderr.writableLength>0&&await new Promise(m=>process.stderr.once("drain",m));return}I(),await i.run()}else{if(I(),!D&&o.messages.length===0){console.error(d.red(c('\u9519\u8BEF\uFF1A\u6CA1\u6709\u8981\u53D1\u7ED9\u52A9\u624B\u7684\u5185\u5BB9\u3002\u7528\u6CD5\uFF1Adal -p "\u4EFB\u52A1"\uFF0C\u6216\u901A\u8FC7\u6807\u51C6\u8F93\u5165\u4F20\u5165\u3002'))),await w.dispose(),process.exitCode=1;return}const i=await Ut(w,{mode:so(r),messages:o.messages,initialMessage:D,initialImages:te});W(),kt(),i!==0&&(process.exitCode=i);return}}u(is,"main");export{uo as createSessionManager,is as main};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var a=Object.defineProperty;var u=(e,t)=>a(e,"name",{value:t,configurable:!0});import{t as d}from"../../dal/i18n.js";const f=4e3,g=32e3,_=256;function x(e){return e.length<=f?e:`${e.slice(0,f)}\u2026`}u(x,"capString");function y(e){if(!e)return{};let t;try{t=JSON.stringify(e,(n,s)=>typeof s=="string"?x(s):s)}catch{return{argsTruncated:!0}}return t===void 0?{}:t.length>g?{argsTruncated:!0}:{args:JSON.parse(t)}}u(y,"capApprovalArgs");function c(e){return e==="deny"?d("\u62D2\u7EDD"):e==="allow_session"?d("\u672C\u4F1A\u8BDD\u5185\u90FD\u5141\u8BB8"):d("\u4EC5\u672C\u6B21\u5141\u8BB8")}u(c,"defaultLabel");function R(e,t,n,s){const i=n.options;if(new Set(i).size!==i.length||i.length===0)return;let o;if(t==="select"){const r=s.options??[];if(r.length!==i.length)return;o=[...r]}else{if(i.length!==2||i[1]!=="deny"||i[0]==="deny")return;o=[c(i[0]),c("deny")]}return{request:{type:"approval_request",id:e,dialogMethod:t,source:n.source,...n.toolCallId?{toolCallId:n.toolCallId}:{},...n.toolName?{toolName:n.toolName}:{},...y(n.args),...n.risk?{risk:{...n.risk}}:{},title:n.title,...n.description?{description:n.description}:{},options:i.map((r,l)=>({id:r,kind:r,label:o[l]})),...s.timeout?{timeout:s.timeout}:{}},responseFor(r){const l=i.indexOf(r);return t==="select"?{type:"extension_ui_response",id:e,value:o[l]}:{type:"extension_ui_response",id:e,confirmed:l===0}},kindOf(r){if(!("cancelled"in r&&r.cancelled)){if(t==="select"){if(!("value"in r))return;const l=o.indexOf(r.value);return l>=0?i[l]:void 0}if("confirmed"in r)return r.confirmed?i[0]:"deny"}}}}u(R,"openApproval");class S{static{u(this,"ResolvedApprovals")}entries=new Map;remember(t,n,s){for(this.entries.set(t,{...n?{optionId:n}:{},via:s});this.entries.size>_;){const i=this.entries.keys().next().value;if(i===void 0)break;this.entries.delete(i)}}get(t){return this.entries.get(t)}}export{g as APPROVAL_ARGS_MAX,f as APPROVAL_ARG_STRING_MAX,S as ResolvedApprovals,y as capApprovalArgs,R as openApproval};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var a=Object.defineProperty;var d=(n,e)=>a(n,"name",{value:e,configurable:!0});function u(n){const e=n.timestamp;return typeof e=="number"&&Number.isFinite(e)&&e>0?e:void 0}d(u,"ownTimestamp");function f(n){const e=n.role;return`${String(e)}:${u(n)??""}`}d(f,"keyOf");function y(n,e){const s=new Map;for(const r of e.entries){const o=Date.parse(r.sourceEntry.timestamp),t=Number.isFinite(o)?o:void 0;for(const m of r.messages){const i=f(m),c=s.get(i)??[];c.push({entryId:r.sourceEntry.id,...t!==void 0?{recordedAt:t}:{}}),s.set(i,c)}}return n.map(r=>{const o=u(r),t=s.get(f(r))?.shift();return{...o!==void 0?{timestamp:o}:t?.recordedAt!==void 0?{timestamp:t.recordedAt}:{},...t?.recordedAt!==void 0?{recordedAt:t.recordedAt}:{},...t?{entryId:t.entryId}:{}}})}d(y,"buildMessageMeta");export{y as buildMessageMeta};
|
|
@@ -4,11 +4,12 @@ import type { PromptDisposition, QueuedInputDisposition, SessionStats } from "..
|
|
|
4
4
|
import type { BackgroundProcessInfo } from "../../core/background-processes.ts";
|
|
5
5
|
import type { BashResult } from "../../core/bash-executor.ts";
|
|
6
6
|
import type { CompactionResult } from "../../core/compaction/index.ts";
|
|
7
|
+
import type { ApprovalOptionKind } from "../../core/extensions/types.ts";
|
|
7
8
|
import type { HostCapability } from "../../core/host-capabilities.ts";
|
|
8
9
|
import type { SandboxStatus } from "../../core/sandbox/shell-sandbox.ts";
|
|
9
10
|
import type { SessionEntry, SessionTreeNode } from "../../core/session-manager.ts";
|
|
10
11
|
import type { JsonAgentSessionEvent } from "../json-event.ts";
|
|
11
|
-
import type { RpcExtensionUIRequest, RpcExtensionUIResponse, RpcHostRequest, RpcSessionState, RpcSlashCommand, TelemetryConsentStatus } from "./rpc-types.ts";
|
|
12
|
+
import type { RpcApprovalRequest, RpcExtensionUIRequest, RpcExtensionUIResponse, RpcHostRequest, RpcMessageMeta, RpcSessionState, RpcSlashCommand, TelemetryConsentStatus } from "./rpc-types.ts";
|
|
12
13
|
export interface RpcClientOptions {
|
|
13
14
|
cliPath?: string;
|
|
14
15
|
cwd?: string;
|
|
@@ -38,6 +39,7 @@ export type RpcExitListener = (exit: RpcProcessExit) => void;
|
|
|
38
39
|
export declare function rpcStderrTail(stderr: string): string;
|
|
39
40
|
export type RpcExtensionUIHandler = (request: RpcExtensionUIRequest) => Promise<RpcExtensionUIResponse | undefined> | RpcExtensionUIResponse | undefined;
|
|
40
41
|
export type RpcHostRequestHandler = (request: RpcHostRequest) => Promise<unknown> | unknown;
|
|
42
|
+
export type RpcApprovalHandler = (request: RpcApprovalRequest) => Promise<ApprovalOptionKind | undefined> | ApprovalOptionKind | undefined;
|
|
41
43
|
export declare class RpcClient {
|
|
42
44
|
private process;
|
|
43
45
|
private stopReadingStdout;
|
|
@@ -45,6 +47,7 @@ export declare class RpcClient {
|
|
|
45
47
|
private pendingRequests;
|
|
46
48
|
private requestId;
|
|
47
49
|
private extensionUIHandler;
|
|
50
|
+
private approvalHandler;
|
|
48
51
|
private hostRequestHandler;
|
|
49
52
|
private stderr;
|
|
50
53
|
private exitError;
|
|
@@ -60,6 +63,7 @@ export declare class RpcClient {
|
|
|
60
63
|
getExit(): RpcProcessExit | undefined;
|
|
61
64
|
onEvent(listener: RpcEventListener): () => void;
|
|
62
65
|
setExtensionUIHandler(handler: RpcExtensionUIHandler | null): void;
|
|
66
|
+
setApprovalHandler(handler: RpcApprovalHandler | null): void;
|
|
63
67
|
getStderr(): string;
|
|
64
68
|
prompt(message: string, images?: ImageContent[], streamingBehavior?: "steer" | "followUp"): Promise<PromptDisposition>;
|
|
65
69
|
steer(message: string, images?: ImageContent[]): Promise<QueuedInputDisposition>;
|
|
@@ -144,6 +148,15 @@ export declare class RpcClient {
|
|
|
144
148
|
getLastAssistantText(): Promise<string | null>;
|
|
145
149
|
setSessionName(name: string): Promise<void>;
|
|
146
150
|
getMessages(): Promise<AgentMessage[]>;
|
|
151
|
+
getMessagesWithMeta(): Promise<{
|
|
152
|
+
messages: AgentMessage[];
|
|
153
|
+
meta: RpcMessageMeta[];
|
|
154
|
+
}>;
|
|
155
|
+
respondToApproval(approvalId: string, optionId: ApprovalOptionKind): Promise<{
|
|
156
|
+
accepted: boolean;
|
|
157
|
+
optionId?: ApprovalOptionKind;
|
|
158
|
+
via: string;
|
|
159
|
+
}>;
|
|
147
160
|
getCommands(): Promise<RpcSlashCommand[]>;
|
|
148
161
|
setHostCapabilities(capabilities: HostCapability[], handler: RpcHostRequestHandler | null): Promise<HostCapability[]>;
|
|
149
162
|
waitForIdle(timeout?: number): Promise<void>;
|
|
@@ -151,6 +164,7 @@ export declare class RpcClient {
|
|
|
151
164
|
promptAndWait(message: string, images?: ImageContent[], timeout?: number): Promise<JsonAgentSessionEvent[]>;
|
|
152
165
|
private handleLine;
|
|
153
166
|
private answerExtensionUIRequest;
|
|
167
|
+
private answerApprovalRequest;
|
|
154
168
|
private answerHostRequest;
|
|
155
169
|
private reportExit;
|
|
156
170
|
private createExitWhileWaitingError;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
2
|
-
`);return e.length>
|
|
1
|
+
var w=Object.defineProperty;var h=(p,t)=>w(p,"name",{value:t,configurable:!0});import{spawn as _}from"node:child_process";import{attachJsonlLineReader as f,serializeJsonLine as d}from"./jsonl.js";const m=20,u=2e3;function E(p){const e=p.split(/\r?\n/u).filter(s=>s.trim().length>0).slice(-m).join(`
|
|
2
|
+
`);return e.length>u?e.slice(-u):e}h(E,"rpcStderrTail");const x=new Set(["select","confirm","input","editor","requestInput","requestChoice"]);class S{static{h(this,"RpcClient")}process=null;stopReadingStdout=null;eventListeners=[];pendingRequests=new Map;requestId=0;extensionUIHandler=null;approvalHandler=null;hostRequestHandler=null;stderr="";exitError=null;options;exitListeners=new Set;exitInfo;stopping=!1;turnInFlight=!1;constructor(t={}){this.options=t}async start(){if(this.process)throw new Error("Client already started");this.exitError=null,this.exitInfo=void 0,this.stopping=!1,this.turnInFlight=!1;const t=this.options.cliPath??"dist/cli.js",e=["--mode","rpc"];this.options.provider&&e.push("--provider",this.options.provider),this.options.model&&e.push("--model",this.options.model),this.options.args&&e.push(...this.options.args);const s=_(process.execPath,[t,...e],{cwd:this.options.cwd,env:{...this.options.inheritEnv===!1?{}:process.env,...this.options.env},stdio:["pipe","pipe","pipe"]});if(this.process=s,s.stderr?.on("data",r=>{this.stderr+=r.toString(),process.stderr.write(r)}),s.once("exit",(r,n)=>{if(this.process!==s)return;this.reportExit({code:r,signal:n});const o=this.createProcessExitError(r,n);this.exitError=o,this.rejectPendingRequests(o)}),s.once("error",r=>{if(this.process!==s)return;const n=new Error(`Agent process error: ${r.message}. Stderr: ${this.stderr}`);s.exitCode===null&&s.signalCode===null&&this.reportExit({code:null,signal:null,error:r.message}),this.exitError=n,this.rejectPendingRequests(n)}),s.stdin?.on("error",r=>{if(this.process!==s)return;const n=this.exitError??new Error(`Agent process stdin error: ${r.message}. Stderr: ${this.stderr}`);this.exitError=n,this.rejectPendingRequests(n)}),this.stopReadingStdout=f(s.stdout,r=>{this.handleLine(r)}),await new Promise(r=>setTimeout(r,100)),this.process.exitCode!==null){const r=this.exitError??this.createProcessExitError(this.process.exitCode,this.process.signalCode);throw this.exitError=r,r}}async stop(){this.process&&(this.stopReadingStdout?.(),this.stopReadingStdout=null,this.stopping=!0,this.process.kill("SIGTERM"),await new Promise(t=>{const e=setTimeout(()=>{this.process?.kill("SIGKILL"),t()},1e3);this.process?.on("exit",()=>{clearTimeout(e),t()})}),this.process=null,this.pendingRequests.clear())}onExit(t){const e=this.exitInfo;return e?(queueMicrotask(()=>t(e)),()=>{}):(this.exitListeners.add(t),()=>{this.exitListeners.delete(t)})}getExit(){return this.exitInfo}onEvent(t){return this.eventListeners.push(t),()=>{const e=this.eventListeners.indexOf(t);e!==-1&&this.eventListeners.splice(e,1)}}setExtensionUIHandler(t){this.extensionUIHandler=t}setApprovalHandler(t){this.approvalHandler=t}getStderr(){return this.stderr}async prompt(t,e,s){const r=await this.send({type:"prompt",message:t,images:e,streamingBehavior:s}),{disposition:n}=this.getData(r);return n!=="handled"&&(this.turnInFlight=!0),n}async steer(t,e){const s=await this.send({type:"steer",message:t,images:e});return this.getData(s).disposition}async followUp(t,e){const s=await this.send({type:"follow_up",message:t,images:e});return this.getData(s).disposition}async abort(){await this.send({type:"abort"})}async clearQueue(){const t=await this.send({type:"clear_queue"});return this.getData(t)}async newSession(t){const e=await this.send({type:"new_session",parentSession:t});return this.getData(e)}async getState(){const t=await this.send({type:"get_state"});return this.getData(t)}async setModel(t,e){const s=await this.send({type:"set_model",provider:t,modelId:e});return this.getData(s)}async cycleModel(){const t=await this.send({type:"cycle_model"});return this.getData(t)}async getAvailableModels(){const t=await this.send({type:"get_available_models"});return this.getData(t).models}async setThinkingLevel(t){await this.send({type:"set_thinking_level",level:t})}async cycleThinkingLevel(){const t=await this.send({type:"cycle_thinking_level"});return this.getData(t)}async getAvailableThinkingLevels(){const t=await this.send({type:"get_available_thinking_levels"});return this.getData(t).levels}async setSteeringMode(t){await this.send({type:"set_steering_mode",mode:t})}async setFollowUpMode(t){await this.send({type:"set_follow_up_mode",mode:t})}async compact(t){const e=await this.send({type:"compact",customInstructions:t});return this.getData(e)}async setAutoCompaction(t){await this.send({type:"set_auto_compaction",enabled:t})}async setAutoRetry(t){await this.send({type:"set_auto_retry",enabled:t})}async abortRetry(){await this.send({type:"abort_retry"})}async bash(t){const e=await this.send({type:"bash",command:t});return this.getData(e)}async abortBash(){await this.send({type:"abort_bash"})}async getSandboxStatus(){const t=await this.send({type:"get_sandbox_status"});return this.getData(t)}async listBackgroundProcesses(){const t=await this.send({type:"list_background_processes"});return this.getData(t).processes}async readBackgroundProcess(t,e){const s=await this.send({type:"read_background_process",processId:t,...e!==void 0?{tail:e}:{}});return this.getData(s)}async stopBackgroundProcess(t){const e=await this.send({type:"stop_background_process",processId:t});return this.getData(e).process}async setEnvironment(t){const e=await this.send({type:"set_environment",...t});return this.getData(e).changed}async setTelemetryConsent(t){const e=await this.send({type:"set_telemetry_consent",usage:t.usage,...t.failures!==void 0?{failures:t.failures}:{}});return this.getData(e)}async getSessionStats(){const t=await this.send({type:"get_session_stats"});return this.getData(t)}async exportHtml(t){const e=await this.send({type:"export_html",outputPath:t});return this.getData(e)}async switchSession(t){const e=await this.send({type:"switch_session",sessionPath:t});return this.getData(e)}async fork(t){const e=await this.send({type:"fork",entryId:t});return this.getData(e)}async clone(){const t=await this.send({type:"clone"});return this.getData(t)}async getForkMessages(){const t=await this.send({type:"get_fork_messages"});return this.getData(t).messages}async getEntries(t){const e=await this.send({type:"get_entries",since:t});return this.getData(e)}async getTree(){const t=await this.send({type:"get_tree"});return this.getData(t)}async getLastAssistantText(){const t=await this.send({type:"get_last_assistant_text"});return this.getData(t).text}async setSessionName(t){await this.send({type:"set_session_name",name:t})}async getMessages(){const t=await this.send({type:"get_messages"});return this.getData(t).messages}async getMessagesWithMeta(){const t=await this.send({type:"get_messages"});return this.getData(t)}async respondToApproval(t,e){const s=await this.send({type:"approval_response",optionId:e},t);return this.getData(s)}async getCommands(){const t=await this.send({type:"get_commands"});return this.getData(t).commands}async setHostCapabilities(t,e){this.hostRequestHandler=e;const s=await this.send({type:"set_host_capabilities",capabilities:t});return this.getData(s).capabilities}waitForIdle(t=6e4){return new Promise((e,s)=>{const r=setTimeout(()=>{n(),o(),s(new Error(`Timeout waiting for agent to become idle. Stderr: ${this.stderr}`))},t),n=this.onEvent(i=>{i.type==="agent_settled"&&(clearTimeout(r),n(),o(),e())}),o=this.onExit(i=>{clearTimeout(r),n(),s(this.createExitWhileWaitingError(i))})})}collectEvents(t=6e4){return new Promise((e,s)=>{const r=[],n=setTimeout(()=>{o(),i(),s(new Error(`Timeout collecting events. Stderr: ${this.stderr}`))},t),o=this.onEvent(a=>{r.push(a),a.type==="agent_settled"&&(clearTimeout(n),o(),i(),e(r))}),i=this.onExit(a=>{clearTimeout(n),o(),s(this.createExitWhileWaitingError(a))})})}async promptAndWait(t,e,s=6e4){const r=this.collectEvents(s);return await this.prompt(t,e),r}handleLine(t){try{const e=JSON.parse(t);if(e.type==="agent_start"?this.turnInFlight=!0:e.type==="agent_settled"&&(this.turnInFlight=!1),e.type==="response"&&e.id&&this.pendingRequests.has(e.id)){const s=this.pendingRequests.get(e.id);this.pendingRequests.delete(e.id),s.resolve(e);return}if(e.type==="approval_request"&&this.approvalHandler&&this.answerApprovalRequest(e),e.type==="extension_ui_request"&&x.has(e.method)&&!(e.approval===!0&&this.approvalHandler)&&this.answerExtensionUIRequest(e),e.type==="host_request"){this.answerHostRequest(e);return}for(const s of[...this.eventListeners])s(e)}catch{}}async answerExtensionUIRequest(t){const e={type:"extension_ui_response",id:t.id,cancelled:!0};let s=e;if(this.extensionUIHandler)try{s=await this.extensionUIHandler(t)??e}catch{s=e}const r=this.process?.stdin;if(!(!r||r.destroyed||!r.writable))try{r.write(d({...s,id:t.id}))}catch{}}async answerApprovalRequest(t){let e="deny";try{e=await this.approvalHandler?.(t)??"deny"}catch{e="deny"}try{await this.respondToApproval(t.id,e)}catch{}}async answerHostRequest(t){let e;if(!this.hostRequestHandler)e={type:"host_response",id:t.id,error:"host has no handler for host requests"};else try{const r=await this.hostRequestHandler(t);e={type:"host_response",id:t.id,result:r??null}}catch(r){e={type:"host_response",id:t.id,error:r instanceof Error?r.message:String(r)}}const s=this.process?.stdin;if(!(!s||s.destroyed||!s.writable))try{s.write(d(e))}catch{}}reportExit(t){if(this.exitInfo)return;const e={code:t.code,signal:t.signal,stderrTail:E(this.stderr),expected:this.stopping,turnInFlight:this.turnInFlight,...t.error?{error:t.error}:{}};this.exitInfo=e,this.turnInFlight=!1;const s=[...this.exitListeners];this.exitListeners.clear();for(const r of s)try{r(e)}catch{}}createExitWhileWaitingError(t){const e=t.signal?`signal ${t.signal}`:`code ${t.code??"unknown"}`,s=t.stderrTail?`
|
|
3
3
|
Last stderr output:
|
|
4
|
-
${t.stderrTail}`:"";return new Error(`Agent process exited (${e}) before the turn finished.${s}`)}createProcessExitError(t,e){return new Error(`Agent process exited (code=${t} signal=${e}). Stderr: ${this.stderr}`)}rejectPendingRequests(t){for(const e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}async send(t){const
|
|
4
|
+
${t.stderrTail}`:"";return new Error(`Agent process exited (${e}) before the turn finished.${s}`)}createProcessExitError(t,e){return new Error(`Agent process exited (code=${t} signal=${e}). Stderr: ${this.stderr}`)}rejectPendingRequests(t){for(const e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}async send(t,e){const s=this.process,r=s?.stdin;if(!s||!r)throw new Error("Client not started");if(this.exitError)throw this.exitError;if(s.exitCode!==null){const i=this.createProcessExitError(s.exitCode,s.signalCode);throw this.exitError=i,i}if(r.destroyed||!r.writable){const i=new Error(`Agent process stdin is not writable. Stderr: ${this.stderr}`);throw this.exitError=i,i}const n=e??`req_${++this.requestId}`,o={...t,id:n};return new Promise((i,a)=>{const l=setTimeout(()=>{this.pendingRequests.delete(n),a(new Error(`Timeout waiting for response to ${t.type}. Stderr: ${this.stderr}`))},this.options.requestTimeoutMs??3e4);this.pendingRequests.set(n,{resolve:h(c=>{clearTimeout(l),i(c)},"resolve"),reject:h(c=>{clearTimeout(l),a(c)},"reject")});try{r.write(d(o))}catch(c){const g=c instanceof Error?c:new Error(String(c)),y=this.pendingRequests.get(n);this.pendingRequests.delete(n),y?.reject(g)}})}getData(t){if(!t.success){const s=t;throw new Error(s.error)}return t.data}}export{S as RpcClient,E as rpcStderrTail};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var N=Object.defineProperty;var i=(u,o)=>N(u,"name",{value:o,configurable:!0});import*as p from"node:crypto";import{resolveExtensionNotify as O}from"../../core/extensions/index.js";import{DEFAULT_HOST_CALL_TIMEOUT_MS as G,getHostCapabilities as L,HostCallError as x,parseHostCapabilities as $}from"../../core/host-capabilities.js";import{flushRawStdout as J,takeOverStdout as W,waitForRawStdoutBackpressure as I,writeRawStdout as j}from"../../core/output-guard.js";import{killTrackedDetachedChildren as H}from"../../utils/shell.js";import{theme as z}from"../interactive/theme/theme.js";import{toJsonEvent as K}from"../json-event.js";import{applyEnvironmentUpdate as Q}from"./environment-update.js";import{attachJsonlLineReader as X,serializeJsonLine as Y}from"./jsonl.js";const Z="Prompt aborted before it started";async function ce(u){W();let o=u.session,k,S;const c=i(e=>{j(Y(e))},"output"),r=i((e,t,s)=>s===void 0?{id:e,type:"response",command:t,success:!0}:{id:e,type:"response",command:t,success:!0,data:s},"success"),d=i((e,t,s)=>({id:e,type:"response",command:t,success:!1,error:s}),"error"),m=new Map,y=new Map,q=i((e,t)=>{const s=p.randomUUID();return new Promise((n,a)=>{const l=i(()=>{clearTimeout(b),t.signal?.removeEventListener("abort",g),y.delete(s)},"cleanup"),w=i(_=>{l(),c({type:"host_request_cancelled",id:s}),a(_)},"giveUp"),g=i(()=>w(new x("aborted","host call aborted")),"onAbort"),b=setTimeout(()=>w(new x("timeout","host did not answer in time")),t.timeoutMs??G);t.signal?.addEventListener("abort",g,{once:!0}),y.set(s,{resolve:i(_=>{l(),n(_)},"resolve"),reject:i(_=>{l(),a(_)},"reject")});const v={type:"host_request",id:s,capability:e.capability,method:e.method,params:e.params};c(v)})},"rpcHostTransport");let E=!1,C=!1;const U=[];function h(e,t,s,n){if(e?.signal?.aborted)return Promise.resolve(t);const a=p.randomUUID();return new Promise((l,w)=>{let g;const b=i(()=>{g&&clearTimeout(g),e?.signal?.removeEventListener("abort",v),m.delete(a)},"cleanup"),v=i(()=>{b(),l(t)},"onAbort");e?.signal?.addEventListener("abort",v,{once:!0}),e?.timeout&&(g=setTimeout(()=>{b(),l(t)},e.timeout)),m.set(a,{resolve:i(_=>{b(),l(n(_))},"resolve"),reject:w}),c({type:"extension_ui_request",id:a,...s})})}i(h,"createDialogPromise");const A=i(()=>({select:i((e,t,s)=>h(s,void 0,{method:"select",title:e,options:t,timeout:s?.timeout},n=>"cancelled"in n&&n.cancelled?void 0:"value"in n?n.value:void 0),"select"),confirm:i((e,t,s)=>h(s,!1,{method:"confirm",title:e,message:t,timeout:s?.timeout},n=>"cancelled"in n&&n.cancelled?!1:"confirmed"in n?n.confirmed:!1),"confirm"),input:i((e,t,s)=>h(s,void 0,{method:"input",title:e,placeholder:t,timeout:s?.timeout},n=>"cancelled"in n&&n.cancelled?void 0:"value"in n?n.value:void 0),"input"),notify(e,t){const s=O(e,t);c({type:"extension_ui_request",id:p.randomUUID(),method:"notify",message:s.message,notifyType:s.type})},setPanel(e,t){c({type:"extension_ui_request",id:p.randomUUID(),method:"setPanel",panelId:e,panel:t})},requestInput:i(e=>h(e,void 0,{method:"requestInput",title:e.title,placeholder:e.placeholder,timeout:e.timeout},t=>"cancelled"in t&&t.cancelled?void 0:"value"in t?t.value:void 0),"requestInput"),requestChoice:i(e=>h(e,void 0,{method:"requestChoice",title:e.title,items:e.items,timeout:e.timeout},t=>"cancelled"in t&&t.cancelled?void 0:"value"in t?t.value:void 0),"requestChoice"),onTerminalInput(){return()=>{}},setStatus(e,t){c({type:"extension_ui_request",id:p.randomUUID(),method:"setStatus",statusKey:e,statusText:t})},setWorkingMessage(e){},setWorkingVisible(e){},setWorkingIndicator(e){},setHiddenThinkingLabel(e){},setWidget(e,t,s){(t===void 0||Array.isArray(t))&&c({type:"extension_ui_request",id:p.randomUUID(),method:"setWidget",widgetKey:e,widgetLines:t,widgetPlacement:s?.placement})},setFooter(e){},setHeader(e){},setTitle(e){c({type:"extension_ui_request",id:p.randomUUID(),method:"setTitle",title:e})},async custom(){},pasteToEditor(e){this.setEditorText(e)},setEditorText(e){c({type:"extension_ui_request",id:p.randomUUID(),method:"set_editor_text",text:e})},getEditorText(){return""},async editor(e,t){const s=p.randomUUID();return new Promise((n,a)=>{m.set(s,{resolve:i(l=>{"cancelled"in l&&l.cancelled?n(void 0):"value"in l?n(l.value):n(void 0)},"resolve"),reject:a}),c({type:"extension_ui_request",id:s,method:"editor",title:e,prefill:t})})},addAutocompleteProvider(){},setEditorComponent(){},getEditorComponent(){},get theme(){return z},getAllThemes(){return[]},getTheme(e){},setTheme(e){return{success:!1,error:"Theme switching not supported in RPC mode"}},getToolsExpanded(){return!1},setToolsExpanded(e){}}),"createExtensionUIContext");u.setRebindSession(async()=>{await f()});const f=i(async()=>{o=u.session,k?.(),S?.(),k=o.subscribe(e=>{c(K(e)),e.type==="agent_settled"&&R()}),S=o.agent.subscribe(async()=>{await I()}),await o.bindExtensions({uiContext:A(),mode:"rpc",commandContextActions:{waitForIdle:i(()=>o.waitForIdle(),"waitForIdle"),newSession:i(async e=>u.newSession(e),"newSession"),fork:i(async(e,t)=>({cancelled:(await u.fork(e,t)).cancelled}),"fork"),navigateTree:i(async(e,t)=>({cancelled:(await o.navigateTree(e,{summarize:t?.summarize,customInstructions:t?.customInstructions,replaceInstructions:t?.replaceInstructions,label:t?.label})).cancelled}),"navigateTree"),switchSession:i(async(e,t)=>u.switchSession(e,t),"switchSession"),reload:i(async()=>{await o.reload()},"reload")},shutdownHandler:i(()=>{E=!0},"shutdownHandler"),onError:i(e=>{c({type:"extension_error",extensionPath:e.extensionPath,event:e.event,error:e.error})},"onError")})},"rebindSession"),F=i(()=>{const e=["SIGTERM","SIGINT"];process.platform!=="win32"&&e.push("SIGHUP");for(const t of e){const s=i(()=>{H(),T(t==="SIGHUP"?129:t==="SIGINT"?130:143,t)},"handler");process.on(t,s),U.push(()=>process.off(t,s))}},"registerSignalHandlers");await f(),F();const D=i(async e=>{const t=e.id;switch(e.type){case"prompt":{let s=!1,n=!1;o.prompt(e.message,{images:e.images,streamingBehavior:e.streamingBehavior,source:"rpc",preflightResult:i(a=>{if(a==="cancelled"){n=!0;return}s=!0,c(r(t,"prompt",{disposition:a}))},"preflightResult")}).then(()=>{n&&!s&&c(d(t,"prompt",Z))},a=>{s||c(d(t,"prompt",a.message))});return}case"steer":{const s=await o.steer(e.message,e.images,{source:"rpc"});return r(t,"steer",{disposition:s})}case"follow_up":{const s=await o.followUp(e.message,e.images,{source:"rpc"});return r(t,"follow_up",{disposition:s})}case"abort":return await o.abort(),r(t,"abort");case"clear_queue":return r(t,"clear_queue",o.clearQueue());case"new_session":{const s=e.parentSession?{parentSession:e.parentSession}:void 0,n=await u.newSession(s);return n.cancelled||await f(),r(t,"new_session",n)}case"get_state":{const s={model:o.model,thinkingLevel:o.thinkingLevel,isStreaming:o.isStreaming,isCompacting:o.isCompacting,steeringMode:o.steeringMode,followUpMode:o.followUpMode,sessionFile:o.sessionFile,sessionId:o.sessionId,sessionName:o.sessionName,autoCompactionEnabled:o.autoCompactionEnabled,messageCount:o.messages.length,pendingMessageCount:o.pendingMessageCount};return r(t,"get_state",s)}case"set_model":{const n=o.modelRuntime.getAvailableSnapshot().find(a=>a.provider===e.provider&&a.id===e.modelId);return n?(await o.setModel(n),r(t,"set_model",n)):d(t,"set_model",`Model not found: ${e.provider}/${e.modelId}`)}case"cycle_model":{const s=await o.cycleModel();return s?r(t,"cycle_model",s):r(t,"cycle_model",null)}case"get_available_models":{const s=o.modelRuntime.getAvailableSnapshot();return r(t,"get_available_models",{models:s})}case"set_thinking_level":return o.setThinkingLevel(e.level),r(t,"set_thinking_level");case"cycle_thinking_level":{const s=o.cycleThinkingLevel();return s?r(t,"cycle_thinking_level",{level:s}):r(t,"cycle_thinking_level",null)}case"get_available_thinking_levels":{const s=o.getAvailableThinkingLevels();return r(t,"get_available_thinking_levels",{levels:s})}case"set_steering_mode":return o.setSteeringMode(e.mode),r(t,"set_steering_mode");case"set_follow_up_mode":return o.setFollowUpMode(e.mode),r(t,"set_follow_up_mode");case"compact":{const s=await o.compact(e.customInstructions);return r(t,"compact",s)}case"set_auto_compaction":return o.setAutoCompactionEnabled(e.enabled),r(t,"set_auto_compaction");case"set_auto_retry":return o.setAutoRetryEnabled(e.enabled),r(t,"set_auto_retry");case"abort_retry":return o.abortRetry(),r(t,"abort_retry");case"bash":{const s=await o.extensionRunner.emitUserBash({type:"user_bash",command:e.command,excludeFromContext:e.excludeFromContext??!1,cwd:o.sessionManager.getCwd()});if(s?.result)return o.recordBashResult(e.command,s.result,{excludeFromContext:e.excludeFromContext}),r(t,"bash",s.result);const n=await o.executeBash(e.command,void 0,{excludeFromContext:e.excludeFromContext,id:t,operations:s?.operations});return r(t,"bash",n)}case"abort_bash":return o.abortBash(),r(t,"abort_bash");case"get_sandbox_status":return r(t,"get_sandbox_status",o.getSandboxStatus()??null);case"list_background_processes":return r(t,"list_background_processes",{processes:o.backgroundProcesses.list()});case"read_background_process":{const{text:s,truncated:n,info:a}=o.backgroundProcesses.read(e.processId,e.tail!==void 0?{tail:e.tail}:{tail:200});return r(t,"read_background_process",{text:s,truncated:n,process:a})}case"stop_background_process":{const s=await o.backgroundProcesses.stop(e.processId);return r(t,"stop_background_process",{process:s})}case"get_session_stats":{const s=o.getSessionStats();return r(t,"get_session_stats",s)}case"export_html":{const s=await o.exportToHtml(e.outputPath);return r(t,"export_html",{path:s})}case"switch_session":{const s=await u.switchSession(e.sessionPath);return s.cancelled||await f(),r(t,"switch_session",s)}case"fork":{const s=await u.fork(e.entryId);return s.cancelled||await f(),r(t,"fork",{text:s.selectedText,cancelled:s.cancelled})}case"clone":{const s=o.sessionManager.getLeafId();if(!s)return d(t,"clone","Cannot clone session: no current entry selected");const n=await u.fork(s,{position:"at"});return n.cancelled||await f(),r(t,"clone",{cancelled:n.cancelled})}case"get_fork_messages":{const s=o.getUserMessagesForForking();return r(t,"get_fork_messages",{messages:s})}case"get_entries":{const s=o.sessionManager;let n=s.getEntries();if(e.since!==void 0){const a=n.findIndex(l=>l.id===e.since);if(a===-1)return d(t,"get_entries",`Entry not found: ${e.since}`);n=n.slice(a+1)}return r(t,"get_entries",{entries:n,leafId:s.getLeafId()})}case"get_tree":{const s=o.sessionManager;return r(t,"get_tree",{tree:s.getTree(),leafId:s.getLeafId()})}case"get_last_assistant_text":{const s=o.getLastAssistantText();return r(t,"get_last_assistant_text",{text:s})}case"set_session_name":{const s=e.name.trim();return s?(o.setSessionName(s),r(t,"set_session_name")):d(t,"set_session_name","Session name cannot be empty")}case"get_messages":return r(t,"get_messages",{messages:o.messages});case"get_commands":{const s=[];for(const n of o.extensionRunner.getRegisteredCommands())s.push({name:n.invocationName,description:n.description,source:"extension",sourceInfo:n.sourceInfo});for(const n of o.promptTemplates)s.push({name:n.name,description:n.description,source:"prompt",sourceInfo:n.sourceInfo});for(const n of o.resourceLoader.getSkills().skills)s.push({name:`skill:${n.name}`,description:n.description,source:"skill",sourceInfo:n.sourceInfo});return r(t,"get_commands",{commands:s})}case"set_host_capabilities":{const s=L();return s.set("rpc",$(e.capabilities),q),r(t,"set_host_capabilities",{capabilities:s.list()})}case"set_environment":{const s=Q({set:e.set,unset:e.unset});return r(t,"set_environment",{changed:s})}case"set_telemetry_consent":{const{usage:s,failures:n}=e;if(typeof s!="boolean"||n!==void 0&&typeof n!="boolean")return d(t,"set_telemetry_consent","set_telemetry_consent: usage must be a boolean, failures a boolean or omitted");const a=globalThis[Symbol.for("dalcode.telemetry.consentApi")];return a?r(t,"set_telemetry_consent",a.set({usage:s,failures:n})):d(t,"set_telemetry_consent","set_telemetry_consent: telemetry is not loaded in this engine")}default:{const s=e;return d(t,s.type,`Unknown command: ${s.type}`)}}},"handleCommand");let M=i(()=>{},"detachInput");async function T(e=0,t){C&&process.exit(e),C=!0;for(const s of U)s();k?.(),S?.(),L().clear("rpc");for(const s of y.values())s.reject(new x("unavailable","RPC host disconnected"));await u.dispose(),M(),process.stdin.pause(),t!=="SIGTERM"&&await J(),process.exit(e)}i(T,"shutdown");async function R(){E&&await T()}i(R,"checkShutdownRequested");const B=i(async e=>{let t;try{t=JSON.parse(e)}catch(n){c(d(void 0,"parse",`Failed to parse command: ${n instanceof Error?n.message:String(n)}`)),await I();return}if(typeof t=="object"&&t!==null&&"type"in t&&t.type==="extension_ui_response"){const n=t,a=m.get(n.id);a&&(m.delete(n.id),a.resolve(n));return}if(typeof t=="object"&&t!==null&&"type"in t&&t.type==="host_response"){const n=t,a=y.get(n.id);a&&("error"in n?a.reject(new x("host_error",String(n.error))):a.resolve(n.result));return}const s=t;try{const n=await D(s);n&&(c(n),await I()),await R()}catch(n){c(d(s.id,s.type,n instanceof Error?n.message:String(n))),await I()}},"handleInputLine"),P=i(()=>{T()},"onInputEnd");return process.stdin.on("end",P),M=(()=>{const e=X(process.stdin,t=>{B(t)});return()=>{e(),process.stdin.off("end",P)}})(),new Promise(()=>{})}i(ce,"runRpcMode");export{Z as PROMPT_ABORTED_BEFORE_START,ce as runRpcMode};
|
|
1
|
+
var z=Object.defineProperty;var i=(d,o)=>z(d,"name",{value:o,configurable:!0});import*as _ from"node:crypto";import{resolveExtensionNotify as K}from"../../core/extensions/index.js";import{DEFAULT_HOST_CALL_TIMEOUT_MS as Q,getHostCapabilities as N,HostCallError as k,parseHostCapabilities as V}from"../../core/host-capabilities.js";import{flushRawStdout as X,takeOverStdout as Y,waitForRawStdoutBackpressure as S,writeRawStdout as Z}from"../../core/output-guard.js";import{killTrackedDetachedChildren as ee}from"../../utils/shell.js";import{theme as te}from"../interactive/theme/theme.js";import{toJsonEvent as se}from"../json-event.js";import{openApproval as ne,ResolvedApprovals as oe}from"./approvals.js";import{applyEnvironmentUpdate as re}from"./environment-update.js";import{attachJsonlLineReader as ie,serializeJsonLine as ae}from"./jsonl.js";import{buildMessageMeta as le}from"./message-meta.js";const ce="Prompt aborted before it started";async function we(d){Y();let o=d.session,T,E;const l=i(e=>{Z(ae(e))},"output"),r=i((e,t,s)=>s===void 0?{id:e,type:"response",command:t,success:!0}:{id:e,type:"response",command:t,success:!0,data:s},"success"),u=i((e,t,s)=>({id:e,type:"response",command:t,success:!1,error:s}),"error"),g=new Map,R=new oe,w=new Map,O=i((e,t)=>{const s=_.randomUUID();return new Promise((n,a)=>{const c=i(()=>{clearTimeout(U),t.signal?.removeEventListener("abort",h),w.delete(s)},"cleanup"),p=i(f=>{c(),l({type:"host_request_cancelled",id:s}),a(f)},"giveUp"),h=i(()=>p(new k("aborted","host call aborted")),"onAbort"),U=setTimeout(()=>p(new k("timeout","host did not answer in time")),t.timeoutMs??Q);t.signal?.addEventListener("abort",h,{once:!0}),w.set(s,{resolve:i(f=>{c(),n(f)},"resolve"),reject:i(f=>{c(),a(f)},"reject")});const b={type:"host_request",id:s,capability:e.capability,method:e.method,params:e.params};l(b)})},"rpcHostTransport");let P=!1,A=!1;const L=[];function v(e,t,s,n){if(e?.signal?.aborted)return Promise.resolve(t);const a=_.randomUUID(),c=s.method,p=e?.approval&&(c==="select"||c==="confirm")?ne(a,c,e.approval,{options:Array.isArray(s.options)?s.options:void 0,timeout:e.timeout}):void 0;return new Promise((h,U)=>{let b;const f=i((y,x)=>{if(!p)return;const I=x?p.kindOf(x):void 0,$=y==="dialog"&&!I?"cancelled":y;R.remember(a,I,$);const H={type:"approval_resolved",id:a,...I?{optionId:I}:{},via:$};l(H)},"settleApproval"),M=i(()=>{b&&clearTimeout(b),e?.signal?.removeEventListener("abort",B),g.delete(a)},"cleanup"),B=i(()=>{M(),f("aborted"),h(t)},"onAbort");e?.signal?.addEventListener("abort",B,{once:!0}),e?.timeout&&(b=setTimeout(()=>{M(),f("timeout"),h(t)},e.timeout)),g.set(a,{resolve:i((y,x="dialog")=>{M(),f(x,y),h(n(y))},"resolve"),reject:U,...p?{approval:p}:{}}),p&&l(p.request),l({type:"extension_ui_request",id:a,...s,...p?{approval:!0}:{}})})}i(v,"createDialogPromise");const j=i(()=>({select:i((e,t,s)=>v(s,void 0,{method:"select",title:e,options:t,timeout:s?.timeout},n=>"cancelled"in n&&n.cancelled?void 0:"value"in n?n.value:void 0),"select"),confirm:i((e,t,s)=>v(s,!1,{method:"confirm",title:e,message:t,timeout:s?.timeout},n=>"cancelled"in n&&n.cancelled?!1:"confirmed"in n?n.confirmed:!1),"confirm"),input:i((e,t,s)=>v(s,void 0,{method:"input",title:e,placeholder:t,timeout:s?.timeout},n=>"cancelled"in n&&n.cancelled?void 0:"value"in n?n.value:void 0),"input"),notify(e,t){const s=K(e,t);l({type:"extension_ui_request",id:_.randomUUID(),method:"notify",message:s.message,notifyType:s.type})},setPanel(e,t){l({type:"extension_ui_request",id:_.randomUUID(),method:"setPanel",panelId:e,panel:t})},requestInput:i(e=>v(e,void 0,{method:"requestInput",title:e.title,placeholder:e.placeholder,timeout:e.timeout},t=>"cancelled"in t&&t.cancelled?void 0:"value"in t?t.value:void 0),"requestInput"),requestChoice:i(e=>v(e,void 0,{method:"requestChoice",title:e.title,items:e.items,timeout:e.timeout},t=>"cancelled"in t&&t.cancelled?void 0:"value"in t?t.value:void 0),"requestChoice"),onTerminalInput(){return()=>{}},setStatus(e,t){l({type:"extension_ui_request",id:_.randomUUID(),method:"setStatus",statusKey:e,statusText:t})},setWorkingMessage(e){},setWorkingVisible(e){},setWorkingIndicator(e){},setHiddenThinkingLabel(e){},setWidget(e,t,s){(t===void 0||Array.isArray(t))&&l({type:"extension_ui_request",id:_.randomUUID(),method:"setWidget",widgetKey:e,widgetLines:t,widgetPlacement:s?.placement})},setFooter(e){},setHeader(e){},setTitle(e){l({type:"extension_ui_request",id:_.randomUUID(),method:"setTitle",title:e})},async custom(){},pasteToEditor(e){this.setEditorText(e)},setEditorText(e){l({type:"extension_ui_request",id:_.randomUUID(),method:"set_editor_text",text:e})},getEditorText(){return""},async editor(e,t){const s=_.randomUUID();return new Promise((n,a)=>{g.set(s,{resolve:i(c=>{"cancelled"in c&&c.cancelled?n(void 0):"value"in c?n(c.value):n(void 0)},"resolve"),reject:a}),l({type:"extension_ui_request",id:s,method:"editor",title:e,prefill:t})})},addAutocompleteProvider(){},setEditorComponent(){},getEditorComponent(){},get theme(){return te},getAllThemes(){return[]},getTheme(e){},setTheme(e){return{success:!1,error:"Theme switching not supported in RPC mode"}},getToolsExpanded(){return!1},setToolsExpanded(e){}}),"createExtensionUIContext");d.setRebindSession(async()=>{await m()});const m=i(async()=>{o=d.session,T?.(),E?.(),T=o.subscribe(e=>{l(se(e)),e.type==="agent_settled"&&q()}),E=o.agent.subscribe(async()=>{await S()}),await o.bindExtensions({uiContext:j(),mode:"rpc",commandContextActions:{waitForIdle:i(()=>o.waitForIdle(),"waitForIdle"),newSession:i(async e=>d.newSession(e),"newSession"),fork:i(async(e,t)=>({cancelled:(await d.fork(e,t)).cancelled}),"fork"),navigateTree:i(async(e,t)=>({cancelled:(await o.navigateTree(e,{summarize:t?.summarize,customInstructions:t?.customInstructions,replaceInstructions:t?.replaceInstructions,label:t?.label})).cancelled}),"navigateTree"),switchSession:i(async(e,t)=>d.switchSession(e,t),"switchSession"),reload:i(async()=>{await o.reload()},"reload")},shutdownHandler:i(()=>{P=!0},"shutdownHandler"),onError:i(e=>{l({type:"extension_error",extensionPath:e.extensionPath,event:e.event,error:e.error})},"onError")})},"rebindSession"),G=i(()=>{const e=["SIGTERM","SIGINT"];process.platform!=="win32"&&e.push("SIGHUP");for(const t of e){const s=i(()=>{ee(),C(t==="SIGHUP"?129:t==="SIGINT"?130:143,t)},"handler");process.on(t,s),L.push(()=>process.off(t,s))}},"registerSignalHandlers");await m(),G();const J=i(async e=>{const t=e.id;switch(e.type){case"prompt":{let s=!1,n=!1;o.prompt(e.message,{images:e.images,streamingBehavior:e.streamingBehavior,source:"rpc",preflightResult:i(a=>{if(a==="cancelled"){n=!0;return}s=!0,l(r(t,"prompt",{disposition:a}))},"preflightResult")}).then(()=>{n&&!s&&l(u(t,"prompt",ce))},a=>{s||l(u(t,"prompt",a.message))});return}case"steer":{const s=await o.steer(e.message,e.images,{source:"rpc"});return r(t,"steer",{disposition:s})}case"follow_up":{const s=await o.followUp(e.message,e.images,{source:"rpc"});return r(t,"follow_up",{disposition:s})}case"abort":return await o.abort(),r(t,"abort");case"clear_queue":return r(t,"clear_queue",o.clearQueue());case"new_session":{const s=e.parentSession?{parentSession:e.parentSession}:void 0,n=await d.newSession(s);return n.cancelled||await m(),r(t,"new_session",n)}case"get_state":{const s={model:o.model,thinkingLevel:o.thinkingLevel,isStreaming:o.isStreaming,isCompacting:o.isCompacting,steeringMode:o.steeringMode,followUpMode:o.followUpMode,sessionFile:o.sessionFile,sessionId:o.sessionId,sessionName:o.sessionName,autoCompactionEnabled:o.autoCompactionEnabled,messageCount:o.messages.length,pendingMessageCount:o.pendingMessageCount};return r(t,"get_state",s)}case"set_model":{const n=o.modelRuntime.getAvailableSnapshot().find(a=>a.provider===e.provider&&a.id===e.modelId);return n?(await o.setModel(n),r(t,"set_model",n)):u(t,"set_model",`Model not found: ${e.provider}/${e.modelId}`)}case"cycle_model":{const s=await o.cycleModel();return s?r(t,"cycle_model",s):r(t,"cycle_model",null)}case"get_available_models":{const s=o.modelRuntime.getAvailableSnapshot();return r(t,"get_available_models",{models:s})}case"set_thinking_level":return o.setThinkingLevel(e.level),r(t,"set_thinking_level");case"cycle_thinking_level":{const s=o.cycleThinkingLevel();return s?r(t,"cycle_thinking_level",{level:s}):r(t,"cycle_thinking_level",null)}case"get_available_thinking_levels":{const s=o.getAvailableThinkingLevels();return r(t,"get_available_thinking_levels",{levels:s})}case"set_steering_mode":return o.setSteeringMode(e.mode),r(t,"set_steering_mode");case"set_follow_up_mode":return o.setFollowUpMode(e.mode),r(t,"set_follow_up_mode");case"compact":{const s=await o.compact(e.customInstructions);return r(t,"compact",s)}case"set_auto_compaction":return o.setAutoCompactionEnabled(e.enabled),r(t,"set_auto_compaction");case"set_auto_retry":return o.setAutoRetryEnabled(e.enabled),r(t,"set_auto_retry");case"abort_retry":return o.abortRetry(),r(t,"abort_retry");case"bash":{const s=await o.extensionRunner.emitUserBash({type:"user_bash",command:e.command,excludeFromContext:e.excludeFromContext??!1,cwd:o.sessionManager.getCwd()});if(s?.result)return o.recordBashResult(e.command,s.result,{excludeFromContext:e.excludeFromContext}),r(t,"bash",s.result);const n=await o.executeBash(e.command,void 0,{excludeFromContext:e.excludeFromContext,id:t,operations:s?.operations});return r(t,"bash",n)}case"abort_bash":return o.abortBash(),r(t,"abort_bash");case"get_sandbox_status":return r(t,"get_sandbox_status",o.getSandboxStatus()??null);case"list_background_processes":return r(t,"list_background_processes",{processes:o.backgroundProcesses.list()});case"read_background_process":{const{text:s,truncated:n,info:a}=o.backgroundProcesses.read(e.processId,e.tail!==void 0?{tail:e.tail}:{tail:200});return r(t,"read_background_process",{text:s,truncated:n,process:a})}case"stop_background_process":{const s=await o.backgroundProcesses.stop(e.processId);return r(t,"stop_background_process",{process:s})}case"get_session_stats":{const s=o.getSessionStats();return r(t,"get_session_stats",s)}case"export_html":{const s=await o.exportToHtml(e.outputPath);return r(t,"export_html",{path:s})}case"switch_session":{const s=await d.switchSession(e.sessionPath);return s.cancelled||await m(),r(t,"switch_session",s)}case"fork":{const s=await d.fork(e.entryId);return s.cancelled||await m(),r(t,"fork",{text:s.selectedText,cancelled:s.cancelled})}case"clone":{const s=o.sessionManager.getLeafId();if(!s)return u(t,"clone","Cannot clone session: no current entry selected");const n=await d.fork(s,{position:"at"});return n.cancelled||await m(),r(t,"clone",{cancelled:n.cancelled})}case"get_fork_messages":{const s=o.getUserMessagesForForking();return r(t,"get_fork_messages",{messages:s})}case"get_entries":{const s=o.sessionManager;let n=s.getEntries();if(e.since!==void 0){const a=n.findIndex(c=>c.id===e.since);if(a===-1)return u(t,"get_entries",`Entry not found: ${e.since}`);n=n.slice(a+1)}return r(t,"get_entries",{entries:n,leafId:s.getLeafId()})}case"get_tree":{const s=o.sessionManager;return r(t,"get_tree",{tree:s.getTree(),leafId:s.getLeafId()})}case"get_last_assistant_text":{const s=o.getLastAssistantText();return r(t,"get_last_assistant_text",{text:s})}case"set_session_name":{const s=e.name.trim();return s?(o.setSessionName(s),r(t,"set_session_name")):u(t,"set_session_name","Session name cannot be empty")}case"get_messages":{const s=o.messages,n=le(s,o.sessionManager.buildSessionProjection());return r(t,"get_messages",{messages:s,meta:n})}case"get_commands":{const s=[];for(const n of o.extensionRunner.getRegisteredCommands())s.push({name:n.invocationName,description:n.description,source:"extension",sourceInfo:n.sourceInfo});for(const n of o.promptTemplates)s.push({name:n.name,description:n.description,source:"prompt",sourceInfo:n.sourceInfo});for(const n of o.resourceLoader.getSkills().skills)s.push({name:`skill:${n.name}`,description:n.description,source:"skill",sourceInfo:n.sourceInfo});return r(t,"get_commands",{commands:s})}case"set_host_capabilities":{const s=N();return s.set("rpc",V(e.capabilities),O),r(t,"set_host_capabilities",{capabilities:s.list()})}case"set_environment":{const s=re({set:e.set,unset:e.unset});return r(t,"set_environment",{changed:s})}case"set_telemetry_consent":{const{usage:s,failures:n}=e;if(typeof s!="boolean"||n!==void 0&&typeof n!="boolean")return u(t,"set_telemetry_consent","set_telemetry_consent: usage must be a boolean, failures a boolean or omitted");const a=globalThis[Symbol.for("dalcode.telemetry.consentApi")];return a?r(t,"set_telemetry_consent",a.set({usage:s,failures:n})):u(t,"set_telemetry_consent","set_telemetry_consent: telemetry is not loaded in this engine")}case"approval_response":{const s=g.get(e.id);if(s?.approval){const a=s.approval.request.options.find(c=>c.id===e.optionId);return a?(s.resolve(s.approval.responseFor(a.kind),"approval_response"),r(t,"approval_response",{accepted:!0,optionId:a.kind,via:"approval_response"})):u(t,"approval_response",`Unknown option ${String(e.optionId)} for approval ${e.id}; expected one of ${s.approval.request.options.map(c=>c.id).join(", ")}`)}const n=R.get(e.id);return n?r(t,"approval_response",{accepted:!1,...n}):u(t,"approval_response",`Unknown approval: ${e.id}`)}default:{const s=e;return u(t,s.type,`Unknown command: ${s.type}`)}}},"handleCommand");let F=i(()=>{},"detachInput");async function C(e=0,t){A&&process.exit(e),A=!0;for(const s of L)s();T?.(),E?.(),N().clear("rpc");for(const s of w.values())s.reject(new k("unavailable","RPC host disconnected"));await d.dispose(),F(),process.stdin.pause(),t!=="SIGTERM"&&await X(),process.exit(e)}i(C,"shutdown");async function q(){P&&await C()}i(q,"checkShutdownRequested");const W=i(async e=>{let t;try{t=JSON.parse(e)}catch(n){l(u(void 0,"parse",`Failed to parse command: ${n instanceof Error?n.message:String(n)}`)),await S();return}if(typeof t=="object"&&t!==null&&"type"in t&&t.type==="extension_ui_response"){const n=t,a=g.get(n.id);a&&(g.delete(n.id),a.resolve(n));return}if(typeof t=="object"&&t!==null&&"type"in t&&t.type==="host_response"){const n=t,a=w.get(n.id);a&&("error"in n?a.reject(new k("host_error",String(n.error))):a.resolve(n.result));return}const s=t;try{const n=await J(s);n&&(l(n),await S()),await q()}catch(n){l(u(s.id,s.type,n instanceof Error?n.message:String(n))),await S()}},"handleInputLine"),D=i(()=>{C()},"onInputEnd");return process.stdin.on("end",D),F=(()=>{const e=ie(process.stdin,t=>{W(t)});return()=>{e(),process.stdin.off("end",D)}})(),new Promise(()=>{})}i(we,"runRpcMode");export{ce as PROMPT_ABORTED_BEFORE_START,we as runRpcMode};
|
|
@@ -4,6 +4,7 @@ import type { PromptDisposition, QueuedInputDisposition, SessionStats } from "..
|
|
|
4
4
|
import type { BackgroundProcessInfo } from "../../core/background-processes.ts";
|
|
5
5
|
import type { BashResult } from "../../core/bash-executor.ts";
|
|
6
6
|
import type { CompactionResult } from "../../core/compaction/index.ts";
|
|
7
|
+
import type { ApprovalOptionKind, ApprovalSource } from "../../core/extensions/types.ts";
|
|
7
8
|
import type { HostCapability } from "../../core/host-capabilities.ts";
|
|
8
9
|
import type { SandboxStatus } from "../../core/sandbox/shell-sandbox.ts";
|
|
9
10
|
import type { SessionEntry, SessionTreeNode } from "../../core/session-manager.ts";
|
|
@@ -159,7 +160,7 @@ export type RpcCommand = {
|
|
|
159
160
|
type: "set_telemetry_consent";
|
|
160
161
|
usage: boolean;
|
|
161
162
|
failures?: boolean;
|
|
162
|
-
};
|
|
163
|
+
} | RpcApprovalResponse;
|
|
163
164
|
export interface TelemetryConsentStatus {
|
|
164
165
|
usage: {
|
|
165
166
|
decided: boolean;
|
|
@@ -453,6 +454,7 @@ export type RpcResponse = {
|
|
|
453
454
|
success: true;
|
|
454
455
|
data: {
|
|
455
456
|
messages: AgentMessage[];
|
|
457
|
+
meta: RpcMessageMeta[];
|
|
456
458
|
};
|
|
457
459
|
} | {
|
|
458
460
|
id?: string;
|
|
@@ -484,6 +486,16 @@ export type RpcResponse = {
|
|
|
484
486
|
command: "set_telemetry_consent";
|
|
485
487
|
success: true;
|
|
486
488
|
data: TelemetryConsentStatus;
|
|
489
|
+
} | {
|
|
490
|
+
id?: string;
|
|
491
|
+
type: "response";
|
|
492
|
+
command: "approval_response";
|
|
493
|
+
success: true;
|
|
494
|
+
data: {
|
|
495
|
+
accepted: boolean;
|
|
496
|
+
optionId?: ApprovalOptionKind;
|
|
497
|
+
via: RpcApprovalResolved["via"];
|
|
498
|
+
};
|
|
487
499
|
} | {
|
|
488
500
|
id?: string;
|
|
489
501
|
type: "response";
|
|
@@ -498,6 +510,7 @@ export type RpcExtensionUIRequest = {
|
|
|
498
510
|
title: string;
|
|
499
511
|
options: string[];
|
|
500
512
|
timeout?: number;
|
|
513
|
+
approval?: true;
|
|
501
514
|
} | {
|
|
502
515
|
type: "extension_ui_request";
|
|
503
516
|
id: string;
|
|
@@ -505,6 +518,7 @@ export type RpcExtensionUIRequest = {
|
|
|
505
518
|
title: string;
|
|
506
519
|
message: string;
|
|
507
520
|
timeout?: number;
|
|
521
|
+
approval?: true;
|
|
508
522
|
} | {
|
|
509
523
|
type: "extension_ui_request";
|
|
510
524
|
id: string;
|
|
@@ -589,6 +603,46 @@ export type RpcExtensionUIResponse = {
|
|
|
589
603
|
id: string;
|
|
590
604
|
cancelled: true;
|
|
591
605
|
};
|
|
606
|
+
export interface RpcApprovalOption {
|
|
607
|
+
id: ApprovalOptionKind;
|
|
608
|
+
kind: ApprovalOptionKind;
|
|
609
|
+
label: string;
|
|
610
|
+
}
|
|
611
|
+
export interface RpcApprovalRequest {
|
|
612
|
+
type: "approval_request";
|
|
613
|
+
id: string;
|
|
614
|
+
dialogMethod: "select" | "confirm";
|
|
615
|
+
source: ApprovalSource;
|
|
616
|
+
toolCallId?: string;
|
|
617
|
+
toolName?: string;
|
|
618
|
+
args?: Record<string, unknown>;
|
|
619
|
+
argsTruncated?: true;
|
|
620
|
+
risk?: {
|
|
621
|
+
level: "low" | "medium" | "high";
|
|
622
|
+
reason: string;
|
|
623
|
+
ruleId?: string;
|
|
624
|
+
};
|
|
625
|
+
title: string;
|
|
626
|
+
description?: string;
|
|
627
|
+
options: RpcApprovalOption[];
|
|
628
|
+
timeout?: number;
|
|
629
|
+
}
|
|
630
|
+
export interface RpcApprovalResponse {
|
|
631
|
+
type: "approval_response";
|
|
632
|
+
id: string;
|
|
633
|
+
optionId: ApprovalOptionKind;
|
|
634
|
+
}
|
|
635
|
+
export interface RpcApprovalResolved {
|
|
636
|
+
type: "approval_resolved";
|
|
637
|
+
id: string;
|
|
638
|
+
optionId?: ApprovalOptionKind;
|
|
639
|
+
via: "approval_response" | "dialog" | "cancelled" | "timeout" | "aborted";
|
|
640
|
+
}
|
|
641
|
+
export interface RpcMessageMeta {
|
|
642
|
+
timestamp?: number;
|
|
643
|
+
recordedAt?: number;
|
|
644
|
+
entryId?: string;
|
|
645
|
+
}
|
|
592
646
|
export interface RpcHostRequest {
|
|
593
647
|
type: "host_request";
|
|
594
648
|
id: string;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dalcode/dal-advisor",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.44",
|
|
4
4
|
"private": true,
|
|
5
5
|
"description": "advisor: the model asks another strong model to review its current plan and point out risks. Adapted from @juicesharp/rpiv-advisor 2.13.8 (MIT).",
|
|
6
6
|
"license": "MIT",
|
|
@@ -20,8 +20,8 @@
|
|
|
20
20
|
]
|
|
21
21
|
},
|
|
22
22
|
"dependencies": {
|
|
23
|
-
"@dalcode/dal-pi-kit": "1.0.
|
|
24
|
-
"@dalcode/dal-router": "1.0.
|
|
23
|
+
"@dalcode/dal-pi-kit": "1.0.44",
|
|
24
|
+
"@dalcode/dal-router": "1.0.44",
|
|
25
25
|
"typebox": "1.3.27"
|
|
26
26
|
},
|
|
27
27
|
"peerDependencies": {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dalcode/dal-awake",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.44",
|
|
4
4
|
"private": true,
|
|
5
5
|
"description": "Keeps the computer from going to sleep while a long agent run is in progress, and lets it sleep again when the run ends. Adapted from @narumitw/pi-caffeinate (MIT).",
|
|
6
6
|
"type": "module",
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
]
|
|
19
19
|
},
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@dalcode/dal-pi-kit": "1.0.
|
|
21
|
+
"@dalcode/dal-pi-kit": "1.0.44"
|
|
22
22
|
},
|
|
23
23
|
"peerDependencies": {
|
|
24
24
|
"@earendil-works/pi-coding-agent": "^1.0.9"
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dalcode/dal-bridge",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.44",
|
|
4
4
|
"private": true,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
]
|
|
19
19
|
},
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@dalcode/dal-pi-kit": "1.0.
|
|
21
|
+
"@dalcode/dal-pi-kit": "1.0.44",
|
|
22
22
|
"typebox": "1.3.7"
|
|
23
23
|
},
|
|
24
24
|
"peerDependencies": {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var j=Object.defineProperty;var A=(o,F)=>j(o,"name",{value:F,configurable:!0});var H=Object.defineProperty,d=A((o,F)=>H(o,"name",{value:F,configurable:!0}),"d");import{t}from"@dalcode/dal-pi-kit";import{getProcessShellSandbox as R,registerPermissionAskHandler as q,registerSandboxEscalationHandler as V}from"@earendil-works/pi-coding-agent";import{Type as m}from"typebox";import{AskUserInputError as W,askUserSchema as G,buildAskUserRequest as z,describeAnswers as J,THUMBNAIL_CHANNEL as K}from"./ask-user.js";import{askUserTimeoutMs as Q,BridgeClient as X,planTimeoutMs as Y,readBridgeConfig as Z,readSubagentAttribution as uu}from"./client.js";const eu=m.Object({goal:m.String({description:t("\u8FD9\u4E2A\u8BA1\u5212\u8981\u8FBE\u6210\u4EC0\u4E48\uFF0C\u4E00\u53E5\u8BDD\u8BF4\u660E")}),reasoning:m.Optional(m.String({description:t("\u4E3A\u4EC0\u4E48\u9009\u8FD9\u4E2A\u65B9\u6848")})),steps:m.Array(m.Object({title:m.String({description:t("\u8FD9\u4E00\u6B65\u505A\u4EC0\u4E48")}),description:m.Optional(m.String({description:t("\u8FD9\u4E00\u6B65\u7684\u7EC6\u8282")}))}),{description:t("\u6309\u987A\u5E8F\u6392\u5217\u7684\u6267\u884C\u6B65\u9AA4")})}),tu=new Set(["read","grep","ripgrep","find","fd","ls","glob","todo_read","todo","lsp","terminal_read","review_report"]),ou=new Set(["read","grep","ripgrep","find","fd","ls","glob","lsp"]),
|
|
1
|
+
var j=Object.defineProperty;var A=(o,F)=>j(o,"name",{value:F,configurable:!0});var H=Object.defineProperty,d=A((o,F)=>H(o,"name",{value:F,configurable:!0}),"d");import{t}from"@dalcode/dal-pi-kit";import{getProcessShellSandbox as R,registerPermissionAskHandler as q,registerSandboxEscalationHandler as V}from"@earendil-works/pi-coding-agent";import{Type as m}from"typebox";import{AskUserInputError as W,askUserSchema as G,buildAskUserRequest as z,describeAnswers as J,THUMBNAIL_CHANNEL as K}from"./ask-user.js";import{askUserTimeoutMs as Q,BridgeClient as X,planTimeoutMs as Y,readBridgeConfig as Z,readSubagentAttribution as uu}from"./client.js";const eu=m.Object({goal:m.String({description:t("\u8FD9\u4E2A\u8BA1\u5212\u8981\u8FBE\u6210\u4EC0\u4E48\uFF0C\u4E00\u53E5\u8BDD\u8BF4\u660E")}),reasoning:m.Optional(m.String({description:t("\u4E3A\u4EC0\u4E48\u9009\u8FD9\u4E2A\u65B9\u6848")})),steps:m.Array(m.Object({title:m.String({description:t("\u8FD9\u4E00\u6B65\u505A\u4EC0\u4E48")}),description:m.Optional(m.String({description:t("\u8FD9\u4E00\u6B65\u7684\u7EC6\u8282")}))}),{description:t("\u6309\u987A\u5E8F\u6392\u5217\u7684\u6267\u884C\u6B65\u9AA4")})}),tu=new Set(["read","grep","ripgrep","find","fd","ls","glob","todo_read","todo","lsp","terminal_read","review_report"]),ou=new Set(["read","grep","ripgrep","find","fd","ls","glob","lsp"]),I="DALCODE_BRIDGE_EVALUATE_READ_TOOLS",ru="submit_plan",S="ask_user";function x(o){return o.scope==="session"?"session":"once"}A(x,"ee"),d(x,"escalationScope");function k(o){const F=o.grant,p=d(l=>Array.isArray(l)?l.filter(E=>typeof E=="string"&&E.length>0):[],"list"),n=p(F?.allowDomains),s=p(F?.allowWrite);return{approved:!0,scope:x(o),...n.length>0||s.length>0?{grant:{allowDomains:n,allowWrite:s}}:{}}}A(k,"h"),d(k,"escalationApproval");function _(o){const F=o.input;for(const p of["command","file_path","path","filePath"]){const n=F[p];if(typeof n=="string"&&n.length>0)return n}}A(_,"R"),d(_,"ruleContentFor");function N(o,F){const p=o.input,n=o.toolName==="process";if(o.toolName!=="bash"&&!(n&&p.action==="start")||typeof p.command!="string"||p.command.length===0)return;const s=R(),l=s?.planNetworkEscalation({command:p.command,cwd:F.cwd});if(!(!s||!l))return{toolCallId:o.toolCallId,toolName:o.toolName,command:p.command,cwd:F.cwd,level:s.level,mode:"allow",justification:l.justification,allowDomains:l.allow_domains,allowWrite:[],background:n,trigger:l.trigger}}A(N,"ne"),d(N,"plannedNetworkEscalation");let g,T=!1,B,P=!1;function L(o,F){const p=Z();if(!p)return;const n=new X(p,F),s=uu();function l(u){const e=u.sessionManager.getSessionId();return s?{sessionId:s.parentSessionId,subagent:{id:s.subagentId,sessionId:e,...s.parentTaskId?{parentTaskId:s.parentTaskId}:{},...s.parentSubagentId?{parentSubagentId:s.parentSubagentId}:{},...s.label?{label:s.label}:{}}}:{sessionId:e}}A(l,"c"),d(l,"caller");let E,b=0;function f(u){const e=u.model;return{provider:e?.provider??"unknown",model:e?.id??e?.name??"unknown"}}A(f,"_"),d(f,"describeModel");const w=new Map,C=new Set,O=process.env[I]==="1";o.on("tool_call",async(u,e)=>{const r=ou.has(u.toolName);if((r?!O:tu.has(u.toolName))||u.toolName===ru||u.toolName===S)return;const i=u.input.sandbox_escalation,c=i?void 0:N(u,e),a=await n.post("/api/internal/pi-bridge/permission",{...l(e),toolName:u.toolName,toolInput:u.input,ruleContent:_(u),...i||c?{category:"sandbox_escalation"}:{},...c?{sandboxEscalation:c}:{},...r?{readOnly:!0}:{}});if(!a)return{block:!0,reason:t("dal-bridge\uFF1A\u65E0\u6CD5\u8054\u7CFB DAL Code \u53D6\u5F97\u6388\u6743\uFF0C\u5DF2\u62D2\u7EDD\u6267\u884C\u3002"),denied:{source:"bridge",ruleId:"unreachable"}};if(a.decision==="deny")return{block:!0,reason:a.message??t("dal-bridge\uFF1A\u7528\u6237\u5DF2\u62D2\u7EDD\u8BE5\u64CD\u4F5C\u3002"),denied:{source:"bridge"}};(i||c)&&w.set(u.toolCallId,k(a)),C.add(u.toolCallId),C.size>1e3&&C.delete(C.values().next().value)});const y=d(async(u,e)=>{if(C.delete(u.toolCallId))return{approved:!0};const r=await n.post("/api/internal/pi-bridge/permission",{...l(e),toolName:u.toolName,toolInput:u.input,ruleContent:_({input:u.input}),category:"permission_rule",rule:u.rule,ruleSource:u.source});return r?r.decision==="allow"?{approved:!0}:{approved:!1,message:r.message??t("dal-bridge\uFF1A\u7528\u6237\u5DF2\u62D2\u7EDD\u8BE5\u64CD\u4F5C\u3002")}:{approved:!1,message:t("dal-bridge\uFF1A\u65E0\u6CD5\u8054\u7CFB DAL Code \u53D6\u5F97\u6388\u6743\uFF0C\u5DF2\u62D2\u7EDD\u6267\u884C\u3002")}},"approveRule");B=y,P||(q((u,e)=>B?.(u,e)),P=!0);const h=d(async(u,e)=>{const r=w.get(u.toolCallId);if(r)return w.delete(u.toolCallId),r;if(!e)return;const i=await n.post("/api/internal/pi-bridge/permission",{...l(e),toolName:u.toolName,toolInput:{command:u.command},ruleContent:u.command,category:"sandbox_escalation",sandboxEscalation:u});return i?i.decision==="allow"?k(i):{approved:!1,message:i.message??t("dal-bridge\uFF1A\u7528\u6237\u5DF2\u62D2\u7EDD\u8BE5\u64CD\u4F5C\u3002")}:{approved:!1,message:t("dal-bridge\uFF1A\u65E0\u6CD5\u8054\u7CFB DAL Code \u53D6\u5F97\u6388\u6743\uFF0C\u5DF2\u62D2\u7EDD\u6267\u884C\u3002")}},"approveEscalation");g=h,T||(V((u,e)=>g?.(u,e)),T=!0),o.on("session_shutdown",()=>{g===h&&(g=void 0),B===y&&(B=void 0)}),o.on("after_provider_response",(u,e)=>{u.status>=400?E={...f(e),reason:`HTTP ${u.status}`}:(E=void 0,b=0)}),o.on("before_provider_request",async(u,e)=>{if(!E)return;const r=f(e);if(r.provider===E.provider&&r.model===E.model)return;b+=1;const i={provider:E.provider,model:E.model},c=E.reason;E=void 0,await n.post("/api/internal/pi-bridge/provider-fallback",{...l(e),from:i,to:r,reason:c,attempt:b,blocked:!0});const a=new Error(t("dal-bridge\uFF1A\u8BF7\u6C42\u5931\u8D25\u540E\u4E0D\u5141\u8BB8\u81EA\u52A8\u6362\u6A21\u578B\u3002")+` ${i.provider}/${i.model} \u2192 ${r.provider}/${r.model} (${c})`);throw a.name="ProviderSwapAborted",a}),o.registerTool({name:"submit_plan",label:t("\u63D0\u4EA4\u8BA1\u5212\u5F85\u5BA1\u6279"),description:t(t("\u5728\u52A8\u624B\u6539\u52A8\u4E4B\u524D\uFF0C\u628A\u8BA1\u5212\u63D0\u4EA4\u7ED9\u7528\u6237\u5BA1\u6279\u3002\u8FD4\u56DE\u662F\u5426\u7EE7\u7EED\u6267\u884C\uFF0C\u4EE5\u53CA\u7528\u6237\u7ED9\u51FA\u7684\u53CD\u9988\u3002")+t("\u5F53\u4EFB\u52A1\u662F\u591A\u6B65\u9AA4\u7684\u3001\u6216\u4F1A\u6539\u52A8\u591A\u4E2A\u6587\u4EF6\u65F6\u4F7F\u7528\u3002")),promptSnippet:t("submit_plan - \u591A\u6B65\u9AA4\u4EFB\u52A1\u52A8\u624B\u524D\u5148\u63D0\u4EA4\u8BA1\u5212\u5F85\u7528\u6237\u5BA1\u6279"),parameters:eu,execute:d(async(u,e,r,i,c)=>{const a=await n.post("/api/internal/pi-bridge/plan",{...l(c),goal:e.goal,reasoning:e.reasoning,steps:e.steps},{timeoutMs:Y()});return!a||a.decision==="cancel"?{content:[{type:"text",text:a?.feedback?`Plan not approved. User feedback: ${a.feedback}`:"Plan not approved. Stop and wait for further instructions."}],details:{approved:!1,...a?.feedback?{feedback:a.feedback}:{}}}:{content:[{type:"text",text:"Plan approved. Proceed with the steps."}],details:{approved:!0}}},"execute")});const U=d((u,e)=>{let r;return o.events.emit(K,{ref:u,...e!==void 0?{title:e}:{},reply:d(i=>{r=i},"reply")}),r},"resolveThumbnail");o.registerTool({name:S,label:t("\u8BE2\u95EE\u7528\u6237"),description:t("\u52A8\u624B\u505A PPT\u3001\u6587\u6863\u3001\u8868\u683C\u3001\u9875\u9762\u4E4B\u524D\uFF0C\u7528\u4E00\u5F20\u5361\u7247\u5411\u7528\u6237\u786E\u8BA4\u4F1A\u6539\u53D8\u4EA7\u51FA\u7684\u5173\u952E\u51B3\u5B9A\uFF08\u6700\u591A 3 \u9898\uFF09\u3002\u9898\u578B\uFF1Achoice \u9009\u9879\uFF08\u53EF\u5E26\u7F29\u7565\u56FE\uFF09\u3001swatch \u914D\u8272\u3001outline \u53EF\u6392\u5E8F\u5927\u7EB2\u3001slider \u6570\u503C\u3001text \u81EA\u7531\u6587\u672C\u3002\u6BCF\u9898\u90FD\u8981\u6709\u63A8\u8350\u9879\u3002"),promptSnippet:t("ask_user - \u5F00\u5DE5\u524D\u7528\u4E00\u5F20\u5361\u7247\u786E\u8BA4\u5173\u952E\u51B3\u5B9A\uFF08\u6700\u591A 3 \u9898\uFF0C\u6BCF\u9898\u6709\u63A8\u8350\u9879\uFF09"),promptGuidelines:[t("ask_user \u53EA\u5728\u5F00\u5DE5\u524D\u95EE\u4E00\u6B21\uFF0C\u4E00\u8F6E\u6700\u591A 3 \u9898\uFF1B\u540C\u4E00\u4EFB\u52A1\u4E4B\u540E\u4E0D\u518D\u8FFD\u95EE\uFF0C\u9664\u975E\u7528\u6237\u4E3B\u52A8\u8981\u6C42\u3002"),t("\u53EA\u95EE\u4F1A\u6539\u53D8\u4EA7\u51FA\u7684\u51B3\u5B9A\uFF08\u53D7\u4F17/\u7528\u9014\u3001\u98CE\u683C\u6216\u4E3B\u9898\u3001\u7BC7\u5E45\u3001\u5927\u7EB2\u987A\u5E8F\uFF09\uFF1B\u80FD\u4ECE\u7528\u6237\u539F\u8BDD\u3001\u9644\u4EF6\u6216\u9879\u76EE\u6587\u4EF6\u63A8\u65AD\u51FA\u7684\u4E0D\u95EE\u3002"),t("\u7528\u6237\u8BF4\u4E86\u300C\u76F4\u63A5\u505A / \u4F60\u51B3\u5B9A / \u5FEB\u901F\u51FA\u4E00\u7248\u300D\uFF0C\u6216\u662F\u5728\u4FEE\u6539\u5DF2\u6709\u6587\u4EF6\uFF08\u5E26\u5B9A\u4F4D\u3001\u300C\u628A\u7B2C 3 \u9875\u6539\u6210\u2026\u300D\uFF09\u65F6\uFF0C\u4E0D\u8981\u8C03\u7528 ask_user\u3002"),t("\u6BCF\u9898\u90FD\u6807\u51FA\u63A8\u8350\u9879\uFF08recommended\uFF09\uFF1B\u98CE\u683C\u9898\u4F18\u5148\u7528 thumbnail \u7F29\u7565\u56FE\uFF08theme:\u2026 / page:\u2026 / doc:\u2026\uFF09\uFF0C\u914D\u8272\u7528 swatch\u3002"),t("\u7528\u6237\u8DF3\u8FC7\u65F6\u6309\u63A8\u8350\u9879\u7EE7\u7EED\uFF0C\u5E76\u5728\u56DE\u590D\u91CC\u7528\u4E00\u53E5\u8BDD\u8BF4\u660E\u7528\u4E86\u54EA\u4E9B\u63A8\u8350\u9879\u3002")],parameters:G,execute:d(async(u,e,r,i,c)=>{let a;try{a=z(e,c.cwd,U)}catch(v){throw v instanceof W?new Error(`ask_user: ${v.message}`):v}const D=await n.post("/api/internal/pi-bridge/ask-user",{...l(c),...a},{timeoutMs:Q()});if(!D||D.cancelled)return{content:[{type:"text",text:"User did not answer. Stop and wait for further instructions."}],details:{answered:!1,request:a}};const{text:M,skipped:$}=J(a,D);return{content:[{type:"text",text:M}],details:{answered:!0,answers:D.answers??{},...D.structured?{structured:D.structured}:{},...D.summary?{summary:D.summary}:{},skipped:$,request:a}}},"execute")})}A(L,"te"),d(L,"default");export{I as EVALUATE_READS_ENV,L as default};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dalcode/dal-capabilities",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.44",
|
|
4
4
|
"private": true,
|
|
5
5
|
"description": "Capability center for DAL: switches on the reviewed MCP connectors, skills and engine packages a task needs (installed automatically from the signed DAL market), with /capabilities to list, disable and enable them.",
|
|
6
6
|
"license": "MIT",
|
|
@@ -23,9 +23,9 @@
|
|
|
23
23
|
]
|
|
24
24
|
},
|
|
25
25
|
"dependencies": {
|
|
26
|
-
"@dalcode/dal-mcp": "1.0.
|
|
27
|
-
"@dalcode/dal-pi-kit": "1.0.
|
|
28
|
-
"@dalcode/deepailab": "1.0.
|
|
26
|
+
"@dalcode/dal-mcp": "1.0.44",
|
|
27
|
+
"@dalcode/dal-pi-kit": "1.0.44",
|
|
28
|
+
"@dalcode/deepailab": "1.0.44"
|
|
29
29
|
},
|
|
30
30
|
"peerDependencies": {
|
|
31
31
|
"@earendil-works/pi-coding-agent": "^1.0.9"
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dalcode/dal-compat",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.44",
|
|
4
4
|
"private": true,
|
|
5
5
|
"description": "Claude Code compatibility: the user's and project's .claude/rules/ and .claude/CLAUDE.md apply in DAL. Grown from the claude-rules extension example.",
|
|
6
6
|
"type": "module",
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
]
|
|
19
19
|
},
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@dalcode/dal-pi-kit": "1.0.
|
|
21
|
+
"@dalcode/dal-pi-kit": "1.0.44",
|
|
22
22
|
"minimatch": "10.2.6"
|
|
23
23
|
},
|
|
24
24
|
"peerDependencies": {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dalcode/dal-dap",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.44",
|
|
4
4
|
"private": true,
|
|
5
5
|
"description": "Debugger for DAL: breakpoints, stepping, call stacks and variables in Node.js and Python programs over the Debug Adapter Protocol, installing the adapter on first use. The DAP client is adapted from oh-my-pi's src/dap (MIT).",
|
|
6
6
|
"license": "MIT",
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
]
|
|
25
25
|
},
|
|
26
26
|
"dependencies": {
|
|
27
|
-
"@dalcode/dal-pi-kit": "1.0.
|
|
27
|
+
"@dalcode/dal-pi-kit": "1.0.44",
|
|
28
28
|
"typebox": "1.3.27"
|
|
29
29
|
},
|
|
30
30
|
"peerDependencies": {
|