@automaton-labs/aib 0.0.5 → 0.0.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/bin/cli.js +2 -2
  2. package/dist/commands/config-command.js +2 -1
  3. package/dist/commands/config-output.js +10 -8
  4. package/dist/commands/doctor.js +2 -1
  5. package/dist/commands/help-command.js +4 -4
  6. package/dist/commands/inspect-format.js +1 -1
  7. package/dist/commands/quick-read.js +8 -8
  8. package/dist/commands/result-view.js +5 -5
  9. package/dist/commands/session-workspace.js +7 -7
  10. package/dist/config/workspace-root.js +3 -3
  11. package/dist/help/bootstrap.md +4 -7
  12. package/dist/help/docs/help-format.md +4 -7
  13. package/dist/help/dsl/bootstrap.md +4 -7
  14. package/dist/help/dsl/docs/help-format.md +4 -7
  15. package/dist/help/dsl/full.md +4 -7
  16. package/dist/help/dsl/topics/help-format.md +4 -7
  17. package/dist/help/full.md +4 -7
  18. package/dist/help/help-meta.json +5 -5
  19. package/dist/help/json/bootstrap.md +4 -7
  20. package/dist/help/json/docs/help-format.md +4 -7
  21. package/dist/help/json/full.md +4 -7
  22. package/dist/help/json/topics/help-format.md +4 -7
  23. package/dist/help/topics/help-format.md +4 -7
  24. package/dist/managed-host/serve-web-autostart.js +1 -1
  25. package/dist/managed-host/serve-web-host.cjs +193 -79
  26. package/dist/observability/config.js +1 -1
  27. package/dist/payloads/read-stdin-json.js +1 -1
  28. package/dist/runtime/managed-runtime-provisioning.js +1 -1
  29. package/dist/runtime/run-command.js +1 -1
  30. package/dist/session/server.js +7 -5
  31. package/dist/shared/errors.js +14 -13
  32. package/dist/shared/stdin-examples.js +3 -0
  33. package/dist/tracing/trace.js +5 -3
  34. package/extension/vscode-refactor-bridge-extension.vsix +0 -0
  35. package/package.json +1 -1
  36. package/runtimes/launcher/linux-x64/aib +0 -0
  37. package/runtimes/launcher/win-x64/aib.exe +0 -0
  38. package/scripts/provision-runtime.cjs +25 -1
package/dist/bin/cli.js CHANGED
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var O=exports&&exports.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0});const F=O(require("node:fs")),Z=O(require("node:path")),W=require("../payloads/read-stdin-json"),ee=require("../commands/doctor"),te=require("../commands/init-workspace"),j=require("../commands/inspect"),re=require("../commands/imports-command"),ne=require("../commands/config-command"),se=require("../commands/diagnostics-command"),ie=require("../commands/execution-command"),oe=require("../commands/feedback-command"),ae=require("../commands/observability-command"),ce=require("../commands/generate-docs-command"),ue=require("../commands/help-command"),de=require("../commands/runtime-command"),le=require("../commands/reveal-command"),fe=require("../commands/result-view"),pe=require("../commands/quick-read"),q=require("../commands/captured-input"),G=require("../commands/session-workspace"),U=require("../commands/session-workspace"),$=require("../config/path-aliases"),L=require("../session/client"),me=require("../session/server"),_e=require("../commands/module-plan-cache"),H=require("../config/resolve-command-alias"),Ce=require("../config/auto-start-ide"),o=require("../config/env-vars"),B=require("../client/transport-options"),w=require("../shared/errors"),I=require("../shared/metrics"),J=require("../shared/presentation"),K=require("../tracing/config"),z=require("../tracing/trace"),Q=require("../runtime/input-source");function Ie(e){return e.ok===!1}let V=null,x=Date.now();function Ee(e){const t=[];let i=process.cwd(),r,E,N=process.env[o.CLI_ENV.metrics]==="1",p=(0,B.parseExtensionTransport)(process.env[o.CLI_ENV.transport])??void 0,m,y,_;for(let l=0;l<e.length;l+=1){const f=e[l];if(f){if(f==="--cwd"){const d=e[l+1];if(!d)throw new w.CliError("MISSING_FLAG_VALUE","Expected a value after --cwd.");i=d,l+=1;continue}if(f==="--instance"){const d=e[l+1];if(!d)throw new w.CliError("MISSING_FLAG_VALUE","Expected a value after --instance.");r=d,l+=1;continue}if(f==="--session"||f==="-s"){const d=e[l+1];if(!d)throw new w.CliError("MISSING_FLAG_VALUE",`Expected a value after ${f}.`);E=d,l+=1;continue}if(f==="--metrics"){N=!0;continue}if(f==="--dsl"||f==="--force-dsl"){_="dsl";continue}if(f==="--stdin-format"){const d=e[l+1];if(d!=="auto"&&d!=="dsl")throw new w.CliError("INVALID_STDIN_FORMAT","Expected --stdin-format to be auto or dsl.");_=d,l+=1;continue}if(f==="--trace-dir"){const d=e[l+1];if(!d)throw new w.CliError("MISSING_FLAG_VALUE","Expected a value after --trace-dir.");y=d,l+=1;continue}if(f==="--auto-start-ide"){m="serve-web";continue}if(f==="--no-auto-start-ide"){m="off";continue}if(f==="--transport"){const d=e[l+1],c=(0,B.parseExtensionTransport)(d);if(!c)throw new w.CliError("INVALID_TRANSPORT","Expected --transport to be either http or websocket.");p=c,l+=1;continue}t.push(f)}}const h=process.env[o.CLI_ENV.traceDir];return{commandArgs:t,cwd:i,instanceId:r,sessionId:E,metricsEnabled:N,transport:p,autoStartIde:(0,Ce.resolveAutoStartIdePolicy)(m),trace:(0,K.resolveTraceConfig)(i,{...y!==void 0?{flagTraceDir:y}:{},...h!==void 0?{envTraceDir:h}:{}}),..._!==void 0?{stdinFormat:_}:{}}}async function Se(){x=Date.now();const e=(0,I.metricsNow)(),t=[],{commandArgs:i,cwd:r,instanceId:E,sessionId:N,metricsEnabled:p,transport:m,autoStartIde:y,trace:_,stdinFormat:h}=Ee(process.argv.slice(2));await(0,U.runWithSessionOverride)(N,async()=>{const[l,...f]=i,d=(0,W.stripStdinFormatFlags)(f),c=d.restArgs,X=(0,I.metricsNow)(),s=await(0,H.resolveCanonicalCommandAlias)(l??"ping",r,E,y);if(p&&(0,I.recordSpan)(t,"cli.aliasResolution",X),(0,H.isRemovedAgentCommand)(s))throw new w.CliError("UNKNOWN_COMMAND",`Unknown command: ${s}`,{availableCommands:["doctor","diagnostics","listInstances","ping","runtimeInfo","printConfig","init-skill-usage","init","help","generate-docs","config","qr","sync","reveal","inspect","imports","view","execution","move","rename","refactor","modulePlan","session","runtime","trace","observability","feedback","note"]});if(s==="session"&&(c[0]??"status")==="serve"){await(0,me.runSessionServerCli)();return}if(s==="trace"){const n=(0,K.runTraceCommand)(r,c,_);u(n);return}if(s==="diagnostics"){await(0,se.runDiagnosticsCommand)(c);return}if(s==="observability"){b(r,s,c,_);const n=(0,ae.runObservabilityCommand)(r,c);u(n);return}if(s==="feedback"||s==="note"){b(r,s,c,_);const n=(0,oe.runFeedbackCommand)(r,c,s);u(n);return}if(s==="init"){const n=(0,te.runInitWorkspace)(r,c);u(n);return}if(s==="help"){const n=(0,ue.runHelpCommand)(c);u(n);return}if(s==="generate-docs"){const n=(0,ce.runGenerateDocsCommand)(r,c);u(n);return}if(s==="config"){b(r,s,c,_);const n=(0,ne.runConfigCommand)(r,c);u(n);return}if(s==="runtime"){const n=await(0,de.runRuntimeCommand)(r,c);n.ok===!1&&(process.exitCode=1),u(n);return}if(s==="reveal"){b(r,s,c,_);const n=(0,le.runRevealCommand)(r,c);u(n);return}if(s==="qr"){b(r,s,c,_);const n=await(0,pe.runQuickReadCommand)(r,c);n.ok===!1&&(process.exitCode=1),u(n);return}const D=Ae(s,c),P=D?(0,U.readEffectiveSessionPathAliases)(r):{},a=D?(0,$.expandPathAliasesInArgs)(r,c,P):c,A=await(0,Q.resolveCommandInputSource)({command:s,cwd:r,restArgs:a,readStdinInput:()=>(0,W.readStdinPayloadWithSource)({command:s,restArgs:a,...d.format!==void 0||h!==void 0?{format:d.format??h}:{}})}),C=D?(0,$.expandPathAliasesInJson)(r,A.payload,P):A.payload;if(V=(0,z.startTrace)({cwd:r,argv:process.argv.slice(2),command:s,restArgs:a,..._.absoluteTraceDir!==void 0?{traceDir:_.absoluteTraceDir}:_.traceDir!==void 0?{traceDir:_.traceDir}:{},...C!==void 0?{stdinPayload:C}:{},startedAtMs:x}),s==="session"){const n=a[0]??"status";if(n==="init"||n==="clear"||n==="where"||n==="read"||n==="write"||n==="prefs"||n==="aliases"||n==="list"||n==="use"){const S=(0,G.runSessionWorkspaceCommand)(r,a,C);u(S);return}if(n==="status"){const S=(0,G.runSessionWorkspaceCommand)(r,a,C),g=await(0,L.getSessionStatus)();u({...S,runtime:Ne(g)});return}if(n==="start"){const S=await(0,L.startSession)();u(S);return}if(n==="stop"){const S=await(0,L.stopSession)();u(S);return}throw new w.CliError("UNKNOWN_SESSION_COMMAND",`Unknown aib session command: ${n}`)}if(s==="imports"&&a[0]==="normalize"){const n=(0,q.attachCapturedInput)(r,"imports",C,await(0,re.runImportsCommand)(r,a,C,{...E!==void 0?{explicitInstanceId:E}:{},autoStartIde:y,...m!==void 0?{transport:m}:{},...p?{metricsEnabled:!0}:{}},p?t:void 0),A.source);u(n);return}if(s==="execution"){const n=(0,ie.runExecutionCommand)(r,a);u(n);return}if(s==="view"){const n=(0,fe.runResultViewCommand)(r,a,C);u(n);return}if(s==="doctor"){const n=await(0,ee.runDoctor)({cwd:r,runtime:a.includes("--runtime"),verbose:a.includes("--verbose"),json:a.includes("--json")});n.ok===!1&&(process.exitCode=1),u(n);return}if(s==="inspect"&&(a[0]==="graph"||a[0]==="tree"||a[0]==="cycles")){const n=(0,I.metricsNow)(),S=a[0]==="tree"?"tree":a[0]==="cycles"?"cycles":"graph",g=(0,q.attachCapturedInput)(r,S,C,await(0,j.runInspect)(r,a,C,{...E!==void 0?{explicitInstanceId:E}:{},autoStartIde:y,...m!==void 0?{transport:m}:{},...p?{metricsEnabled:!0}:{}}),A.source);p&&((0,I.recordSpan)(t,"cli.inspectGraph",n),(0,I.recordSpan)(t,"cli.total",e)),u(p?(0,I.appendMetrics)(g,t):g,m);return}if(s==="inspect"&&a.includes("--stdin")&&he(C)){const n=(0,I.metricsNow)(),S=(0,q.attachCapturedInput)(r,be(C),C,await(0,j.runInspect)(r,a,C,{...E!==void 0?{explicitInstanceId:E}:{},autoStartIde:y,...m!==void 0?{transport:m}:{},...p?{metricsEnabled:!0}:{}}),A.source);p&&((0,I.recordSpan)(t,"cli.inspectLocal",n),(0,I.recordSpan)(t,"cli.total",e)),u(p?(0,I.appendMetrics)(S,t):S,m);return}if((0,Q.commandRequiresPayload)(s,a,A))throw new w.CliError("STDIN_REQUIRED",`${s} currently expects a payload on stdin or --from.`);const v={command:s,restArgs:a,cwd:r},M=we(s,a);M&&(v.modulePlanExecutionId=M),N!==void 0&&(v.sessionId=N),E!==void 0&&(v.instanceId=E),C!==void 0&&(v.stdinPayload=C),A.source!==void 0&&(v.stdinInputSource=A.source),p&&(v.metricsEnabled=!0),m&&(v.transport=m),v.autoStartIde=y.mode;const k=ve();Object.keys(k).length>0&&(v.env=k);const Y=(0,I.metricsNow)(),T=await(0,L.callSession)(v,p?t:void 0);p&&((0,I.recordSpan)(t,"cli.callSession",Y),(0,I.recordSpan)(t,"cli.total",e));const R=p?(0,I.appendMetrics)(T,t):T;Ie(R)&&(process.exitCode=1),u(R,m)})}function ve(){const e=[o.CLI_ENV.managedHostScript,o.CLI_ENV.managedHostKind,o.CLI_ENV.managedHostRunDir,o.CLI_ENV.codeServerPath,o.CLI_ENV.extensionVsix,o.CLI_ENV.ideCommand,o.CLI_ENV.chromePath,o.CLI_ENV.managedHostWaitMs,o.CLI_ENV.workspaceRoot,o.CLI_ENV.disableWatchers,o.CLI_ENV.trace,o.CLI_ENV.traceDir,o.CLI_ENV.failureSnapshots,o.CLI_ENV.productStorageDir,o.CLI_ENV.metrics,o.CLI_ENV.metricsDir,o.CLI_ENV.metricsTag,o.CLI_ENV.mutationImpactMetrics,o.CLI_ENV.mutationImpactStream,o.CLI_ENV.testPostMutationCyclesDelayMs,o.CLI_ENV.testRefactorBatchDelayMs,o.CLI_ENV.testRenameDelayMs,o.CLI_ENV.modulePlanSyncWaitMs,o.CLI_ENV.refactorBatchSyncWaitMs,o.CLI_ENV.renameSyncWaitMs],t={};for(const i of e){const r=process.env[i];r!==void 0&&(t[i]=r)}return t}function we(e,t){if(e!=="modulePlan")return null;const i=t[0]??"";return i!=="execute"&&i!=="apply"?null:ye()??(0,_e.buildModulePlanExecutionId)()}function ye(){const e=process.env.AIB_MODULE_PLAN_EXECUTION_ID;return e&&/^exec_[a-z0-9_-]+$/i.test(e)?e:null}function b(e,t,i,r){V=(0,z.startTrace)({cwd:e,argv:process.argv.slice(2),command:t,restArgs:i,...r.absoluteTraceDir!==void 0?{traceDir:r.absoluteTraceDir}:r.traceDir!==void 0?{traceDir:r.traceDir}:{},startedAtMs:x})}function Ae(e,t){return e==="session"||e==="execution"||e==="observability"||e==="doctor"||e==="reveal"||e==="view"||e==="imports"&&t[0]==="normalize"||e==="inspect"&&(t[0]==="graph"||t[0]==="tree"||t[0]==="cycles"||t[0]==="imports"||t.includes("--stdin"))}function Ne(e){if(e.running===!0){const t=e.session&&typeof e.session=="object"&&!Array.isArray(e.session)?e.session:{},i=typeof t.pid=="number"?` pid ${t.pid}`:"",r=typeof t.port=="number"?` port ${t.port}`:"";return`running${i}${r}`.trim()}return e.processAlive===!0&&e.healthy===!1?"unhealthy":"stopped"}function he(e){return!e||typeof e!="object"||Array.isArray(e)?!1:e.op==="tree"||e.op==="cycles"||e.op==="imports"?!0:Array.isArray(e.requests)&&e.requests.some(t=>t&&typeof t=="object"&&!Array.isArray(t)&&(t.op==="tree"||t.op==="cycles"||t.op==="imports"))}function be(e){if(!e||typeof e!="object"||Array.isArray(e))return"inspect";const t=Array.isArray(e.requests)?e.requests.filter(i=>i&&typeof i=="object"&&!Array.isArray(i)):[e];return t.every(i=>i.op==="cycles")?"cycles":t.every(i=>i.op==="tree")?"tree":t.every(i=>i.op==="imports")?"imports":"inspect"}Se().catch(e=>{const t=(0,w.errorPayload)(e);u(t),process.exitCode=1});function u(e,t){const i=(0,J.createCliPresentationEnvelope)(e);V?.enabled&&V.complete({output:i.tracePayload,exitCode:e.ok===!1?1:ge(process.exitCode),durationMs:Date.now()-x,...t?{transport:t}:{}});const r=process.env.AIB_CANONICAL_JSON_PATH;r&&(F.default.mkdirSync(Z.default.dirname(r),{recursive:!0}),F.default.writeFileSync(r,`${JSON.stringify(i.tracePayload,null,2)}
3
- `)),process.stdout.write((0,J.presentCliEnvelope)(i,process.env.AIB_FORCE_JSON==="1"?"json":"agent"))}function ge(e){return typeof e=="number"?e:0}
2
+ "use strict";var W=exports&&exports.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0});const j=W(require("node:fs")),Z=W(require("node:path")),q=require("../payloads/read-stdin-json"),ee=require("../commands/doctor"),te=require("../commands/init-workspace"),G=require("../commands/inspect"),re=require("../commands/imports-command"),ne=require("../commands/config-command"),se=require("../commands/diagnostics-command"),ie=require("../commands/execution-command"),oe=require("../commands/feedback-command"),ae=require("../commands/observability-command"),ce=require("../commands/generate-docs-command"),ue=require("../commands/help-command"),de=require("../commands/runtime-command"),le=require("../commands/reveal-command"),fe=require("../commands/result-view"),pe=require("../commands/quick-read"),P=require("../commands/captured-input"),U=require("../commands/session-workspace"),$=require("../commands/session-workspace"),B=require("../config/path-aliases"),x=require("../session/client"),me=require("../session/server"),_e=require("../commands/module-plan-cache"),H=require("../config/resolve-command-alias"),Ce=require("../config/auto-start-ide"),o=require("../config/env-vars"),J=require("../client/transport-options"),y=require("../shared/errors"),E=require("../shared/metrics"),K=require("../shared/presentation"),z=require("../tracing/config"),M=require("../tracing/trace"),Q=require("../runtime/input-source");function Ie(e){return e.ok===!1}let g=null,D=Date.now();function Se(e){const r=[];let i=process.cwd(),n,C,N=process.env[o.CLI_ENV.metrics]==="1",l=(0,J.parseExtensionTransport)(process.env[o.CLI_ENV.transport])??void 0,I,A,f;for(let m=0;m<e.length;m+=1){const _=e[m];if(_){if(_==="--cwd"){const d=e[m+1];if(!d)throw new y.CliError("MISSING_FLAG_VALUE","Expected a value after --cwd.");i=d,m+=1;continue}if(_==="--instance"){const d=e[m+1];if(!d)throw new y.CliError("MISSING_FLAG_VALUE","Expected a value after --instance.");n=d,m+=1;continue}if(_==="--session"||_==="-s"){const d=e[m+1];if(!d)throw new y.CliError("MISSING_FLAG_VALUE",`Expected a value after ${_}.`);C=d,m+=1;continue}if(_==="--metrics"){N=!0;continue}if(_==="--dsl"||_==="--force-dsl"){f="dsl";continue}if(_==="--stdin-format"){const d=e[m+1];if(d!=="auto"&&d!=="dsl")throw new y.CliError("INVALID_STDIN_FORMAT","Expected --stdin-format to be auto or dsl.");f=d,m+=1;continue}if(_==="--trace-dir"){const d=e[m+1];if(!d)throw new y.CliError("MISSING_FLAG_VALUE","Expected a value after --trace-dir.");A=d,m+=1;continue}if(_==="--auto-start-ide"){I="serve-web";continue}if(_==="--no-auto-start-ide"){I="off";continue}if(_==="--transport"){const d=e[m+1],c=(0,J.parseExtensionTransport)(d);if(!c)throw new y.CliError("INVALID_TRANSPORT","Expected --transport to be either http or websocket.");l=c,m+=1;continue}r.push(_)}}const h=process.env[o.CLI_ENV.traceDir];return{commandArgs:r,cwd:i,instanceId:n,sessionId:C,metricsEnabled:N,transport:l,autoStartIde:(0,Ce.resolveAutoStartIdePolicy)(I),trace:(0,z.resolveTraceConfig)(i,{...A!==void 0?{flagTraceDir:A}:{},...h!==void 0?{envTraceDir:h}:{}}),...f!==void 0?{stdinFormat:f}:{}}}async function Ee(){D=Date.now();const e=(0,E.metricsNow)(),r=[],{commandArgs:i,cwd:n,instanceId:C,sessionId:N,metricsEnabled:l,transport:I,autoStartIde:A,trace:f,stdinFormat:h}=Se(process.argv.slice(2));await(0,$.runWithSessionOverride)(N,async()=>{const[m,..._]=i,d=(0,q.stripStdinFormatFlags)(_),c=d.restArgs,X=(0,E.metricsNow)(),s=await(0,H.resolveCanonicalCommandAlias)(m??"ping",n,C,A);if(l&&(0,E.recordSpan)(r,"cli.aliasResolution",X),(0,H.isRemovedAgentCommand)(s))throw new y.CliError("UNKNOWN_COMMAND",`Unknown command: ${s}`,{availableCommands:["doctor","diagnostics","listInstances","ping","runtimeInfo","printConfig","init-skill-usage","init","help","generate-docs","config","qr","sync","reveal","inspect","imports","view","execution","move","rename","refactor","modulePlan","session","runtime","trace","observability","feedback","note"]});if(s==="session"&&(c[0]??"status")==="serve"){await(0,me.runSessionServerCli)();return}if(s==="trace"){const t=(0,z.runTraceCommand)(n,c,f);u(t);return}if(s==="diagnostics"){await(0,se.runDiagnosticsCommand)(c);return}if(s==="observability"){L(n,s,c,f);const t=(0,ae.runObservabilityCommand)(n,c);u(t);return}if(s==="feedback"||s==="note"){L(n,s,c,f);const t=(0,oe.runFeedbackCommand)(n,c,s);u(t);return}if(s==="init"){const t=(0,te.runInitWorkspace)(n,c);u(t);return}if(s==="help"){const t=(0,ue.runHelpCommand)(c);u(t);return}if(s==="generate-docs"){const t=(0,ce.runGenerateDocsCommand)(n,c);u(t);return}if(s==="config"){L(n,s,c,f);const t=(0,ne.runConfigCommand)(n,c);u(t);return}if(s==="runtime"){const t=await(0,de.runRuntimeCommand)(n,c);t.ok===!1&&(process.exitCode=1),u(t);return}if(s==="reveal"){L(n,s,c,f);const t=(0,le.runRevealCommand)(n,c);u(t);return}if(s==="qr"){const t=c.includes("--stdin")?await(0,q.readRawStdinText)():void 0;g=(0,M.startTrace)({cwd:n,argv:process.argv.slice(2),command:s,restArgs:c,...f.absoluteTraceDir!==void 0?{traceDir:f.absoluteTraceDir}:f.traceDir!==void 0?{traceDir:f.traceDir}:{},...t!==void 0?{stdinSource:{format:"qr",text:t}}:{},startedAtMs:D});const p=await(0,pe.runQuickReadCommand)(n,c,t!==void 0?{rawStdin:t}:{});p.ok===!1&&(process.exitCode=1),u(p);return}const V=Ae(s,c),k=V?(0,$.readEffectiveSessionPathAliases)(n):{},a=V?(0,B.expandPathAliasesInArgs)(n,c,k):c,v=await(0,Q.resolveCommandInputSource)({command:s,cwd:n,restArgs:a,readStdinInput:()=>(0,q.readStdinPayloadWithSource)({command:s,restArgs:a,...d.format!==void 0||h!==void 0?{format:d.format??h}:{}})}),S=V?(0,B.expandPathAliasesInJson)(n,v.payload,k):v.payload;if(g=(0,M.startTrace)({cwd:n,argv:process.argv.slice(2),command:s,restArgs:a,...f.absoluteTraceDir!==void 0?{traceDir:f.absoluteTraceDir}:f.traceDir!==void 0?{traceDir:f.traceDir}:{},...S!==void 0?{stdinPayload:S}:{},...v.source!==void 0?{stdinSource:v.source}:{},startedAtMs:D}),s==="session"){const t=a[0]??"status";if(t==="init"||t==="clear"||t==="where"||t==="read"||t==="write"||t==="prefs"||t==="aliases"||t==="list"||t==="use"){const p=(0,U.runSessionWorkspaceCommand)(n,a,S);u(p);return}if(t==="status"){const p=(0,U.runSessionWorkspaceCommand)(n,a,S),b=await(0,x.getSessionStatus)();u({...p,runtime:Ne(b)});return}if(t==="start"){const p=await(0,x.startSession)();u(p);return}if(t==="stop"){const p=await(0,x.stopSession)();u(p);return}throw new y.CliError("UNKNOWN_SESSION_COMMAND",`Unknown aib session command: ${t}`)}if(s==="imports"&&a[0]==="normalize"){const t=(0,P.attachCapturedInput)(n,"imports",S,await(0,re.runImportsCommand)(n,a,S,{...C!==void 0?{explicitInstanceId:C}:{},autoStartIde:A,...I!==void 0?{transport:I}:{},...l?{metricsEnabled:!0}:{}},l?r:void 0),v.source);u(t);return}if(s==="execution"){const t=(0,ie.runExecutionCommand)(n,a);u(t);return}if(s==="view"){const t=(0,fe.runResultViewCommand)(n,a,S);t.ok===!1&&(process.exitCode=1),u(t);return}if(s==="doctor"){const t=a.includes("--progress"),p=a.includes("--json"),b=await(0,ee.runDoctor)({cwd:n,runtime:a.includes("--runtime"),verbose:a.includes("--verbose"),json:p,progress:t});b.ok===!1&&(process.exitCode=1),u(b,void 0,{suppressStdout:t&&!p&&process.env.AIB_FORCE_JSON!=="1"});return}if(s==="inspect"&&(a[0]==="graph"||a[0]==="tree"||a[0]==="cycles")){const t=(0,E.metricsNow)(),p=a[0]==="tree"?"tree":a[0]==="cycles"?"cycles":"graph",b=(0,P.attachCapturedInput)(n,p,S,await(0,G.runInspect)(n,a,S,{...C!==void 0?{explicitInstanceId:C}:{},autoStartIde:A,...I!==void 0?{transport:I}:{},...l?{metricsEnabled:!0}:{}}),v.source);l&&((0,E.recordSpan)(r,"cli.inspectGraph",t),(0,E.recordSpan)(r,"cli.total",e)),u(l?(0,E.appendMetrics)(b,r):b,I);return}if(s==="inspect"&&a.includes("--stdin")&&be(S)){const t=(0,E.metricsNow)(),p=(0,P.attachCapturedInput)(n,he(S),S,await(0,G.runInspect)(n,a,S,{...C!==void 0?{explicitInstanceId:C}:{},autoStartIde:A,...I!==void 0?{transport:I}:{},...l?{metricsEnabled:!0}:{}}),v.source);l&&((0,E.recordSpan)(r,"cli.inspectLocal",t),(0,E.recordSpan)(r,"cli.total",e)),u(l?(0,E.appendMetrics)(p,r):p,I);return}if((0,Q.commandRequiresPayload)(s,a,v))throw new y.CliError("STDIN_REQUIRED",`${s} currently expects a payload on stdin or --from.`);const w={command:s,restArgs:a,cwd:n},T=we(s,a);T&&(w.modulePlanExecutionId=T),N!==void 0&&(w.sessionId=N),C!==void 0&&(w.instanceId=C),S!==void 0&&(w.stdinPayload=S),v.source!==void 0&&(w.stdinInputSource=v.source),l&&(w.metricsEnabled=!0),I&&(w.transport=I),w.autoStartIde=A.mode;const R=ve();Object.keys(R).length>0&&(w.env=R);const Y=(0,E.metricsNow)(),O=await(0,x.callSession)(w,l?r:void 0);l&&((0,E.recordSpan)(r,"cli.callSession",Y),(0,E.recordSpan)(r,"cli.total",e));const F=l?(0,E.appendMetrics)(O,r):O;Ie(F)&&(process.exitCode=1),u(F,I)})}function ve(){const e=[o.CLI_ENV.managedHostScript,o.CLI_ENV.managedHostKind,o.CLI_ENV.managedHostRunDir,o.CLI_ENV.codeServerPath,o.CLI_ENV.extensionVsix,o.CLI_ENV.ideCommand,o.CLI_ENV.chromePath,o.CLI_ENV.managedHostWaitMs,o.CLI_ENV.workspaceRoot,o.CLI_ENV.disableWatchers,o.CLI_ENV.trace,o.CLI_ENV.traceDir,o.CLI_ENV.failureSnapshots,o.CLI_ENV.productStorageDir,o.CLI_ENV.metrics,o.CLI_ENV.metricsDir,o.CLI_ENV.metricsTag,o.CLI_ENV.mutationImpactMetrics,o.CLI_ENV.mutationImpactStream,o.CLI_ENV.testPostMutationCyclesDelayMs,o.CLI_ENV.testRefactorBatchDelayMs,o.CLI_ENV.testRenameDelayMs,o.CLI_ENV.modulePlanSyncWaitMs,o.CLI_ENV.refactorBatchSyncWaitMs,o.CLI_ENV.renameSyncWaitMs],r={};for(const i of e){const n=process.env[i];n!==void 0&&(r[i]=n)}return r}function we(e,r){if(e!=="modulePlan")return null;const i=r[0]??"";return i!=="execute"&&i!=="apply"?null:ye()??(0,_e.buildModulePlanExecutionId)()}function ye(){const e=process.env.AIB_MODULE_PLAN_EXECUTION_ID;return e&&/^exec_[a-z0-9_-]+$/i.test(e)?e:null}function L(e,r,i,n){g=(0,M.startTrace)({cwd:e,argv:process.argv.slice(2),command:r,restArgs:i,...n.absoluteTraceDir!==void 0?{traceDir:n.absoluteTraceDir}:n.traceDir!==void 0?{traceDir:n.traceDir}:{},startedAtMs:D})}function Ae(e,r){return e==="session"||e==="execution"||e==="observability"||e==="doctor"||e==="reveal"||e==="view"||e==="imports"&&r[0]==="normalize"||e==="inspect"&&(r[0]==="graph"||r[0]==="tree"||r[0]==="cycles"||r[0]==="imports"||r.includes("--stdin"))}function Ne(e){if(e.running===!0){const r=e.session&&typeof e.session=="object"&&!Array.isArray(e.session)?e.session:{},i=typeof r.pid=="number"?` pid ${r.pid}`:"",n=typeof r.port=="number"?` port ${r.port}`:"";return`running${i}${n}`.trim()}return e.processAlive===!0&&e.healthy===!1?"unhealthy":"stopped"}function be(e){return!e||typeof e!="object"||Array.isArray(e)?!1:e.op==="tree"||e.op==="cycles"||e.op==="imports"?!0:Array.isArray(e.requests)&&e.requests.some(r=>r&&typeof r=="object"&&!Array.isArray(r)&&(r.op==="tree"||r.op==="cycles"||r.op==="imports"))}function he(e){if(!e||typeof e!="object"||Array.isArray(e))return"inspect";const r=Array.isArray(e.requests)?e.requests.filter(i=>i&&typeof i=="object"&&!Array.isArray(i)):[e];return r.every(i=>i.op==="cycles")?"cycles":r.every(i=>i.op==="tree")?"tree":r.every(i=>i.op==="imports")?"imports":"inspect"}Ee().catch(e=>{const r=(0,y.errorPayload)(e);u(r),process.exitCode=1});function u(e,r,i={}){const n=(0,K.createCliPresentationEnvelope)(e),C=(0,K.presentCliEnvelope)(n,process.env.AIB_FORCE_JSON==="1"?"json":"agent"),N=i.suppressStdout===!0?"":C;g?.enabled&&g.complete({output:n.tracePayload,stdoutText:N,exitCode:e.ok===!1?1:ge(process.exitCode),durationMs:Date.now()-D,...r?{transport:r}:{}});const l=process.env.AIB_CANONICAL_JSON_PATH;l&&(j.default.mkdirSync(Z.default.dirname(l),{recursive:!0}),j.default.writeFileSync(l,`${JSON.stringify(n.tracePayload,null,2)}
3
+ `)),i.suppressStdout!==!0&&process.stdout.write(C)}function ge(e){return typeof e=="number"?e:0}
@@ -1 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.runConfigCommand=A,exports.readConfigTextInput=c;const p=require("../shared/agent-text"),l=require("../shared/errors"),m=require("../config/import-rules"),d=require("../config/path-aliases"),h=require("../config/local-config"),u=require("../config/workspace-root"),C=require("./session-workspace"),x=require("./normalize-imports"),r=require("./config-output");function A(e,o=[]){const t=T(o,"--session-dir");if(t)return _(e,t);const n=y(o);if(!n)throw new l.CliError("CONFIG_USAGE","Usage: aib config [all|aliases|rules|session] [--session-dir .tmp/aib]");const s=c(e),i={ok:!0,root:s.root,configPath:s.configPath,view:n,pathAliases:s.aliases,configPathAliases:s.configAliases,sessionPathAliases:s.sessionAliases,importRules:(0,m.importRulesToJson)(s.importRules),importNormalize:s.importNormalize.map(D),graphExclude:[...s.graphExclude],tree:{onlyDirs:{exclude:[...s.tree.onlyDirs.exclude]},files:{exclude:[...s.tree.files.exclude]}},sync:{tsconfig:{exclude:[...s.sync.tsconfig.exclude]}},session:(0,r.configSessionPayload)(s)};return(0,p.attachAgentText)(i,M(s,n))}function _(e,o){const t=c(e),n=(0,u.updateWorkspaceConfig)(e,{sessionDir:o}),s=c(e),i=(0,u.workspaceConfigSummary)(n),a=t.sessionDir!==s.sessionDir,f={ok:!0,config:"aib.json",status:a?"updated":"unchanged",root:s.root,configPath:s.configPath,...i};return(0,p.attachAgentText)(f,(0,r.formatSessionDirMutationText)(s,a))}function y(e){if(e.length===0)return"default";if(e.length!==1)return null;const o=e[0];return o==="all"||o==="aliases"||o==="rules"||o==="session"?o:null}function T(e,o){if(!e.includes(o))return null;let t=null;for(let n=0;n<e.length;n+=1){if(e[n]!==o)throw new l.CliError("CONFIG_USAGE","Usage: aib config [--session-dir .tmp/aib]");if(t!==null)throw new l.CliError("CONFIG_USAGE",`${o} can be provided only once.`);const i=e[n+1];if(!i||i.startsWith("--"))throw new l.CliError("MISSING_FLAG_VALUE",`Expected a value after ${o}.`);t=i,n+=1}return t}function D(e){return{...e.scope?{scope:e.scope}:{},...e.mode?{to:e.mode}:{},...e.preferAlias?{preferAlias:e.preferAlias}:{},...e.exclude.length>0?{exclude:e.exclude}:{}}}function c(e){const o=(0,u.resolveRequiredWorkspaceRoot)(e),t=(0,u.workspaceConfigSummary)(o.config),n=(0,d.readConfigPathAliases)(e),s=(0,C.readSessionPathAliasOverrides)(e),i=(0,d.effectivePathAliases)(e,s),a=(0,m.readConfigImportRules)(e),f=(0,x.readWorkspaceNormalizeImportRules)(e),g=(0,h.resolveLocalCliConfig)(e);return{root:o.root,configPath:o.configPath,workspaceRoot:String(t["workspace.root"]??"."),sessionDir:typeof t.sessionDir=="string"?t.sessionDir:null,aliases:i,configAliases:n,sessionAliases:s,importRules:a,importNormalize:f.rules,graphExclude:g.config.inspect.graph.exclude,tree:g.config.inspect.tree,sync:g.config.sync,sessionAutoClean:t["session.autoClean"]!==!1,sessionTtlCleanMinutes:typeof t["session.ttlCleanMinutes"]=="number"?t["session.ttlCleanMinutes"]:60,sessionAutoDelete:t["session.autoDelete"]!==!1,sessionTtlDeleteMinutes:typeof t["session.ttlDeleteMinutes"]=="number"?t["session.ttlDeleteMinutes"]:60,runtimeAutoStopManagedIde:t["runtime.autoStopManagedIde"]!==!1,runtimeManagedIdeTtlMinutes:typeof t["runtime.managedIdeTtlMinutes"]=="number"?t["runtime.managedIdeTtlMinutes"]:15}}function M(e,o){switch(o){case"all":return(0,r.formatConfigAllText)(e);case"aliases":return(0,r.formatConfigAliasesText)(e);case"rules":return(0,r.formatConfigRulesText)(e);case"session":return(0,r.formatConfigSessionText)(e);case"default":return(0,r.formatConfigDefaultText)(e)}}
1
+ "use strict";var _=exports&&exports.__createBinding||(Object.create?(function(e,t,n,s){s===void 0&&(s=n);var o=Object.getOwnPropertyDescriptor(t,n);(!o||("get"in o?!t.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,s,o)}):(function(e,t,n,s){s===void 0&&(s=n),e[s]=t[n]})),C=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),y=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var s=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(s[s.length]=o);return s},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var s=e(t),o=0;o<s.length;o++)s[o]!=="default"&&_(n,t,s[o]);return C(n,t),n}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.runConfigCommand=x,exports.readConfigTextInput=c;const d=y(require("node:fs")),p=require("../shared/agent-text"),a=require("../shared/errors"),h=require("../config/import-rules"),m=require("../config/path-aliases"),b=require("../config/local-config"),u=require("../config/workspace-root"),A=require("./session-workspace"),O=require("./normalize-imports"),i=require("./config-output");function x(e,t=[]){if(t[0]==="upgrade"){if(t.length!==1)throw new a.CliError("CONFIG_USAGE","Usage: aib config upgrade");return v(e)}const n=S(t,"--session-dir");if(n)return P(e,n);const s=D(t);if(!s)throw new a.CliError("CONFIG_USAGE","Usage: aib config [all|aliases|rules|session] [--session-dir .tmp/aib]");const o=c(e),r={ok:!0,root:o.root,configPath:o.configPath,view:s,pathAliases:o.aliases,configPathAliases:o.configAliases,sessionPathAliases:o.sessionAliases,importRules:(0,h.importRulesToJson)(o.importRules),importNormalize:o.importNormalize.map(T),graphExclude:[...o.graphExclude],tree:{onlyDirs:{exclude:[...o.tree.onlyDirs.exclude]},files:{exclude:[...o.tree.files.exclude]}},sync:{tsconfig:{exclude:[...o.sync.tsconfig.exclude]}},session:(0,i.configSessionPayload)(o)};return(0,p.attachAgentText)(r,w(o,s))}function P(e,t){const n=c(e),s=(0,u.updateWorkspaceConfig)(e,{sessionDir:t}),o=c(e),r=(0,u.workspaceConfigSummary)(s),l=n.sessionDir!==o.sessionDir,f={ok:!0,config:"aib.json",status:l?"updated":"unchanged",root:o.root,configPath:o.configPath,...r};return(0,p.attachAgentText)(f,(0,i.formatSessionDirMutationText)(o,l))}function v(e){const t=(0,u.resolveWorkspaceRoot)(e);if(!t||!d.existsSync(t.configPath))throw new a.CliError("CONFIG_UPGRADE_CONFIG_NOT_FOUND","No aib.json config was found to upgrade.",{cwd:e});const n={},s={...t.config};for(const[o,r]of Object.entries(u.MATERIALIZED_INSPECT_DEFAULTS))Object.prototype.hasOwnProperty.call(s,o)||(s[o]=r,n[o]=r);return Object.keys(n).length>0&&d.writeFileSync(t.configPath,`${JSON.stringify(s,null,2)}
2
+ `,"utf8"),(0,p.attachAgentText)({ok:!0,status:Object.keys(n).length>0?"upgraded":"up-to-date",root:t.root,configPath:t.configPath,added:n,unchanged:"existing fields preserved"},(0,i.formatConfigUpgradeText)(n))}function D(e){if(e.length===0)return"default";if(e.length!==1)return null;const t=e[0];return t==="all"||t==="aliases"||t==="rules"||t==="session"?t:null}function S(e,t){if(!e.includes(t))return null;let n=null;for(let s=0;s<e.length;s+=1){if(e[s]!==t)throw new a.CliError("CONFIG_USAGE","Usage: aib config [--session-dir .tmp/aib]");if(n!==null)throw new a.CliError("CONFIG_USAGE",`${t} can be provided only once.`);const r=e[s+1];if(!r||r.startsWith("--"))throw new a.CliError("MISSING_FLAG_VALUE",`Expected a value after ${t}.`);n=r,s+=1}return n}function T(e){return{...e.scope?{scope:e.scope}:{},...e.mode?{to:e.mode}:{},...e.preferAlias?{preferAlias:e.preferAlias}:{},...e.exclude.length>0?{exclude:e.exclude}:{}}}function c(e){const t=(0,u.resolveRequiredWorkspaceRoot)(e),n=(0,u.workspaceConfigSummary)(t.config),s=(0,m.readConfigPathAliases)(e),o=(0,A.readSessionPathAliasOverrides)(e),r=(0,m.effectivePathAliases)(e,o),l=(0,h.readConfigImportRules)(e),f=(0,O.readWorkspaceNormalizeImportRules)(e),g=(0,b.resolveLocalCliConfig)(e);return{root:t.root,configPath:t.configPath,workspaceRoot:String(n["workspace.root"]??"."),sessionDir:typeof n.sessionDir=="string"?n.sessionDir:null,aliases:r,configAliases:s,sessionAliases:o,importRules:l,importNormalize:f.rules,graphExclude:g.config.inspect.graph.exclude,tree:g.config.inspect.tree,sync:g.config.sync,sessionAutoClean:n["session.autoClean"]!==!1,sessionTtlCleanMinutes:typeof n["session.ttlCleanMinutes"]=="number"?n["session.ttlCleanMinutes"]:60,sessionAutoDelete:n["session.autoDelete"]!==!1,sessionTtlDeleteMinutes:typeof n["session.ttlDeleteMinutes"]=="number"?n["session.ttlDeleteMinutes"]:60,runtimeAutoStopManagedIde:n["runtime.autoStopManagedIde"]!==!1,runtimeManagedIdeTtlMinutes:typeof n["runtime.managedIdeTtlMinutes"]=="number"?n["runtime.managedIdeTtlMinutes"]:15}}function w(e,t){switch(t){case"all":return(0,i.formatConfigAllText)(e);case"aliases":return(0,i.formatConfigAliasesText)(e);case"rules":return(0,i.formatConfigRulesText)(e);case"session":return(0,i.formatConfigSessionText)(e);case"default":return(0,i.formatConfigDefaultText)(e)}}
@@ -1,8 +1,10 @@
1
- "use strict";var S=exports&&exports.__createBinding||(Object.create?(function(e,t,n,o){o===void 0&&(o=n);var s=Object.getOwnPropertyDescriptor(t,n);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,o,s)}):(function(e,t,n,o){o===void 0&&(o=n),e[o]=t[n]})),A=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),O=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var o=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(o[o.length]=s);return o},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var o=e(t),s=0;s<o.length;s++)o[s]!=="default"&&S(n,t,o[s]);return A(n,t),n}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.CONFIG_SECTION_NAMES=void 0,exports.formatConfigDefaultText=_,exports.formatConfigAllText=T,exports.formatConfigAliasesText=M,exports.formatConfigRulesText=$,exports.formatConfigSessionText=D,exports.formatInitText=I,exports.formatSessionDirMutationText=N,exports.configSessionPayload=b;const i=O(require("node:path"));exports.CONFIG_SECTION_NAMES=["pathAliases","importRules","importNormalize","inspect.graph.exclude","inspect.tree.onlyDirs.exclude","inspect.tree.files.exclude","sync.tsconfig.exclude"];function _(e){return[...a(e),...c(e,exports.CONFIG_SECTION_NAMES)].join(`
2
- `)}function T(e){return[...a(e),...l(e),...c(e,exports.CONFIG_SECTION_NAMES)].join(`
3
- `)}function M(e){return[...v("pathAliases",h(e.aliases,e.configAliases,e.sessionAliases)),...g(exports.CONFIG_SECTION_NAMES.filter(t=>t!=="pathAliases"&&m(e,t).length===0))].join(`
4
- `)}function $(e){const t=exports.CONFIG_SECTION_NAMES.filter(n=>n!=="pathAliases");return x(c(e,t)).join(`
5
- `)}function D(e){return[...a(e),...l(e)].join(`
6
- `)}function I(e,t){return[t==="created"?"aib workspace initialized":t==="unchanged"?"aib config unchanged":"aib config updated","",...a(e),...l(e),...c(e,exports.CONFIG_SECTION_NAMES)].join(`
7
- `)}function N(e,t){return[t?"aib config updated":"aib config unchanged","",...a(e),...l(e),"","other config fields preserved"].join(`
8
- `)}function b(e){return{"workspace.root":e.workspaceRoot,...e.sessionDir?{sessionDir:e.sessionDir}:{},"session.autoClean":e.sessionAutoClean,"session.ttlCleanMinutes":e.sessionTtlCleanMinutes,"session.autoDelete":e.sessionAutoDelete,"session.ttlDeleteMinutes":e.sessionTtlDeleteMinutes,"runtime.autoStopManagedIde":e.runtimeAutoStopManagedIde,"runtime.managedIdeTtlMinutes":e.runtimeManagedIdeTtlMinutes}}function a(e){return[`root: ${e.root}`,`workspace.root: ${e.workspaceRoot}`,`config: ${C(e.root,e.configPath)}`,`sessionDir: ${w(e)}`]}function l(e){const t=[];return e.sessionDir&&t.push("new sessions: <sessionDir>/<name>/**"),t.push(`session cleanup: ${u(e.sessionAutoClean,e.sessionTtlCleanMinutes)}`,`session deletion: ${u(e.sessionAutoDelete,e.sessionTtlDeleteMinutes)}`,`runtime cleanup: ${u(e.runtimeAutoStopManagedIde,e.runtimeManagedIdeTtlMinutes)}`),t.length>0?["",...t]:[]}function c(e,t){const n=[],o=[];for(const s of t){const r=m(e,s);if(r.length===0){o.push(s);continue}n.push("",`${s}:`,...r)}return n.push(...g(o)),n}function v(e,t){return t.length>0?[`${e}:`,...t]:[`${e}: not set`]}function g(e){return e.length>0?["","not set:",...e.map(t=>` ${t}`)]:[]}function x(e){return e[0]===""?e.slice(1):e}function m(e,t){switch(t){case"pathAliases":return h(e.aliases,e.configAliases,e.sessionAliases);case"importRules":return j(e.importRules);case"importNormalize":return y(e.importNormalize);case"inspect.graph.exclude":return f(e.graphExclude);case"inspect.tree.onlyDirs.exclude":return f(e.tree.onlyDirs.exclude);case"inspect.tree.files.exclude":return f(e.tree.files.exclude);case"sync.tsconfig.exclude":return f(e.sync.tsconfig.exclude)}}function h(e,t,n){const o=Object.entries(e).sort(([s],[r])=>s.localeCompare(r));return o.length===0?[]:o.map(([s,r])=>{const d=Object.prototype.hasOwnProperty.call(n,s),p=Object.prototype.hasOwnProperty.call(t,s);return` @${s} -> ${r}${d&&p?" (session overrides config)":d?" (session)":""}`})}function j(e){return e.length===0?[]:e.map(t=>{const n=[t.specifier?`specifier=${t.specifier}`:null,t.ending?`ending=${t.ending}`:null,t.builtin?`builtin=${t.builtin}`:null,t.unusedImports?`unusedImports=${t.unusedImports}`:null].filter(o=>o!==null);return` ${t.scope}: ${n.length>0?n.join(" "):"defaults"}`})}function y(e){return e.length===0?[]:e.map(t=>{const n=[t.mode?`to=${t.mode}`:null,t.preferAlias?`preferAlias=${t.preferAlias}`:null,t.exclude.length>0?`exclude=${t.exclude.join(" ")}`:null].filter(o=>o!==null);return` ${t.scope??"*"}: ${n.length>0?n.join(" "):"defaults"}`})}function f(e){return e.map(t=>` ${t}`)}function C(e,t){const n=i.resolve(e),o=i.resolve(t);if(E(n,o))return"<root>";const s=i.relative(n,o);return s&&!s.startsWith("..")&&!i.isAbsolute(s)?`<root>/${P(s)}`:o}function w(e){if(!e.sessionDir)return"not set";const t=i.isAbsolute(e.sessionDir)?e.sessionDir:i.resolve(e.root,e.sessionDir);return C(e.root,t)}function u(e,t){return e?`after ${t} minutes of inactivity`:"disabled"}function E(e,t){return process.platform==="win32"?e.toLowerCase()===t.toLowerCase():e===t}function P(e){return e.replace(/\\/g,"/")}
1
+ "use strict";var O=exports&&exports.__createBinding||(Object.create?(function(e,t,n,o){o===void 0&&(o=n);var s=Object.getOwnPropertyDescriptor(t,n);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,o,s)}):(function(e,t,n,o){o===void 0&&(o=n),e[o]=t[n]})),S=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),A=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var o=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(o[o.length]=s);return o},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var o=e(t),s=0;s<o.length;s++)o[s]!=="default"&&O(n,t,o[s]);return S(n,t),n}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.CONFIG_SECTION_NAMES=void 0,exports.formatConfigDefaultText=T,exports.formatConfigAllText=_,exports.formatConfigAliasesText=$,exports.formatConfigRulesText=b,exports.formatConfigSessionText=M,exports.formatInitText=x,exports.formatSessionDirMutationText=D,exports.formatConfigUpgradeText=I,exports.configSessionPayload=N;const i=A(require("node:path"));exports.CONFIG_SECTION_NAMES=["pathAliases","importRules","importNormalize","inspect.graph.exclude","inspect.tree.onlyDirs.exclude","inspect.tree.files.exclude","sync.tsconfig.exclude"];function T(e){return[...a(e),...l(e,exports.CONFIG_SECTION_NAMES)].join(`
2
+ `)}function _(e){return[...a(e),...c(e),...l(e,exports.CONFIG_SECTION_NAMES)].join(`
3
+ `)}function $(e){return[...v("pathAliases",h(e.aliases,e.configAliases,e.sessionAliases)),...g(exports.CONFIG_SECTION_NAMES.filter(t=>t!=="pathAliases"&&m(e,t).length===0))].join(`
4
+ `)}function b(e){const t=exports.CONFIG_SECTION_NAMES.filter(n=>n!=="pathAliases");return j(l(e,t)).join(`
5
+ `)}function M(e){return[...a(e),...c(e)].join(`
6
+ `)}function x(e,t){return[t==="created"?"aib workspace initialized":t==="unchanged"?"aib config unchanged":"aib config updated","",...a(e),...c(e),...l(e,exports.CONFIG_SECTION_NAMES)].join(`
7
+ `)}function D(e,t){return[t?"aib config updated":"aib config unchanged","",...a(e),...c(e),"","other config fields preserved"].join(`
8
+ `)}function I(e){const t=Object.entries(e);return t.length===0?["aib config is up to date","","unchanged: existing fields preserved"].join(`
9
+ `):["aib config upgraded","","added:",...t.map(([n,o])=>` ${n}: ${o}`),"","unchanged: existing fields preserved"].join(`
10
+ `)}function N(e){return{"workspace.root":e.workspaceRoot,...e.sessionDir?{sessionDir:e.sessionDir}:{},"session.autoClean":e.sessionAutoClean,"session.ttlCleanMinutes":e.sessionTtlCleanMinutes,"session.autoDelete":e.sessionAutoDelete,"session.ttlDeleteMinutes":e.sessionTtlDeleteMinutes,"runtime.autoStopManagedIde":e.runtimeAutoStopManagedIde,"runtime.managedIdeTtlMinutes":e.runtimeManagedIdeTtlMinutes}}function a(e){return[`root: ${e.root}`,`workspace.root: ${e.workspaceRoot}`,`config: ${p(e.root,e.configPath)}`,`sessionDir: ${E(e)}`]}function c(e){const t=[];return e.sessionDir&&t.push("new sessions: <sessionDir>/<name>/**"),t.push(`session cleanup: ${u(e.sessionAutoClean,e.sessionTtlCleanMinutes)}`,`session deletion: ${u(e.sessionAutoDelete,e.sessionTtlDeleteMinutes)}`,`runtime cleanup: ${u(e.runtimeAutoStopManagedIde,e.runtimeManagedIdeTtlMinutes)}`),t.length>0?["",...t]:[]}function l(e,t){const n=[],o=[];for(const s of t){const r=m(e,s);if(r.length===0){o.push(s);continue}n.push("",`${s}:`,...r)}return n.push(...g(o)),n}function v(e,t){return t.length>0?[`${e}:`,...t]:[`${e}: not set`]}function g(e){return e.length>0?["","not set:",...e.map(t=>` ${t}`)]:[]}function j(e){return e[0]===""?e.slice(1):e}function m(e,t){switch(t){case"pathAliases":return h(e.aliases,e.configAliases,e.sessionAliases);case"importRules":return y(e.importRules);case"importNormalize":return w(e.importNormalize);case"inspect.graph.exclude":return f(e.graphExclude);case"inspect.tree.onlyDirs.exclude":return f(e.tree.onlyDirs.exclude);case"inspect.tree.files.exclude":return f(e.tree.files.exclude);case"sync.tsconfig.exclude":return f(e.sync.tsconfig.exclude)}}function h(e,t,n){const o=Object.entries(e).sort(([s],[r])=>s.localeCompare(r));return o.length===0?[]:o.map(([s,r])=>{const d=Object.prototype.hasOwnProperty.call(n,s),C=Object.prototype.hasOwnProperty.call(t,s);return` @${s} -> ${r}${d&&C?" (session overrides config)":d?" (session)":""}`})}function y(e){return e.length===0?[]:e.map(t=>{const n=[t.specifier?`specifier=${t.specifier}`:null,t.ending?`ending=${t.ending}`:null,t.builtin?`builtin=${t.builtin}`:null,t.unusedImports?`unusedImports=${t.unusedImports}`:null].filter(o=>o!==null);return` ${t.scope}: ${n.length>0?n.join(" "):"defaults"}`})}function w(e){return e.length===0?[]:e.map(t=>{const n=[t.mode?`to=${t.mode}`:null,t.preferAlias?`preferAlias=${t.preferAlias}`:null,t.exclude.length>0?`exclude=${t.exclude.join(" ")}`:null].filter(o=>o!==null);return` ${t.scope??"*"}: ${n.length>0?n.join(" "):"defaults"}`})}function f(e){return e.map(t=>` ${t}`)}function p(e,t){const n=i.resolve(e),o=i.resolve(t);if(P(n,o))return"<root>";const s=i.relative(n,o);return s&&!s.startsWith("..")&&!i.isAbsolute(s)?`<root>/${R(s)}`:o}function E(e){if(!e.sessionDir)return"not set";const t=i.isAbsolute(e.sessionDir)?e.sessionDir:i.resolve(e.root,e.sessionDir);return p(e.root,t)}function u(e,t){return e?`after ${t} minutes of inactivity`:"disabled"}function P(e,t){return process.platform==="win32"?e.toLowerCase()===t.toLowerCase():e===t}function R(e){return e.replace(/\\/g,"/")}
@@ -1 +1,2 @@
1
- "use strict";var k=exports&&exports.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var s=Object.getOwnPropertyDescriptor(e,n);(!s||("get"in s?!e.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,s)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),N=exports&&exports.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),b=exports&&exports.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(r[r.length]=s);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),s=0;s<r.length;s++)r[s]!=="default"&&k(n,e,r[s]);return N(n,e),n}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.runDoctor=q;const i=b(require("node:fs")),a=b(require("node:path")),E=require("node:child_process"),c=require("../config/env-vars"),f=require("../shared/diagnostic-catalog"),d=require("../shared/hints"),w=require("../managed-host/extension-vsix-resolver"),x=require("../managed-host/serve-web-autostart"),D=require("./ping"),O=require("../shared/agent-text"),j=require("../shared/errors"),A=require("../diagnostics/readiness-text"),v=require("../runtime/bundled-node"),V=require("../runtime/managed-runtime-provisioning"),M=["code.cmd","code.exe","code"],L=["code"];function l(t,e){return t.ok||!e?t:{...t,code:e.code,...e.hints&&e.hints.length>0?{hints:e.hints}:{}}}async function q(t){const e=[],n=a.resolve(__dirname,"..",".."),r=Z(),s=t.runtime===!0;s&&(0,V.ensureManagedRuntimeProvisioned)(n),e.push(B()),e.push(F(n)),e.push(W(n,r)),e.push(K(n,r)),e.push(X(n)),e.push(G(n)),e.push($(n)),e.push(z(s)),s&&e.every(u=>u.severity!=="required"||u.ok)&&e.push(...await R(t.cwd));const o=e.filter(u=>u.severity==="required"&&!u.ok),g=e.filter(u=>u.severity==="optional"&&!u.ok),p={ok:o.length===0,command:"doctor",mode:s?"runtime-install-gate":"static",cwd:a.resolve(t.cwd),generatedAt:new Date().toISOString(),platform:{node:process.version,platform:process.platform,arch:process.arch},packageRoot:n,repoRoot:r,summary:{checkCount:e.length,passedCount:e.filter(u=>u.ok).length,failedRequiredCount:o.length,failedOptionalCount:g.length},checks:e};return t.json===!0?p:(0,O.attachAgentText)(p,(0,A.formatDoctorText)(p,{verbose:t.verbose===!0}))}async function R(t){const e=[];let n=!1;try{const r=await(0,x.startManagedServeWebForCwd)(t);n=!0,e.push({id:"managed-runtime-start",ok:!0,severity:"required",message:"Managed IDE runtime starts and activates the bridge.",details:H(r)})}catch(r){return e.push(S("managed-runtime-start","Managed IDE runtime failed to start or activate the bridge.",r)),e}try{const r=await(0,D.runPing)(t);e.push({id:"bridge-ping",ok:!0,severity:"required",message:"Bridge ping succeeds through the managed runtime.",details:T(r)})}catch(r){e.push(S("bridge-ping","Bridge ping failed through the managed runtime.",r))}if(n)try{const r=await(0,x.stopManagedServeWebForCwd)(t);e.push({id:"managed-runtime-stop",ok:r.stopped===!0,severity:"required",message:r.stopped===!0?"Managed IDE runtime stops cleanly.":"Managed IDE runtime stop did not report a stopped runtime.",details:r})}catch(r){e.push(S("managed-runtime-stop","Managed IDE runtime stop failed.",r))}return e}function S(t,e,n){const r=n instanceof j.CliError?n:null;return{id:t,ok:!1,severity:"required",message:e,code:r?.code??"DOCTOR_RUNTIME_CHECK_FAILED",details:{error:n instanceof Error?n.message:String(n),...r?.details&&typeof r.details=="object"&&!Array.isArray(r.details)?{details:r.details}:{}},hints:r?.details&&typeof r.details=="object"&&!Array.isArray(r.details)&&Array.isArray(r.details.hints)?r.details.hints:(0,f.buildAutoStartHints)()}}function H(t){const e=t.metadata&&typeof t.metadata=="object"&&!Array.isArray(t.metadata)?t.metadata:{},n=t.artifacts&&typeof t.artifacts=="object"&&!Array.isArray(t.artifacts)?t.artifacts:{};return{hostId:typeof t.hostId=="string"?t.hostId:null,hostKind:typeof t.hostKind=="string"?t.hostKind:e.hostKind??null,reused:t.reused===!0,codeCommand:typeof t.codeCommand=="string"?t.codeCommand:e.codeCommand??null,codeCommandSource:typeof t.codeCommandSource=="string"?t.codeCommandSource:e.codeCommandSource??null,runDir:typeof t.runDir=="string"?t.runDir:e.runDir??null,logsDir:typeof n.logsDir=="string"?n.logsDir:e.logsDir??null,instanceId:typeof e.instanceId=="string"?e.instanceId:null,serveWebPid:typeof e.serveWebPid=="number"?e.serveWebPid:null,browserPid:typeof e.browserPid=="number"?e.browserPid:null}}function T(t){const e=t.selectedInstance&&typeof t.selectedInstance=="object"&&!Array.isArray(t.selectedInstance)?t.selectedInstance:{},n=t.response&&typeof t.response=="object"&&!Array.isArray(t.response)?t.response:{};return{instanceId:typeof e.instanceId=="string"?e.instanceId:n.instanceId??null,reason:typeof e.reason=="string"?e.reason:null,matchedWorkspace:typeof e.matchedWorkspace=="string"?e.matchedWorkspace:null,pid:typeof n.pid=="number"?n.pid:null,protocolVersion:typeof n.protocolVersion=="number"?n.protocolVersion:null,extensionVersion:typeof n.extensionVersion=="string"?n.extensionVersion:null}}function B(){const t=Number(process.versions.node.split(".")[0]??"0"),e=Number.isInteger(t)&&t>=20;return l({id:"node-version",ok:e,severity:"required",message:e?"Node.js version is supported.":"Node.js 20 or newer is required.",details:{node:process.version,required:">=20"}},{code:"DOCTOR_NODE_VERSION_UNSUPPORTED",hints:[(0,d.actionHint)("Install Node.js 20 or newer, then retry the CLI command.")]})}function F(t){const e=a.join(t,"package.json"),n=a.join(t,"dist","bin","aib.js"),r=i.existsSync(e)&&i.existsSync(n);return l({id:"cli-package-root",ok:r,severity:"required",message:r?"CLI package root looks complete.":"CLI package root is missing package metadata or the built bin.",details:{packageRoot:t,packageJsonPath:e,packageJsonExists:i.existsSync(e),binPath:n,binExists:i.existsSync(n)}},{code:"DOCTOR_CLI_PACKAGE_INCOMPLETE",hints:[(0,d.commandHint)("npm run cli:build","Build the local CLI package."),(0,d.actionHint)("For an installed package, reinstall the CLI package.")]})}function W(t,e){const n=a.join(t,"dist","managed-host","manage-serve-web-host.cjs"),r=e?a.join(e,"scripts","managed-host","manage-serve-web-host.cjs"):null,s=_(c.CLI_ENV.managedHostScript),o=!!(s&&i.existsSync(s)||i.existsSync(n)||r&&i.existsSync(r));return l({id:"managed-host-assets",ok:o,severity:"required",message:o?"Managed host assets are available.":"Managed host assets were not found.",details:{env:c.CLI_ENV.managedHostScript,envScriptPath:s,envScriptExists:s?i.existsSync(s):!1,packagedScriptPath:n,packagedScriptExists:i.existsSync(n),repoScriptPath:r,repoScriptExists:r?i.existsSync(r):!1}},{code:"DOCTOR_MANAGED_HOST_ASSETS_MISSING",hints:(0,f.buildAutoStartHints)()})}function K(t,e){try{const n=(0,w.resolveExtensionVsixPath)({packageRoot:t,repoRoot:e}),r=i.existsSync(n.path);return l({id:"extension-vsix",ok:r,severity:"required",message:r?"Extension VSIX is available.":"Extension VSIX path resolved but the file does not exist.",details:{...n,exists:r}},{code:"DOCTOR_EXTENSION_VSIX_MISSING",hints:[(0,d.configHint)(c.CLI_ENV.extensionVsix,"Point to an existing packaged VSIX artifact."),(0,d.commandHint)("npm --prefix packages/extension run package:vsix","Build a local VSIX artifact.")]})}catch(n){return{id:"extension-vsix",ok:!1,severity:"required",message:"Extension VSIX resolution failed.",code:"DOCTOR_EXTENSION_VSIX_RESOLUTION_FAILED",details:{error:n instanceof Error?n.message:String(n),code:typeof n=="object"&&n!==null&&"code"in n?String(n.code):null},hints:(0,f.buildAutoStartHints)()}}}function G(t){const e=process.env[c.CLI_ENV.ideCommand]?.trim(),n=process.env[c.CLI_ENV.managedHostKind]?.trim()||U(t),r=_(c.CLI_ENV.codeServerPath),s=a.join(t,"runtimes","code-server","node_modules","code-server","out","node","entry.js"),o=(0,v.resolveNodeRuntime)(t),g=i.existsSync(s)?`${o.command} ${s}`:null,p=a.join(t,"runtimes","code-server","bin",process.platform==="win32"?"code-server.cmd":"code-server"),u=[r,g,p,"code-server"].filter(m=>!!m),y=e?[e]:n==="code-server"?u:process.platform==="win32"?M:L,h=y.map(m=>({candidate:m,result:m===g?{ok:!0,path:s}:C(m)})).find(m=>m.result.ok),I=!!h;return l({id:"ide-command",ok:I,severity:"required",message:I?"VS Code CLI command is available.":"VS Code CLI command was not found.",details:{env:c.CLI_ENV.ideCommand,codeServerEnv:c.CLI_ENV.codeServerPath,hostKindEnv:c.CLI_ENV.managedHostKind,hostKind:n,explicitIdeCommand:e||null,nodeRuntimeCommand:o.command,nodeRuntimeSource:o.source,candidates:y,resolvedCommand:h?.candidate??null,resolvedPath:h?.result.path??null}},{code:"DOCTOR_IDE_COMMAND_MISSING",hints:[(0,d.configHint)(c.CLI_ENV.ideCommand,"Set an explicit VS Code-compatible CLI command path."),(0,d.configHint)(c.CLI_ENV.codeServerPath,"Set an explicit Coder code-server executable path when using the code-server managed host."),(0,d.actionHint)("Install VS Code, install Coder code-server, or include a packaged code-server runtime.")]})}function X(t){const e=(0,v.findPackagedNodeRuntime)(t),n=(0,v.resolveNodeRuntime)(t),r=i.existsSync(a.join(t,"runtimes","code-server","node_modules","code-server","out","node","entry.js"));return l({id:"managed-runtime-node",ok:!!e||!r,severity:r?"required":"optional",message:e?"Bundled Node runtime is available for managed runtime.":r?"Bundled Node runtime is missing for package-local code-server.":"Bundled Node runtime is not needed because package-local code-server is not present.",details:{env:c.CLI_ENV.nodePath,packagedNodePath:e,resolvedCommand:n.command,resolvedSource:n.source,packagedCodeServerPresent:r}},{code:"DOCTOR_MANAGED_RUNTIME_NODE_MISSING",hints:[(0,d.commandHint)("node scripts/runtime/provision-managed-runtimes.cjs --node","Provision the bundled Node runtime."),(0,d.actionHint)("For installed packages, reprovision or reinstall the managed runtime bundle.")]})}function U(t){const e=a.join(t,"runtimes","code-server","node_modules","code-server","out","node","entry.js");return i.existsSync(e)?"code-server":null}function $(t){const e=_(c.CLI_ENV.chromePath),r=[e,J(t),"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe","C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe","google-chrome","chromium","chromium-browser","microsoft-edge"].filter(o=>!!o).map(o=>({candidate:o,result:C(o)})).find(o=>o.result.ok),s=!!r;return l({id:"headless-browser",ok:s,severity:"required",message:s?"Headless browser command is available.":"Chrome or Edge was not found for managed serve-web activation.",details:{env:c.CLI_ENV.chromePath,explicitChromePath:e,resolvedCommand:r?.candidate??null}},{code:"DOCTOR_HEADLESS_BROWSER_MISSING",hints:[(0,d.configHint)(c.CLI_ENV.chromePath,"Set an explicit Chrome or Edge executable path."),(0,d.actionHint)("Install Chrome, Edge, Chromium, or another compatible headless browser.")]})}function J(t){const e=[a.join(t,"runtimes","browser"),a.join(t,"runtimes","chrome"),a.join(t,"runtimes","chromium")],n=process.platform==="win32"?new Set(["chrome.exe","chromium.exe","msedge.exe"]):new Set(["chrome","chromium"]);for(const r of e){const s=P(r,n,5);if(s)return s}return null}function P(t,e,n){if(!i.existsSync(t)||n<0)return null;let r;try{r=i.readdirSync(t,{withFileTypes:!0})}catch{return null}for(const s of r){const o=a.join(t,s.name);if(s.isFile()&&e.has(s.name)&&C(o).ok)return o}for(const s of r){if(!s.isDirectory())continue;const o=P(a.join(t,s.name),e,n-1);if(o)return o}return null}function z(t){const e=process.platform==="win32"||process.platform==="linux";return l({id:"managed-runtime-platform",ok:e||t!==!0,severity:t?"required":"optional",message:e?"Managed serve-web auto-start is supported on this platform.":"Managed serve-web auto-start is currently supported on Windows and Linux.",details:{platform:process.platform,runtimeRequested:t}},{code:"DOCTOR_MANAGED_RUNTIME_PLATFORM_UNSUPPORTED",hints:[(0,d.actionHint)("Run static doctor checks only, or use a Windows/Linux environment for managed runtime.")]})}function Z(){const t=[a.resolve(__dirname),process.cwd()];for(const e of t){let n=e;for(;;){const r=a.join(n,"scripts","managed-host","manage-serve-web-host.cjs"),s=a.join(n,"package.json");if(i.existsSync(r)&&i.existsSync(s))return n;const o=a.dirname(n);if(o===n)break;n=o}}return null}function _(t){const e=process.env[t];return e&&e.trim()?a.resolve(e.trim()):null}function C(t){if(Q(t))return{ok:i.existsSync(t),status:i.existsSync(t)?0:1,error:null};const e=process.platform==="win32"?(0,E.spawnSync)("where.exe",[t],{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","pipe"]}):(0,E.spawnSync)("sh",["-lc",`command -v "${t.replace(/"/g,'\\"')}"`],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return{ok:e.status===0,status:e.status,error:e.error?e.error.message:null}}function Q(t){return t.includes("\\")||t.includes("/")||/^[A-Za-z]:/.test(t)}
1
+ "use strict";var D=exports&&exports.__createBinding||(Object.create?(function(t,e,n,r){r===void 0&&(r=n);var o=Object.getOwnPropertyDescriptor(e,n);(!o||("get"in o?!e.__esModule:o.writable||o.configurable))&&(o={enumerable:!0,get:function(){return e[n]}}),Object.defineProperty(t,r,o)}):(function(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]})),O=exports&&exports.__setModuleDefault||(Object.create?(function(t,e){Object.defineProperty(t,"default",{enumerable:!0,value:e})}):function(t,e){t.default=e}),E=exports&&exports.__importStar||(function(){var t=function(e){return t=Object.getOwnPropertyNames||function(n){var r=[];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(r[r.length]=o);return r},t(e)};return function(e){if(e&&e.__esModule)return e;var n={};if(e!=null)for(var r=t(e),o=0;o<r.length;o++)r[o]!=="default"&&D(n,e,r[o]);return O(n,e),n}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.runDoctor=H;const i=E(require("node:fs")),a=E(require("node:path")),x=require("node:child_process"),d=require("../config/env-vars"),_=require("../shared/diagnostic-catalog"),u=require("../shared/hints"),j=require("../managed-host/extension-vsix-resolver"),N=require("../managed-host/serve-web-autostart"),A=require("./ping"),M=require("../shared/agent-text"),V=require("../shared/errors"),L=require("../diagnostics/readiness-text"),C=require("../runtime/bundled-node"),g=require("../runtime/managed-runtime-provisioning"),q=["code.cmd","code.exe","code"],R=["code"];function l(t,e){return t.ok||!e?t:{...t,code:e.code,...e.hints&&e.hints.length>0?{hints:e.hints}:{}}}async function H(t){const e=[],n=a.resolve(__dirname,"..",".."),r=ee(),o=t.runtime===!0,s=T(t.progress===!0);if(o){s("checking runtime files");const c=(0,g.isManagedRuntimeComplete)(n);s(c?"runtime files: ok":"provisioning runtime"),(0,g.ensureManagedRuntimeProvisioned)(n),c||s((0,g.isManagedRuntimeComplete)(n)?"runtime ready":"runtime files: missing")}e.push(m(s,"node version",W)),e.push(m(s,"package layout",()=>G(n))),e.push(m(s,"managed host assets",()=>X(n,r))),e.push(m(s,"extension VSIX",()=>U(n,r))),e.push(m(s,"bundled node",()=>J(n))),e.push(m(s,"code-server",()=>$(n))),e.push(m(s,"browser",()=>Z(n))),e.push(m(s,"platform",()=>Y(o))),o&&e.every(c=>c.severity!=="required"||c.ok)&&e.push(...await K(t.cwd,s));const p=e.filter(c=>c.severity==="required"&&!c.ok),v=e.filter(c=>c.severity==="optional"&&!c.ok),h={ok:p.length===0,command:"doctor",mode:o?"runtime-install-gate":"static",cwd:a.resolve(t.cwd),generatedAt:new Date().toISOString(),platform:{node:process.version,platform:process.platform,arch:process.arch},packageRoot:n,repoRoot:r,summary:{checkCount:e.length,passedCount:e.filter(c=>c.ok).length,failedRequiredCount:p.length,failedOptionalCount:v.length},checks:e};return t.progress===!0&&(p.length===0?(s("all checks passed"),s("you are good to go 👍")):s("checks failed")),t.json===!0?h:(0,M.attachAgentText)(h,(0,L.formatDoctorText)(h,{verbose:t.verbose===!0}))}function T(t){return t?e=>{process.stderr.write(`${e}
2
+ `)}:()=>{}}function m(t,e,n){t(`checking ${e}`);const r=n();return t(`${e}: ${r.ok?"ok":"failed"}`),r}async function K(t,e){const n=[];let r=!1;try{e("starting managed runtime; please wait");const o=await(0,N.startManagedServeWebForCwd)(t);r=!0,e("managed runtime: started"),n.push({id:"managed-runtime-start",ok:!0,severity:"required",message:"Managed IDE runtime starts and activates the bridge.",details:B(o)})}catch(o){return e("managed runtime: failed"),n.push(y("managed-runtime-start","Managed IDE runtime failed to start or activate the bridge.",o)),n}try{e("pinging runtime");const o=await(0,A.runPing)(t);e("runtime ping: ok"),n.push({id:"bridge-ping",ok:!0,severity:"required",message:"Bridge ping succeeds through the managed runtime.",details:F(o)})}catch(o){e("runtime ping: failed"),n.push(y("bridge-ping","Bridge ping failed through the managed runtime.",o))}if(r)try{e("stopping managed runtime");const o=await(0,N.stopManagedServeWebForCwd)(t);e(o.stopped===!0?"managed runtime: stopped":"managed runtime: stop incomplete"),n.push({id:"managed-runtime-stop",ok:o.stopped===!0,severity:"required",message:o.stopped===!0?"Managed IDE runtime stops cleanly.":"Managed IDE runtime stop did not report a stopped runtime.",details:o})}catch(o){e("managed runtime stop: failed"),n.push(y("managed-runtime-stop","Managed IDE runtime stop failed.",o))}return n}function y(t,e,n){const r=n instanceof V.CliError?n:null;return{id:t,ok:!1,severity:"required",message:e,code:r?.code??"DOCTOR_RUNTIME_CHECK_FAILED",details:{error:n instanceof Error?n.message:String(n),...r?.details&&typeof r.details=="object"&&!Array.isArray(r.details)?{details:r.details}:{}},hints:r?.details&&typeof r.details=="object"&&!Array.isArray(r.details)&&Array.isArray(r.details.hints)?r.details.hints:(0,_.buildAutoStartHints)()}}function B(t){const e=t.metadata&&typeof t.metadata=="object"&&!Array.isArray(t.metadata)?t.metadata:{},n=t.artifacts&&typeof t.artifacts=="object"&&!Array.isArray(t.artifacts)?t.artifacts:{};return{hostId:typeof t.hostId=="string"?t.hostId:null,hostKind:typeof t.hostKind=="string"?t.hostKind:e.hostKind??null,reused:t.reused===!0,codeCommand:typeof t.codeCommand=="string"?t.codeCommand:e.codeCommand??null,codeCommandSource:typeof t.codeCommandSource=="string"?t.codeCommandSource:e.codeCommandSource??null,runDir:typeof t.runDir=="string"?t.runDir:e.runDir??null,logsDir:typeof n.logsDir=="string"?n.logsDir:e.logsDir??null,instanceId:typeof e.instanceId=="string"?e.instanceId:null,serveWebPid:typeof e.serveWebPid=="number"?e.serveWebPid:null,browserPid:typeof e.browserPid=="number"?e.browserPid:null}}function F(t){const e=t.selectedInstance&&typeof t.selectedInstance=="object"&&!Array.isArray(t.selectedInstance)?t.selectedInstance:{},n=t.response&&typeof t.response=="object"&&!Array.isArray(t.response)?t.response:{};return{instanceId:typeof e.instanceId=="string"?e.instanceId:n.instanceId??null,reason:typeof e.reason=="string"?e.reason:null,matchedWorkspace:typeof e.matchedWorkspace=="string"?e.matchedWorkspace:null,pid:typeof n.pid=="number"?n.pid:null,protocolVersion:typeof n.protocolVersion=="number"?n.protocolVersion:null,extensionVersion:typeof n.extensionVersion=="string"?n.extensionVersion:null}}function W(){const t=Number(process.versions.node.split(".")[0]??"0"),e=Number.isInteger(t)&&t>=20;return l({id:"node-version",ok:e,severity:"required",message:e?"Node.js version is supported.":"Node.js 20 or newer is required.",details:{node:process.version,required:">=20"}},{code:"DOCTOR_NODE_VERSION_UNSUPPORTED",hints:[(0,u.actionHint)("Install Node.js 20 or newer, then retry the CLI command.")]})}function G(t){const e=a.join(t,"package.json"),n=a.join(t,"dist","bin","aib.js"),r=i.existsSync(e)&&i.existsSync(n);return l({id:"cli-package-root",ok:r,severity:"required",message:r?"CLI package root looks complete.":"CLI package root is missing package metadata or the built bin.",details:{packageRoot:t,packageJsonPath:e,packageJsonExists:i.existsSync(e),binPath:n,binExists:i.existsSync(n)}},{code:"DOCTOR_CLI_PACKAGE_INCOMPLETE",hints:[(0,u.commandHint)("npm run cli:build","Build the local CLI package."),(0,u.actionHint)("For an installed package, reinstall the CLI package.")]})}function X(t,e){const n=a.join(t,"dist","managed-host","manage-serve-web-host.cjs"),r=e?a.join(e,"scripts","managed-host","manage-serve-web-host.cjs"):null,o=I(d.CLI_ENV.managedHostScript),s=!!(o&&i.existsSync(o)||i.existsSync(n)||r&&i.existsSync(r));return l({id:"managed-host-assets",ok:s,severity:"required",message:s?"Managed host assets are available.":"Managed host assets were not found.",details:{env:d.CLI_ENV.managedHostScript,envScriptPath:o,envScriptExists:o?i.existsSync(o):!1,packagedScriptPath:n,packagedScriptExists:i.existsSync(n),repoScriptPath:r,repoScriptExists:r?i.existsSync(r):!1}},{code:"DOCTOR_MANAGED_HOST_ASSETS_MISSING",hints:(0,_.buildAutoStartHints)()})}function U(t,e){try{const n=(0,j.resolveExtensionVsixPath)({packageRoot:t,repoRoot:e}),r=i.existsSync(n.path);return l({id:"extension-vsix",ok:r,severity:"required",message:r?"Extension VSIX is available.":"Extension VSIX path resolved but the file does not exist.",details:{...n,exists:r}},{code:"DOCTOR_EXTENSION_VSIX_MISSING",hints:[(0,u.configHint)(d.CLI_ENV.extensionVsix,"Point to an existing packaged VSIX artifact."),(0,u.commandHint)("npm --prefix packages/extension run package:vsix","Build a local VSIX artifact.")]})}catch(n){return{id:"extension-vsix",ok:!1,severity:"required",message:"Extension VSIX resolution failed.",code:"DOCTOR_EXTENSION_VSIX_RESOLUTION_FAILED",details:{error:n instanceof Error?n.message:String(n),code:typeof n=="object"&&n!==null&&"code"in n?String(n.code):null},hints:(0,_.buildAutoStartHints)()}}}function $(t){const e=process.env[d.CLI_ENV.ideCommand]?.trim(),n=process.env[d.CLI_ENV.managedHostKind]?.trim()||z(t),r=I(d.CLI_ENV.codeServerPath),o=a.join(t,"runtimes","code-server","node_modules","code-server","out","node","entry.js"),s=(0,g.managedRuntimePlatformStatus)(t),p=(0,C.resolveNodeRuntime)(t),v=i.existsSync(o)&&s.ok?`${p.command} ${o}`:null,h=a.join(t,"runtimes","code-server","bin",process.platform==="win32"?"code-server.cmd":"code-server"),c=[r,v,h,"code-server"].filter(f=>!!f),P=e?[e]:n==="code-server"?c:process.platform==="win32"?q:R,S=P.map(f=>({candidate:f,result:f===v?{ok:!0,path:o}:b(f)})).find(f=>f.result.ok),k=!!S;return l({id:"ide-command",ok:k,severity:"required",message:k?"VS Code CLI command is available.":"VS Code CLI command was not found.",details:{env:d.CLI_ENV.ideCommand,codeServerEnv:d.CLI_ENV.codeServerPath,hostKindEnv:d.CLI_ENV.managedHostKind,hostKind:n,explicitIdeCommand:e||null,nodeRuntimeCommand:p.command,nodeRuntimeSource:p.source,platformMarker:{ok:s.ok,reason:s.reason,expectedPlatformKey:s.expectedPlatformKey,actualPlatformKey:s.actualPlatformKey,markerPath:s.markerPath},candidates:P,resolvedCommand:S?.candidate??null,resolvedPath:S?.result.path??null}},{code:"DOCTOR_IDE_COMMAND_MISSING",hints:[(0,u.configHint)(d.CLI_ENV.ideCommand,"Set an explicit VS Code-compatible CLI command path."),(0,u.configHint)(d.CLI_ENV.codeServerPath,"Set an explicit Coder code-server executable path when using the code-server managed host."),(0,u.actionHint)("Install VS Code, install Coder code-server, or include a packaged code-server runtime.")]})}function J(t){const e=(0,C.findPackagedNodeRuntime)(t),n=(0,C.resolveNodeRuntime)(t),r=(0,g.managedRuntimePlatformStatus)(t),o=i.existsSync(a.join(t,"runtimes","code-server","node_modules","code-server","out","node","entry.js"))&&r.ok;return l({id:"managed-runtime-node",ok:!!e||!o,severity:o?"required":"optional",message:e?"Bundled Node runtime is available for managed runtime.":o?"Bundled Node runtime is missing for package-local code-server.":"Bundled Node runtime is not needed because package-local code-server is not present.",details:{env:d.CLI_ENV.nodePath,packagedNodePath:e,resolvedCommand:n.command,resolvedSource:n.source,packagedCodeServerPresent:o,platformMarker:{ok:r.ok,reason:r.reason,expectedPlatformKey:r.expectedPlatformKey,actualPlatformKey:r.actualPlatformKey,markerPath:r.markerPath}}},{code:"DOCTOR_MANAGED_RUNTIME_NODE_MISSING",hints:[(0,u.commandHint)("node scripts/runtime/provision-managed-runtimes.cjs --node","Provision the bundled Node runtime."),(0,u.actionHint)("For installed packages, reprovision or reinstall the managed runtime bundle.")]})}function z(t){const e=a.join(t,"runtimes","code-server","node_modules","code-server","out","node","entry.js");return i.existsSync(e)&&(0,g.managedRuntimePlatformStatus)(t).ok?"code-server":null}function Z(t){const e=I(d.CLI_ENV.chromePath),r=[e,Q(t),"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe","C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe","C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe","google-chrome","chromium","chromium-browser","microsoft-edge"].filter(s=>!!s).map(s=>({candidate:s,result:b(s)})).find(s=>s.result.ok),o=!!r;return l({id:"headless-browser",ok:o,severity:"required",message:o?"Headless browser command is available.":"Chrome or Edge was not found for managed serve-web activation.",details:{env:d.CLI_ENV.chromePath,explicitChromePath:e,resolvedCommand:r?.candidate??null}},{code:"DOCTOR_HEADLESS_BROWSER_MISSING",hints:[(0,u.configHint)(d.CLI_ENV.chromePath,"Set an explicit Chrome or Edge executable path."),(0,u.actionHint)("Install Chrome, Edge, Chromium, or another compatible headless browser.")]})}function Q(t){const e=[a.join(t,"runtimes","browser"),a.join(t,"runtimes","chrome"),a.join(t,"runtimes","chromium")],n=process.platform==="win32"?new Set(["chrome.exe","chromium.exe","msedge.exe"]):new Set(["chrome","chromium"]);for(const r of e){const o=w(r,n,5);if(o)return o}return null}function w(t,e,n){if(!i.existsSync(t)||n<0)return null;let r;try{r=i.readdirSync(t,{withFileTypes:!0})}catch{return null}for(const o of r){const s=a.join(t,o.name);if(o.isFile()&&e.has(o.name)&&b(s).ok)return s}for(const o of r){if(!o.isDirectory())continue;const s=w(a.join(t,o.name),e,n-1);if(s)return s}return null}function Y(t){const e=process.platform==="win32"||process.platform==="linux";return l({id:"managed-runtime-platform",ok:e||t!==!0,severity:t?"required":"optional",message:e?"Managed serve-web auto-start is supported on this platform.":"Managed serve-web auto-start is currently supported on Windows and Linux.",details:{platform:process.platform,runtimeRequested:t}},{code:"DOCTOR_MANAGED_RUNTIME_PLATFORM_UNSUPPORTED",hints:[(0,u.actionHint)("Run static doctor checks only, or use a Windows/Linux environment for managed runtime.")]})}function ee(){const t=[a.resolve(__dirname),process.cwd()];for(const e of t){let n=e;for(;;){const r=a.join(n,"scripts","managed-host","manage-serve-web-host.cjs"),o=a.join(n,"package.json");if(i.existsSync(r)&&i.existsSync(o))return n;const s=a.dirname(n);if(s===n)break;n=s}}return null}function I(t){const e=process.env[t];return e&&e.trim()?a.resolve(e.trim()):null}function b(t){if(te(t))return{ok:i.existsSync(t),status:i.existsSync(t)?0:1,error:null};const e=process.platform==="win32"?(0,x.spawnSync)("where.exe",[t],{encoding:"utf8",windowsHide:!0,stdio:["ignore","pipe","pipe"]}):(0,x.spawnSync)("sh",["-lc",`command -v "${t.replace(/"/g,'\\"')}"`],{encoding:"utf8",stdio:["ignore","pipe","pipe"]});return{ok:e.status===0,status:e.status,error:e.error?e.error.message:null}}function te(t){return t.includes("\\")||t.includes("/")||/^[A-Za-z]:/.test(t)}
@@ -1,7 +1,7 @@
1
- "use strict";var w=exports&&exports.__createBinding||(Object.create?(function(e,t,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}):(function(e,t,n,i){i===void 0&&(i=n),e[i]=t[n]})),v=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),m=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var i=e(t),s=0;s<i.length;s++)i[s]!=="default"&&w(n,t,i[s]);return v(n,t),n}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.runHelpCommand=_,exports.resolveHelpRoot=d;const c=m(require("node:fs")),o=m(require("node:path")),p=require("../content/content-bundle"),u=require("../shared/agent-text"),j=require("../shared/errors"),h=new Map([["inspect file","inspect.file"],["inspect imports","inspect.imports"],["inspect exports","inspect.exports"],["inspect members","inspect.members"],["inspect code","inspect.code"],["inspect deps","inspect.deps"],["inspect dependencies","inspect.deps"],["inspect usages","inspect.usages"],["inspect usage","inspect.usages"],["inspect graph","inspect.graph"],["inspect tree","inspect.tree"],["inspect duplicates","inspect.duplicates"],["inspect duplicate","inspect.duplicates"],["inspect cycles","inspect.cycles"],["inspect cycle","inspect.cycles"],["refactor batch","refactor.batch"],["module plan","modulePlan"],["moduleplan","modulePlan"]]),g=["help-protocol","quick-map","help-format","basics","dsl","patterns","config-setup.aliases","config-setup.excludes","config-setup.import-normalize","config-setup.import-rules","config-setup.tsconfigs","session","prefs","selectors","inspect","inspect.file","inspect.imports","inspect.exports","inspect.members","inspect.code","inspect.deps","inspect.usages","inspect.graph","inspect.tree","inspect.duplicates","inspect.cycles","mutation","imports.normalize","rename","move","modulePlan","refactor.batch","view","qr","reveal"];function _(e){if(O(e))return C();const t=$(e);if(t.length===0)return f();const n=d(),i=H(t,n);if(i.targets.length===0&&i.unknown.length===0)return f();const s=i.targets.map(r=>{const a=o.join(n.dir,r.file);return c.existsSync(a)?{target:r,text:c.readFileSync(a,"utf8").trim()}:null}).filter(r=>r!==null);if(s.length===1&&i.unknown.length===0){const r=s[0];return r?(0,u.attachAgentText)({operation:"help",topic:r.target.id,source:n.source},r.text):f()}const l=[...s.map(r=>`// ${r.target.id}
1
+ "use strict";var w=exports&&exports.__createBinding||(Object.create?(function(e,t,n,i){i===void 0&&(i=n);var s=Object.getOwnPropertyDescriptor(t,n);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,i,s)}):(function(e,t,n,i){i===void 0&&(i=n),e[i]=t[n]})),_=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),m=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var i=[];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(i[i.length]=s);return i},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var i=e(t),s=0;s<i.length;s++)i[s]!=="default"&&w(n,t,i[s]);return _(n,t),n}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.runHelpCommand=x,exports.resolveHelpRoot=d;const c=m(require("node:fs")),o=m(require("node:path")),p=require("../content/content-bundle"),u=require("../shared/agent-text"),v=require("../shared/errors"),j=require("../shared/stdin-examples"),h=new Map([["inspect file","inspect.file"],["inspect imports","inspect.imports"],["inspect exports","inspect.exports"],["inspect members","inspect.members"],["inspect code","inspect.code"],["inspect deps","inspect.deps"],["inspect dependencies","inspect.deps"],["inspect usages","inspect.usages"],["inspect usage","inspect.usages"],["inspect graph","inspect.graph"],["inspect tree","inspect.tree"],["inspect duplicates","inspect.duplicates"],["inspect duplicate","inspect.duplicates"],["inspect cycles","inspect.cycles"],["inspect cycle","inspect.cycles"],["refactor batch","refactor.batch"],["module plan","modulePlan"],["moduleplan","modulePlan"]]),g=["help-protocol","quick-map","help-format","basics","dsl","patterns","config-setup.aliases","config-setup.excludes","config-setup.import-normalize","config-setup.import-rules","config-setup.tsconfigs","session","prefs","selectors","inspect","inspect.file","inspect.imports","inspect.exports","inspect.members","inspect.code","inspect.deps","inspect.usages","inspect.graph","inspect.tree","inspect.duplicates","inspect.cycles","mutation","imports.normalize","rename","move","modulePlan","refactor.batch","view","qr","reveal"];function x(e){if(H(e))return T();const t=S(e);if(t.length===0)return f();const n=d(),i=$(t,n);if(i.targets.length===0&&i.unknown.length===0)return f();const s=i.targets.map(r=>{const a=o.join(n.dir,r.file);return c.existsSync(a)?{target:r,text:O(c.readFileSync(a,"utf8").trim())}:null}).filter(r=>r!==null);if(s.length===1&&i.unknown.length===0){const r=s[0];return r?(0,u.attachAgentText)({operation:"help",topic:r.target.id,source:n.source},r.text):f()}const l=[...s.map(r=>`// ${r.target.id}
2
2
  ${r.text}`),...i.unknown.length>0?[["Unknown help topics:",...i.unknown].join(`
3
3
  `)]:[]].join(`
4
4
 
5
- `);if(i.unknown.length>0)throw new j.CliError("HELP_TOPIC_NOT_FOUND",l,{topics:s.map(r=>r.target.id),unknown:i.unknown,helpRoot:n.dir,available:g});return(0,u.attachAgentText)({operation:"help",topics:s.map(r=>r.target.id),source:n.source},l)}function O(e){const t=e.filter(n=>n!=="help");return t.length===1&&t[0]==="status"}function f(){const e=["Run as: aib help <topic...>","","Start here if this is your first AIB pass:"," bootstrap","","Always after context compaction:"," aib help help-protocol quick-map"," aib config aliases","","Help conventions:"," help-format","","Refresh workflow model:"," basics patterns","","Core focused topics:"," session"," prefs"," selectors"," dsl"," inspect"," mutation","","Feature topics:"," inspect.file"," inspect.imports"," inspect.exports"," inspect.members"," inspect.code"," inspect.deps"," inspect.usages"," inspect.graph"," inspect.tree"," inspect.duplicates"," inspect.cycles"," rename"," move"," modulePlan"," refactor.batch"," imports.normalize"," view"," qr"," reveal"].join(`
6
- `);return(0,u.attachAgentText)({operation:"help",topic:"index",available:g},e)}function $(e){return e.filter(t=>t!=="help")}function H(e,t){if(e.length===0)return{targets:[],unknown:[]};if(e.includes("--full"))return{targets:[{id:"full",input:"--full",file:"full.md"}],unknown:[]};const n=S(e,t);if(n)return{targets:[n],unknown:[]};const i=[],s=[];for(const l of e.filter(r=>!r.startsWith("--"))){const r=l.trim(),a=x(r,t);if(a){i.push(a);continue}s.push(r)}return{targets:i,unknown:s}}function S(e,t){const n=e.join(" ").trim();if(!n)return null;if(n==="bootstrap")return{id:"bootstrap",input:n,file:"bootstrap.md"};const i=h.get(n.toLowerCase());if(i)return{id:i,input:n,file:o.join("topics",`${i}.md`)};const s=n.replace(/\s+/g,".");return b(t,s)?{id:s,input:n,file:o.join("topics",`${s}.md`)}:null}function x(e,t){if(!e)return null;if(e==="bootstrap")return{id:"bootstrap",input:e,file:"bootstrap.md"};if(e==="full")return{id:"full",input:e,file:"full.md"};const n=h.get(e.toLowerCase());if(n)return{id:n,input:e,file:o.join("topics",`${n}.md`)};if(b(t,e))return{id:e,input:e,file:o.join("topics",`${e}.md`)};const i=T(t,e);return i?{id:i,input:e,file:o.join("topics",`${i}.md`)}:null}function C(){const e=d(),t=k(e.dir),n=(0,p.collectContentCandidates)(),i=t&&y(t.topics)?Object.keys(t.topics).length:P(e.dir),s=typeof t?.contentHash=="string"?t.contentHash:void 0,l=["aib help status","",`source: ${e.source}`,`path: ${e.dir}`,`assets: ${(0,p.directoryHasHelp)(e.dir)?"ok":"missing"}`,`metadata: ${t?"ok":"missing help-meta.json"}`,...typeof t?.helpVersion=="string"?[`version: ${t.helpVersion}`]:[],...typeof t?.generatedAt=="string"?[`generatedAt: ${t.generatedAt}`]:[],...typeof t?.sourceCommit=="string"?[`sourceCommit: ${t.sourceCommit}`]:[],...s?[`contentHash: ${q(s)}`]:[],`topics: ${i}`,"","checked:",...n.map(r=>{const a=r.valid?"ok":`skip (${r.reason??"invalid"})`;return`${r.source}: ${a} ${r.dir}`})].join(`
7
- `);return(0,u.attachAgentText)({operation:"help.status",source:e.source,path:e.dir,assetsOk:(0,p.directoryHasHelp)(e.dir),metadataOk:t!==null,topicCount:i,meta:t??null,candidates:n},l)}function d(){return(0,p.resolveContentRoot)()}function k(e){const t=o.join(e,"help-meta.json");if(!c.existsSync(t))return null;try{const n=JSON.parse(c.readFileSync(t,"utf8"));return y(n)?n:null}catch{return null}}function P(e){const t=o.join(e,"topics");return c.existsSync(t)?c.readdirSync(t).filter(n=>n.endsWith(".md")).length:0}function b(e,t){return c.existsSync(o.join(e.dir,"topics",`${t}.md`))}function T(e,t){const n=A(e.dir),i=t.toLowerCase(),s=n.filter(l=>{const r=l.toLowerCase();return r.endsWith(`.${i}`)||r===i});return s.length===1?s[0]??null:null}function A(e){const t=o.join(e,"topics");return c.existsSync(t)?c.readdirSync(t).filter(n=>n.endsWith(".md")).map(n=>n.replace(/\.md$/,"")).sort():[]}function q(e){return e.replace(/^sha256:/,"sha256:").slice(0,19)}function y(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}
5
+ `);if(i.unknown.length>0)throw new v.CliError("HELP_TOPIC_NOT_FOUND",l,{topics:s.map(r=>r.target.id),unknown:i.unknown,helpRoot:n.dir,available:g});return(0,u.attachAgentText)({operation:"help",topics:s.map(r=>r.target.id),source:n.source},l)}function H(e){const t=e.filter(n=>n!=="help");return t.length===1&&t[0]==="status"}function f(){const e=["Run as: aib help <topic...>","","Start here if this is your first AIB pass:"," bootstrap","","Always after context compaction:"," aib help help-protocol quick-map"," aib config aliases","","Help conventions:"," help-format","","Refresh workflow model:"," basics patterns","","Core focused topics:"," session"," prefs"," selectors"," dsl"," inspect"," mutation","","Feature topics:"," inspect.file"," inspect.imports"," inspect.exports"," inspect.members"," inspect.code"," inspect.deps"," inspect.usages"," inspect.graph"," inspect.tree"," inspect.duplicates"," inspect.cycles"," rename"," move"," modulePlan"," refactor.batch"," imports.normalize"," view"," qr"," reveal"].join(`
6
+ `);return(0,u.attachAgentText)({operation:"help",topic:"index",available:g},e)}function O(e){return e.replace(/\{\{stdin\.examples\}\}/g,(0,j.formatStdinExamples)({includeQr:!1}))}function S(e){return e.filter(t=>t!=="help")}function $(e,t){if(e.length===0)return{targets:[],unknown:[]};if(e.includes("--full"))return{targets:[{id:"full",input:"--full",file:"full.md"}],unknown:[]};const n=C(e,t);if(n)return{targets:[n],unknown:[]};const i=[],s=[];for(const l of e.filter(r=>!r.startsWith("--"))){const r=l.trim(),a=k(r,t);if(a){i.push(a);continue}s.push(r)}return{targets:i,unknown:s}}function C(e,t){const n=e.join(" ").trim();if(!n)return null;if(n==="bootstrap")return{id:"bootstrap",input:n,file:"bootstrap.md"};const i=h.get(n.toLowerCase());if(i)return{id:i,input:n,file:o.join("topics",`${i}.md`)};const s=n.replace(/\s+/g,".");return b(t,s)?{id:s,input:n,file:o.join("topics",`${s}.md`)}:null}function k(e,t){if(!e)return null;if(e==="bootstrap")return{id:"bootstrap",input:e,file:"bootstrap.md"};if(e==="full")return{id:"full",input:e,file:"full.md"};const n=h.get(e.toLowerCase());if(n)return{id:n,input:e,file:o.join("topics",`${n}.md`)};if(b(t,e))return{id:e,input:e,file:o.join("topics",`${e}.md`)};const i=q(t,e);return i?{id:i,input:e,file:o.join("topics",`${i}.md`)}:null}function T(){const e=d(),t=P(e.dir),n=(0,p.collectContentCandidates)(),i=t&&y(t.topics)?Object.keys(t.topics).length:A(e.dir),s=typeof t?.contentHash=="string"?t.contentHash:void 0,l=["aib help status","",`source: ${e.source}`,`path: ${e.dir}`,`assets: ${(0,p.directoryHasHelp)(e.dir)?"ok":"missing"}`,`metadata: ${t?"ok":"missing help-meta.json"}`,...typeof t?.helpVersion=="string"?[`version: ${t.helpVersion}`]:[],...typeof t?.generatedAt=="string"?[`generatedAt: ${t.generatedAt}`]:[],...typeof t?.sourceCommit=="string"?[`sourceCommit: ${t.sourceCommit}`]:[],...s?[`contentHash: ${I(s)}`]:[],`topics: ${i}`,"","checked:",...n.map(r=>{const a=r.valid?"ok":`skip (${r.reason??"invalid"})`;return`${r.source}: ${a} ${r.dir}`})].join(`
7
+ `);return(0,u.attachAgentText)({operation:"help.status",source:e.source,path:e.dir,assetsOk:(0,p.directoryHasHelp)(e.dir),metadataOk:t!==null,topicCount:i,meta:t??null,candidates:n},l)}function d(){return(0,p.resolveContentRoot)()}function P(e){const t=o.join(e,"help-meta.json");if(!c.existsSync(t))return null;try{const n=JSON.parse(c.readFileSync(t,"utf8"));return y(n)?n:null}catch{return null}}function A(e){const t=o.join(e,"topics");return c.existsSync(t)?c.readdirSync(t).filter(n=>n.endsWith(".md")).length:0}function b(e,t){return c.existsSync(o.join(e.dir,"topics",`${t}.md`))}function q(e,t){const n=M(e.dir),i=t.toLowerCase(),s=n.filter(l=>{const r=l.toLowerCase();return r.endsWith(`.${i}`)||r===i});return s.length===1?s[0]??null:null}function M(e){const t=o.join(e,"topics");return c.existsSync(t)?c.readdirSync(t).filter(n=>n.endsWith(".md")).map(n=>n.replace(/\.md$/,"")).sort():[]}function I(e){return e.replace(/^sha256:/,"sha256:").slice(0,19)}function y(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}
@@ -7,7 +7,7 @@
7
7
  `).replace(/\n{3,}/g,`
8
8
 
9
9
  `).trimEnd()}function Dt(e,r){const t=Array.isArray(r.items)?r.items.filter(l).filter(i=>y(i.referenceCount)>0):[];t.length>0&&_(e);const{ownerGroups:n,standalone:s}=ne(t);for(const[i,o]of n){e.push(""),e.push(`// ${i}:`);for(const f of o)e.push(...$e(f,!1))}s.length>0&&n.length>0&&e.push("");for(const i of s)e.push(...$e(i,!0))}function $e(e,r){const t=typeof e.entity=="string"?e.entity:"",n=H(t),i=[`${r?t:n.name}: ${y(e.referenceCount)} refs`],o=Array.isArray(e.usedBy)?e.usedBy.filter(l):[];for(const f of o){const c=typeof f.file=="string"?f.file:"";c&&i.push(`${c}:`);const a=Array.isArray(f.locations)?f.locations.filter(l):[];for(const u of a){const p=typeof u.line=="number"?` l${u.line}`:"",d=typeof u.container=="string"?u.container:"";i.push(`${d}${p}`.trim())}}return typeof e.hidden=="string"&&i.push(e.hidden),i}function jt(e,r){const t=Array.isArray(r.blocks)?r.blocks.filter(l):[];t.length>0&&_(e);const{ownerGroups:n,standalone:s}=ne(t);for(const[o,f]of n){e.push(`// ${o}:`);for(const[c,a]of Te(f,u=>H(typeof u.entity=="string"?u.entity:"").name)){c&&e.push(`// ${c}`);for(const u of a)e.push(...Se(u,!1,!1))}}s.length>0&&n.length>0&&e.push("");for(const[o,f]of Te(s,c=>typeof c.entity=="string"?c.entity:"")){o&&e.push(`// ${o}`);for(const c of f)e.push(...Se(c,!1,!1))}const i=Array.isArray(r.hiddenBlocks)?r.hiddenBlocks.filter(l):[];for(const o of i){const f=typeof o.entity=="string"?o.entity:"",c=typeof o.hidden=="string"?o.hidden:"";c&&e.push(f?`${f}: ${c}`:c)}}function Se(e,r,t=!0){const n=typeof e.entity=="string"?e.entity:"",s=H(n),i=r?n:s.name,o=[];t&&i&&o.push(`// ${i}`);const f=typeof e.file=="string"?e.file:"",c=typeof e.line=="number"?` l${e.line}`:"";if((f||c)&&o.push(`// ${f}${c}`.trim()),typeof e.code=="string")o.push(e.code.trimEnd());else if(l(e.omitted)){const a=typeof e.omitted.reason=="string"?e.omitted.reason:"omitted";o.push(`// ${a}`)}return o}function Ft(e,r){const t=De(r);t&&e.push(...t.split(/\r?\n/))}function Nt(e){const r=Array.isArray(e.results)?e.results.filter(l):l(e)?[e]:[];if(r.length===0)return null;const t=[];for(const n of r){const s=typeof n.operation=="string"?n.operation:"modulePlan.preview",i=typeof n.planId=="string"?n.planId:"";if(t.push(i?`${s} ${i}`:s),n.ok===!1&&typeof n.code=="string"&&t.push(`blocked: ${n.code}`),typeof n.summary=="string"&&t.push(n.summary),typeof n.integrity=="string"&&t.push(n.integrity),l(n.api)&&typeof n.api.status=="string"){const o=typeof n.api.before=="number"?n.api.before:null,f=typeof n.api.after=="number"?n.api.after:null;t.push(o!==null&&f!==null?`api: ${n.api.status} ${o}->${f}`:`api: ${n.api.status}`)}if(typeof n.cycles=="string"&&t.push(`cycles: ${n.cycles}`),Array.isArray(n.targets)&&n.targets.length>0){t.push("targets:");for(const o of n.targets.filter(l)){const f=typeof o.file=="string"?o.file:"",c=typeof o.summary=="string"?o.summary:"";f&&c&&t.push(`${f}: ${c}`)}}if(Array.isArray(n.blocking)&&n.blocking.length>0){t.push("blocking:");for(const o of n.blocking.filter(l)){const f=typeof o.code=="string"?o.code:"MODULE_PLAN_BLOCKING",c=Array.isArray(o.symbols)?o.symbols.filter(a=>typeof a=="string"):[];t.push(c.length>0?`${f}: ${c.join(", ")}`:f),Array.isArray(o.suggestedFixes)&&o.suggestedFixes.length>0&&t.push(`suggestedFixes: ${o.suggestedFixes.length}`)}}if(Array.isArray(n.remainingBlocking)&&n.remainingBlocking.length>0&&t.push(`remainingBlocking: ${n.remainingBlocking.length}`),Array.isArray(n.resolved)&&n.resolved.length>0&&t.push(`resolved: ${n.resolved.length}`),Array.isArray(n.changes)&&n.changes.length>0){t.push("changes:");for(const o of n.changes.filter(f=>typeof f=="string"))t.push(o)}l(n.preview)&&typeof n.preview.summary=="string"&&t.push(`preview: ${n.preview.summary}`),typeof n.next=="string"&&t.push(`next: ${n.next}`)}return t.join(`
10
- `)}function ke(e,r,t){const n=C(t);if(e.push(r),n.length===0){e.push(r==="exports:"?"no exports":"no top-level declarations");return}for(const s of n)e.push(s)}function Ce(e,r){r.hasNonDeclarationText===!0&&e.push("file has non-declaration text")}function Bt(e,r,t){const n=typeof t.entity=="string"?t.entity:"";if(e.push(`// ${[r,n].filter(s=>s!=="").join(" ")}:`),D(t)){e.push(`not found symbols: ${E(t).join(", ")}`);return}typeof t.meta=="string"&&t.meta!==""&&e.push(`// ${t.meta}`),typeof t.saved=="string"&&t.saved!==""&&e.push(`saved: ${t.saved}`),typeof t.code=="string"?e.push(t.code.trimEnd()):G(t)?Gt(e,t):te(t)&&Oe(e,t)}function Ut(e,r,t){const n=[];for(const s of t){if(G(s)){n.push(s);continue}Bt(e,r,s)}Ie(e,n,r)}function te(e){return typeof e.saved=="string"&&e.saved!==""}function Oe(e,r){e.push(`saved: ${r.saved}`),typeof r.next=="string"&&r.next!==""&&e.push(`next: ${r.next}`)}function G(e){return e.reason==="CODE_TOO_LARGE_FOR_STDOUT"||e.reason==="SLICE_TOO_LARGE_FOR_STDOUT"}function Gt(e,r){const t=typeof r.reason=="string"?r.reason:"CODE_TOO_LARGE_FOR_STDOUT",n=Ht(r)??t;e.push(`code omitted: ${n}`),typeof r.hint=="string"&&r.hint!==""&&e.push(`hint: ${r.hint}`)}function Ie(e,r,t){if(r.length===0)return;const n=t==="slice"?"slice":"code",s=Array.from(new Set(r.map(f=>typeof f.limit=="number"?f.limit:null).filter(f=>f!==null))),i=s.length===1?`; limit ${s[0]} non-empty lines`:"";e.push(`// ${n} omitted${i}`);for(const f of r){const c=typeof f.entity=="string"&&f.entity!==""?f.entity:"unknown",a=typeof f.meta=="string"?f.meta:typeof f.rangeMeta=="string"?f.rangeMeta:"",u=typeof f.nonEmptyLines=="number"&&f.nonEmptyLines>0?f.nonEmptyLines:typeof f.lineCount=="number"&&f.lineCount>0?f.lineCount:0,p=u>0?`${u}NEL`:"";e.push(`// ${[c,a,p].filter(d=>d!=="").join(" ")}`)}const o=Array.from(new Set(r.map(f=>typeof f.view=="string"?f.view:"").filter(f=>f!=="")));for(const f of o)e.push(`view: ${f}`)}function Ht(e){const r=typeof e.hint=="string"?e.hint:"";return/^(?:Code|Slice) is ([^.]+)\./.exec(r)?.[1]??null}function Me(e,r,t){const n=[],s=z(n);if(Array.isArray(e.results))for(const i of e.results)l(i)&&Ee(n,s,i,r,t);else Ee(n,s,e,r,t);return n.length>0?n.join(`
10
+ `)}function ke(e,r,t){const n=C(t);if(e.push(r),n.length===0){e.push(r==="exports:"?"no exports":"no top-level declarations");return}for(const s of n)e.push(s)}function Ce(e,r){r.hasNonDeclarationText===!0&&e.push("file has non-declaration text")}function Bt(e,r,t){const n=typeof t.entity=="string"?t.entity:"";if(e.push(`// ${[r,n].filter(s=>s!=="").join(" ")}:`),D(t)){e.push(`not found symbols: ${E(t).join(", ")}`);return}typeof t.meta=="string"&&t.meta!==""&&e.push(`// ${t.meta}`),typeof t.saved=="string"&&t.saved!==""&&e.push(`saved: ${t.saved}`),typeof t.code=="string"?e.push(t.code.trimEnd()):G(t)?Gt(e,t):te(t)&&Oe(e,t)}function Ut(e,r,t){const n=[];for(const s of t){if(G(s)){n.push(s);continue}Bt(e,r,s)}Ie(e,n,r)}function te(e){return typeof e.saved=="string"&&e.saved!==""}function Oe(e,r){e.push(`saved: ${r.saved}`),typeof r.next=="string"&&r.next!==""&&e.push(`next: ${r.next}`)}function G(e){return e.reason==="CODE_TOO_LARGE_FOR_STDOUT"||e.reason==="SLICE_TOO_LARGE_FOR_STDOUT"}function Gt(e,r){const t=typeof r.reason=="string"?r.reason:"CODE_TOO_LARGE_FOR_STDOUT",n=Ht(r)??t;e.push(`code omitted: ${n}`),typeof r.hint=="string"&&r.hint!==""&&e.push(`hint: ${r.hint}`)}function Ie(e,r,t){if(r.length===0)return;const n=t==="slice"?"slice":"code",s=Array.from(new Set(r.map(f=>typeof f.limit=="number"?f.limit:null).filter(f=>f!==null))),i=s.length===1?`; limit ${s[0]} NEL`:"";e.push(`// ${n} omitted${i}`);for(const f of r){const c=typeof f.entity=="string"&&f.entity!==""?f.entity:"unknown",a=typeof f.meta=="string"?f.meta:typeof f.rangeMeta=="string"?f.rangeMeta:"",u=typeof f.nonEmptyLines=="number"&&f.nonEmptyLines>0?f.nonEmptyLines:typeof f.lineCount=="number"&&f.lineCount>0?f.lineCount:0,p=u>0?`${u} NEL`:"";e.push(`// ${[c,a,p].filter(d=>d!=="").join(" ")}`)}const o=Array.from(new Set(r.map(f=>typeof f.view=="string"?f.view:"").filter(f=>f!=="")));for(const f of o)e.push(`view: ${f}`)}function Ht(e){const r=typeof e.hint=="string"?e.hint:"";return/^(?:Code|Slice) is ([^.]+)\./.exec(r)?.[1]??null}function Me(e,r,t){const n=[],s=z(n);if(Array.isArray(e.results))for(const i of e.results)l(i)&&Ee(n,s,i,r,t);else Ee(n,s,e,r,t);return n.length>0?n.join(`
11
11
  `):null}function Ee(e,r,t,n,s){r(typeof t.file=="string"?t.file:s??"");const i=C(t[n]);if(i.length===0)e.push(`${n==="exports"?"exports":"file"}:`),e.push(n==="exports"?"no exports":"no top-level declarations");else for(const f of i)e.push(f);n==="symbols"&&Ce(e,t),typeof t.summary=="string"&&e.push(`summary: ${t.summary}`);const o=C(t.reexports);o.length>0&&e.push(`reexports: ${o.join(", ")}`),typeof t.page=="string"&&e.push(`page: ${t.page}`),typeof t.hint=="string"&&e.push(`hint: ${t.hint}`)}function Vt(e,r){const t=[],n=z(t);if(l(e.members)&&!Array.isArray(e.members)){n(typeof e.file=="string"?e.file:r??"");for(const[s,i]of Object.entries(e.members))l(i)&&K(t,s,i)}else if(Array.isArray(e.results))for(const s of e.results)l(s)&&(n(typeof s.file=="string"?s.file:r??""),K(t,typeof s.entity=="string"?s.entity:"",s));else n(typeof e.file=="string"?e.file:r??""),K(t,typeof e.entity=="string"?e.entity:"",e);return t.length>0?t.join(`
12
12
  `):null}function K(e,r,t){if(D(t)){e.push("members:"),e.push(`not found symbols: ${E(t).join(", ")}`);return}const n=C(t.members);if(!(!r&&n.length===0)){if(r&&e.push(`// ${r}:`),n.length===0){e.push("no members");return}typeof t.count=="number"&&e.push(`// count: ${t.count}`),typeof t.page=="string"&&e.push(`// page: ${t.page}`);for(const s of n)e.push(s);typeof t.view=="string"&&e.push(`view: ${t.view}`)}}function qt(e,r){const t=[],n=z(t);if(l(e.deps)){n(typeof e.file=="string"?e.file:r??"");const s=[];for(const[i,o]of Object.entries(e.deps))l(o)&&s.push({entity:i,type:o.type,value:o.value,unknown:o.unknown});J(t,s)}else if(Array.isArray(e.results)){const s=[];for(const i of e.results)l(i)&&(n(typeof i.file=="string"?i.file:r??""),s.push({entity:typeof i.entity=="string"?i.entity:"",missingSymbols:E(i),type:i.depsType,value:i.depsValue,unknown:i.depsUnknown}));J(t,s)}else n(typeof e.file=="string"?e.file:r??""),J(t,[{entity:typeof e.entity=="string"?e.entity:"",missingSymbols:E(e),type:e.depsType,value:e.depsValue,unknown:e.depsUnknown}]);return t.length>0?t.join(`
13
13
  `):null}function _(e){e.length>0&&e[e.length-1]!==""&&e.push("")}function z(e){let r="";return t=>{t&&t!==r&&(e.push(`// ${t}`),r=t)}}function J(e,r){const t=[],n=[];let s=!1;for(const i of r){if(i.missingSymbols&&i.missingSymbols.length>0){n.push(...i.missingSymbols);continue}const o=C(i.type),f=C(i.value),c=C(i.unknown);if(o.length===0&&f.length===0&&c.length===0){i.entity&&t.push(i.entity);continue}s||(e.push("deps"),s=!0),Wt(e,i.entity,{type:o,value:f,unknown:c})}t.length>0&&(s||(e.push("deps"),s=!0),e.push(`No deps for: ${t.join(", ")}`)),n.length>0&&(s||e.push("deps"),e.push(`not found symbols: ${n.join(", ")}`))}function Wt(e,r,t){!r&&t.type.length===0&&t.value.length===0&&t.unknown.length===0||(r&&e.push(`${r}:`),t.type.length>0&&e.push(`type: ${t.type.join(", ")}`),t.value.length>0&&e.push(`value: ${t.value.join(", ")}`),t.unknown.length>0&&e.push(`unknown: ${t.unknown.join(", ")}`))}function C(e){return Array.isArray(e)?e.filter(r=>typeof r=="string"&&r!==""):[]}function O(e,r){return e.length>0&&e.every(t=>l(t)&&t.op===r)}function Kt(e){return Array.isArray(e.items)?e.items.filter(l):Array.isArray(e.results)?e.results.filter(l):[e]}function zt(e,r,t,n){return typeof e.file=="string"&&e.file!==""?e.file:n||(typeof r.sourceFile=="string"&&r.sourceFile!==""?h(r.sourceFile,t):"")}function Jt(e,r,t,n){if(e!=="code"&&e!=="slice")return[];const s=Yt(t.saves,t.sharedSaves,r.length);return s.length===0?[]:s.map(i=>{const o=r.map((a,u)=>({rawResult:a,save:t.saves?.[u]??null,includeRanges:t.ranges?.[u]??t.includeRanges})).filter(a=>a.save===i&&l(a.rawResult)).map(a=>({rawResult:a.rawResult,includeRanges:a.includeRanges})).map(({rawResult:a,includeRanges:u})=>{const p=typeof a.code=="string"?a.code:"",d=F(a.entity,n),g=p===""?y(a.lineCount):p.split(/\r?\n/).length,A=t.codeMeta===!1||!u?"":L(a.entity,g),v=[d,A].filter(m=>m!=="").join(" ");return v?`// ${v}
@@ -1,11 +1,11 @@
1
- "use strict";var E=exports&&exports.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),R=exports&&exports.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),p=exports&&exports.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(n){var r=[];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(r[r.length]=i);return r},e(t)};return function(t){if(t&&t.__esModule)return t;var n={};if(t!=null)for(var r=e(t),i=0;i<r.length;i++)r[i]!=="default"&&E(n,t,r[i]);return R(n,t),n}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.runQuickReadCommand=A;const _=p(require("node:fs/promises")),m=p(require("node:path")),w=require("../config/path-display"),q=require("../config/path-aliases"),F=require("../shared/agent-text"),f=require("../shared/errors"),N=require("./session-workspace"),v=80;async function A(e,t){const n=(0,N.readEffectiveSessionPathAliases)(e),r=(0,w.buildDisplayPathAliases)(e,n),i=t.includes("--stdin")?M(e,n,r,await L()):[h(e,n,r,t)],s=await $(O(i)),c={ok:s.some(o=>o.error===void 0),blocks:s.map(o=>({file:o.file,...o.window!==void 0?{window:o.window}:{},...o.content!==void 0?{content:o.content}:{},...o.error!==void 0?{error:o.error}:{}}))};return(0,F.attachAgentText)(c,b(s))}function O(e){const t=new Set(e.filter(i=>i.windows.some(s=>s.kind==="all")).map(i=>i.resolvedFile));if(t.size===0)return e;const n=new Set,r=[];for(const i of e){if(!t.has(i.resolvedFile)){r.push(i);continue}n.has(i.resolvedFile)||(n.add(i.resolvedFile),r.push({...i,windows:[{kind:"all"}]}))}return r}async function $(e){const t=new Map;for(const r of e)t.has(r.resolvedFile)||t.set(r.resolvedFile,y(r.resolvedFile));const n=[];for(const r of e){const i=await t.get(r.resolvedFile);if(i.error!==void 0||i.lines===void 0){n.push({file:r.displayFile,error:i.error??"read failed"});continue}for(const s of r.windows)n.push({file:r.displayFile,window:x(s),content:I(i.lines,s).join(`
2
- `)})}return n}async function y(e){let t;try{t=await _.stat(e)}catch(r){return{error:(typeof r=="object"&&r!==null&&"code"in r?String(r.code):"")==="ENOENT"?"file not found":"cannot stat file"}}if(t.isDirectory())return{error:"is a directory"};if(!t.isFile())return{error:"not a regular file"};let n;try{n=await _.readFile(e)}catch{return{error:"cannot read file"}}return Q(n)?{error:"binary file"}:{lines:C(n.toString("utf8"))}}function Q(e){const t=Math.min(e.length,8192);for(let n=0;n<t;n+=1)if(e[n]===0)return!0;return!1}function C(e){const t=e.replace(/\r\n/g,`
1
+ "use strict";var R=exports&&exports.__createBinding||(Object.create?(function(e,n,r,t){t===void 0&&(t=r);var i=Object.getOwnPropertyDescriptor(n,r);(!i||("get"in i?!n.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return n[r]}}),Object.defineProperty(e,t,i)}):(function(e,n,r,t){t===void 0&&(t=r),e[t]=n[r]})),m=exports&&exports.__setModuleDefault||(Object.create?(function(e,n){Object.defineProperty(e,"default",{enumerable:!0,value:n})}):function(e,n){e.default=n}),h=exports&&exports.__importStar||(function(){var e=function(n){return e=Object.getOwnPropertyNames||function(r){var t=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(t[t.length]=i);return t},e(n)};return function(n){if(n&&n.__esModule)return n;var r={};if(n!=null)for(var t=e(n),i=0;i<t.length;i++)t[i]!=="default"&&R(r,n,t[i]);return m(r,n),r}})();Object.defineProperty(exports,"__esModule",{value:!0}),exports.runQuickReadCommand=y;const p=h(require("node:fs/promises")),q=h(require("node:path")),_=require("../config/path-display"),F=require("../config/path-aliases"),N=require("../shared/agent-text"),f=require("../shared/errors"),A=require("./session-workspace"),v=80;async function y(e,n,r={}){const t=(0,A.readEffectiveSessionPathAliases)(e),i=(0,_.buildDisplayPathAliases)(e,t),s=n.includes("--stdin")?x(e,t,i,r.rawStdin??await U()):w(e,t,i,n),u=await O(I(s)),l={ok:u.some(o=>o.error===void 0),blocks:u.map(o=>({file:o.file,...o.window!==void 0?{window:o.window}:{},...o.content!==void 0?{content:o.content}:{},...o.error!==void 0?{error:o.error}:{}}))};return(0,N.attachAgentText)(l,W(u))}function I(e){const n=new Set(e.filter(i=>i.windows.some(s=>s.kind==="all")).map(i=>i.resolvedFile));if(n.size===0)return e;const r=new Set,t=[];for(const i of e){if(!n.has(i.resolvedFile)){t.push(i);continue}r.has(i.resolvedFile)||(r.add(i.resolvedFile),t.push({...i,windows:[{kind:"all"}]}))}return t}async function O(e){const n=new Map;for(const t of e)n.has(t.resolvedFile)||n.set(t.resolvedFile,$(t.resolvedFile));const r=[];for(const t of e){const i=await n.get(t.resolvedFile);if(i.error!==void 0||i.lines===void 0){r.push({file:t.displayFile,error:i.error??"read failed"});continue}for(const s of t.windows)r.push({file:t.displayFile,window:B(s),content:S(i.lines,s).join(`
2
+ `)})}return r}async function $(e){let n;try{n=await p.stat(e)}catch(t){return{error:(typeof t=="object"&&t!==null&&"code"in t?String(t.code):"")==="ENOENT"?"file not found":"cannot stat file"}}if(n.isDirectory())return{error:"is a directory"};if(!n.isFile())return{error:"not a regular file"};let r;try{r=await p.readFile(e)}catch{return{error:"cannot read file"}}return Q(r)?{error:"binary file"}:{lines:C(r.toString("utf8"))}}function Q(e){const n=Math.min(e.length,8192);for(let r=0;r<n;r+=1)if(e[r]===0)return!0;return!1}function C(e){const n=e.replace(/\r\n/g,`
3
3
  `).replace(/\r/g,`
4
- `);return t.endsWith(`
5
- `)?t.slice(0,-1).split(`
6
- `):t.split(`
7
- `)}function I(e,t){return t.kind==="all"?e:t.kind==="head"?e.slice(0,t.count):t.kind==="tail"?e.slice(Math.max(0,e.length-t.count)):e.slice(t.offset-1,t.offset-1+t.limit)}function M(e,t,n,r){const i=r.replace(/^\uFEFF/,"").split(/\r?\n/),s=[];for(let u=0;u<i.length;u+=1){const c=i[u]?.trim()??"";if(!c||c.startsWith("#"))continue;const o=B(c);if(o.length===0)continue;const l=o[0]==="qr"?o.slice(1):o;try{s.push(h(e,t,n,l))}catch(a){throw a instanceof f.CliError?new f.CliError(a.code,`qr stdin line ${u+1}: ${a.message}`,a.details):a}}if(s.length===0)throw new f.CliError("QR_STDIN_EMPTY","qr --stdin expects at least one qr line.");return s}function h(e,t,n,r){const i=r.filter(o=>o!=="--stdin");if(i.length===0)throw new f.CliError("QR_FILE_REQUIRED","qr expects a file path.");if(i[0]==="qr")return h(e,t,n,i.slice(1));const s=i[0]??"";if(s.startsWith("-")||T(s))throw new f.CliError("QR_FILE_REQUIRED","qr expects a file path before window flags.");const u=m.resolve(e,(0,q.expandPathAliasValue)(e,s,t)),c=S(i.slice(1));return{file:s,resolvedFile:u,displayFile:(0,w.compactDisplayPath)(e,u,n),windows:c}}function S(e){let t=!1,n=null,r=null,i=null,s=null;for(let o=0;o<e.length;o+=1){const l=e[o]??"",a=P(l);if(a){c(a.key,a.value);continue}if(l==="-a"||l==="--all"||l==="a"||l==="all"||l==="+all"){t=!0;continue}if(l==="-h"||l==="--head"){n=d(e,++o,l);continue}if(l==="-t"||l==="--tail"){r=d(e,++o,l);continue}if(l==="-o"||l==="--offset"){i=d(e,++o,l);continue}if(l==="-l"||l==="--limit"){s=d(e,++o,l);continue}throw new f.CliError("QR_UNKNOWN_ARGUMENT",`Unknown qr argument: ${l}`)}if(i===null!=(s===null))throw new f.CliError("QR_RANGE_INCOMPLETE","qr range reads require both o=<line> and l=<count>.");if(t)return[{kind:"all"}];const u=[];return n!==null&&u.push({kind:"head",count:n}),i!==null&&s!==null&&u.push({kind:"range",offset:i,limit:s}),r!==null&&u.push({kind:"tail",count:r}),u.length>0?u:[{kind:"head",count:v}];function c(o,l){if(o==="a"||o==="all"){t=D(l,o);return}const a=g(l,o);if(o==="h"||o==="head"){n=a;return}if(o==="t"||o==="tail"){r=a;return}if(o==="o"||o==="offset"){i=a;return}if(o==="l"||o==="limit"){s=a;return}throw new f.CliError("QR_UNKNOWN_ARGUMENT",`Unknown qr window field: ${o}`)}}function D(e,t){if(e==="true"||e==="1"||e==="yes")return!0;if(e==="false"||e==="0"||e==="no")return!1;throw new f.CliError("QR_INVALID_BOOLEAN",`${t} expects true or false.`)}function P(e){const t=e.indexOf("=");return t<=0?null:{key:e.slice(0,t),value:e.slice(t+1)}}function d(e,t,n){const r=e[t];if(!r||r.startsWith("-"))throw new f.CliError("QR_MISSING_FLAG_VALUE",`Expected a positive integer after ${n}.`);return g(r,n)}function g(e,t){const n=Number(e);if(!Number.isInteger(n)||n<1)throw new f.CliError("QR_INVALID_NUMBER",`${t} expects a positive integer.`);return n}function T(e){return/^(?:h|head|t|tail|o|offset|l|limit|a|all)=/.test(e)||e==="+all"}function b(e){return e.map(t=>{if(t.error!==void 0)return`// ${t.file} - ${t.error}`;const n=`// ${t.file}${t.window?` ${t.window}`:""}`;return t.content?`${n}
8
- ${t.content}`:`${n}
4
+ `);return n.endsWith(`
5
+ `)?n.slice(0,-1).split(`
6
+ `):n.split(`
7
+ `)}function S(e,n){return n.kind==="all"?e:n.kind==="head"?e.slice(0,n.count):n.kind==="tail"?e.slice(Math.max(0,e.length-n.count)):e.slice(n.offset-1,n.offset-1+n.limit)}function x(e,n,r,t){const i=t.replace(/^\uFEFF/,"").split(/\r?\n/),s=[];for(let u=0;u<i.length;u+=1){const c=i[u]?.trim()??"";if(!c||c.startsWith("#"))continue;const l=L(c);if(l.length===0)continue;const o=l[0]==="qr"?l.slice(1):l;try{s.push(...w(e,n,r,o))}catch(a){throw a instanceof f.CliError?new f.CliError(a.code,`qr stdin line ${u+1}: ${a.message}`,a.details):a}}if(s.length===0)throw new f.CliError("QR_STDIN_EMPTY","qr --stdin expects at least one qr line.");return s}function w(e,n,r,t){const i=t.filter(a=>a!=="--stdin"),s=i[0]==="qr"?i.slice(1):i,u=s.findIndex(T),c=u===-1?s:s.slice(0,u),l=u===-1?[]:s.slice(u);if(c.length===0)throw new f.CliError("QR_FILE_REQUIRED","qr expects a file path.");const o=b(l);return c.map(a=>M(e,n,r,a,o))}function M(e,n,r,t,i){if(!t||t.startsWith("-")||E(t))throw new f.CliError("QR_FILE_REQUIRED","qr expects a file path before window flags.");const s=q.resolve(e,(0,F.expandPathAliasValue)(e,t,n));return{file:t,resolvedFile:s,displayFile:(0,_.compactDisplayPath)(e,s,r),windows:i}}function b(e){let n=!1,r=null,t=null,i=null,s=null;for(let l=0;l<e.length;l+=1){const o=e[l]??"",a=P(o);if(a){c(a.key,a.value);continue}if(o==="-a"||o==="--all"||o==="a"||o==="all"||o==="+all"){n=!0;continue}if(o==="-h"||o==="--head"){r=d(e,++l,o);continue}if(o==="-t"||o==="--tail"){t=d(e,++l,o);continue}if(o==="-o"||o==="--offset"){i=d(e,++l,o);continue}if(o==="-l"||o==="--limit"){s=d(e,++l,o);continue}throw new f.CliError("QR_UNKNOWN_ARGUMENT",`Unknown qr argument: ${o}`)}if(i===null!=(s===null))throw new f.CliError("QR_RANGE_INCOMPLETE","qr range reads require both o=<line> and l=<count>.");if(n)return[{kind:"all"}];const u=[];return r!==null&&u.push({kind:"head",count:r}),i!==null&&s!==null&&u.push({kind:"range",offset:i,limit:s}),t!==null&&u.push({kind:"tail",count:t}),u.length>0?u:[{kind:"head",count:v}];function c(l,o){if(l==="a"||l==="all"){n=D(o,l);return}const a=g(o,l);if(l==="h"||l==="head"){r=a;return}if(l==="t"||l==="tail"){t=a;return}if(l==="o"||l==="offset"){i=a;return}if(l==="l"||l==="limit"){s=a;return}throw new f.CliError("QR_UNKNOWN_ARGUMENT",`Unknown qr window field: ${l}`)}}function D(e,n){if(e==="true"||e==="1"||e==="yes")return!0;if(e==="false"||e==="0"||e==="no")return!1;throw new f.CliError("QR_INVALID_BOOLEAN",`${n} expects true or false.`)}function P(e){const n=e.indexOf("=");return n<=0?null:{key:e.slice(0,n),value:e.slice(n+1)}}function d(e,n,r){const t=e[n];if(!t||t.startsWith("-"))throw new f.CliError("QR_MISSING_FLAG_VALUE",`Expected a positive integer after ${r}.`);return g(t,r)}function g(e,n){const r=Number(e);if(!Number.isInteger(r)||r<1)throw new f.CliError("QR_INVALID_NUMBER",`${n} expects a positive integer.`);return r}function E(e){return/^(?:h|head|t|tail|o|offset|l|limit|a|all)=/.test(e)||e==="+all"}function T(e){return e.startsWith("-")||E(e)||e==="a"||e==="all"}function W(e){return e.map(n=>{if(n.error!==void 0)return`// ${n.file} - ${n.error}`;const r=`// ${n.file}${n.window?` ${n.window}`:""}`;return n.content?`${r}
8
+ ${n.content}`:`${r}
9
9
  `}).join(`
10
10
 
11
- `)}function x(e){return e.kind==="all"?"all":e.kind==="head"?`h=${e.count}`:e.kind==="tail"?`t=${e.count}`:`o=${e.offset} l=${e.limit}`}function B(e){const t=[];let n="",r=null;for(let i=0;i<e.length;i+=1){const s=e[i]??"";if(r){s===r?r=null:n+=s;continue}if(s==='"'||s==="'"){r=s;continue}if(/\s/.test(s)){n.length>0&&(t.push(n),n="");continue}n+=s}if(r)throw new f.CliError("QR_UNTERMINATED_QUOTE","qr input has an unterminated quote.");return n.length>0&&t.push(n),t}async function L(){const e=[];for await(const t of process.stdin)e.push(Buffer.isBuffer(t)?t:Buffer.from(String(t)));return Buffer.concat(e).toString("utf8")}
11
+ `)}function B(e){return e.kind==="all"?"all":e.kind==="head"?`h=${e.count}`:e.kind==="tail"?`t=${e.count}`:`o=${e.offset} l=${e.limit}`}function L(e){const n=[];let r="",t=null;for(let i=0;i<e.length;i+=1){const s=e[i]??"";if(t){s===t?t=null:r+=s;continue}if(s==='"'||s==="'"){t=s;continue}if(/\s/.test(s)){r.length>0&&(n.push(r),r="");continue}r+=s}if(t)throw new f.CliError("QR_UNTERMINATED_QUOTE","qr input has an unterminated quote.");return r.length>0&&n.push(r),n}async function U(){const e=[];for await(const n of process.stdin)e.push(Buffer.isBuffer(n)?n:Buffer.from(String(n)));return Buffer.concat(e).toString("utf8")}
@@ -1,6 +1,6 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.runResultViewCommand=S;const x=require("../shared/agent-text"),p=require("../shared/errors"),w=require("./inspect-cycles"),g=require("./session-workspace");function S(e,t,s){if(s!==void 0)return M(e,s);const i=t.find(u=>!u.startsWith("--"));if(!i)throw new p.CliError("VIEW_HANDLE_REQUIRED","Usage: aib view aib:res_<id>");const n=V(i),r=N(t.slice(1));if(n.short)return L((0,g.readSessionResultViewJson)(e,n.id),r,i);if(n.kind==="cycles")return(0,w.buildCyclesViewResponse)((0,g.readSessionResultJson)(e,n.kind,n.id),{...r.detail!==void 0?{detail:_(r.detail)}:{},...r.offset!==void 0?{offset:r.offset}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.index!==void 0?{index:r.index}:{},...r.kind!==void 0?{kind:b(r.kind)}:{},resultHandle:i});const d={ok:!1,code:"UNSUPPORTED_RESULT_VIEW",error:`aib view does not support result kind: ${n.kind}`};return(0,x.attachAgentText)(d,`unsupported result view: ${n.kind}`)}function M(e,t){const s=Array.isArray(t.views)?t.views.filter(m):m(t.view)?[t.view]:m(t)?[t]:[];if(s.length===0)throw new p.CliError("VIEW_HANDLE_REQUIRED","view expects a handle.");const i=s.map(n=>{const r=o(n.handle)??o(n.from)??"";if(!r)throw new p.CliError("VIEW_HANDLE_REQUIRED","view expects a handle.");const d=V(r),u={...o(n.detail)!==void 0?{detail:o(n.detail)}:{},...h(n.offset)!==void 0?{offset:h(n.offset)}:{},...h(n.limit)!==void 0?{limit:h(n.limit)}:{},...h(n.index)!==void 0?{index:h(n.index)}:{},...o(n.kind)!==void 0?{kind:o(n.kind)}:{},...k(n.only).length>0?{only:k(n.only)}:{},...k(n.except).length>0?{except:k(n.except)}:{}};return d.short?L((0,g.readSessionResultViewJson)(e,d.id),u,r):d.kind==="cycles"?(0,w.buildCyclesViewResponse)((0,g.readSessionResultJson)(e,d.kind,d.id),{...u.detail!==void 0?{detail:_(u.detail)}:{},...u.offset!==void 0?{offset:u.offset}:{},...u.limit!==void 0?{limit:u.limit}:{},...u.index!==void 0?{index:u.index}:{},...u.kind!==void 0?{kind:b(u.kind)}:{},resultHandle:r}):(0,x.attachAgentText)({ok:!1,code:"UNSUPPORTED_RESULT_VIEW",error:`aib view does not support result kind: ${d.kind}`},`unsupported result view: ${d.kind}`)});return i.length===1?i[0]:(0,x.attachAgentText)({results:i},i.map(n=>{if(!m(n))return"";const r=n.__aib_text;return typeof r=="string"?r.trimEnd():""}).filter(n=>n!=="").join(`
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.runResultViewCommand=D;const x=require("../shared/agent-text"),h=require("../shared/errors"),E=require("./inspect-cycles"),g=require("./session-workspace");function D(t,e,r){if(r!==void 0)return M(t,r);const n=e.find(u=>!u.startsWith("--"));if(!n)throw new h.CliError("VIEW_HANDLE_REQUIRED","Usage: aib view aib:res_<id>");const i=V(n),s=T(e.slice(1));if(i.short)return L((0,g.readSessionResultViewJson)(t,i.id),s,n);if(i.kind==="cycles")return(0,E.buildCyclesViewResponse)((0,g.readSessionResultJson)(t,i.kind,i.id),{...s.detail!==void 0?{detail:b(s.detail)}:{},...s.offset!==void 0?{offset:s.offset}:{},...s.limit!==void 0?{limit:s.limit}:{},...s.index!==void 0?{index:s.index}:{},...s.kind!==void 0?{kind:A(s.kind)}:{},resultHandle:n});const d={ok:!1,code:"UNSUPPORTED_RESULT_VIEW",error:`aib view does not support result kind: ${i.kind}`};return(0,x.attachAgentText)(d,`unsupported result view: ${i.kind}`)}function M(t,e){const r=Array.isArray(e.views),n=Array.isArray(e.views)?e.views:[],i=r?n.filter(m):m(e.view)?[e.view]:m(e)?[e]:[];if(i.length===0)throw new h.CliError("VIEW_HANDLE_REQUIRED","view expects a handle.");const s=i.map((u,f)=>{try{return N(t,u)}catch(c){if(!r||i.length===1)throw c;return{...(0,h.errorPayload)(c),index:f}}});if(s.length===1)return s[0];const d=s.filter(u=>m(u)&&u.ok===!1).length;return(0,x.attachAgentText)({ok:d===0,...d>0?{batchOk:!1,failedCount:d}:{},results:s},s.map(u=>{if(!m(u))return"";const f=(0,x.readAgentText)(u);return typeof f=="string"?f.trimEnd():""}).filter(u=>u!=="").join(`
2
2
 
3
- `))}function V(e){if(/^aib:res_[A-Za-z0-9_-]+$/.test(e))return{kind:"view",id:e.slice(4),short:!0};const t=e.split(":");if(t.length!==4||t[0]!=="aib"||t[1]!=="result"||!t[2]||!t[3])throw new p.CliError("INVALID_RESULT_HANDLE",`Invalid result handle: ${e}`,{expected:"aib:res_<id>"});return{kind:t[2],id:t[3],short:!1}}function N(e){const t={},s=I(e,"--detail"),i=A(e,"--offset"),n=A(e,"--limit"),r=A(e,"--index"),d=I(e,"--kind"),u=$(e,"--only").flatMap(E),f=$(e,"--except").flatMap(E);return s!==void 0&&(t.detail=s),i!==void 0&&(t.offset=i),n!==void 0&&(t.limit=n),r!==void 0&&(t.index=r),d!==void 0&&(t.kind=d),u.length>0&&(t.only=u),f.length>0&&(t.except=f),t}function L(e,t,s){const i=o(e.kind);return e.op==="cycles"?(0,w.buildCyclesViewResponse)(e,{...t.detail!==void 0?{detail:_(t.detail)}:{},...t.offset!==void 0?{offset:t.offset}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.index!==void 0?{index:t.index}:{},...t.kind!==void 0?{kind:b(t.kind)}:{},resultHandle:s}):i==="code"?U(e,t,s):i==="members"||i==="duplicates"||i==="usages"?T(e,t,s,i):(0,x.attachAgentText)({ok:!1,code:"UNSUPPORTED_RESULT_VIEW",error:`aib view does not support result kind: ${i??"unknown"}`},`unsupported result view: ${i??"unknown"}`)}function T(e,t,s,i){const n=Array.isArray(e.items)?e.items.filter(m):[],r=C(n,t,y=>[o(y.name),o(y.text)?.split(/\s+/)[0]]),d=Math.max(0,t.offset??0),u=r.length||1,f=Math.max(1,t.limit??u),c=r.slice(d,d+f),l=Math.max(0,r.length-d-c.length),a={ok:!0,op:"view",handle:s,kind:i,source:o(e.source)??"inspect",...o(e.file)!==void 0?{file:o(e.file)}:{},...o(e.entity)!==void 0?{entity:o(e.entity)}:{},...o(e.target)!==void 0?{target:o(e.target)}:{},...o(e.detail)!==void 0?{detail:o(e.detail)}:{},items:c,offset:d,limit:f,...l>0?{hidden:l}:{}};return(0,x.attachAgentText)(a,O(a))}function U(e,t,s){const i=Array.isArray(e.items)?e.items.filter(m):[],n=C(i,t,a=>[o(a.entity),o(a.name)]),r=Math.max(0,t.offset??0),d=n.length||1,u=Math.max(1,t.limit??d),f=n.slice(r,r+u),c=Math.max(0,n.length-r-f.length),l={ok:!0,op:"view",handle:s,kind:"code",source:o(e.source)??"inspect",items:f,offset:r,limit:u,...c>0?{hidden:c}:{},...f.length===0&&i.length>0&&H(t)?{noMatches:!0}:{}};return(0,x.attachAgentText)(l,W(l))}function W(e){const t=[],s=Array.isArray(e.items)?e.items.filter(m):[];if(s.length===0&&e.noMatches===!0)return t.push("no hidden code matched view filters"),t.join(`
4
- `);let i="";for(const r of s){const d=o(r.file)??"";d&&d!==i&&(t.length>0&&t.push(""),t.push(`// ${d}`),i=d);const u=o(r.entity)??"",f=o(r.meta)??o(r.rangeMeta)??"",c=[u,f].filter(a=>a!=="").join(" ");c&&t.push(`// ${c}`);const l=o(r.code);l&&t.push(l.trimEnd())}const n=h(e.hidden)??0;return n>0&&t.push(`+ ${n} more hidden code blocks`),t.join(`
5
- `)}function O(e){const t=[],s=o(e.file),i=o(e.target),n=o(e.kind)??"",r=o(e.detail);s?t.push(`// ${s}`):n==="usages"?t.push(r?`usages ${r}`:"usages"):i&&t.push(`duplicates ${i}`);const d=o(e.entity);d&&t.push(`// ${d}:`);const u=Array.isArray(e.items)?e.items.filter(m):[];if(n==="usages")for(const[c,l]of j(u,a=>o(a.name)??"")){c&&t.push(`${c}:`);for(const a of l){const y=o(a.text);y&&t.push(y.trimEnd())}}else for(const c of u){const l=o(c.text);l&&t.push(l.trimEnd())}const f=h(e.hidden)??0;return f>0&&t.push(`+ ${f} more hidden ${n==="members"?"members":n==="usages"?"usages":"items"}`),t.join(`
6
- `)}function j(e,t){const s=new Map;for(const i of e){const n=t(i),r=s.get(n)??[];r.push(i),s.set(n,r)}return Array.from(s.entries())}function _(e){if(e==="summary"||e==="sum")return"summary";if(e==="imports"||e==="files")return e;throw new p.CliError("INVALID_CYCLES_DETAIL","aib view cycles --detail expects summary, imports, or files.")}function b(e){if(e==="runtime"||e==="type-only"||e==="mixed")return e;throw new p.CliError("INVALID_CYCLES_KIND","aib view cycles --kind expects runtime, type-only, or mixed.")}function I(e,t){const s=e.indexOf(t),i=s>=0?e[s+1]:void 0;return i&&!i.startsWith("--")?i:void 0}function $(e,t){const s=[];for(let i=0;i<e.length;i+=1){if(e[i]!==t)continue;const n=e[i+1];n&&!n.startsWith("--")&&s.push(n)}return s}function A(e,t){const s=I(e,t);if(s===void 0)return;const i=Number(s),n=t==="--offset"?0:1;if(!Number.isInteger(i)||i<n)throw new p.CliError("INVALID_VIEW_OPTION",`${t} expects ${n===0?"a non-negative":"a positive"} integer.`);return i}function m(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function o(e){return typeof e=="string"&&e!==""?e:void 0}function h(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function k(e){return typeof e=="string"&&e!==""?E(e):Array.isArray(e)?e.filter(t=>typeof t=="string"&&t!=="").flatMap(E):[]}function C(e,t,s){const i=t.only??[],n=t.except??[],r=i.length>0?e.filter(d=>D(s(d),i)):e;return n.length===0?r:r.filter(d=>!D(s(d),n))}function H(e){return(e.only?.length??0)>0||(e.except?.length??0)>0}function D(e,t){return e.some(s=>s!==void 0&&t.some(i=>P(s,i)))}function P(e,t){if(e===t)return!0;const s=e.split(".").pop()??e,i=t.split(".").pop()??t;return s===i&&!t.includes(".")}function E(e){const t=e.trim();return(q(t)??R(t)).flatMap(F)}function F(e){const t=e.trim(),s=t.match(/^(.+)\.\{(.+)\}$/);if(s){const i=s[1],n=s[2];if(i&&n)return R(n).map(r=>`${i}.${r}`)}return t?[t]:[]}function q(e){if(!e.startsWith("[")||!e.endsWith("]"))return null;const t=e.slice(1,-1).trim();return t?R(t):[]}function R(e){const t=[];let s="",i=0;for(const n of e){if(n==="{"?i+=1:n==="}"&&i>0&&(i-=1),n===","&&i===0){s.trim()&&t.push(s.trim()),s="";continue}s+=n}return s.trim()&&t.push(s.trim()),t}
3
+ `))}function N(t,e){const r=o(e.handle)??o(e.from)??"";if(!r)throw new h.CliError("VIEW_HANDLE_REQUIRED","view expects a handle.");const n=V(r),i={...o(e.detail)!==void 0?{detail:o(e.detail)}:{},...p(e.offset)!==void 0?{offset:p(e.offset)}:{},...p(e.limit)!==void 0?{limit:p(e.limit)}:{},...p(e.index)!==void 0?{index:p(e.index)}:{},...o(e.kind)!==void 0?{kind:o(e.kind)}:{},...k(e.only).length>0?{only:k(e.only)}:{},...k(e.except).length>0?{except:k(e.except)}:{}};return n.short?L((0,g.readSessionResultViewJson)(t,n.id),i,r):n.kind==="cycles"?(0,E.buildCyclesViewResponse)((0,g.readSessionResultJson)(t,n.kind,n.id),{...i.detail!==void 0?{detail:b(i.detail)}:{},...i.offset!==void 0?{offset:i.offset}:{},...i.limit!==void 0?{limit:i.limit}:{},...i.index!==void 0?{index:i.index}:{},...i.kind!==void 0?{kind:A(i.kind)}:{},resultHandle:r}):(0,x.attachAgentText)({ok:!1,code:"UNSUPPORTED_RESULT_VIEW",error:`aib view does not support result kind: ${n.kind}`},`unsupported result view: ${n.kind}`)}function V(t){if(/^aib:res_[A-Za-z0-9_-]+$/.test(t))return{kind:"view",id:t.slice(4),short:!0};const e=t.split(":");if(e.length!==4||e[0]!=="aib"||e[1]!=="result"||!e[2]||!e[3])throw new h.CliError("INVALID_RESULT_HANDLE",`Invalid result handle: ${t}`,{expected:"aib:res_<id>"});return{kind:e[2],id:e[3],short:!1}}function T(t){const e={},r=I(t,"--detail"),n=_(t,"--offset"),i=_(t,"--limit"),s=_(t,"--index"),d=I(t,"--kind"),u=$(t,"--only").flatMap(w),f=$(t,"--except").flatMap(w);return r!==void 0&&(e.detail=r),n!==void 0&&(e.offset=n),i!==void 0&&(e.limit=i),s!==void 0&&(e.index=s),d!==void 0&&(e.kind=d),u.length>0&&(e.only=u),f.length>0&&(e.except=f),e}function L(t,e,r){const n=o(t.kind);return t.op==="cycles"?(0,E.buildCyclesViewResponse)(t,{...e.detail!==void 0?{detail:b(e.detail)}:{},...e.offset!==void 0?{offset:e.offset}:{},...e.limit!==void 0?{limit:e.limit}:{},...e.index!==void 0?{index:e.index}:{},...e.kind!==void 0?{kind:A(e.kind)}:{},resultHandle:r}):n==="code"?W(t,e,r):n==="members"||n==="duplicates"||n==="usages"?U(t,e,r,n):(0,x.attachAgentText)({ok:!1,code:"UNSUPPORTED_RESULT_VIEW",error:`aib view does not support result kind: ${n??"unknown"}`},`unsupported result view: ${n??"unknown"}`)}function U(t,e,r,n){const i=Array.isArray(t.items)?t.items.filter(m):[],s=C(i,e,y=>[o(y.name),o(y.text)?.split(/\s+/)[0]]),d=Math.max(0,e.offset??0),u=s.length||1,f=Math.max(1,e.limit??u),c=s.slice(d,d+f),l=Math.max(0,s.length-d-c.length),a={ok:!0,op:"view",handle:r,kind:n,source:o(t.source)??"inspect",...o(t.file)!==void 0?{file:o(t.file)}:{},...o(t.entity)!==void 0?{entity:o(t.entity)}:{},...o(t.target)!==void 0?{target:o(t.target)}:{},...o(t.detail)!==void 0?{detail:o(t.detail)}:{},items:c,offset:d,limit:f,...l>0?{hidden:l}:{}};return(0,x.attachAgentText)(a,P(a))}function W(t,e,r){const n=Array.isArray(t.items)?t.items.filter(m):[],i=C(n,e,a=>[o(a.entity),o(a.name)]),s=Math.max(0,e.offset??0),d=i.length||1,u=Math.max(1,e.limit??d),f=i.slice(s,s+u),c=Math.max(0,i.length-s-f.length),l={ok:!0,op:"view",handle:r,kind:"code",source:o(t.source)??"inspect",items:f,offset:s,limit:u,...c>0?{hidden:c}:{},...f.length===0&&n.length>0&&H(e)?{noMatches:!0}:{}};return(0,x.attachAgentText)(l,O(l))}function O(t){const e=[],r=Array.isArray(t.items)?t.items.filter(m):[];if(r.length===0&&t.noMatches===!0)return e.push("no hidden code matched view filters"),e.join(`
4
+ `);let n="";for(const s of r){const d=o(s.file)??"";d&&d!==n&&(e.length>0&&e.push(""),e.push(`// ${d}`),n=d);const u=o(s.entity)??"",f=o(s.meta)??o(s.rangeMeta)??"",c=[u,f].filter(a=>a!=="").join(" ");c&&e.push(`// ${c}`);const l=o(s.code);l&&e.push(l.trimEnd())}const i=p(t.hidden)??0;return i>0&&e.push(`+ ${i} more hidden code blocks`),e.join(`
5
+ `)}function P(t){const e=[],r=o(t.file),n=o(t.target),i=o(t.kind)??"",s=o(t.detail);r?e.push(`// ${r}`):i==="usages"?e.push(s?`usages ${s}`:"usages"):n&&e.push(`duplicates ${n}`);const d=o(t.entity);d&&e.push(`// ${d}:`);const u=Array.isArray(t.items)?t.items.filter(m):[];if(i==="usages")for(const[c,l]of j(u,a=>o(a.name)??"")){c&&e.push(`${c}:`);for(const a of l){const y=o(a.text);y&&e.push(y.trimEnd())}}else for(const c of u){const l=o(c.text);l&&e.push(l.trimEnd())}const f=p(t.hidden)??0;return f>0&&e.push(`+ ${f} more hidden ${i==="members"?"members":i==="usages"?"usages":"items"}`),e.join(`
6
+ `)}function j(t,e){const r=new Map;for(const n of t){const i=e(n),s=r.get(i)??[];s.push(n),r.set(i,s)}return Array.from(r.entries())}function b(t){if(t==="summary"||t==="sum")return"summary";if(t==="imports"||t==="files")return t;throw new h.CliError("INVALID_CYCLES_DETAIL","aib view cycles --detail expects summary, imports, or files.")}function A(t){if(t==="runtime"||t==="type-only"||t==="mixed")return t;throw new h.CliError("INVALID_CYCLES_KIND","aib view cycles --kind expects runtime, type-only, or mixed.")}function I(t,e){const r=t.indexOf(e),n=r>=0?t[r+1]:void 0;return n&&!n.startsWith("--")?n:void 0}function $(t,e){const r=[];for(let n=0;n<t.length;n+=1){if(t[n]!==e)continue;const i=t[n+1];i&&!i.startsWith("--")&&r.push(i)}return r}function _(t,e){const r=I(t,e);if(r===void 0)return;const n=Number(r),i=e==="--offset"?0:1;if(!Number.isInteger(n)||n<i)throw new h.CliError("INVALID_VIEW_OPTION",`${e} expects ${i===0?"a non-negative":"a positive"} integer.`);return n}function m(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function o(t){return typeof t=="string"&&t!==""?t:void 0}function p(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function k(t){return typeof t=="string"&&t!==""?w(t):Array.isArray(t)?t.filter(e=>typeof e=="string"&&e!=="").flatMap(w):[]}function C(t,e,r){const n=e.only??[],i=e.except??[],s=n.length>0?t.filter(d=>S(r(d),n)):t;return i.length===0?s:s.filter(d=>!S(r(d),i))}function H(t){return(t.only?.length??0)>0||(t.except?.length??0)>0}function S(t,e){return t.some(r=>r!==void 0&&e.some(n=>F(r,n)))}function F(t,e){if(t===e)return!0;const r=t.split(".").pop()??t,n=e.split(".").pop()??e;return r===n&&!e.includes(".")}function w(t){const e=t.trim();return(J(e)??R(e)).flatMap(q)}function q(t){const e=t.trim(),r=e.match(/^(.+)\.\{(.+)\}$/);if(r){const n=r[1],i=r[2];if(n&&i)return R(i).map(s=>`${n}.${s}`)}return e?[e]:[]}function J(t){if(!t.startsWith("[")||!t.endsWith("]"))return null;const e=t.slice(1,-1).trim();return e?R(e):[]}function R(t){const e=[];let r="",n=0;for(const i of t){if(i==="{"?n+=1:i==="}"&&n>0&&(n-=1),i===","&&n===0){r.trim()&&e.push(r.trim()),r="";continue}r+=i}return r.trim()&&e.push(r.trim()),e}