@north-light/crouter 0.3.321 → 0.3.323
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/progress-painter.mjs +89 -0
- package/bin/runtime-selector.mjs +123 -4
- package/dist/api/client.d.ts +35 -18
- package/dist/api/client.js +2 -2
- package/dist/api/dto/broker-ops.d.ts +9 -0
- package/dist/api/dto/canvas.d.ts +23 -1
- package/dist/api/dto/modelauth.d.ts +15 -0
- package/dist/api/dto/nodes.d.ts +8 -0
- package/dist/api/errors.d.ts +6 -3
- package/dist/api/errors.js +1 -1
- package/dist/api/index.d.ts +2 -2
- package/dist/api/index.js +1 -1
- package/dist/api/node-transport.d.ts +18 -0
- package/dist/api/node-transport.js +1 -0
- package/dist/api/routes.d.ts +3 -0
- package/dist/api/routes.js +1 -1
- package/dist/builtin-memory/crouter-sdk.md +86 -0
- package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/provider-rotation.js +1 -1
- package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/provider-rotation.ts +1 -1
- package/dist/cli.js +8 -2
- package/dist/clients/attach/chrome/canvas-panels.js +1 -1
- package/dist/clients/attach/overlays/graph.d.ts +6 -5
- package/dist/clients/attach/overlays/graph.js +1 -1
- package/dist/clients/attach/render/chat-view.d.ts +5 -1
- package/dist/clients/attach/render/chat-view.js +1 -1
- package/dist/clients/attach/session/frames.d.ts +1 -0
- package/dist/clients/attach/session/frames.js +1 -1
- package/dist/clients/attach/viewer.js +576 -576
- package/dist/commands/api-client.js +3 -3
- package/dist/commands/memory/read.js +2 -2
- package/dist/commands/node/create.js +3 -3
- package/dist/commands/sys/branch.js +1 -1
- package/dist/commands/sys/connect.d.ts +1 -0
- package/dist/commands/sys/connect.js +3 -0
- package/dist/commands/sys/daemon.js +1 -1
- package/dist/commands/sys/panels/plugins-panel.js +1 -1
- package/dist/commands/sys/panels/provider-panel.d.ts +4 -0
- package/dist/commands/sys/panels/provider-panel.js +1 -1
- package/dist/commands/sys/provider-login.d.ts +8 -0
- package/dist/commands/sys/provider-login.js +9 -0
- package/dist/commands/sys/setup-core.d.ts +4 -0
- package/dist/commands/sys/setup-core.js +7 -4
- package/dist/commands/sys/setup-wizard.d.ts +1 -1
- package/dist/commands/sys/setup-wizard.js +1 -1
- package/dist/commands/sys.js +1 -1
- package/dist/core/canvas/canvas.d.ts +24 -0
- package/dist/core/canvas/canvas.js +29 -15
- package/dist/core/canvas/migrations.js +35 -32
- package/dist/core/canvas/nav-model.d.ts +1 -1
- package/dist/core/canvas/nav-model.js +1 -1
- package/dist/core/canvas/nav-render.d.ts +31 -25
- package/dist/core/canvas/nav-render.js +1 -1
- package/dist/core/canvas/paths.d.ts +4 -4
- package/dist/core/canvas/render-source.d.ts +6 -16
- package/dist/core/canvas/render-source.js +9 -9
- package/dist/core/canvas/types.d.ts +16 -0
- package/dist/core/config.js +1 -1
- package/dist/core/provider-credential.d.ts +6 -0
- package/dist/core/provider-credential.js +1 -0
- package/dist/core/runtime/boot-root.d.ts +2 -0
- package/dist/core/runtime/boot-root.js +1 -1
- package/dist/core/runtime/broker/daemon-ops.d.ts +2 -1
- package/dist/core/runtime/broker/daemon-ops.js +1 -1
- package/dist/core/runtime/front-door-login.d.ts +2 -0
- package/dist/core/runtime/front-door-login.js +1 -0
- package/dist/core/runtime/front-door.js +7 -5
- package/dist/core/runtime/nerd-font.d.ts +19 -1
- package/dist/core/runtime/nerd-font.js +2 -2
- package/dist/core/runtime/progress-bar.d.ts +13 -0
- package/dist/core/runtime/progress-bar.js +2 -0
- package/dist/core/runtime/provider-credential-gate.d.ts +4 -0
- package/dist/core/runtime/provider-credential-gate.js +2 -0
- package/dist/core/runtime/spawn-env.d.ts +7 -0
- package/dist/core/runtime/spawn-env.js +1 -1
- package/dist/core/secrets.d.ts +3 -0
- package/dist/core/secrets.js +2 -2
- package/dist/core/subscription-state.d.ts +1 -1
- package/dist/core/subscription-state.js +3 -3
- package/dist/core/termrender/termrender.d.ts +3 -1
- package/dist/core/termrender/termrender.js +13 -13
- package/dist/core/user-settings.d.ts +4 -0
- package/dist/core/user-settings.js +1 -1
- package/dist/daemon/api/handlers/broker-ops.js +1 -1
- package/dist/daemon/api/handlers/canvas.js +4 -4
- package/dist/daemon/api/handlers/health.d.ts +1 -1
- package/dist/daemon/api/handlers/health.js +3 -3
- package/dist/daemon/api/handlers/modelauth.js +1 -1
- package/dist/daemon/api/map.d.ts +15 -1
- package/dist/daemon/api/map.js +2 -2
- package/dist/daemon/api/server.d.ts +5 -1
- package/dist/daemon/api/server.js +4 -4
- package/dist/daemon/crtrd-cli.js +1 -1
- package/dist/daemon/fleet.js +1 -1
- package/dist/daemon/manage.d.ts +1 -0
- package/dist/daemon/manage.js +2 -2
- package/dist/pi-extensions/canvas-stophook.js +1 -1
- package/dist/types.d.ts +7 -0
- package/dist/types.js +1 -1
- package/docs/sdk/README.md +54 -0
- package/docs/sdk/client.md +92 -0
- package/docs/sdk/docker.md +63 -0
- package/docs/sdk/errors.md +85 -0
- package/docs/sdk/getting-started.md +160 -0
- package/docs/sdk/memory.md +107 -0
- package/docs/sdk/migration.md +108 -0
- package/docs/sdk/nodes.md +193 -0
- package/docs/sdk/resources.md +71 -0
- package/docs/sdk/streaming.md +124 -0
- package/package.json +1 -1
- package/runtime.lock.json +6 -6
- package/scripts/install-runtime.mjs +7 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var v=Object.defineProperty;var a=(e,o)=>v(e,"name",{value:o,configurable:!0});import{request as A}from"node:http";import{homedir as R}from"node:os";import{join as w}from"node:path";import{CrtrClient as S}from"./client.js";import{envHomeOverride as T}from"../shared/env.js";const O=".crouter",k="crtrd.sock",L=Symbol.for("@north-light/crouter-api/local-socket-fetch");function x(){const e=T(),o=e!==void 0&&e!==""?e:w(R(),O,"canvas");return w(o,k)}a(x,"defaultSocketPath");function H(e){const o=a(function(n,s={}){const m=n instanceof URL?n:new URL(typeof n=="string"?n:n.url),E=s.method??"GET",h={};if(s.headers!==void 0)for(const[l,u]of new Headers(s.headers).entries())h[l]=u;const f=typeof s.body=="string"?s.body:void 0;return f!==void 0&&(h["content-length"]=String(Buffer.byteLength(f))),new Promise((l,u)=>{const i=A({socketPath:e,path:m.pathname+m.search,method:E,headers:h},t=>{const g=new ReadableStream({start(d){t.on("data",r=>d.enqueue(new Uint8Array(r))),t.on("end",()=>d.close()),t.on("error",r=>d.error(r))},cancel(){t.destroy()}}),y=new Headers;for(const[d,r]of Object.entries(t.headers))if(r!==void 0)for(const C of Array.isArray(r)?r:[r])y.append(d,C);const b=t.statusCode??0;l(new Response(b===204?null:g,{status:b,statusText:t.statusMessage,headers:y}))});i.on("error",t=>u(new TypeError("fetch failed",{cause:t})));const c=s.signal,p=a(()=>{i.destroy(),u(c?.reason??new DOMException("The operation was aborted.","AbortError"))},"abort");if(c!=null){if(c.aborted){p();return}c.addEventListener("abort",p,{once:!0})}f!==void 0&&i.write(f),i.end()})},"fetchOverSocket");return o[L]=!0,o}a(H,"socketFetch");function D(e={}){const{socketPath:o,...n}=e;return new S({baseUrl:"http://localhost",fetch:H(o??x()),autostart:!0,...n})}a(D,"localClient");export{x as defaultSocketPath,D as localClient,H as socketFetch};
|
package/dist/api/routes.d.ts
CHANGED
|
@@ -33,6 +33,7 @@ export declare const routes: {
|
|
|
33
33
|
readonly nodeBrokerSettle: (id: string) => string;
|
|
34
34
|
readonly nodeBrokerParkComplete: (id: string) => string;
|
|
35
35
|
readonly nodeBrokerParkActivity: (id: string) => string;
|
|
36
|
+
readonly nodeBrokerTelemetry: (id: string) => string;
|
|
36
37
|
readonly nodeMailClaim: (id: string) => string;
|
|
37
38
|
readonly nodeMailAcknowledge: (id: string) => string;
|
|
38
39
|
readonly nodeBrokerModel: (id: string) => string;
|
|
@@ -75,6 +76,7 @@ export declare const routes: {
|
|
|
75
76
|
readonly canvasHistoryStats: () => string;
|
|
76
77
|
readonly canvasSnapshot: () => string;
|
|
77
78
|
readonly canvasRoster: () => string;
|
|
79
|
+
readonly canvasGraph: () => string;
|
|
78
80
|
readonly canvasPrune: () => string;
|
|
79
81
|
readonly humanReviews: () => string;
|
|
80
82
|
readonly humanReview: (reviewId: string) => string;
|
|
@@ -109,6 +111,7 @@ export declare const routes: {
|
|
|
109
111
|
readonly profileResume: (name: string) => string;
|
|
110
112
|
readonly profileMetadata: (name: string) => string;
|
|
111
113
|
readonly modelAuths: () => string;
|
|
114
|
+
readonly modelAuthReadiness: () => string;
|
|
112
115
|
readonly modelAuth: (provider: string) => string;
|
|
113
116
|
readonly filePeek: () => string;
|
|
114
117
|
readonly memoryResolve: () => string;
|
package/dist/api/routes.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var s=Object.defineProperty;var o=(e,n)=>s(e,"name",{value:n,configurable:!0});const a="v1",$="/v1",t={healthz:o(()=>"/healthz","healthz"),status:o(()=>"/v1/status","status"),daemonRestart:o(()=>"/v1/daemon/restart","daemonRestart"),daemonMigrate:o(()=>"/v1/daemon/migrate","daemonMigrate"),daemonAdmit:o(()=>"/v1/daemon/admit","daemonAdmit"),nodes:o(()=>"/v1/nodes","nodes"),reviveAll:o(()=>"/v1/nodes/revive-all","reviveAll"),node:o(e=>`/v1/nodes/${e}`,"node"),nodeOutcome:o(e=>`/v1/nodes/${e}/outcome`,"nodeOutcome"),nodeOutcomeDelivery:o(e=>`/v1/nodes/${e}/outcome-delivery`,"nodeOutcomeDelivery"),nodeSnapshot:o(e=>`/v1/nodes/${e}/snapshot`,"nodeSnapshot"),nodeSubject:o(e=>`/v1/nodes/${e}/subject`,"nodeSubject"),nodeSession:o(e=>`/v1/nodes/${e}/session`,"nodeSession"),nodeChatInventory:o(e=>`/v1/nodes/${e}/chat-inventory`,"nodeChatInventory"),prospectiveChatInventory:o(()=>"/v1/prospective-chat-inventory","prospectiveChatInventory"),nodeTranscript:o(e=>`/v1/nodes/${e}/transcript`,"nodeTranscript"),nodeContext:o(e=>`/v1/nodes/${e}/context`,"nodeContext"),nodeArtifacts:o(e=>`/v1/nodes/${e}/artifacts`,"nodeArtifacts"),nodeReports:o(e=>`/v1/nodes/${e}/reports`,"nodeReports"),nodeResult:o(e=>`/v1/nodes/${e}/result`,"nodeResult"),nodeJobs:o(e=>`/v1/nodes/${e}/jobs`,"nodeJobs"),nodeJob:o((e,n)=>`/v1/nodes/${e}/jobs/${n}`,"nodeJob"),nodeMessages:o(e=>`/v1/nodes/${e}/messages`,"nodeMessages"),nodeInterrupt:o(e=>`/v1/nodes/${e}/interrupt`,"nodeInterrupt"),nodeFork:o(e=>`/v1/nodes/${e}/fork`,"nodeFork"),nodeRevive:o(e=>`/v1/nodes/${e}/revive`,"nodeRevive"),nodeRelaunchRoot:o(e=>`/v1/nodes/${e}/relaunch-root`,"nodeRelaunchRoot"),nodeBrokerSessionBound:o(e=>`/v1/nodes/${e}/broker/session-bound`,"nodeBrokerSessionBound"),nodeBrokerSettle:o(e=>`/v1/nodes/${e}/broker/settle`,"nodeBrokerSettle"),nodeBrokerParkComplete:o(e=>`/v1/nodes/${e}/broker/park-complete`,"nodeBrokerParkComplete"),nodeBrokerParkActivity:o(e=>`/v1/nodes/${e}/broker/park-activity`,"nodeBrokerParkActivity"),nodeMailClaim:o(e=>`/v1/nodes/${e}/mail/claim`,"nodeMailClaim"),nodeMailAcknowledge:o(e=>`/v1/nodes/${e}/mail/acknowledge`,"nodeMailAcknowledge"),nodeBrokerModel:o(e=>`/v1/nodes/${e}/broker/model`,"nodeBrokerModel"),nodeBrokerExtensionState:o(e=>`/v1/nodes/${e}/broker/extension-state`,"nodeBrokerExtensionState"),nodeBrokerGeneratedName:o(e=>`/v1/nodes/${e}/broker/generated-name`,"nodeBrokerGeneratedName"),nodeBrokerPersonaAck:o(e=>`/v1/nodes/${e}/broker/persona-ack`,"nodeBrokerPersonaAck"),brokerTurn:o(e=>`/v1/broker/${e}/turn`,"brokerTurn"),brokerProviderRetry:o(e=>`/v1/broker/${e}/provider-retry`,"brokerProviderRetry"),brokerFault:o(e=>`/v1/broker/${e}/fault`,"brokerFault"),brokerRecovery:o(e=>`/v1/broker/${e}/recovery`,"brokerRecovery"),nodeFault:o(e=>`/v1/nodes/${e}/fault`,"nodeFault"),nodeClose:o(e=>`/v1/nodes/${e}/close`,"nodeClose"),nodeRecycle:o(e=>`/v1/nodes/${e}/recycle`,"nodeRecycle"),nodeDemote:o(e=>`/v1/nodes/${e}/demote`,"nodeDemote"),nodePromote:o(e=>`/v1/nodes/${e}/promote`,"nodePromote"),nodeYield:o(e=>`/v1/nodes/${e}/yield`,"nodeYield"),nodeWait:o(e=>`/v1/nodes/${e}/wait`,"nodeWait"),nodeConfig:o(e=>`/v1/nodes/${e}/config`,"nodeConfig"),nodeWorktreeClose:o(e=>`/v1/nodes/${e}/worktree/close`,"nodeWorktreeClose"),nodeWorktreeAbandon:o(e=>`/v1/nodes/${e}/worktree/abandon`,"nodeWorktreeAbandon"),quarantinedWorktrees:o(()=>"/v1/worktrees/quarantined","quarantinedWorktrees"),nodeAttach:o(e=>`/v1/nodes/${e}/attach`,"nodeAttach"),focuses:o(()=>"/v1/focuses","focuses"),focusByNode:o(()=>"/v1/focuses/by-node","focusByNode"),focusByPane:o(()=>"/v1/focuses/by-pane","focusByPane"),focus:o(e=>`/v1/focuses/${e}`,"focus"),nodeSubscriptions:o(e=>`/v1/nodes/${e}/subscriptions`,"nodeSubscriptions"),nodeSubscription:o((e,n)=>`/v1/nodes/${e}/subscriptions/${n}`,"nodeSubscription"),crons:o(()=>"/v1/crons","crons"),cron:o(e=>`/v1/crons/${e}`,"cron"),cronPause:o(e=>`/v1/crons/${e}/pause`,"cronPause"),cronResume:o(e=>`/v1/crons/${e}/resume`,"cronResume"),cronRun:o(e=>`/v1/crons/${e}/run`,"cronRun"),cronsPoke:o(()=>"/v1/crons/poke","cronsPoke"),canvasAttention:o(()=>"/v1/canvas/attention","canvasAttention"),canvasAttentionCounts:o(()=>"/v1/canvas/attention/counts","canvasAttentionCounts"),canvasHistorySearch:o(()=>"/v1/canvas/history/search","canvasHistorySearch"),canvasHistoryGrep:o(()=>"/v1/canvas/history/grep","canvasHistoryGrep"),canvasHistoryRead:o(()=>"/v1/canvas/history/read","canvasHistoryRead"),canvasHistoryStats:o(()=>"/v1/canvas/history/stats","canvasHistoryStats"),canvasSnapshot:o(()=>"/v1/canvas/snapshot","canvasSnapshot"),canvasRoster:o(()=>"/v1/canvas/roster","canvasRoster"),canvasPrune:o(()=>"/v1/canvas/prune","canvasPrune"),humanReviews:o(()=>"/v1/human/reviews","humanReviews"),humanReview:o(e=>`/v1/human/reviews/${e}`,"humanReview"),humanReviewSubmit:o(e=>`/v1/human/reviews/${e}/submit`,"humanReviewSubmit"),humanReviewCancel:o(e=>`/v1/human/reviews/${e}/cancel`,"humanReviewCancel"),humanReviewDocument:o(e=>`/v1/human/reviews/${e}/document`,"humanReviewDocument"),humanReviewComments:o(e=>`/v1/human/reviews/${e}/comments`,"humanReviewComments"),humanReviewCommentEvents:o(e=>`/v1/human/reviews/${e}/comment-events`,"humanReviewCommentEvents"),humanReviewCommentRanges:o(e=>`/v1/human/reviews/${e}/comment-ranges`,"humanReviewCommentRanges"),humanComment:o(e=>`/v1/human/comments/${e}`,"humanComment"),humanCommentEdit:o(e=>`/v1/human/comments/${e}/edit`,"humanCommentEdit"),humanCommentResolve:o(e=>`/v1/human/comments/${e}/resolve`,"humanCommentResolve"),humanCommentReopen:o(e=>`/v1/human/comments/${e}/reopen`,"humanCommentReopen"),humanCommentDelete:o(e=>`/v1/human/comments/${e}/delete`,"humanCommentDelete"),humanCommentFork:o(e=>`/v1/human/comments/${e}/fork`,"humanCommentFork"),humanInbox:o(()=>"/v1/human/inbox","humanInbox"),humanInboxTicket:o(e=>`/v1/human/inbox/${e}`,"humanInboxTicket"),humanInboxRespond:o(e=>`/v1/human/inbox/${e}/respond`,"humanInboxRespond"),humanInboxProgress:o(e=>`/v1/human/inbox/${e}/progress`,"humanInboxProgress"),humanInboxResponse:o(e=>`/v1/human/inbox/${e}/response`,"humanInboxResponse"),humanInboxCancel:o(e=>`/v1/human/inbox/${e}/cancel`,"humanInboxCancel"),humanInboxFeedbackResolve:o((e,n)=>`/v1/human/inbox/${e}/feedback-comments/${n}/resolve`,"humanInboxFeedbackResolve"),humanRequests:o(()=>"/v1/human/requests","humanRequests"),humanRequest:o(e=>`/v1/human/requests/${e}`,"humanRequest"),humanRequestReplace:o(e=>`/v1/human/requests/${e}/replace`,"humanRequestReplace"),humanRequestRespond:o(e=>`/v1/human/requests/${e}/respond`,"humanRequestRespond"),humanRequestDismiss:o(e=>`/v1/human/requests/${e}/dismiss`,"humanRequestDismiss"),humanRequestCancel:o(e=>`/v1/human/requests/${e}/cancel`,"humanRequestCancel"),profiles:o(()=>"/v1/profiles","profiles"),profile:o(e=>`/v1/profiles/${e}`,"profile"),profilePause:o(e=>`/v1/profiles/${e}/pause`,"profilePause"),profileResume:o(e=>`/v1/profiles/${e}/resume`,"profileResume"),profileMetadata:o(e=>`/v1/profiles/${e}/metadata`,"profileMetadata"),modelAuths:o(()=>"/v1/model-auth","modelAuths"),modelAuth:o(e=>`/v1/model-auth/${e}`,"modelAuth"),filePeek:o(()=>"/v1/files/peek","filePeek"),memoryResolve:o(()=>"/v1/memory/resolve","memoryResolve")};export{a as API_VERSION,t as routes};
|
|
1
|
+
var s=Object.defineProperty;var o=(e,n)=>s(e,"name",{value:n,configurable:!0});const a="v1",$="/v1",t={healthz:o(()=>"/healthz","healthz"),status:o(()=>"/v1/status","status"),daemonRestart:o(()=>"/v1/daemon/restart","daemonRestart"),daemonMigrate:o(()=>"/v1/daemon/migrate","daemonMigrate"),daemonAdmit:o(()=>"/v1/daemon/admit","daemonAdmit"),nodes:o(()=>"/v1/nodes","nodes"),reviveAll:o(()=>"/v1/nodes/revive-all","reviveAll"),node:o(e=>`/v1/nodes/${e}`,"node"),nodeOutcome:o(e=>`/v1/nodes/${e}/outcome`,"nodeOutcome"),nodeOutcomeDelivery:o(e=>`/v1/nodes/${e}/outcome-delivery`,"nodeOutcomeDelivery"),nodeSnapshot:o(e=>`/v1/nodes/${e}/snapshot`,"nodeSnapshot"),nodeSubject:o(e=>`/v1/nodes/${e}/subject`,"nodeSubject"),nodeSession:o(e=>`/v1/nodes/${e}/session`,"nodeSession"),nodeChatInventory:o(e=>`/v1/nodes/${e}/chat-inventory`,"nodeChatInventory"),prospectiveChatInventory:o(()=>"/v1/prospective-chat-inventory","prospectiveChatInventory"),nodeTranscript:o(e=>`/v1/nodes/${e}/transcript`,"nodeTranscript"),nodeContext:o(e=>`/v1/nodes/${e}/context`,"nodeContext"),nodeArtifacts:o(e=>`/v1/nodes/${e}/artifacts`,"nodeArtifacts"),nodeReports:o(e=>`/v1/nodes/${e}/reports`,"nodeReports"),nodeResult:o(e=>`/v1/nodes/${e}/result`,"nodeResult"),nodeJobs:o(e=>`/v1/nodes/${e}/jobs`,"nodeJobs"),nodeJob:o((e,n)=>`/v1/nodes/${e}/jobs/${n}`,"nodeJob"),nodeMessages:o(e=>`/v1/nodes/${e}/messages`,"nodeMessages"),nodeInterrupt:o(e=>`/v1/nodes/${e}/interrupt`,"nodeInterrupt"),nodeFork:o(e=>`/v1/nodes/${e}/fork`,"nodeFork"),nodeRevive:o(e=>`/v1/nodes/${e}/revive`,"nodeRevive"),nodeRelaunchRoot:o(e=>`/v1/nodes/${e}/relaunch-root`,"nodeRelaunchRoot"),nodeBrokerSessionBound:o(e=>`/v1/nodes/${e}/broker/session-bound`,"nodeBrokerSessionBound"),nodeBrokerSettle:o(e=>`/v1/nodes/${e}/broker/settle`,"nodeBrokerSettle"),nodeBrokerParkComplete:o(e=>`/v1/nodes/${e}/broker/park-complete`,"nodeBrokerParkComplete"),nodeBrokerParkActivity:o(e=>`/v1/nodes/${e}/broker/park-activity`,"nodeBrokerParkActivity"),nodeBrokerTelemetry:o(e=>`/v1/nodes/${e}/broker/telemetry`,"nodeBrokerTelemetry"),nodeMailClaim:o(e=>`/v1/nodes/${e}/mail/claim`,"nodeMailClaim"),nodeMailAcknowledge:o(e=>`/v1/nodes/${e}/mail/acknowledge`,"nodeMailAcknowledge"),nodeBrokerModel:o(e=>`/v1/nodes/${e}/broker/model`,"nodeBrokerModel"),nodeBrokerExtensionState:o(e=>`/v1/nodes/${e}/broker/extension-state`,"nodeBrokerExtensionState"),nodeBrokerGeneratedName:o(e=>`/v1/nodes/${e}/broker/generated-name`,"nodeBrokerGeneratedName"),nodeBrokerPersonaAck:o(e=>`/v1/nodes/${e}/broker/persona-ack`,"nodeBrokerPersonaAck"),brokerTurn:o(e=>`/v1/broker/${e}/turn`,"brokerTurn"),brokerProviderRetry:o(e=>`/v1/broker/${e}/provider-retry`,"brokerProviderRetry"),brokerFault:o(e=>`/v1/broker/${e}/fault`,"brokerFault"),brokerRecovery:o(e=>`/v1/broker/${e}/recovery`,"brokerRecovery"),nodeFault:o(e=>`/v1/nodes/${e}/fault`,"nodeFault"),nodeClose:o(e=>`/v1/nodes/${e}/close`,"nodeClose"),nodeRecycle:o(e=>`/v1/nodes/${e}/recycle`,"nodeRecycle"),nodeDemote:o(e=>`/v1/nodes/${e}/demote`,"nodeDemote"),nodePromote:o(e=>`/v1/nodes/${e}/promote`,"nodePromote"),nodeYield:o(e=>`/v1/nodes/${e}/yield`,"nodeYield"),nodeWait:o(e=>`/v1/nodes/${e}/wait`,"nodeWait"),nodeConfig:o(e=>`/v1/nodes/${e}/config`,"nodeConfig"),nodeWorktreeClose:o(e=>`/v1/nodes/${e}/worktree/close`,"nodeWorktreeClose"),nodeWorktreeAbandon:o(e=>`/v1/nodes/${e}/worktree/abandon`,"nodeWorktreeAbandon"),quarantinedWorktrees:o(()=>"/v1/worktrees/quarantined","quarantinedWorktrees"),nodeAttach:o(e=>`/v1/nodes/${e}/attach`,"nodeAttach"),focuses:o(()=>"/v1/focuses","focuses"),focusByNode:o(()=>"/v1/focuses/by-node","focusByNode"),focusByPane:o(()=>"/v1/focuses/by-pane","focusByPane"),focus:o(e=>`/v1/focuses/${e}`,"focus"),nodeSubscriptions:o(e=>`/v1/nodes/${e}/subscriptions`,"nodeSubscriptions"),nodeSubscription:o((e,n)=>`/v1/nodes/${e}/subscriptions/${n}`,"nodeSubscription"),crons:o(()=>"/v1/crons","crons"),cron:o(e=>`/v1/crons/${e}`,"cron"),cronPause:o(e=>`/v1/crons/${e}/pause`,"cronPause"),cronResume:o(e=>`/v1/crons/${e}/resume`,"cronResume"),cronRun:o(e=>`/v1/crons/${e}/run`,"cronRun"),cronsPoke:o(()=>"/v1/crons/poke","cronsPoke"),canvasAttention:o(()=>"/v1/canvas/attention","canvasAttention"),canvasAttentionCounts:o(()=>"/v1/canvas/attention/counts","canvasAttentionCounts"),canvasHistorySearch:o(()=>"/v1/canvas/history/search","canvasHistorySearch"),canvasHistoryGrep:o(()=>"/v1/canvas/history/grep","canvasHistoryGrep"),canvasHistoryRead:o(()=>"/v1/canvas/history/read","canvasHistoryRead"),canvasHistoryStats:o(()=>"/v1/canvas/history/stats","canvasHistoryStats"),canvasSnapshot:o(()=>"/v1/canvas/snapshot","canvasSnapshot"),canvasRoster:o(()=>"/v1/canvas/roster","canvasRoster"),canvasGraph:o(()=>"/v1/canvas/graph","canvasGraph"),canvasPrune:o(()=>"/v1/canvas/prune","canvasPrune"),humanReviews:o(()=>"/v1/human/reviews","humanReviews"),humanReview:o(e=>`/v1/human/reviews/${e}`,"humanReview"),humanReviewSubmit:o(e=>`/v1/human/reviews/${e}/submit`,"humanReviewSubmit"),humanReviewCancel:o(e=>`/v1/human/reviews/${e}/cancel`,"humanReviewCancel"),humanReviewDocument:o(e=>`/v1/human/reviews/${e}/document`,"humanReviewDocument"),humanReviewComments:o(e=>`/v1/human/reviews/${e}/comments`,"humanReviewComments"),humanReviewCommentEvents:o(e=>`/v1/human/reviews/${e}/comment-events`,"humanReviewCommentEvents"),humanReviewCommentRanges:o(e=>`/v1/human/reviews/${e}/comment-ranges`,"humanReviewCommentRanges"),humanComment:o(e=>`/v1/human/comments/${e}`,"humanComment"),humanCommentEdit:o(e=>`/v1/human/comments/${e}/edit`,"humanCommentEdit"),humanCommentResolve:o(e=>`/v1/human/comments/${e}/resolve`,"humanCommentResolve"),humanCommentReopen:o(e=>`/v1/human/comments/${e}/reopen`,"humanCommentReopen"),humanCommentDelete:o(e=>`/v1/human/comments/${e}/delete`,"humanCommentDelete"),humanCommentFork:o(e=>`/v1/human/comments/${e}/fork`,"humanCommentFork"),humanInbox:o(()=>"/v1/human/inbox","humanInbox"),humanInboxTicket:o(e=>`/v1/human/inbox/${e}`,"humanInboxTicket"),humanInboxRespond:o(e=>`/v1/human/inbox/${e}/respond`,"humanInboxRespond"),humanInboxProgress:o(e=>`/v1/human/inbox/${e}/progress`,"humanInboxProgress"),humanInboxResponse:o(e=>`/v1/human/inbox/${e}/response`,"humanInboxResponse"),humanInboxCancel:o(e=>`/v1/human/inbox/${e}/cancel`,"humanInboxCancel"),humanInboxFeedbackResolve:o((e,n)=>`/v1/human/inbox/${e}/feedback-comments/${n}/resolve`,"humanInboxFeedbackResolve"),humanRequests:o(()=>"/v1/human/requests","humanRequests"),humanRequest:o(e=>`/v1/human/requests/${e}`,"humanRequest"),humanRequestReplace:o(e=>`/v1/human/requests/${e}/replace`,"humanRequestReplace"),humanRequestRespond:o(e=>`/v1/human/requests/${e}/respond`,"humanRequestRespond"),humanRequestDismiss:o(e=>`/v1/human/requests/${e}/dismiss`,"humanRequestDismiss"),humanRequestCancel:o(e=>`/v1/human/requests/${e}/cancel`,"humanRequestCancel"),profiles:o(()=>"/v1/profiles","profiles"),profile:o(e=>`/v1/profiles/${e}`,"profile"),profilePause:o(e=>`/v1/profiles/${e}/pause`,"profilePause"),profileResume:o(e=>`/v1/profiles/${e}/resume`,"profileResume"),profileMetadata:o(e=>`/v1/profiles/${e}/metadata`,"profileMetadata"),modelAuths:o(()=>"/v1/model-auth","modelAuths"),modelAuthReadiness:o(()=>"/v1/model-auth/readiness","modelAuthReadiness"),modelAuth:o(e=>`/v1/model-auth/${e}`,"modelAuth"),filePeek:o(()=>"/v1/files/peek","filePeek"),memoryResolve:o(()=>"/v1/memory/resolve","memoryResolve")};export{a as API_VERSION,t as routes};
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
---
|
|
2
|
+
kind: knowledge
|
|
3
|
+
description: Driving a crouter daemon from an application with @north-light/crouter-sdk
|
|
4
|
+
when-and-why-to-read: When you are writing or reviewing application code that runs a crtr agent — installing @north-light/crouter-sdk, constructing a client, creating a node and reading its result, or connecting a browser to a daemon — this reference should be read because `generate()` and `local()` were deleted, and phase-2 streaming and phase-3 memory methods do not exist yet.
|
|
5
|
+
short-form: The application-facing client for a crtrd daemon. Construction and transports, `client.nodes` create/wait/parse, the returned-not-thrown outcome union, the error classes, and which parts of the surface have not shipped.
|
|
6
|
+
surfaces:
|
|
7
|
+
- on: boot
|
|
8
|
+
at: name
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
# `@north-light/crouter-sdk`
|
|
12
|
+
|
|
13
|
+
One client an application installs to drive a crouter daemon over its `/v1` API: create agent runs, wait for typed results, and reach the rest of the daemon. Resource methods issue `/v1` requests; `createAndWait`, `parse`, and `auth.status` compose requests. crtrd stays the sole owner of canvas state. The runtime model behind the objects — nodes, the canvas, lifecycle, reports — is `internal/nodes-and-canvas`.
|
|
14
|
+
|
|
15
|
+
## Check what has shipped before you write against it
|
|
16
|
+
|
|
17
|
+
The surface ships in three cuts, and **phases 2 and 3 do not exist**. Streaming (`client.nodes.stream`, `client.nodes.events`, `GET /v1/nodes/{id}/events`) is phase 2. Memory (`client.memory` and every `/v1/memory` route but `resolve`) is phase 3. Writing code against a phase-2 or phase-3 method produces something that typechecks against the design document and fails at runtime.
|
|
18
|
+
|
|
19
|
+
Phase 1 is client construction and transports, `client.nodes` create / retrieve / list / outcome / waitForOutcome / createAndWait / parse / message / cancel / interrupt, `nodes.reports.list`, `profiles`, `system.status`, `files.peek`, the error hierarchy, and per-request options.
|
|
20
|
+
|
|
21
|
+
Confirm against the installed package's types rather than against any document, including this one.
|
|
22
|
+
|
|
23
|
+
## The published README is stale
|
|
24
|
+
|
|
25
|
+
`generate()`, `local()`, and the `Environment` interface were **deleted**, not deprecated — a hard cut with no shim. Code written from the npm README or from training data will call `generate({ prompt, schema, env: local() })` and will not compile. The replacement is `new Crouter()` plus `client.nodes.parse({ prompt, output_schema })`.
|
|
26
|
+
|
|
27
|
+
## A run, end to end
|
|
28
|
+
|
|
29
|
+
An agent run needs a daemon. `npm i -g @north-light/crouter` installs `crtr` and `crtrd`; `new Crouter()` starts the daemon itself on a cold socket, so nothing has to be running first.
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
import Crouter from '@north-light/crouter-sdk';
|
|
33
|
+
import { z } from 'zod';
|
|
34
|
+
|
|
35
|
+
const client = new Crouter();
|
|
36
|
+
|
|
37
|
+
const run = await client.nodes.parse({
|
|
38
|
+
prompt: 'Read package.json here and report its name and version.',
|
|
39
|
+
cwd: '/path/to/repo',
|
|
40
|
+
output_schema: z.object({ name: z.string(), version: z.string() }),
|
|
41
|
+
root: true,
|
|
42
|
+
root_lifecycle: 'terminal',
|
|
43
|
+
});
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
`root: true` means the run has no parent node and reports to nobody, which is what an application's run is. `root_lifecycle: 'terminal'` finishes and reaps; `'resident'` keeps the node for a person to open. Wire fields are `snake_case` and the SDK does not camelize them.
|
|
47
|
+
|
|
48
|
+
## The agent's own outcome is returned, never thrown
|
|
49
|
+
|
|
50
|
+
A run that refused the schema, hit its deadline, or crashed comes back as a value. Wrapping the call in `try`/`catch` and treating the catch as the failure path silently drops every agent-side outcome, because none of them throw.
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
if (run.kind === 'result') use(run.output_parsed);
|
|
54
|
+
else if (run.reason === 'declined') handleRefusal(run.declined?.reason, run.declined?.retryable);
|
|
55
|
+
else handleFailure(run.reason, run.detail);
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
A decline is `kind: 'failure'` with `reason: 'declined'` — narrow on `reason`, not on `kind`. `output_parsed` is non-null exactly when `kind === 'result'`. A Zod schema supplies its inferred output type; a Standard Schema supplies `~standard.types.output`; a JSON-Schema literal or any other `{ toJSONSchema() }` object makes it `unknown`. The SDK does not re-validate the result because the daemon already enforced the schema when the agent submitted.
|
|
59
|
+
|
|
60
|
+
Exceptions are for the layer underneath: `BadRequestError`, `AuthenticationError`, `PermissionDeniedError`, `NotFoundError`, `ConflictError`, `UnprocessableEntityError`, `RateLimitError`, `InternalServerError`, `APIConnectionError`, `APIConnectionTimeoutError`, `APIUserAbortError`, all extending `APIError` with `status`, `code`, `message`, `details`, `headers`. Branch on `code` — it is the stable machine-readable identity (`node_id_exists`, `daemon_unavailable`, `node_dormant`).
|
|
61
|
+
|
|
62
|
+
## A retried create spawns a second agent unless you pass `node_id`
|
|
63
|
+
|
|
64
|
+
`maxRetries` (default 2) covers connection errors and 429/5xx on `GET`, `HEAD`, and `DELETE`. **`POST` and `PATCH` are never retried**, because a mutation whose response was interrupted may already have been applied. A caller that wants a retry-safe create passes `node_id`: the duplicate then fails with `409 node_id_exists`, which the caller catches and turns into a `waitForOutcome` on the run that already exists.
|
|
65
|
+
|
|
66
|
+
## `waitForOutcome` has no time bound
|
|
67
|
+
|
|
68
|
+
It polls until the node settles, however long that takes. Bound it from one side or the other: a `deadline` on `create` makes the daemon cancel the run, a `signal` makes your client stop waiting. Aborting the signal stops the client, not the agent — `client.nodes.cancel(id)` stops the agent, `client.nodes.interrupt(id)` stops only the current turn.
|
|
69
|
+
|
|
70
|
+
Before streaming ships, progress comes from `client.nodes.reports.list(id)`.
|
|
71
|
+
|
|
72
|
+
## Reaching a daemon that is not on this machine
|
|
73
|
+
|
|
74
|
+
`new Crouter()` uses the owner's unix socket, which authenticates by filesystem permission. A browser has no unix sockets and a remote process has no access to that one, so both use the TCP listener with a bearer token: `new Crouter({ baseURL, token })`.
|
|
75
|
+
|
|
76
|
+
The listener is off until someone runs `crtr sys connect` on the daemon's machine, which stores the address and token and hands the daemon over to a successor that boots with it on, then prints both to paste into the application. The token is the owner credential — whoever holds it reaches the whole surface. Cross-origin calls work only when a token is set; an unauthenticated listener stays same-origin so that no page the user happens to visit can drive their daemon. A page served over HTTPS calling `http://localhost:<port>` also needs Chrome's Local Network Access permission, which the browser prompts for once per site and which requires no response header.
|
|
77
|
+
|
|
78
|
+
`baseURL` and `socketPath` are mutually exclusive — passing both throws `TypeError` at construction. Options fall back to `CRTR_BASE_URL`, `CRTR_SOCKET`, `CRTR_HOME`, and `CRTRD_TOKEN`, read once at construction.
|
|
79
|
+
|
|
80
|
+
## Reaching a route the SDK does not wrap
|
|
81
|
+
|
|
82
|
+
`client.request(method, path, body?, options?)` carries the same authentication, retry policy, and error mapping as every generated method. Some routes are deliberately outside the typed surface — tmux focuses, a node's own inbox mail claim, local attach, and the broker's control plane — because an external caller invoking them either cannot use the result or becomes a second writer to state the broker and daemon coordinate between themselves.
|
|
83
|
+
|
|
84
|
+
## The full reference
|
|
85
|
+
|
|
86
|
+
Page-per-topic detail — the complete create-parameter table, the streaming event table, the memory scope object, the resource map with its phase markers, and the migration table — lives in the crouter repository under `docs/sdk/`, published at <https://github.com/vallum-security/crouter/tree/main/docs/sdk>. The remaining `TODO(verify)` markers belong only to the phase-2 streaming and phase-3 memory pages.
|
|
@@ -668,7 +668,7 @@ async function runManagedProvider(state, model, context, options, stream) {
|
|
|
668
668
|
}
|
|
669
669
|
if (!reauthenticated) {
|
|
670
670
|
const attemptAt = Date.now();
|
|
671
|
-
await recordSubscriptionMutation(`recording ${getProviderLabel(providerId)} authentication failure`, () => markSubscriptionAuthenticationFailed(providerId, credential.label, INVALID_REFRESH_TOKEN_BACKOFF_MS, attemptAt));
|
|
671
|
+
await recordSubscriptionMutation(`recording ${getProviderLabel(providerId)} authentication failure`, () => markSubscriptionAuthenticationFailed(providerId, credential.label, credential, INVALID_REFRESH_TOKEN_BACKOFF_MS, attemptAt));
|
|
672
672
|
authFailures.add(`${providerId}/${credential.label}`);
|
|
673
673
|
continue;
|
|
674
674
|
}
|
|
@@ -864,7 +864,7 @@ async function runManagedProvider(
|
|
|
864
864
|
}
|
|
865
865
|
if (!reauthenticated) {
|
|
866
866
|
const attemptAt = Date.now();
|
|
867
|
-
await recordSubscriptionMutation(`recording ${getProviderLabel(providerId)} authentication failure`, () => markSubscriptionAuthenticationFailed(providerId, credential.label, INVALID_REFRESH_TOKEN_BACKOFF_MS, attemptAt));
|
|
867
|
+
await recordSubscriptionMutation(`recording ${getProviderLabel(providerId)} authentication failure`, () => markSubscriptionAuthenticationFailed(providerId, credential.label, credential, INVALID_REFRESH_TOKEN_BACKOFF_MS, attemptAt));
|
|
868
868
|
authFailures.add(`${providerId}/${credential.label}`);
|
|
869
869
|
continue;
|
|
870
870
|
}
|
package/dist/cli.js
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
3
|
-
|
|
2
|
+
var l=Object.defineProperty;var i=(r,t)=>l(r,"name",{value:t,configurable:!0});import"./suppress-experimental-warnings.js";import{mkdirSync as d,openSync as u,renameSync as y,rmSync as g,statSync as a,writeFileSync as w}from"node:fs";import{homedir as v}from"node:os";import{dirname as p,join as c}from"node:path";import{enableCompileCache as h}from"node:module";import{fileURLToPath as m}from"node:url";import{isDaemonControlInvocation as R,resolveDaemonControlRoot as S,resolveRoot as E}from"./build-root.js";import{maybeBootRoot as _}from"./core/runtime/front-door.js";import{maybeAutoUpdate as b}from"./core/auto-update.js";import{ensureProjectScope as A}from"./core/bootstrap.js";import{provisionExports as C,pruneLegacyExports as $}from"./core/host-exports/export.js";import{revalidateBundlePlugins as k}from"./core/command-plugins/revalidate.js";import{runCli as I}from"./core/command.js";import{dispatchWithStaleRecovery as x}from"./core/manifest-recovery.js";import{installStdoutErrorPolicy as N}from"./core/stdout-errors.js";import{handle as O}from"./core/io.js";import{CrtrError as T}from"./core/errors.js";import{ApiError as F}from"./api/index.js";import{mark as o}from"./core/timing.js";u(m(import.meta.url),"r"),N(),o("cli.entry",{cmd:process.argv[2]??"(bare)"});try{h()}catch{}o("cli.compile_cache");const P=c(p(m(import.meta.url)),".."),n=c(v(),".crouter","first-run.json");function s(r){return(r instanceof Error?r.message:String(r)).split(/\r?\n/,1)[0]??""}i(s,"errorMessage");function D(r){const t=p(n);d(t,{recursive:!0});const e=`${n}.${process.pid}.${Date.now()}.tmp`;try{w(e,JSON.stringify({packageVersion:r,completedAt:new Date().toISOString()})+`
|
|
3
|
+
`,"utf8"),y(e,n)}finally{g(e,{force:!0})}}i(D,"writeFirstRunMarker");async function U(){if(process.env.CRTR_NO_AUTO_INIT==="1")return;try{if(a(n,{throwIfNoEntry:!1})!==void 0)return}catch(t){process.stderr.write(`crtr: first-run reconcile marker check failed: ${s(t)}
|
|
4
|
+
`);return}try{if(a(c(P,".git"),{throwIfNoEntry:!1})!==void 0)return}catch(t){process.stderr.write(`crtr: first-run reconcile source check failed: ${s(t)}
|
|
5
|
+
`);return}let r;try{const{reconcileFirstRun:t}=await import("./commands/sys/setup-core.js");r=await t((e,f)=>{process.stderr.write(`crtr: first-run reconcile ${e} failed: ${s(f)}
|
|
6
|
+
`)})}catch(t){process.stderr.write(`crtr: first-run reconcile failed: ${s(t)}
|
|
7
|
+
`)}finally{if(r!==void 0)try{D(r)}catch(t){process.stderr.write(`crtr: first-run reconcile marker failed: ${s(t)}
|
|
8
|
+
`)}}}i(U,"maybeReconcileFirstRun");async function j(){if($(process.argv),await U(),await _(process.argv),o("cli.front_door_passed"),R(process.argv)){await I(await S(),process.argv);return}await k(process.argv),o("cli.plugins_revalidated");const r=await E(process.argv[2]);o("cli.root_resolved"),C(r,process.argv),A(process.argv),b(process.argv),o("cli.dispatch_start"),await x(r,process.argv),o("cli.dispatch_done")}i(j,"main"),j().catch(r=>{(r instanceof Error&&r.name==="AbortError"||r instanceof Error&&/operation was aborted/i.test(r.message))&&(process.stderr.write(`crtr: Interrupted
|
|
9
|
+
`),process.exit(130)),(r instanceof F||r instanceof T)&&(O(r),process.exit(typeof process.exitCode=="number"?process.exitCode:1));const e=r instanceof Error?r.message:String(r);process.stderr.write(`crtr: ${e}
|
|
4
10
|
`),process.exit(1)});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var z=Object.defineProperty;var
|
|
1
|
+
var z=Object.defineProperty;var i=(s,a)=>z(s,"name",{value:a,configurable:!0});import{navLabel as B,nodeGlyph as Q,truncate as U,tokensCell as X,cycleBadge as Y,askBadge as Z,activityCell as j,fillWidth as I,RESET as m,DIM as nn,GREEN as tn}from"../../../core/canvas/nav-render.js";const en=34,on=40;import{RemoteCanvasSource as sn}from"../../../core/canvas/remote-canvas-source.js";import{cronWaitSummary as an}from"./cron-wait.js";import{bashJobsWaitSummary as cn}from"./bash-jobs.js";import{reviewWaitSummary as rn}from"./review-wait.js";const dn=12,un=6,N=22;function A(s,a){return s.length>a?`${s.slice(0,a-1)}\u2026`:s+" ".repeat(a-s.length)}i(A,"nameCell");function fn(s,a){return s.length>=a?s.slice(0,a):" ".repeat(a-s.length)+s}i(fn,"padStartVisible");async function gn(s,a,c,h,x=[],v=[],H=[]){const k=h instanceof sn,_=new Map,b=new Map,M=new Map,l=i(n=>{const t=_.get(n);if(t!==void 0)return t;const e=h.getNode(n).catch(()=>null);return _.set(n,e),e},"node"),p=i(n=>{const t=b.get(n);if(t!==void 0)return t;const e=(async()=>{const o=await h.subscriptionsOf(n).catch(()=>[]),f=[];for(const d of o)(await l(d.node_id))?.kind!=="human"&&f.push(d.node_id);return f})();return b.set(n,e),e},"convoChildIds"),S=i(n=>{const t=M.get(n);if(t!==void 0)return t;const e=h.subscribersOf(n).then(o=>o[0]?.node_id).catch(()=>{});return M.set(n,e),e},"managerOf"),D=i(async n=>{const t=[];for(const e of await p(n)){const o=(await l(e))?.status;(o==="active"||o==="idle")&&t.push(e)}return t},"liveReports"),P=i(async n=>{let t=n;const e=new Set([t]);for(;;){const o=await S(t);if(o===void 0||e.has(o))break;e.add(o),t=o}return t},"climbRoot"),R=new Map,F=i(async n=>{const t=new Set,e=i(async o=>{const f=(await l(o))?.status==="active";if(t.has(o))return f?1:0;t.add(o);let d=0;for(const y of await p(o))d+=await e(y);return R.set(o,d),d+(f?1:0)},"visit");await e(n)},"computeActivity"),G=i(async n=>{if(n===null||n.mode!=="orchestrator")return"";const t=(await p(n.node_id)).length;return t>0?` ${nn}\u2933${t}${m}`:""},"childBadgeFor"),K=i(n=>{if(n===null||n.status==="active")return"";const t=R.get(n.node_id)??0;return t>0?` ${tn}\u21E3${t}${m}`:""},"liveBelowBadgeFor"),$=c?.muted??(n=>n),L=c?.faint??(n=>n);await F(await P(s));const r=await S(s),w=await D(s),g=[...r!==void 0?[r]:[],...w],T=await Promise.all(g.map(n=>l(n))),V=g.length>0?Math.min(N,Math.max(...g.map((n,t)=>B(T[t]??null,n).length))):N,W=i(async(n,t)=>{const e=await l(n),o=A(B(e,n),V),f=L(A(e?.kind??"",dn)),d=$(fn(X(e,k),un)),y=`${Y(e)}${await G(e)}${K(e)}${Z(n,a)}${j(e,k)}`,q=` ${t} ${Q(e)} ${o} ${f} ${d}${y}`;return U(q)},"row"),J=[...r!==void 0?[r]:[],...w],u=[];r!==void 0&&u.push({key:`node:${r}`,kind:"node",nodeId:r,line:await W(r,"\u2191")});for(const n of w)u.push({key:`node:${n}`,kind:"node",nodeId:n,line:await W(n,"\u2193")});for(const n of H){const t=c?c.info("\u270E"):"\u270E",e=rn(n,Math.max(8,I()-on));u.push({key:`review:${n.review_id}`,kind:"review",companionNodeId:n.companion_node_id,line:` ${t} ${$(`${e} \xB7 \u21B5 companion`)}${m}`})}const C=v.length===1?" \xB7 x stop":"",E=cn(v,Date.now(),I()-(en+C.length));if(E!==void 0){const n=c?c.info("\u2699"):"\u2699";u.push({key:"bash",kind:"bash",line:` ${n} ${$(`${E} \xB7 \u21B5 details${C}`)}${m}`})}const O=an(x);if(O!==void 0){const n=c?c.info("\u25F7"):"\u25F7";u.push({key:"crons",kind:"crons",line:` ${n} ${$(`${O} \xB7 \u21B5 details`)}${m}`})}return{reports:u.map(n=>n.line),reportIds:J,items:u}}i(gn,"buildCanvasPanelLines");export{gn as buildCanvasPanelLines};
|
|
@@ -33,11 +33,6 @@ export declare class GraphOverlay implements Component {
|
|
|
33
33
|
* commands against a remote graph row. See the file header. */
|
|
34
34
|
private readonly remote;
|
|
35
35
|
constructor(tui: TUI, self: string, getAsks: () => Record<string, number>, palette: AttachPalette, bindings: BindingResolution<BindingId>, source: CanvasSource, role?: ClientRole, onRefreshFailure?: (cause?: unknown) => void, onNotice?: (message: string) => void);
|
|
36
|
-
/** The tmux-focus set for `isAttached`, fetched via crtrd (was nav-model's
|
|
37
|
-
* focusedNodeIds → listFocuses db read). Empty for a remote source (a remote
|
|
38
|
-
* node id may collide with a local focus row); a failed API call degrades to
|
|
39
|
-
* empty rather than throwing the whole snapshot. */
|
|
40
|
-
private fetchFocused;
|
|
41
36
|
setBindings(bindings: BindingResolution<BindingId>): void;
|
|
42
37
|
private matches;
|
|
43
38
|
private hint;
|
|
@@ -53,6 +48,12 @@ export declare class GraphOverlay implements Component {
|
|
|
53
48
|
/** Repaint if shown (the low-rate ask poll calls this). */
|
|
54
49
|
refresh(): void;
|
|
55
50
|
invalidate(): void;
|
|
51
|
+
/** Local: ONE `/v1/canvas/graph` read supplies the display rows, both edge
|
|
52
|
+
* directions, and the focus set — no enriched node list, no roster call, no
|
|
53
|
+
* separate focus query. Remote: unchanged — a remote canvas exposes only the
|
|
54
|
+
* per-node `CanvasSource` reads, and its focus set stays empty (a remote node
|
|
55
|
+
* id may collide with a local focus row). */
|
|
56
|
+
private fetchInput;
|
|
56
57
|
private buildSnapshot;
|
|
57
58
|
/** Fold state is presentation-only. Reproject the visible DFS from the fully
|
|
58
59
|
* fetched topology so h/l never cross the daemon boundary. The explicit stack
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var N=Object.defineProperty;var $=(S,t)=>N(S,"name",{value:t,configurable:!0});import{execFile as O}from"node:child_process";import{matchesKey as P,truncateToWidth as C}from"@earendil-works/pi-tui";import{formatBinding as H,matchesPiTuiInput as B}from"../../../core/keybindings/index.js";import{fullName as L}from"../../../core/canvas/labels.js";import{faultSummary as F}from"../../../core/canvas/status-glyph.js";import{RemoteCanvasSource as G}from"../../../core/canvas/remote-canvas-source.js";import{cliClient as K}from"../../../commands/api-client.js";import{statusRank as M}from"../../../core/canvas/node-order.js";import{beginFrameTelem as E,navLabel as W,nodeGlyph as j,tokensCell as Y,cycleBadge as D,askBadge as V,activityCell as U,shortId as A,visibleWidth as _,fillBar as k,fillWidth as q,truncate as X,isAttached as z,VIEWPORT_FALLBACK_ROWS as J,DIM as R,RESET as p,BOLD as T,YELLOW as Q,REVERSE as Z,BG_ATTACHED as tt,GREEN as et}from"../../../core/canvas/nav-render.js";const st=.72,it={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},rt=[["crtr.graph.dismiss","dismiss"],["crtr.graph.focus","focus"],["crtr.graph.revive","revive"],["crtr.graph.close-subtree","close"],["crtr.graph.focus-manager","manager"]],nt=[["crtr.graph.dismiss","dismiss"]],ot=[["crtr.graph.down","down"],["crtr.graph.up","up"],["crtr.graph.first","first"],["crtr.graph.last","last"],["crtr.graph.collapse-or-manager","fold/manager"],["crtr.graph.expand-or-child","expand/child"]];class $t{static{$(this,"GraphOverlay")}tui;self;getAsks;palette;bindings;source;role;onRefreshFailure;onNotice;handle;userExpanded=new Set;userCollapsed=new Set;folds={userExpanded:this.userExpanded,userCollapsed:this.userCollapsed};cursorId;scrollTop=0;pendingConfirm;snapshot;snapshotSeq=0;remote;constructor(t,s,e,r,o,h,d="controller",l=()=>{},n=()=>{}){this.tui=t,this.self=s,this.getAsks=e,this.palette=r,this.bindings=o,this.source=h,this.role=d,this.onRefreshFailure=l,this.onNotice=n,this.remote=h instanceof G}async fetchFocused(){if(this.remote)return new Set;try{return new Set((await K().listFocuses()).map(t=>t.node_id))}catch{return new Set}}setBindings(t){this.bindings=t,this.handle!==void 0&&this.tui.requestRender()}matches(t,s){return B(this.bindings,t,s,(e,r)=>P(e,r))}hint(t){return t.flatMap(([s,e])=>this.bindings.gestures(s).length===0?[]:[`${H(this.bindings,s)} ${e}`])}fitHints(t,s){const r=[];let o=0;for(const h of this.hint(t)){const d=(r.length===0?0:3)+_(h);if(o+d>s)break;r.push(h),o+=d}return r.join(" \xB7 ")}isOpen(){return this.handle!==void 0}open(){this.handle===void 0&&(this.scrollTop=0,this.pendingConfirm=void 0,this.cursorId=this.self,this.handle=this.tui.showOverlay(this,it),this.refresh())}close(){this.handle!==void 0&&(this.pendingConfirm=void 0,this.handle.hide(),this.handle=void 0,this.tui.requestRender())}toggle(){this.handle===void 0?this.open():this.close()}refresh(){if(this.handle===void 0)return;const t=++this.snapshotSeq;this.buildSnapshot().then(s=>{t===this.snapshotSeq&&(this.snapshot=s,this.tui.requestRender())}).catch(s=>{this.onRefreshFailure(s),this.tui.requestRender()})}invalidate(){this.refresh()}async buildSnapshot(){E();const[t,s]=await Promise.all([this.source.listNodes().catch(()=>[]),this.fetchFocused()]),e=new Map(t.map(i=>[i.node_id,i])),r=new Map,o=new Map,h=new Map,d=new Map,l=$(async i=>{const a=r.get(i);if(a!==void 0)return a;let f;try{f=await this.source.subscriptionsOf(i)}catch{f=[]}const w=f.map(g=>g.node_id).filter(g=>e.get(g)?.kind!=="human");return r.set(i,w),w},"children"),n=$(async i=>{if(h.has(i))return h.get(i);let a;try{a=(await this.source.subscribersOf(i))[0]?.node_id}catch{a=void 0}return h.set(i,a),a},"manager"),c=$(async()=>{let i=this.self;const a=new Set([i]);for(;;){const f=await n(i);if(f===void 0||a.has(f))break;a.add(f),i=f}return i},"climbRoot"),u=$(async i=>{const a=o.get(i);if(a!==void 0)return a;const f=[...await l(i)];return f.sort((w,g)=>M(e.get(w)?.status)-M(e.get(g)?.status)),o.set(i,f),f},"sortedChildren"),v=new Set,m=new Set,x=$(async i=>{const a=e.get(i)?.status==="active";if(m.has(i))return{active:a?1:0,reveal:a||i===this.self};m.add(i);let f=0,w=!1;for(const g of await l(i)){const y=await x(g);f+=y.active,y.reveal&&(w=!0)}return d.set(i,f),w&&v.add(i),{active:f+(a?1:0),reveal:w||a||i===this.self}},"visitActivity"),I=await c();await x(I),await Promise.all([...r.keys()].map(i=>u(i)));const b={root:I,rows:[],autoExpanded:v,activeBelow:d,nodes:e,childIds:r,sortedChildIds:o,managerOf:h,focused:s};return b.rows=this.projectRows(b),b}projectRows(t){const s=[],e=new Set,r=[{id:t.root,prefix:"",isRoot:!0,isLast:!0}];for(;r.length>0;){const{id:o,prefix:h,isRoot:d,isLast:l}=r.pop(),n=d?"":l?"\u2514\u2500 ":"\u251C\u2500 ";if(e.has(o)){s.push({id:o,hasKids:!1,isSelf:o===this.self,branch:h+n,cycle:!0,collapsed:!1});continue}e.add(o);const c=t.sortedChildIds.get(o)??[],u=this.folds.userExpanded.has(o)?!1:this.folds.userCollapsed.has(o)?!0:!t.autoExpanded.has(o);if(s.push({id:o,hasKids:c.length>0,isSelf:o===this.self,branch:h+n,cycle:!1,collapsed:u}),u)continue;const v=d?"":h+(l?" ":"\u2502 ");for(let m=c.length-1;m>=0;m--)r.push({id:c[m],prefix:v,isRoot:!1,isLast:m===c.length-1})}return s}repaintFolds(){this.snapshot!==void 0&&(this.snapshot.rows=this.projectRows(this.snapshot)),this.tui.requestRender()}renderSnapshotRow(t,s,e,r){const o=$((g,y)=>e?k(g,q(),Z):y?k(g,q(),tt):X(g),"wrap");if(s.cycle){const g=`${s.branch} ${R}\u21BA ${A(s.id)}${p}`;return o(g,!1)}const h=t.nodes.get(s.id)??null,d=j(h),l=W(h,s.id),n=s.isSelf?`${T}${l}${p}`:l,c=`${R}${h?.kind??""}${p}`,u=`${R}${Y(s.id,this.remote)}${p}`,v=s.hasKids&&s.collapsed,m=!e&&v?`${R}\u25B8${p} `:" ",x=D(h),I=t.childIds.get(s.id)?.length??0,b=h!==null&&I>0?` ${R}\u2933${I}${p}`:"",i=h!==null&&h.status!=="active"&&(t.activeBelow.get(h.node_id)??0)>0?` ${et}\u21E3${t.activeBelow.get(h.node_id)??0}${p}`:"",a=h?.fault??null,f=a!==null?` \xB7 ${F(a)}`:"",w=`${s.branch}${m}${d} ${n} ${c} ${u}${x}${b}${i}${V(s.id,r)}${U(s.id,h,this.remote)}${f}`;return o(w,z(s.id,h,t.focused,this.remote))}render(t){E();const s=this.getAsks(),e=this.snapshot?.rows??[];let r=e.findIndex(i=>i.id===this.cursorId);r<0&&(r=e.findIndex(i=>i.id===this.self),r<0&&(r=0)),this.cursorId=e[r]?.id??this.self;const o=process.stdout.rows??J,h=Math.max(3,Math.min(Math.floor(o*st),o-2)),d=Math.max(2,Math.min(e.length,h-2));let l=d;for(let i=0;i<4;i++){r<this.scrollTop&&(this.scrollTop=r),r>=this.scrollTop+l&&(this.scrollTop=r-l+1),this.scrollTop=Math.max(0,Math.min(this.scrollTop,Math.max(0,e.length-l)));const a=d-(this.scrollTop>0?1:0)-(this.scrollTop+l<e.length?1:0);if(a===l)break;l=Math.max(1,a)}const n=Math.min(e.length,this.scrollTop+l),c=[];this.scrollTop>0&&c.push(`${R} \u2191 ${this.scrollTop} more${p}`);for(let i=this.scrollTop;i<n;i++){const a=this.snapshot;c.push(a!==void 0?this.renderSnapshotRow(a,e[i],i===r,s):"")}for(n<e.length&&c.push(`${R} \u2193 ${e.length-n} more${p}`);c.length<d;)c.push("");const u=e.length>0?`${T}\u2317 canvas graph${p} ${R}(${r+1}/${e.length})${p}`:`${T}\u2317 canvas graph${p} ${R}(loading)${p}`,v=this.pendingConfirm!==void 0?`${Q}${this.pendingConfirm.label} ${T}${this.hint([["crtr.graph.confirm.accept","accept"],["crtr.graph.confirm.cancel","cancel"]]).join(" \xB7 ")}${p}`:`${R}${this.fitHints([...this.remote||this.role!=="controller"?nt:rt,...ot],Math.max(1,t-5))}${p}`,m=this.palette.border,x=Math.max(1,t-4),I=c.map(i=>`${m("\u2502")} ${C(i,x,"",!0)} ${m("\u2502")}`),b=this.palette.surface;return[this.borderRow("\u256D","\u256E",u,t),...I,this.borderRow("\u2570","\u256F",v,t)].map(b)}borderRow(t,s,e,r){const o=this.palette.border,h=Math.max(1,r-5),d=C(e,h,"\u2026"),l=Math.max(0,r-5-_(d));return`${o(`${t}\u2500`)} ${d} ${o("\u2500".repeat(l)+s)}`}handleInput(t){try{this.dispatch(t)}catch{}}dispatch(t){if(this.pendingConfirm!==void 0){if(this.matches("crtr.graph.confirm.accept",t)){const n=this.pendingConfirm.action;this.pendingConfirm=void 0,n()}else this.pendingConfirm=void 0;this.tui.requestRender();return}if(this.matches("crtr.graph.dismiss",t)){this.close();return}const s=this.snapshot,e=s?.rows??[];let r=e.findIndex(n=>n.id===this.cursorId);r<0&&(r=Math.max(0,e.findIndex(n=>n.id===this.self)));const o=e[r],h=$(n=>n!==void 0&&!n.cycle,"isSelectable"),d=$((n,c)=>{for(let u=n+c;u>=0&&u<e.length;u+=c)if(h(e[u]))return u;return n},"step"),l=$(n=>{const c=n===1?0:e.length-1;for(let u=c;u>=0&&u<e.length;u+=n)if(h(e[u]))return u;return r},"edge");if(this.matches("crtr.graph.down",t)){r=d(r,1),this.cursorId=e[r]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.up",t)){r=d(r,-1),this.cursorId=e[r]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.first",t)){this.cursorId=e[l(1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.last",t)){this.cursorId=e[l(-1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.collapse-or-manager",t)){if(o!==void 0&&o.hasKids&&!o.collapsed)this.userCollapsed.add(o.id),this.userExpanded.delete(o.id),this.repaintFolds();else{const n=s?.managerOf.get(this.cursorId??this.self);n!==void 0&&e.some(c=>c.id===n)&&(this.cursorId=n),this.tui.requestRender()}return}if(this.matches("crtr.graph.expand-or-child",t)){if(o!==void 0&&o.collapsed&&o.hasKids)this.userExpanded.add(o.id),this.userCollapsed.delete(o.id),this.repaintFolds();else if(o!==void 0&&o.hasKids){const n=s?.sortedChildIds.get(o.id)?.[0];n!==void 0&&(this.cursorId=n),this.tui.requestRender()}return}if(this.matches("crtr.graph.focus",t)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot focus nodes");return}this.cursorId!==void 0&&this.focusTarget(this.cursorId),this.close();return}if(this.matches("crtr.graph.revive",t)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot revive nodes");return}const n=this.cursorId,c=n===void 0?null:s?.nodes.get(n)??null;n!==void 0&&c!==null&&c.status!=="active"&&c.status!=="idle"&&(this.reviveTarget(n),this.close());return}if(this.matches("crtr.graph.focus-manager",t)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot focus nodes");return}const n=s?.managerOf.get(this.self);n!==void 0&&(this.focusTarget(n),this.close());return}if(this.matches("crtr.graph.close-subtree",t)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot close nodes");return}const n=this.cursorId??this.self,c=s?.nodes.get(n)??null,u=c!==null?L(c):A(n);this.pendingConfirm={label:`kill ${u}?`,action:$(()=>this.shellCrtr(["node","lifecycle","close","--node",n]),"action")},this.tui.requestRender();return}}focusTarget(t){const s=["surface","node","focus",t],e=process.env.TMUX_PANE;e!==void 0&&e!==""&&s.push("--pane",e),this.shellCrtr(s)}reviveTarget(t){this.shellCrtr(["node","lifecycle","revive",t],()=>this.focusTarget(t))}shellCrtr(t,s){try{O("crtr",t,r=>{r==null&&s?.()}).stdin?.end()}catch{}}}export{$t as GraphOverlay};
|
|
1
|
+
var q=Object.defineProperty;var p=(m,e)=>q(m,"name",{value:e,configurable:!0});import{execFile as N}from"node:child_process";import{matchesKey as O,truncateToWidth as C}from"@earendil-works/pi-tui";import{formatBinding as P,matchesPiTuiInput as H}from"../../../core/keybindings/index.js";import{fullName as B}from"../../../core/canvas/labels.js";import{faultSummary as L}from"../../../core/canvas/status-glyph.js";import{RemoteCanvasSource as G}from"../../../core/canvas/remote-canvas-source.js";import{cliClient as F}from"../../../commands/api-client.js";import{statusRank as S}from"../../../core/canvas/node-order.js";import{navLabel as K,nodeGlyph as W,tokensCell as j,cycleBadge as Y,askBadge as D,activityCell as V,shortId as M,visibleWidth as E,fillBar as k,fillWidth as A,truncate as z,isAttached as U,VIEWPORT_FALLBACK_ROWS as X,DIM as v,RESET as g,BOLD as T,YELLOW as J,REVERSE as Q,BG_ATTACHED as Z,GREEN as tt}from"../../../core/canvas/nav-render.js";const et=.72,st={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},it=[["crtr.graph.dismiss","dismiss"],["crtr.graph.focus","focus"],["crtr.graph.revive","revive"],["crtr.graph.close-subtree","close"],["crtr.graph.focus-manager","manager"]],nt=[["crtr.graph.dismiss","dismiss"]],rt=[["crtr.graph.down","down"],["crtr.graph.up","up"],["crtr.graph.first","first"],["crtr.graph.last","last"],["crtr.graph.collapse-or-manager","fold/manager"],["crtr.graph.expand-or-child","expand/child"]];function ot(m){return{node_id:m.node_id,name:m.name,kind:m.kind,description:m.description??void 0,cycles:m.cycles??void 0,status:m.status,frozen_at:m.frozen_at,pi_pid:m.pi_pid,telemetry_context_tokens:m.telemetry_context_tokens,telemetry_last_activity:m.telemetry_last_activity,fault:m.fault??null,streaming:m.streaming}}p(ot,"graphRow");class $t{static{p(this,"GraphOverlay")}tui;self;getAsks;palette;bindings;source;role;onRefreshFailure;onNotice;handle;userExpanded=new Set;userCollapsed=new Set;folds={userExpanded:this.userExpanded,userCollapsed:this.userCollapsed};cursorId;scrollTop=0;pendingConfirm;snapshot;snapshotSeq=0;remote;constructor(e,s,i,t,n,c,d="controller",l=()=>{},r=()=>{}){this.tui=e,this.self=s,this.getAsks=i,this.palette=t,this.bindings=n,this.source=c,this.role=d,this.onRefreshFailure=l,this.onNotice=r,this.remote=c instanceof G}setBindings(e){this.bindings=e,this.handle!==void 0&&this.tui.requestRender()}matches(e,s){return H(this.bindings,e,s,(i,t)=>O(i,t))}hint(e){return e.flatMap(([s,i])=>this.bindings.gestures(s).length===0?[]:[`${P(this.bindings,s)} ${i}`])}fitHints(e,s){const t=[];let n=0;for(const c of this.hint(e)){const d=(t.length===0?0:3)+E(c);if(n+d>s)break;t.push(c),n+=d}return t.join(" \xB7 ")}isOpen(){return this.handle!==void 0}open(){this.handle===void 0&&(this.scrollTop=0,this.pendingConfirm=void 0,this.cursorId=this.self,this.handle=this.tui.showOverlay(this,st),this.refresh())}close(){this.handle!==void 0&&(this.pendingConfirm=void 0,this.handle.hide(),this.handle=void 0,this.tui.requestRender())}toggle(){this.handle===void 0?this.open():this.close()}refresh(){if(this.handle===void 0)return;const e=++this.snapshotSeq;this.buildSnapshot().then(s=>{e===this.snapshotSeq&&(this.snapshot=s,this.tui.requestRender())}).catch(s=>{this.onRefreshFailure(s),this.tui.requestRender()})}invalidate(){this.refresh()}async fetchInput(){if(this.remote){const t=await this.source.listNodes().catch(()=>[]);return{nodes:new Map(t.map(n=>[n.node_id,n])),subscriptions:p(async n=>(await this.source.subscriptionsOf(n)).map(c=>c.node_id),"subscriptions"),subscribers:p(async n=>(await this.source.subscribersOf(n)).map(c=>c.node_id),"subscribers"),focused:new Set}}const e=await F().canvasGraph(),s=new Map,i=new Map;for(const t of e.edges){const n=s.get(t.from_id);n===void 0?s.set(t.from_id,[t.to_id]):n.push(t.to_id);const c=i.get(t.to_id);c===void 0?i.set(t.to_id,[t.from_id]):c.push(t.from_id)}return{nodes:new Map(e.nodes.map(t=>[t.node_id,ot(t)])),subscriptions:p(t=>Promise.resolve(s.get(t)??[]),"subscriptions"),subscribers:p(t=>Promise.resolve(i.get(t)??[]),"subscribers"),focused:new Set(e.focused_node_ids)}}async buildSnapshot(){const e=await this.fetchInput(),{nodes:s,focused:i}=e,t=new Map,n=new Map,c=new Map,d=new Map,l=p(async o=>{const a=t.get(o);if(a!==void 0)return a;let f;try{f=await e.subscriptions(o)}catch{f=[]}const b=f.filter(w=>s.get(w)?.kind!=="human");return t.set(o,b),b},"children"),r=p(async o=>{if(c.has(o))return c.get(o);let a;try{a=(await e.subscribers(o))[0]}catch{a=void 0}return c.set(o,a),a},"manager"),h=p(async()=>{let o=this.self;const a=new Set([o]);for(;;){const f=await r(o);if(f===void 0||a.has(f))break;a.add(f),o=f}return o},"climbRoot"),u=p(async o=>{const a=n.get(o);if(a!==void 0)return a;const f=[...await l(o)];return f.sort((b,w)=>S(s.get(b)?.status)-S(s.get(w)?.status)),n.set(o,f),f},"sortedChildren"),R=new Set,$=new Set,y=p(async o=>{const a=s.get(o)?.status==="active";if($.has(o))return{active:a?1:0,reveal:a||o===this.self};$.add(o);let f=0,b=!1;for(const w of await l(o)){const x=await y(w);f+=x.active,x.reveal&&(b=!0)}return d.set(o,f),b&&R.add(o),{active:f+(a?1:0),reveal:b||a||o===this.self}},"visitActivity"),I=await h();await y(I),await Promise.all([...t.keys()].map(o=>u(o)));const _={root:I,rows:[],autoExpanded:R,activeBelow:d,nodes:s,childIds:t,sortedChildIds:n,managerOf:c,focused:i};return _.rows=this.projectRows(_),_}projectRows(e){const s=[],i=new Set,t=[{id:e.root,prefix:"",isRoot:!0,isLast:!0}];for(;t.length>0;){const{id:n,prefix:c,isRoot:d,isLast:l}=t.pop(),r=d?"":l?"\u2514\u2500 ":"\u251C\u2500 ";if(i.has(n)){s.push({id:n,hasKids:!1,isSelf:n===this.self,branch:c+r,cycle:!0,collapsed:!1});continue}i.add(n);const h=e.sortedChildIds.get(n)??[],u=this.folds.userExpanded.has(n)?!1:this.folds.userCollapsed.has(n)?!0:!e.autoExpanded.has(n);if(s.push({id:n,hasKids:h.length>0,isSelf:n===this.self,branch:c+r,cycle:!1,collapsed:u}),u)continue;const R=d?"":c+(l?" ":"\u2502 ");for(let $=h.length-1;$>=0;$--)t.push({id:h[$],prefix:R,isRoot:!1,isLast:$===h.length-1})}return s}repaintFolds(){this.snapshot!==void 0&&(this.snapshot.rows=this.projectRows(this.snapshot)),this.tui.requestRender()}renderSnapshotRow(e,s,i,t){const n=p((w,x)=>i?k(w,A(),Q):x?k(w,A(),Z):z(w),"wrap");if(s.cycle){const w=`${s.branch} ${v}\u21BA ${M(s.id)}${g}`;return n(w,!1)}const c=e.nodes.get(s.id)??null,d=W(c),l=K(c,s.id),r=s.isSelf?`${T}${l}${g}`:l,h=`${v}${c?.kind??""}${g}`,u=`${v}${j(c,this.remote)}${g}`,R=s.hasKids&&s.collapsed,$=!i&&R?`${v}\u25B8${g} `:" ",y=Y(c),I=e.childIds.get(s.id)?.length??0,_=c!==null&&I>0?` ${v}\u2933${I}${g}`:"",o=c!==null&&c.status!=="active"&&(e.activeBelow.get(c.node_id)??0)>0?` ${tt}\u21E3${e.activeBelow.get(c.node_id)??0}${g}`:"",a=c?.fault??null,f=a!==null?` \xB7 ${L(a)}`:"",b=`${s.branch}${$}${d} ${r} ${h} ${u}${y}${_}${o}${D(s.id,t)}${V(c,this.remote)}${f}`;return n(b,U(s.id,c,e.focused,this.remote))}render(e){const s=this.getAsks(),i=this.snapshot?.rows??[];let t=i.findIndex(o=>o.id===this.cursorId);t<0&&(t=i.findIndex(o=>o.id===this.self),t<0&&(t=0)),this.cursorId=i[t]?.id??this.self;const n=process.stdout.rows??X,c=Math.max(3,Math.min(Math.floor(n*et),n-2)),d=Math.max(2,Math.min(i.length,c-2));let l=d;for(let o=0;o<4;o++){t<this.scrollTop&&(this.scrollTop=t),t>=this.scrollTop+l&&(this.scrollTop=t-l+1),this.scrollTop=Math.max(0,Math.min(this.scrollTop,Math.max(0,i.length-l)));const a=d-(this.scrollTop>0?1:0)-(this.scrollTop+l<i.length?1:0);if(a===l)break;l=Math.max(1,a)}const r=Math.min(i.length,this.scrollTop+l),h=[];this.scrollTop>0&&h.push(`${v} \u2191 ${this.scrollTop} more${g}`);for(let o=this.scrollTop;o<r;o++){const a=this.snapshot;h.push(a!==void 0?this.renderSnapshotRow(a,i[o],o===t,s):"")}for(r<i.length&&h.push(`${v} \u2193 ${i.length-r} more${g}`);h.length<d;)h.push("");const u=i.length>0?`${T}\u2317 canvas graph${g} ${v}(${t+1}/${i.length})${g}`:`${T}\u2317 canvas graph${g} ${v}(loading)${g}`,R=this.pendingConfirm!==void 0?`${J}${this.pendingConfirm.label} ${T}${this.hint([["crtr.graph.confirm.accept","accept"],["crtr.graph.confirm.cancel","cancel"]]).join(" \xB7 ")}${g}`:`${v}${this.fitHints([...this.remote||this.role!=="controller"?nt:it,...rt],Math.max(1,e-5))}${g}`,$=this.palette.border,y=Math.max(1,e-4),I=h.map(o=>`${$("\u2502")} ${C(o,y,"",!0)} ${$("\u2502")}`),_=this.palette.surface;return[this.borderRow("\u256D","\u256E",u,e),...I,this.borderRow("\u2570","\u256F",R,e)].map(_)}borderRow(e,s,i,t){const n=this.palette.border,c=Math.max(1,t-5),d=C(i,c,"\u2026"),l=Math.max(0,t-5-E(d));return`${n(`${e}\u2500`)} ${d} ${n("\u2500".repeat(l)+s)}`}handleInput(e){try{this.dispatch(e)}catch{}}dispatch(e){if(this.pendingConfirm!==void 0){if(this.matches("crtr.graph.confirm.accept",e)){const r=this.pendingConfirm.action;this.pendingConfirm=void 0,r()}else this.pendingConfirm=void 0;this.tui.requestRender();return}if(this.matches("crtr.graph.dismiss",e)){this.close();return}const s=this.snapshot,i=s?.rows??[];let t=i.findIndex(r=>r.id===this.cursorId);t<0&&(t=Math.max(0,i.findIndex(r=>r.id===this.self)));const n=i[t],c=p(r=>r!==void 0&&!r.cycle,"isSelectable"),d=p((r,h)=>{for(let u=r+h;u>=0&&u<i.length;u+=h)if(c(i[u]))return u;return r},"step"),l=p(r=>{const h=r===1?0:i.length-1;for(let u=h;u>=0&&u<i.length;u+=r)if(c(i[u]))return u;return t},"edge");if(this.matches("crtr.graph.down",e)){t=d(t,1),this.cursorId=i[t]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.up",e)){t=d(t,-1),this.cursorId=i[t]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.first",e)){this.cursorId=i[l(1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.last",e)){this.cursorId=i[l(-1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.collapse-or-manager",e)){if(n!==void 0&&n.hasKids&&!n.collapsed)this.userCollapsed.add(n.id),this.userExpanded.delete(n.id),this.repaintFolds();else{const r=s?.managerOf.get(this.cursorId??this.self);r!==void 0&&i.some(h=>h.id===r)&&(this.cursorId=r),this.tui.requestRender()}return}if(this.matches("crtr.graph.expand-or-child",e)){if(n!==void 0&&n.collapsed&&n.hasKids)this.userExpanded.add(n.id),this.userCollapsed.delete(n.id),this.repaintFolds();else if(n!==void 0&&n.hasKids){const r=s?.sortedChildIds.get(n.id)?.[0];r!==void 0&&(this.cursorId=r),this.tui.requestRender()}return}if(this.matches("crtr.graph.focus",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot focus nodes");return}this.cursorId!==void 0&&this.focusTarget(this.cursorId),this.close();return}if(this.matches("crtr.graph.revive",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot revive nodes");return}const r=this.cursorId,h=r===void 0?null:s?.nodes.get(r)??null;r!==void 0&&h!==null&&h.status!=="active"&&h.status!=="idle"&&(this.reviveTarget(r),this.close());return}if(this.matches("crtr.graph.focus-manager",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot focus nodes");return}const r=s?.managerOf.get(this.self);r!==void 0&&(this.focusTarget(r),this.close());return}if(this.matches("crtr.graph.close-subtree",e)){if(this.remote)return;if(this.role!=="controller"){this.onNotice("Read-only observer attach \u2014 cannot close nodes");return}const r=this.cursorId??this.self,h=s?.nodes.get(r)??null,u=h!==null?B(h):M(r);this.pendingConfirm={label:`kill ${u}?`,action:p(()=>this.shellCrtr(["node","lifecycle","close","--node",r]),"action")},this.tui.requestRender();return}}focusTarget(e){const s=["surface","node","focus",e],i=process.env.TMUX_PANE;i!==void 0&&i!==""&&s.push("--pane",i),this.shellCrtr(s)}reviveTarget(e){this.shellCrtr(["node","lifecycle","revive",e],()=>this.focusTarget(e))}shellCrtr(e,s){try{N("crtr",e,t=>{t==null&&s?.()}).stdin?.end()}catch{}}}export{$t as GraphOverlay};
|
|
@@ -317,7 +317,11 @@ export declare class ChatView {
|
|
|
317
317
|
/** Swap the single active activity indicator (working/compaction/retry). */
|
|
318
318
|
private setActivity;
|
|
319
319
|
private showStatus;
|
|
320
|
-
|
|
320
|
+
/** Append an error to the transcript. pi's own error events land here, and so
|
|
321
|
+
* do the broker's `error` frames: their text is the engine's own and is
|
|
322
|
+
* routinely multi-line (pi's login help is three lines), which the one-row
|
|
323
|
+
* status notice cannot show. */
|
|
324
|
+
showError(message: string): void;
|
|
321
325
|
private crtrOutputTheme;
|
|
322
326
|
/** Extract the tool-call content items from an assistant message. */
|
|
323
327
|
private assistantToolCalls;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var v=Object.defineProperty;var p=(h,t)=>v(h,"name",{value:t,configurable:!0});import{Container as j,Loader as F,Spacer as d,Text as x}from"@earendil-works/pi-tui";import{AssistantMessageComponent as L,BashExecutionComponent as M,BranchSummaryMessageComponent as H,CompactionSummaryMessageComponent as W,CustomMessageComponent as $,parseSkillBlock as q,SkillInvocationMessageComponent as V,ToolExecutionComponent as N,UserMessageComponent as S}from"@earendil-works/pi-coding-agent";import{attachMarkdownTheme as u}from"../config.js";import{ContextMessageComponent as U}from"./context-message.js";import{presentationFor as z}from"./card-presentation.js";import{detectInlinePageResult as Y,PageBlockComponent as J}from"./page-block.js";import{CRTR_OUTPUT_CUSTOM_TYPE as K,CrtrOutputMessageComponent as X,createCrtrBashToolDefinition as Q}from"./crtr-output.js";import{CRTR_CYCLE_DIVIDER_CUSTOM_TYPE as Z,endedByAbort as w}from"../../../core/runtime/session-cycles.js";import{parseCard as tt}from"../../../shared/generated-context.js";import{assistantVisibleText as c,isGroupBoundaryKind as et,isTrueUserMessage as C}from"../../../shared/tool-groups.js";import{transformDiagramFences as st}from"./diagram.js";import{styleAttachAgentMarkdown as it,styleAttachMarkdownSource as E,styleAttachMessageMarkdown as ot,styleAttachSummaryMarkdown as O}from"./markdown-source.js";import{createCrtrEditToolDefinition as nt}from"./edit-diff.js";import{GroupActivityRecorder as rt}from"./group-activity.js";import{GroupRecapComponent as at}from"./group-recap.js";import{FoldedToolCallController as ht,bashCallBackgroundHintLines as pt,createCrtrPlainBashToolDefinition as lt,createCrtrReadToolDefinition as dt,createCrtrWriteToolDefinition as ct}from"./tool-calls.js";import{ringCompletionBell as ut}from"../chrome/completion-bell.js";import{extractFilePaths as mt}from"#core/human/visible-paths";import{keepWhenCondensed as ft,liveRegionStart as gt}from"./condensed-history.js";import{ViewerAssistantMessageComponent as A}from"./assistant-message.js";import{CompositeViewportSource as yt,MeasuredContainer as B}from"./measured-container.js";import{readConfig as T,updateRawConfigAtomically as Ct}from"../../../core/config.js";import{DEFAULT_CONDENSED_HISTORY as Tt,DEFAULT_LIVE_CYCLES as kt}from"../../../types.js";import{applySnapshot as bt,applyToolGroupSummary as xt,applyWorkingActivity as St,bashEnd as wt,bashOutput as At,bashStart as Bt,initialConvState as Rt,reduce as Gt}from"../../conversation/projection.js";const I=p(h=>`\x1B[2m${h}\x1B[22m`,"defaultDimStyle"),_=50;function Mt(){try{return T("user").live_cycles}catch{return kt}}p(Mt,"readLiveCycles");function Et(){try{return T("user").condensed_history}catch{return Tt}}p(Et,"readCondensedHistory");function Ot(){try{return T("user").fold_finished_tools}catch{return!1}}p(Ot,"readFoldFinishedTools");function It(){try{return T("user").summarize_tool_calls}catch{return!1}}p(It,"readSummarizeToolCalls");function _t(){try{return T("user").detailed_tool_recaps}catch{return!0}}p(_t,"readDetailedToolRecaps");function Pt(h){try{Ct("user",t=>({...t,fold_finished_tools:h}))}catch{}}p(Pt,"persistFoldFinishedTools");function Dt(h){return typeof h=="object"&&h!==null&&"setExpanded"in h&&typeof h.setExpanded=="function"}p(Dt,"isExpandable");const vt=/\x1b\[[0-9;]*m/g,jt=/\x1b\[([0-9;]*)m/g;function Ft(h){return h.replace(jt,(t,e)=>{const s=e.split(";"),i=[];for(let o=0;o<s.length;o++){const n=Number(s[o]===""?0:s[o]);if(n===38||n===48||n===58){const r=Number(s[o+1]),a=o+(r===5?2:r===2?4:1);n!==48&&i.push(...s.slice(o,a+1)),o=a;continue}n>=40&&n<=47||n>=100&&n<=107||i.push(String(n))}return i.length>0?`\x1B[${i.join(";")}m`:""})}p(Ft,"stripBackground");const Lt=/<from\b[^>]*>[\s\S]*?<\/from>/g;class R extends d{static{p(this,"FoldedToolSeparator")}folded=!1;separatesToolGroup=!1;setFolded(t){this.folded=t,this.refresh()}setSeparatesToolGroup(t){this.separatesToolGroup=t,this.refresh()}refresh(){this.setLines(this.folded&&this.separatesToolGroup?1:0)}}class G extends N{static{p(this,"MinimizableToolComponent")}activityCallId;minimized=!1;expandedState=!1;foldController;resultObserver;setToolView(t,e){this.foldController=t,this.resultObserver=e}updateResult(...t){this.resultObserver?.(t[0],t[1]??!1),super.updateResult(...t)}setExpanded(t){this.expandedState=t,super.setExpanded(t)}setMinimized(t){!this.foldController||this.minimized===t||(this.minimized=t,this.foldController.setFolded(t),super.setExpanded(this.expandedState))}render(t){if(!this.minimized)return[...super.render(t),...pt(this.foldController?.callComponent(),t)];const e=this.foldController?.callComponent();return e?e.render(t).filter(s=>s.replace(vt,"").trim().length>0).map(s=>Ft(s).trimEnd()):super.render(t)}}const Ht=p(h=>`\x1B[31m${h}\x1B[39m`,"defaultErrorStyle"),Wt={accent:p(h=>`\x1B[33m${h}\x1B[39m`,"accent"),active:p(h=>`\x1B[36m${h}\x1B[39m`,"active"),info:p(h=>`\x1B[34m${h}\x1B[39m`,"info"),muted:I,faint:I,border:p(h=>h,"border"),surface:p(h=>h,"surface"),bold:p(h=>`\x1B[1m${h}\x1B[22m`,"bold"),error:Ht,warning:p(h=>`\x1B[33m${h}\x1B[39m`,"warning"),diffAdded:p(h=>`\x1B[32m${h}\x1B[39m`,"diffAdded"),diffRemoved:p(h=>`\x1B[91m${h}\x1B[39m`,"diffRemoved"),bashMode:p(h=>`\x1B[32m${h}\x1B[39m`,"bashMode"),bashModeAlt:p(h=>`\x1B[92m${h}\x1B[39m`,"bashModeAlt")};class ue{static{p(this,"ChatView")}tui;container;historyContainer=new B;statusContainer=new B;bannerContainer;transcript;appendTarget=this.historyContainer;pageBlocks=new Map;inlinePageBlocks;pageOpenHint;backgroundBashHint;liveCycles;condensedHistory;cwd;showImages;imageWidthCells;hideThinking;hiddenThinkingLabel;toolOutputExpanded;foldSettledTools=Ot();summarizeToolCalls=It();detailedToolRecaps=_t();showGroupSummaries=this.summarizeToolCalls&&this.foldSettledTools;groups=[];openGroup;groupSummaries=new Map;nodeRoster=new Map;streamingWasGroupMember=!1;onFooterEvent;onActivityChange;spinnerStyle;dimStyle;errorStyle;recapPalette;labelStyle=p(t=>`\x1B[1m${t}\x1B[22m`,"labelStyle");markdownTransformers=[(t,{messageType:e,availableWidth:s})=>e==="assistant"?st(t,s):t,(t,{messageType:e})=>e==="user"?E(t):it(t)];streamingComponent;streamingToolSeparator;foldedToolSeparatorContents=new Map;pendingTools=new Map;bashComponent;activityLoader;projection=Rt();workingActivity=this.projection.workingActivity;runActive=!1;applyingSnapshot=!1;snapshotGeneration=0;deferredFrames=[];lastAssistantText;transcriptFilePaths=[];copyBlockRecords=[];copyIndex=new Map;condensedCopyBlocks=new WeakMap;constructor(t,e,s={}){if(this.tui=t,this.container=e,this.cwd=s.cwd??process.cwd(),this.showImages=s.showImages??!0,this.imageWidthCells=s.imageWidthCells??60,this.hideThinking=s.hideThinking??!1,this.hiddenThinkingLabel=s.hiddenThinkingLabel??"Thinking...",this.toolOutputExpanded=s.toolOutputExpanded??!1,this.liveCycles=s.liveCycles??Mt(),this.condensedHistory=s.condensedHistory??Et(),this.onFooterEvent=s.onFooterEvent,this.onActivityChange=s.onActivityChange,this.inlinePageBlocks=s.inlinePageBlocks??!1,this.pageOpenHint=s.pageOpenHint??(()=>"crtr human list"),this.backgroundBashHint=s.backgroundBashHint??(()=>null),this.recapPalette=s.palette??Wt,this.spinnerStyle=this.recapPalette.active,this.dimStyle=this.recapPalette.muted,this.errorStyle=this.recapPalette.error,s.banner&&s.banner.length>0){const i=new B;i.addChild(new d(1));for(const o of s.banner)i.addChild(new x(o,1,0));i.addChild(new d(1)),this.bannerContainer=i,this.container.addChild(i)}this.container.addChild(this.historyContainer),this.onActivityChange||this.container.addChild(this.statusContainer),this.transcript=new yt([...this.bannerContainer?[this.bannerContainer]:[],this.historyContainer,...this.onActivityChange?[]:[this.statusContainer]])}transcriptSource(){return this.transcript}async applySnapshot(t){const e=++this.snapshotGeneration;this.applyingSnapshot=!0,this.deferredFrames.length=0,this.resetChat(),this.projection=bt(t,this.projection),this.workingActivity=this.projection.workingActivity,this.runActive=this.projection.isStreaming,this.seedToolGroupSummaries(this.projection.toolGroupSummaryDetails);const s=new Map,i=this.projection.messages,o=i.length-1,n=gt(i,this.liveCycles);if(n>0){const r=await this.buildCondensedBlock(i.slice(0,n),e);if(e!==this.snapshotGeneration)return;r&&this.appendCondensedBlock(r)}for(let r=n;r<i.length;r++){if(!this.projection.isStreaming&&r>n&&(r-n)%_===0&&(await new Promise(l=>setImmediate(l)),e!==this.snapshotGeneration))return;const a=i[r];if(a.role==="assistant"){const l=c(a);l.trim()&&(this.lastAssistantText=l,this.pushTranscriptText(l));const P=r===o&&this.projection.isStreaming&&a.stopReason!=="aborted"&&a.stopReason!=="error",g=c(a).trim()!=="",D=this.assistantToolCalls(a),k=a.stopReason==="aborted"||a.stopReason==="error",y=w(a)?"Interrupted":a.errorMessage??"Error";if(k){for(const m of s.values()){const f={content:[{type:"text",text:y}],isError:!0};m.updateResult(f),this.registerCopyBlock(m,"tool",y),this.settleGroupTool(m,f,!0)}s.clear()}(g||k)&&this.closeOpenGroup();let b;P?(this.streamingComponent=new A(void 0,this.hideThinking,u(),this.hiddenThinkingLabel,this.markdownTransformers),this.appendAssistantPart(this.streamingComponent,!g),this.registerCopyBlock(this.streamingComponent,"assistant",""),this.streamingWasGroupMember=!g,this.streamingComponent.updateContent(a),this.registerCopyBlock(this.streamingComponent,"assistant",c(a)),b=this.streamingToolSeparator=this.appendAssistantSeparator(!g)):b=this.appendAssistantMessage(a,!g&&!k),b&&this.setAssistantSeparatorContent(b,a);for(const m of D){this.pushTranscriptValue(m.arguments);const f=this.appendToolComponent(m.name,m.id,m.arguments);a.stopReason==="aborted"||a.stopReason==="error"?(f.updateResult({content:[{type:"text",text:y}],isError:!0}),this.registerCopyBlock(f,"tool",y),this.settleGroupTool(f,{content:[{type:"text",text:y}],isError:!0},!0)):s.set(m.id,f)}k&&this.closeOpenGroup()}else if(a.role==="toolResult"){this.pushTranscriptText(this.userMessageText(a));const l=s.get(a.toolCallId);l&&(l.updateResult(a),this.registerCopyBlock(l,"tool",this.toolResultText(a)),this.historyContainer.markDirty(l),this.settleGroupTool(l,a,a.isError===!0),s.delete(a.toolCallId),this.maybeAppendPageBlock(a))}else this.addMessageToChat(a)}for(const[r,a]of s)this.pendingTools.set(r,a);this.applyToolDisplay(),this.projection.isStreaming&&this.setActivity(this.makeLoader(this.workingActivity)),this.tui.requestRender(),this.applyingSnapshot=!1,this.replayDeferredFrames()}async buildCondensedBlock(t,e){const s=new j,i=this.appendTarget,o=[];this.appendTarget=s,this.condensedCopyBlocks.set(s,o);try{let n=0;for(const r of t)if(ft(r,this.condensedHistory)){if(n>0&&n%_===0&&(await new Promise(a=>setImmediate(a)),e!==this.snapshotGeneration))return;n++,this.pushTranscriptText(this.userMessageText(r)),this.addMessageToChat(r)}}finally{this.appendTarget=i,this.condensedCopyBlocks.delete(s)}return s.children.length>0?{component:s,copyBlocks:o}:void 0}deferIfBuilding(t){return this.applyingSnapshot?(this.deferredFrames.push(t),!0):!1}replayDeferredFrames(){const t=this.deferredFrames.splice(0);for(const e of t)e()}setWorkingActivity(t){if(this.deferIfBuilding(()=>this.setWorkingActivity(t)))return;const e=this.projection.activity===this.workingActivity;this.projection=St(this.projection,t),this.workingActivity=this.projection.workingActivity,this.runActive&&e&&this.setActivity(this.makeLoader(this.workingActivity))}settleRun(){this.runActive=!1;for(const t of this.pendingTools.values())this.settleGroupTool(t);this.streamingComponent&&(this.historyContainer.removeChild(this.streamingComponent),this.unregisterCopyBlock(this.streamingComponent),this.streamingComponent=void 0),this.streamingToolSeparator=void 0,this.pendingTools.clear(),this.applyToolDisplay(),this.setActivity(void 0),this.settleBashComponent()}dispose(){this.settleRun()}toggleToolsExpanded(){let t;return this.summarizeToolCalls&&this.foldSettledTools?(this.showGroupSummaries=!this.showGroupSummaries,this.toolOutputExpanded=!this.showGroupSummaries,t={kind:"summaries",shown:this.showGroupSummaries}):(this.toolOutputExpanded=!this.toolOutputExpanded,t={kind:"output",expanded:this.toolOutputExpanded}),this.applyToolDisplay(),t}toggleFoldSettledTools(){return this.foldSettledTools=!this.foldSettledTools,Pt(this.foldSettledTools),this.summarizeToolCalls&&this.foldSettledTools&&(this.showGroupSummaries=!0),this.applyToolDisplay(),this.foldSettledTools}applyToolDisplay(){const t=new Set(this.pendingTools.values());for(const e of this.groups)for(const s of e.inFlight)t.add(s);for(const e of this.historyContainer.children)e instanceof G&&e.setMinimized(this.foldSettledTools&&!t.has(e)),Dt(e)&&e.setExpanded(this.toolOutputExpanded);for(const e of this.groups)this.applyGroupDisplay(e);this.updateFoldedToolSeparators(t),this.historyContainer.markDirty(),this.tui.requestRender()}toggleThinking(){this.hideThinking=!this.hideThinking;for(const t of this.historyContainer.children)t instanceof L&&t.setHideThinkingBlock(this.hideThinking);for(const[t,e]of this.foldedToolSeparatorContents)t.setSeparatesToolGroup(e.hasText||!this.hideThinking&&e.hasThinking);return this.historyContainer.markDirty(),this.tui.requestRender(),this.hideThinking}handleEvent(t){if(!this.deferIfBuilding(()=>this.handleEvent(t))){switch(this.projection=Gt(this.projection,t),t.type){case"agent_start":{this.runActive=this.projection.isStreaming;for(const e of this.pendingTools.values())this.settleGroupTool(e);this.pendingTools.clear(),this.setActivity(this.makeLoader(this.workingActivity));break}case"agent_end":{this.settleRun(),ut();break}case"agent_settled":{this.settleRun();break}case"message_start":{if(t.message.role==="custom"||t.message.role==="user")this.addMessageToChat(t.message);else if(t.message.role==="assistant"){const e=c(t.message).trim()!=="";e&&this.closeOpenGroup(),this.streamingComponent=new A(void 0,this.hideThinking,u(),this.hiddenThinkingLabel,this.markdownTransformers),this.streamingWasGroupMember=!e,this.appendAssistantPart(this.streamingComponent,!e),this.registerCopyBlock(this.streamingComponent,"assistant",""),this.streamingComponent.updateContent(t.message),this.registerCopyBlock(this.streamingComponent,"assistant",c(t.message)),this.streamingToolSeparator=this.appendAssistantSeparator(!e),this.setAssistantSeparatorContent(this.streamingToolSeparator,t.message)}break}case"message_update":{if(this.streamingComponent&&t.message.role==="assistant"){this.promoteStreamingAssistantToBoundary(t.message),this.streamingComponent.updateContent(t.message),this.registerCopyBlock(this.streamingComponent,"assistant",c(t.message)),this.historyContainer.markDirty(this.streamingComponent);const e=this.assistantToolCalls(t.message);this.streamingToolSeparator&&this.setAssistantSeparatorContent(this.streamingToolSeparator,t.message);for(const s of e){this.pushTranscriptValue(s.arguments);const i=this.pendingTools.get(s.id);if(i)i.updateArgs(s.arguments),this.noteGroupTool(i,s.name,s.arguments),this.historyContainer.markDirty(i);else{const o=this.appendToolComponent(s.name,s.id,s.arguments);this.pendingTools.set(s.id,o)}}}break}case"message_end":{if(t.message.role!=="assistant")break;const e=t.message.stopReason==="aborted"||t.message.stopReason==="error";if(this.promoteStreamingAssistantToBoundary(t.message,e),this.streamingComponent&&this.registerCopyBlock(this.streamingComponent,"assistant",c(t.message)),t.message.stopReason!=="aborted"&&t.message.stopReason!=="error"){const s=c(t.message);s.trim()&&(this.lastAssistantText=s,this.pushTranscriptText(s))}if(this.streamingComponent){const s=t.message.stopReason;let i=t.message.errorMessage;if(w(t.message)&&(i="Interrupted",t.message.errorMessage=i,t.message.stopReason="aborted"),this.streamingComponent.updateContent(t.message),s==="aborted"||s==="error"){const o=i??"Error";for(const n of this.pendingTools.values())n.updateResult({content:[{type:"text",text:o}],isError:!0}),this.registerCopyBlock(n,"tool",o),this.settleGroupTool(n,{content:[{type:"text",text:o}],isError:!0},!0),this.historyContainer.markDirty(n);this.pendingTools.clear()}else for(const o of this.pendingTools.values())o.setArgsComplete(),this.historyContainer.markDirty(o);this.historyContainer.markDirty(this.streamingComponent),this.streamingComponent=void 0,this.streamingToolSeparator=void 0}e&&(this.closeOpenGroup(),this.applyToolDisplay());break}case"tool_execution_start":{this.pushTranscriptValue(t.args);let e=this.pendingTools.get(t.toolCallId);e?this.noteGroupTool(e,t.toolName,t.args):(e=this.appendToolComponent(t.toolName,t.toolCallId,t.args),this.pendingTools.set(t.toolCallId,e)),e.markExecutionStarted(),this.historyContainer.markDirty(e);break}case"tool_execution_update":{const e=this.projection.partialToolResults.get(t.toolCallId)??t.partialResult;this.pushTranscriptValue(e);const s=this.pendingTools.get(t.toolCallId);s&&(s.updateResult(e,!0),this.registerCopyBlock(s,"tool",this.toolResultText(e)),this.historyContainer.markDirty(s));break}case"tool_execution_end":{const e=this.projection.partialToolResults.get(t.toolCallId)??t.result;this.pushTranscriptValue(e);const s=this.pendingTools.get(t.toolCallId);s&&(s.updateResult(e),this.registerCopyBlock(s,"tool",this.toolResultText(e)),this.pendingTools.delete(t.toolCallId),this.settleGroupTool(s,e,t.isError),this.applyToolDisplay(),this.historyContainer.markDirty(s),this.maybeAppendPageBlock(e));break}case"compaction_start":{const e=t.reason==="manual"?"Compacting context...":"Auto-compacting...";this.setActivity(this.makeLoader(e));break}case"compaction_end":{this.setActivity(this.runActive?this.makeLoader(this.workingActivity):void 0),t.aborted?this.showStatus(t.reason==="manual"?"Compaction cancelled":"Auto-compaction cancelled"):t.result?this.addMessageToChat({role:"compactionSummary",summary:t.result.summary,tokensBefore:t.result.tokensBefore,timestamp:Date.now()}):t.errorMessage&&this.showError(t.errorMessage);break}case"auto_retry_start":{const e=Math.ceil(t.delayMs/1e3);this.setActivity(this.makeLoader(`Retrying (${t.attempt}/${t.maxAttempts}) in ${e}s...`));break}case"auto_retry_end":{this.setActivity(this.runActive?this.makeLoader(this.workingActivity):void 0),t.success||this.showError(`Retry failed after ${t.attempt} attempts: ${t.finalError??"Unknown error"}`);break}case"queue_update":case"session_info_changed":case"thinking_level_changed":this.onFooterEvent?.(t);break;default:break}this.tui.requestRender()}}bashStart(t,e){if(this.deferIfBuilding(()=>this.bashStart(t,e)))return;this.projection=Bt(this.projection,t,e),this.closeOpenGroup(),this.settleBashComponent();let s;s=new M(t,this.componentTui(()=>s),e),this.bashComponent=s,this.append(s),this.tui.requestRender()}bashOutput(t){this.deferIfBuilding(()=>this.bashOutput(t))||(this.projection=At(this.projection,t),this.pushTranscriptText(t),this.bashComponent&&(this.bashComponent.appendOutput(t),this.historyContainer.markDirty(this.bashComponent)),this.tui.requestRender())}bashEnd(t){this.deferIfBuilding(()=>this.bashEnd(t))||(this.projection=wt(this.projection,t),this.settleBashComponent(t),this.tui.requestRender())}addMessageToChat(t){const e=tt(t);if(e!==null&&(t.role!=="custom"||t.display===!0)){this.pushTranscriptText(e.body);const s=e.senders.flatMap(o=>o.entries).filter(o=>o.disposition==="human-answer").map(o=>o.body.trim()).filter(o=>o!=="");if(!(s.length>0&&e.body.replace(Lt,"").trim()===""&&e.senders.every(o=>o.entries.every(n=>n.disposition==="human-answer")))){const o=z(e.kind),n=new U(e,o,this.toolOutputExpanded,this.dimStyle,r=>this.spinnerStyle(this.labelStyle(r)));et(e.kind)?(this.closeOpenGroup(),this.append(n)):this.appendGroupMember(n)?.activity.noteCard(e,o)}for(const o of s)this.appendHumanAnswer(o);return}switch(t.role){case"bashExecution":{this.closeOpenGroup(),this.pushTranscriptText(t.output??"");const s=new M(t.command,this.tui,t.excludeFromContext);t.output&&s.appendOutput(t.output),s.setComplete(t.exitCode,t.cancelled,t.truncated?{truncated:!0}:void 0,t.fullOutputPath),this.append(s);break}case"custom":{if(t.display){if(this.pushTranscriptText(this.userMessageText(t)),t.customType===K){this.appendGroupMember(new X(this.userMessageText(t),this.toolOutputExpanded,this.crtrOutputTheme()));break}if(t.customType===Z){this.closeOpenGroup(),this.append(new d(1)),this.append(new x(this.dimStyle(`\u2500\u2500 ${this.userMessageText(t)} \u2500\u2500`),1,0)),this.append(new d(1));break}const s=new $(ot(t),void 0,u());s.setExpanded(this.toolOutputExpanded),this.appendGroupMember(s)}break}case"compactionSummary":{this.closeOpenGroup(),this.append(new d(1));const s=new W(O(t),u());s.setExpanded(this.toolOutputExpanded),this.append(s);break}case"branchSummary":{this.closeOpenGroup(),this.append(new d(1));const s=new H(O(t),u());s.setExpanded(this.toolOutputExpanded),this.append(s),this.registerCopyBlock(s,"assistant",t.summary);break}case"user":{C(t)&&this.closeOpenGroup();const s=this.userMessageText(t);if(!s)break;this.pushTranscriptText(s),this.chatChildCount()>0&&this.appendUserPart(new d(1),!C(t));const i=q(s);if(i){const o=new V({...i,content:E(i.content)},u());if(o.setExpanded(this.toolOutputExpanded),this.appendUserPart(o,!C(t)),this.registerCopyBlock(o,"user",s),i.userMessage){const n=new S(i.userMessage,u(),void 0,this.markdownTransformers);this.appendUserPart(n,!C(t)),this.registerCopyBlock(n,"user",i.userMessage)}}else{const o=new S(s,u(),void 0,this.markdownTransformers);this.appendUserPart(o,!C(t)),this.registerCopyBlock(o,"user",s)}break}case"assistant":{const s=c(t).trim()!=="";s&&this.closeOpenGroup(),this.appendAssistantMessage(t,!s);break}default:break}}appendAssistantMessage(t,e=!1){const s=new A(void 0,this.hideThinking,u(),this.hiddenThinkingLabel,this.markdownTransformers),i=w(t)?{...t,stopReason:"aborted",errorMessage:"Interrupted"}:t;s.updateContent(i),this.appendAssistantPart(s,e),this.registerCopyBlock(s,"assistant",c(t));const o=this.appendAssistantSeparator(e);return this.setAssistantSeparatorContent(o,t),o}appendAssistantSeparator(t=!1){const e=new R;return t?this.appendGroupMember(e):this.append(e),e}appendAssistantPart(t,e){e?this.appendGroupMember(t):this.append(t)}appendUserPart(t,e){e?this.appendGroupMember(t):this.append(t)}appendHumanAnswer(t){this.closeOpenGroup(),this.chatChildCount()>0&&this.append(new d(1));const e=new S(t,u(),void 0,this.markdownTransformers);this.append(e),this.registerCopyBlock(e,"user",t)}isLiveGroupRegion(){return this.appendTarget===this.historyContainer}ensureGroup(){if(!this.isLiveGroupRegion())return;if(this.openGroup)return this.openGroup;const t=new at,e={members:[],recap:t,activity:new rt(this.cwd,this.nodeRoster),toolCount:0,inFlight:new Set};return this.append(t),this.historyContainer.setHidden(t,!0),this.groups.push(e),this.openGroup=e,e}closeOpenGroup(){this.openGroup=void 0}appendGroupMember(t){const e=this.ensureGroup();return this.append(t),e&&e.members.push(t),e}removeGroupMember(t){for(const e of this.groups){const s=e.members.indexOf(t);s!==-1&&e.members.splice(s,1)}this.historyContainer.setHidden(t,!1)}appendToolComponent(t,e,s){const i=this.isLiveGroupRegion()&&!this.openGroup&&this.historyContainer.children.at(-1)instanceof R?this.historyContainer.children.at(-1):void 0;i&&this.historyContainer.removeChild(i);const o=this.ensureGroup();i&&(this.append(i),o?.members.push(i));const n=this.makeToolComponent(t,e,s);return n.activityCallId=e,this.appendGroupMember(n),this.registerCopyBlock(n,"tool",""),o&&(o.key??=e,o.toolCount++,o.inFlight.add(n),o.activity.noteCall(e,t,s)),n}noteGroupTool(t,e,s){if(t.activityCallId)for(const i of this.groups)i.members.includes(t)&&i.activity.noteCall(t.activityCallId,e,s)}settleGroupTool(t,e,s=!1){for(const i of this.groups)i.inFlight.delete(t),!(!t.activityCallId||!i.members.includes(t))&&(e===void 0?i.activity.resolveWithoutResult(t.activityCallId):i.activity.settle(t.activityCallId,e,s))}promoteStreamingAssistantToBoundary(t,e=!1){!this.streamingWasGroupMember||!e&&c(t).trim()===""||(this.streamingComponent&&this.removeGroupMember(this.streamingComponent),this.streamingToolSeparator&&this.removeGroupMember(this.streamingToolSeparator),this.streamingWasGroupMember=!1,this.closeOpenGroup())}seedToolGroupSummaries(t){this.groupSummaries.clear();for(const[e,s]of Object.entries(t))this.groupSummaries.set(e,s)}applyToolGroupSummary(t,e){if(this.deferIfBuilding(()=>this.applyToolGroupSummary(t,e)))return;this.projection=xt(this.projection,t,e);const s=this.projection.toolGroupSummaryDetails[t];s!==void 0&&(this.groupSummaries.set(t,s),this.applyToolDisplay())}applyGroupDisplay(t){const e=t.key===void 0?void 0:this.groupSummaries.get(t.key),s=this.foldSettledTools&&this.showGroupSummaries&&t.toolCount>0&&t.inFlight.size===0&&e!==void 0;t.recap.setRecap(s?e:void 0,t.toolCount,t.activity.activity(),this.detailedToolRecaps,this.recapPalette),this.historyContainer.setHidden(t.recap,!s);for(const i of t.members)this.historyContainer.setHidden(i,s)}updateFoldedToolSeparators(t=new Set(this.pendingTools.values())){const e=this.historyContainer.children;for(let s=0;s<e.length;s++){const i=e[s];if(!(i instanceof R))continue;const o=e[s+1];i.setFolded(this.foldSettledTools&&!this.historyContainer.hiddenChildren.has(i)&&o instanceof G&&!this.historyContainer.hiddenChildren.has(o)&&!t.has(o)),this.historyContainer.markDirty(i)}}setAssistantSeparatorContent(t,e){const s=e.content,i=Array.isArray(s)?s:[],o=i.some(r=>typeof r=="object"&&r!==null&&r.type==="text"&&typeof r.text=="string"&&r.text.trim()!==""),n=i.some(r=>typeof r=="object"&&r!==null&&r.type==="thinking"&&typeof r.thinking=="string"&&r.thinking.trim()!=="");this.foldedToolSeparatorContents.set(t,{hasText:o,hasThinking:n}),t.setSeparatesToolGroup(o||!this.hideThinking&&n)}makeToolComponent(t,e,s){const i=new ht;let o,n;if(t==="bash"){const a=Q(s,i);a===void 0?n=lt(this.cwd,i,this.backgroundBashHint):(n=a.definition,o=a.observeResult)}else if(t==="edit"){const a=nt(this.cwd,i);n=a.definition,o=a.observeResult}else t==="read"?n=dt(this.cwd,i):t==="write"&&(n=ct(this.cwd,i));let r;return r=new G(t,e,s,{showImages:this.showImages,imageWidthCells:this.imageWidthCells},n,this.componentTui(()=>r),this.cwd),r.setToolView(n===void 0?void 0:i,o),r.setExpanded(this.toolOutputExpanded),r}append(t){this.appendTarget.addChild(t)}chatChildCount(){return this.appendTarget.children.length}resetChat(){this.setActivity(void 0),this.settleBashComponent(),this.streamingComponent=void 0,this.streamingToolSeparator=void 0,this.streamingWasGroupMember=!1,this.foldedToolSeparatorContents.clear(),this.groups.length=0,this.openGroup=void 0,this.groupSummaries.clear(),this.nodeRoster.clear(),this.pendingTools.clear(),this.lastAssistantText=void 0,this.copyBlockRecords.length=0,this.copyIndex.clear(),this.transcriptFilePaths.length=0,this.pageBlocks.clear(),this.historyContainer.clear()}maybeAppendPageBlock(t){if(!this.inlinePageBlocks||this.appendTarget!==this.historyContainer)return;const e=Y(t);if(e===void 0||this.pageBlocks.has(e.pageId))return;const s=new J(e.pageId,this.pageOpenHint);this.pageBlocks.set(e.pageId,s),this.append(s),this.loadPageBlock(s)}async loadPageBlock(t){await t.refresh()&&(this.historyContainer.markDirty(t),this.tui.requestRender())}refreshInFlightTools(){if(this.pendingTools.size!==0){for(const t of this.pendingTools.values())this.historyContainer.markDirty(t);this.tui.requestRender()}}async refreshPageBlocks(){const t=[...this.pageBlocks.values()];(await Promise.all(t.map(async s=>{const i=await s.refresh();return i&&this.historyContainer.markDirty(s),i}))).some(Boolean)&&this.tui.requestRender()}makeLoader(t){let e;const s={requestRender:p(i=>{e&&!this.onActivityChange&&this.statusContainer.markDirty(e),this.tui.requestRender(i)},"requestRender"),terminal:this.tui.terminal};return e=new F(s,this.spinnerStyle,this.dimStyle,t),e}componentTui(t){return{requestRender:p(e=>{this.historyContainer.markDirty(t()),this.tui.requestRender(e)},"requestRender"),terminal:this.tui.terminal}}settleBashComponent(t){if(!this.bashComponent)return;const e=this.bashComponent;e.setComplete(t?.exitCode,t?.cancelled??!0,t?.truncated?{truncated:!0}:void 0,t?.fullOutputPath),this.historyContainer.markDirty(e),this.bashComponent=void 0}setActivity(t){if(this.activityLoader?.stop(),this.activityLoader=t,this.onActivityChange){this.onActivityChange(t);return}this.statusContainer.clear(),t&&this.statusContainer.addChild(t)}showStatus(t){this.closeOpenGroup(),this.append(new d(1)),this.append(new x(this.dimStyle(t),1,0))}showError(t){this.closeOpenGroup(),this.append(new d(1)),this.append(new x(this.errorStyle(t),1,0))}crtrOutputTheme(){return{fg:p((t,e)=>t==="error"?this.errorStyle(e):t==="warning"||t==="accent"||t==="toolTitle"||t==="success"?this.spinnerStyle(e):t==="muted"?this.dimStyle(e):e,"fg"),bg:p((t,e)=>e,"bg"),bold:p(t=>this.labelStyle(t),"bold")}}assistantToolCalls(t){const e=t.content;return Array.isArray(e)?e.filter(s=>typeof s=="object"&&s!==null&&s.type==="toolCall"):[]}getTranscriptFilePathsNewestFirst(){return[...this.transcriptFilePaths]}getLastAssistantText(){const t=this.lastAssistantText?.trim();return t||void 0}blockText(t){const e=this.copyIndex.get(t);return e===void 0?void 0:this.copyBlockRecords[e]?.text}copyBlocks(){return this.copyBlockRecords}getLastToolOutputText(){for(let t=this.copyBlockRecords.length-1;t>=0;t--){const e=this.copyBlockRecords[t];if(e.kind==="tool")return e.text.trim()===""?void 0:e.text}}getTranscriptPlainText(){return this.copyBlockRecords.map(t=>t.text).filter(t=>t.trim()!=="").join(`
|
|
1
|
+
var v=Object.defineProperty;var p=(h,t)=>v(h,"name",{value:t,configurable:!0});import{Container as j,Loader as F,Spacer as d,Text as x}from"@earendil-works/pi-tui";import{AssistantMessageComponent as L,BashExecutionComponent as E,BranchSummaryMessageComponent as H,CompactionSummaryMessageComponent as W,CustomMessageComponent as $,parseSkillBlock as q,SkillInvocationMessageComponent as V,ToolExecutionComponent as N,UserMessageComponent as S}from"@earendil-works/pi-coding-agent";import{attachMarkdownTheme as u}from"../config.js";import{ContextMessageComponent as U}from"./context-message.js";import{presentationFor as z}from"./card-presentation.js";import{detectInlinePageResult as Y,PageBlockComponent as J}from"./page-block.js";import{CRTR_OUTPUT_CUSTOM_TYPE as K,CrtrOutputMessageComponent as X,createCrtrBashToolDefinition as Q}from"./crtr-output.js";import{CRTR_CYCLE_DIVIDER_CUSTOM_TYPE as Z,endedByAbort as w}from"../../../core/runtime/session-cycles.js";import{parseCard as tt}from"../../../shared/generated-context.js";import{assistantVisibleText as c,isGroupBoundaryKind as et,isTrueUserMessage as C}from"../../../shared/tool-groups.js";import{transformDiagramFences as st}from"./diagram.js";import{styleAttachAgentMarkdown as it,styleAttachMarkdownSource as M,styleAttachMessageMarkdown as ot,styleAttachSummaryMarkdown as O}from"./markdown-source.js";import{createCrtrEditToolDefinition as nt}from"./edit-diff.js";import{GroupActivityRecorder as rt}from"./group-activity.js";import{GroupRecapComponent as at}from"./group-recap.js";import{FoldedToolCallController as ht,bashCallBackgroundHintLines as pt,createCrtrPlainBashToolDefinition as lt,createCrtrReadToolDefinition as dt,createCrtrWriteToolDefinition as ct}from"./tool-calls.js";import{ringCompletionBell as ut}from"../chrome/completion-bell.js";import{extractFilePaths as mt}from"#core/human/visible-paths";import{keepWhenCondensed as ft,liveRegionStart as gt}from"./condensed-history.js";import{ViewerAssistantMessageComponent as B}from"./assistant-message.js";import{CompositeViewportSource as yt,MeasuredContainer as A}from"./measured-container.js";import{readConfig as T,updateRawConfigAtomically as Ct}from"../../../core/config.js";import{DEFAULT_CONDENSED_HISTORY as Tt,DEFAULT_LIVE_CYCLES as kt}from"../../../types.js";import{applySnapshot as bt,applyToolGroupSummary as xt,applyWorkingActivity as St,bashEnd as wt,bashOutput as Bt,bashStart as At,initialConvState as Rt,reduce as Gt}from"../../conversation/projection.js";const I=p(h=>`\x1B[2m${h}\x1B[22m`,"defaultDimStyle"),_=50;function Et(){try{return T("user").live_cycles}catch{return kt}}p(Et,"readLiveCycles");function Mt(){try{return T("user").condensed_history}catch{return Tt}}p(Mt,"readCondensedHistory");function Ot(){try{return T("user").fold_finished_tools}catch{return!1}}p(Ot,"readFoldFinishedTools");function It(){try{return T("user").summarize_tool_calls}catch{return!1}}p(It,"readSummarizeToolCalls");function _t(){try{return T("user").detailed_tool_recaps}catch{return!0}}p(_t,"readDetailedToolRecaps");function Pt(h){try{Ct("user",t=>({...t,fold_finished_tools:h}))}catch{}}p(Pt,"persistFoldFinishedTools");function Dt(h){return typeof h=="object"&&h!==null&&"setExpanded"in h&&typeof h.setExpanded=="function"}p(Dt,"isExpandable");const vt=/\x1b\[[0-9;]*m/g,jt=/\x1b\[([0-9;]*)m/g;function Ft(h){return h.replace(jt,(t,e)=>{const s=e.split(";"),i=[];for(let o=0;o<s.length;o++){const n=Number(s[o]===""?0:s[o]);if(n===38||n===48||n===58){const r=Number(s[o+1]),a=o+(r===5?2:r===2?4:1);n!==48&&i.push(...s.slice(o,a+1)),o=a;continue}n>=40&&n<=47||n>=100&&n<=107||i.push(String(n))}return i.length>0?`\x1B[${i.join(";")}m`:""})}p(Ft,"stripBackground");const Lt=/<from\b[^>]*>[\s\S]*?<\/from>/g;class R extends d{static{p(this,"FoldedToolSeparator")}folded=!1;separatesToolGroup=!1;setFolded(t){this.folded=t,this.refresh()}setSeparatesToolGroup(t){this.separatesToolGroup=t,this.refresh()}refresh(){this.setLines(this.folded&&this.separatesToolGroup?1:0)}}class G extends N{static{p(this,"MinimizableToolComponent")}activityCallId;minimized=!1;expandedState=!1;foldController;resultObserver;setToolView(t,e){this.foldController=t,this.resultObserver=e}updateResult(...t){this.resultObserver?.(t[0],t[1]??!1),super.updateResult(...t)}setExpanded(t){this.expandedState=t,super.setExpanded(t)}setMinimized(t){!this.foldController||this.minimized===t||(this.minimized=t,this.foldController.setFolded(t),super.setExpanded(this.expandedState))}render(t){if(!this.minimized)return[...super.render(t),...pt(this.foldController?.callComponent(),t)];const e=this.foldController?.callComponent();return e?e.render(t).filter(s=>s.replace(vt,"").trim().length>0).map(s=>Ft(s).trimEnd()):super.render(t)}}const Ht=p(h=>`\x1B[31m${h}\x1B[39m`,"defaultErrorStyle"),Wt={accent:p(h=>`\x1B[33m${h}\x1B[39m`,"accent"),active:p(h=>`\x1B[36m${h}\x1B[39m`,"active"),info:p(h=>`\x1B[34m${h}\x1B[39m`,"info"),muted:I,faint:I,border:p(h=>h,"border"),surface:p(h=>h,"surface"),bold:p(h=>`\x1B[1m${h}\x1B[22m`,"bold"),error:Ht,warning:p(h=>`\x1B[33m${h}\x1B[39m`,"warning"),diffAdded:p(h=>`\x1B[32m${h}\x1B[39m`,"diffAdded"),diffRemoved:p(h=>`\x1B[91m${h}\x1B[39m`,"diffRemoved"),bashMode:p(h=>`\x1B[32m${h}\x1B[39m`,"bashMode"),bashModeAlt:p(h=>`\x1B[92m${h}\x1B[39m`,"bashModeAlt")};class ue{static{p(this,"ChatView")}tui;container;historyContainer=new A;statusContainer=new A;bannerContainer;transcript;appendTarget=this.historyContainer;pageBlocks=new Map;inlinePageBlocks;pageOpenHint;backgroundBashHint;liveCycles;condensedHistory;cwd;showImages;imageWidthCells;hideThinking;hiddenThinkingLabel;toolOutputExpanded;foldSettledTools=Ot();summarizeToolCalls=It();detailedToolRecaps=_t();showGroupSummaries=this.summarizeToolCalls&&this.foldSettledTools;groups=[];openGroup;groupSummaries=new Map;nodeRoster=new Map;streamingWasGroupMember=!1;onFooterEvent;onActivityChange;spinnerStyle;dimStyle;errorStyle;recapPalette;labelStyle=p(t=>`\x1B[1m${t}\x1B[22m`,"labelStyle");markdownTransformers=[(t,{messageType:e,availableWidth:s})=>e==="assistant"?st(t,s):t,(t,{messageType:e})=>e==="user"?M(t):it(t)];streamingComponent;streamingToolSeparator;foldedToolSeparatorContents=new Map;pendingTools=new Map;bashComponent;activityLoader;projection=Rt();workingActivity=this.projection.workingActivity;runActive=!1;applyingSnapshot=!1;snapshotGeneration=0;deferredFrames=[];lastAssistantText;transcriptFilePaths=[];copyBlockRecords=[];copyIndex=new Map;condensedCopyBlocks=new WeakMap;constructor(t,e,s={}){if(this.tui=t,this.container=e,this.cwd=s.cwd??process.cwd(),this.showImages=s.showImages??!0,this.imageWidthCells=s.imageWidthCells??60,this.hideThinking=s.hideThinking??!1,this.hiddenThinkingLabel=s.hiddenThinkingLabel??"Thinking...",this.toolOutputExpanded=s.toolOutputExpanded??!1,this.liveCycles=s.liveCycles??Et(),this.condensedHistory=s.condensedHistory??Mt(),this.onFooterEvent=s.onFooterEvent,this.onActivityChange=s.onActivityChange,this.inlinePageBlocks=s.inlinePageBlocks??!1,this.pageOpenHint=s.pageOpenHint??(()=>"crtr human list"),this.backgroundBashHint=s.backgroundBashHint??(()=>null),this.recapPalette=s.palette??Wt,this.spinnerStyle=this.recapPalette.active,this.dimStyle=this.recapPalette.muted,this.errorStyle=this.recapPalette.error,s.banner&&s.banner.length>0){const i=new A;i.addChild(new d(1));for(const o of s.banner)i.addChild(new x(o,1,0));i.addChild(new d(1)),this.bannerContainer=i,this.container.addChild(i)}this.container.addChild(this.historyContainer),this.onActivityChange||this.container.addChild(this.statusContainer),this.transcript=new yt([...this.bannerContainer?[this.bannerContainer]:[],this.historyContainer,...this.onActivityChange?[]:[this.statusContainer]])}transcriptSource(){return this.transcript}async applySnapshot(t){const e=++this.snapshotGeneration;this.applyingSnapshot=!0,this.deferredFrames.length=0,this.resetChat(),this.projection=bt(t,this.projection),this.workingActivity=this.projection.workingActivity,this.runActive=this.projection.isStreaming,this.seedToolGroupSummaries(this.projection.toolGroupSummaryDetails);const s=new Map,i=this.projection.messages,o=i.length-1,n=gt(i,this.liveCycles);if(n>0){const r=await this.buildCondensedBlock(i.slice(0,n),e);if(e!==this.snapshotGeneration)return;r&&this.appendCondensedBlock(r)}for(let r=n;r<i.length;r++){if(!this.projection.isStreaming&&r>n&&(r-n)%_===0&&(await new Promise(l=>setImmediate(l)),e!==this.snapshotGeneration))return;const a=i[r];if(a.role==="assistant"){const l=c(a);l.trim()&&(this.lastAssistantText=l,this.pushTranscriptText(l));const P=r===o&&this.projection.isStreaming&&a.stopReason!=="aborted"&&a.stopReason!=="error",g=c(a).trim()!=="",D=this.assistantToolCalls(a),k=a.stopReason==="aborted"||a.stopReason==="error",y=w(a)?"Interrupted":a.errorMessage??"Error";if(k){for(const m of s.values()){const f={content:[{type:"text",text:y}],isError:!0};m.updateResult(f),this.registerCopyBlock(m,"tool",y),this.settleGroupTool(m,f,!0)}s.clear()}(g||k)&&this.closeOpenGroup();let b;P?(this.streamingComponent=new B(void 0,this.hideThinking,u(),this.hiddenThinkingLabel,this.markdownTransformers),this.appendAssistantPart(this.streamingComponent,!g),this.registerCopyBlock(this.streamingComponent,"assistant",""),this.streamingWasGroupMember=!g,this.streamingComponent.updateContent(a),this.registerCopyBlock(this.streamingComponent,"assistant",c(a)),b=this.streamingToolSeparator=this.appendAssistantSeparator(!g)):b=this.appendAssistantMessage(a,!g&&!k),b&&this.setAssistantSeparatorContent(b,a);for(const m of D){this.pushTranscriptValue(m.arguments);const f=this.appendToolComponent(m.name,m.id,m.arguments);a.stopReason==="aborted"||a.stopReason==="error"?(f.updateResult({content:[{type:"text",text:y}],isError:!0}),this.registerCopyBlock(f,"tool",y),this.settleGroupTool(f,{content:[{type:"text",text:y}],isError:!0},!0)):s.set(m.id,f)}k&&this.closeOpenGroup()}else if(a.role==="toolResult"){this.pushTranscriptText(this.userMessageText(a));const l=s.get(a.toolCallId);l&&(l.updateResult(a),this.registerCopyBlock(l,"tool",this.toolResultText(a)),this.historyContainer.markDirty(l),this.settleGroupTool(l,a,a.isError===!0),s.delete(a.toolCallId),this.maybeAppendPageBlock(a))}else this.addMessageToChat(a)}for(const[r,a]of s)this.pendingTools.set(r,a);this.applyToolDisplay(),this.projection.isStreaming&&this.setActivity(this.makeLoader(this.workingActivity)),this.tui.requestRender(),this.applyingSnapshot=!1,this.replayDeferredFrames()}async buildCondensedBlock(t,e){const s=new j,i=this.appendTarget,o=[];this.appendTarget=s,this.condensedCopyBlocks.set(s,o);try{let n=0;for(const r of t)if(ft(r,this.condensedHistory)){if(n>0&&n%_===0&&(await new Promise(a=>setImmediate(a)),e!==this.snapshotGeneration))return;n++,this.pushTranscriptText(this.userMessageText(r)),this.addMessageToChat(r)}}finally{this.appendTarget=i,this.condensedCopyBlocks.delete(s)}return s.children.length>0?{component:s,copyBlocks:o}:void 0}deferIfBuilding(t){return this.applyingSnapshot?(this.deferredFrames.push(t),!0):!1}replayDeferredFrames(){const t=this.deferredFrames.splice(0);for(const e of t)e()}setWorkingActivity(t){if(this.deferIfBuilding(()=>this.setWorkingActivity(t)))return;const e=this.projection.activity===this.workingActivity;this.projection=St(this.projection,t),this.workingActivity=this.projection.workingActivity,this.runActive&&e&&this.setActivity(this.makeLoader(this.workingActivity))}settleRun(){this.runActive=!1;for(const t of this.pendingTools.values())this.settleGroupTool(t);this.streamingComponent&&(this.historyContainer.removeChild(this.streamingComponent),this.unregisterCopyBlock(this.streamingComponent),this.streamingComponent=void 0),this.streamingToolSeparator=void 0,this.pendingTools.clear(),this.applyToolDisplay(),this.setActivity(void 0),this.settleBashComponent()}dispose(){this.settleRun()}toggleToolsExpanded(){let t;return this.summarizeToolCalls&&this.foldSettledTools?(this.showGroupSummaries=!this.showGroupSummaries,this.toolOutputExpanded=!this.showGroupSummaries,t={kind:"summaries",shown:this.showGroupSummaries}):(this.toolOutputExpanded=!this.toolOutputExpanded,t={kind:"output",expanded:this.toolOutputExpanded}),this.applyToolDisplay(),t}toggleFoldSettledTools(){return this.foldSettledTools=!this.foldSettledTools,Pt(this.foldSettledTools),this.summarizeToolCalls&&this.foldSettledTools&&(this.showGroupSummaries=!0),this.applyToolDisplay(),this.foldSettledTools}applyToolDisplay(){const t=new Set(this.pendingTools.values());for(const e of this.groups)for(const s of e.inFlight)t.add(s);for(const e of this.historyContainer.children)e instanceof G&&e.setMinimized(this.foldSettledTools&&!t.has(e)),Dt(e)&&e.setExpanded(this.toolOutputExpanded);for(const e of this.groups)this.applyGroupDisplay(e);this.updateFoldedToolSeparators(t),this.historyContainer.markDirty(),this.tui.requestRender()}toggleThinking(){this.hideThinking=!this.hideThinking;for(const t of this.historyContainer.children)t instanceof L&&t.setHideThinkingBlock(this.hideThinking);for(const[t,e]of this.foldedToolSeparatorContents)t.setSeparatesToolGroup(e.hasText||!this.hideThinking&&e.hasThinking);return this.historyContainer.markDirty(),this.tui.requestRender(),this.hideThinking}handleEvent(t){if(!this.deferIfBuilding(()=>this.handleEvent(t))){switch(this.projection=Gt(this.projection,t),t.type){case"agent_start":{this.runActive=this.projection.isStreaming;for(const e of this.pendingTools.values())this.settleGroupTool(e);this.pendingTools.clear(),this.setActivity(this.makeLoader(this.workingActivity));break}case"agent_end":{this.settleRun(),ut();break}case"agent_settled":{this.settleRun();break}case"message_start":{if(t.message.role==="custom"||t.message.role==="user")this.addMessageToChat(t.message);else if(t.message.role==="assistant"){const e=c(t.message).trim()!=="";e&&this.closeOpenGroup(),this.streamingComponent=new B(void 0,this.hideThinking,u(),this.hiddenThinkingLabel,this.markdownTransformers),this.streamingWasGroupMember=!e,this.appendAssistantPart(this.streamingComponent,!e),this.registerCopyBlock(this.streamingComponent,"assistant",""),this.streamingComponent.updateContent(t.message),this.registerCopyBlock(this.streamingComponent,"assistant",c(t.message)),this.streamingToolSeparator=this.appendAssistantSeparator(!e),this.setAssistantSeparatorContent(this.streamingToolSeparator,t.message)}break}case"message_update":{if(this.streamingComponent&&t.message.role==="assistant"){this.promoteStreamingAssistantToBoundary(t.message),this.streamingComponent.updateContent(t.message),this.registerCopyBlock(this.streamingComponent,"assistant",c(t.message)),this.historyContainer.markDirty(this.streamingComponent);const e=this.assistantToolCalls(t.message);this.streamingToolSeparator&&this.setAssistantSeparatorContent(this.streamingToolSeparator,t.message);for(const s of e){this.pushTranscriptValue(s.arguments);const i=this.pendingTools.get(s.id);if(i)i.updateArgs(s.arguments),this.noteGroupTool(i,s.name,s.arguments),this.historyContainer.markDirty(i);else{const o=this.appendToolComponent(s.name,s.id,s.arguments);this.pendingTools.set(s.id,o)}}}break}case"message_end":{if(t.message.role!=="assistant")break;const e=t.message.stopReason==="aborted"||t.message.stopReason==="error";if(this.promoteStreamingAssistantToBoundary(t.message,e),this.streamingComponent&&this.registerCopyBlock(this.streamingComponent,"assistant",c(t.message)),t.message.stopReason!=="aborted"&&t.message.stopReason!=="error"){const s=c(t.message);s.trim()&&(this.lastAssistantText=s,this.pushTranscriptText(s))}if(this.streamingComponent){const s=t.message.stopReason;let i=t.message.errorMessage;if(w(t.message)&&(i="Interrupted",t.message.errorMessage=i,t.message.stopReason="aborted"),this.streamingComponent.updateContent(t.message),s==="aborted"||s==="error"){const o=i??"Error";for(const n of this.pendingTools.values())n.updateResult({content:[{type:"text",text:o}],isError:!0}),this.registerCopyBlock(n,"tool",o),this.settleGroupTool(n,{content:[{type:"text",text:o}],isError:!0},!0),this.historyContainer.markDirty(n);this.pendingTools.clear()}else for(const o of this.pendingTools.values())o.setArgsComplete(),this.historyContainer.markDirty(o);this.historyContainer.markDirty(this.streamingComponent),this.streamingComponent=void 0,this.streamingToolSeparator=void 0}e&&(this.closeOpenGroup(),this.applyToolDisplay());break}case"tool_execution_start":{this.pushTranscriptValue(t.args);let e=this.pendingTools.get(t.toolCallId);e?this.noteGroupTool(e,t.toolName,t.args):(e=this.appendToolComponent(t.toolName,t.toolCallId,t.args),this.pendingTools.set(t.toolCallId,e)),e.markExecutionStarted(),this.historyContainer.markDirty(e);break}case"tool_execution_update":{const e=this.projection.partialToolResults.get(t.toolCallId)??t.partialResult;this.pushTranscriptValue(e);const s=this.pendingTools.get(t.toolCallId);s&&(s.updateResult(e,!0),this.registerCopyBlock(s,"tool",this.toolResultText(e)),this.historyContainer.markDirty(s));break}case"tool_execution_end":{const e=this.projection.partialToolResults.get(t.toolCallId)??t.result;this.pushTranscriptValue(e);const s=this.pendingTools.get(t.toolCallId);s&&(s.updateResult(e),this.registerCopyBlock(s,"tool",this.toolResultText(e)),this.pendingTools.delete(t.toolCallId),this.settleGroupTool(s,e,t.isError),this.applyToolDisplay(),this.historyContainer.markDirty(s),this.maybeAppendPageBlock(e));break}case"compaction_start":{const e=t.reason==="manual"?"Compacting context...":"Auto-compacting...";this.setActivity(this.makeLoader(e));break}case"compaction_end":{this.setActivity(this.runActive?this.makeLoader(this.workingActivity):void 0),t.aborted?this.showStatus(t.reason==="manual"?"Compaction cancelled":"Auto-compaction cancelled"):t.result?this.addMessageToChat({role:"compactionSummary",summary:t.result.summary,tokensBefore:t.result.tokensBefore,timestamp:Date.now()}):t.errorMessage&&this.showError(t.errorMessage);break}case"auto_retry_start":{const e=Math.ceil(t.delayMs/1e3);this.setActivity(this.makeLoader(`Retrying (${t.attempt}/${t.maxAttempts}) in ${e}s...`));break}case"auto_retry_end":{this.setActivity(this.runActive?this.makeLoader(this.workingActivity):void 0),t.success||this.showError(`Retry failed after ${t.attempt} attempts: ${t.finalError??"Unknown error"}`);break}case"queue_update":case"session_info_changed":case"thinking_level_changed":this.onFooterEvent?.(t);break;default:break}this.tui.requestRender()}}bashStart(t,e){if(this.deferIfBuilding(()=>this.bashStart(t,e)))return;this.projection=At(this.projection,t,e),this.closeOpenGroup(),this.settleBashComponent();let s;s=new E(t,this.componentTui(()=>s),e),this.bashComponent=s,this.append(s),this.tui.requestRender()}bashOutput(t){this.deferIfBuilding(()=>this.bashOutput(t))||(this.projection=Bt(this.projection,t),this.pushTranscriptText(t),this.bashComponent&&(this.bashComponent.appendOutput(t),this.historyContainer.markDirty(this.bashComponent)),this.tui.requestRender())}bashEnd(t){this.deferIfBuilding(()=>this.bashEnd(t))||(this.projection=wt(this.projection,t),this.settleBashComponent(t),this.tui.requestRender())}addMessageToChat(t){const e=tt(t);if(e!==null&&(t.role!=="custom"||t.display===!0)){this.pushTranscriptText(e.body);const s=e.senders.flatMap(o=>o.entries).filter(o=>o.disposition==="human-answer").map(o=>o.body.trim()).filter(o=>o!=="");if(!(s.length>0&&e.body.replace(Lt,"").trim()===""&&e.senders.every(o=>o.entries.every(n=>n.disposition==="human-answer")))){const o=z(e.kind),n=new U(e,o,this.toolOutputExpanded,this.dimStyle,r=>this.spinnerStyle(this.labelStyle(r)));et(e.kind)?(this.closeOpenGroup(),this.append(n)):this.appendGroupMember(n)?.activity.noteCard(e,o)}for(const o of s)this.appendHumanAnswer(o);return}switch(t.role){case"bashExecution":{this.closeOpenGroup(),this.pushTranscriptText(t.output??"");const s=new E(t.command,this.tui,t.excludeFromContext);t.output&&s.appendOutput(t.output),s.setComplete(t.exitCode,t.cancelled,t.truncated?{truncated:!0}:void 0,t.fullOutputPath),this.append(s);break}case"custom":{if(t.display){if(this.pushTranscriptText(this.userMessageText(t)),t.customType===K){this.appendGroupMember(new X(this.userMessageText(t),this.toolOutputExpanded,this.crtrOutputTheme()));break}if(t.customType===Z){this.closeOpenGroup(),this.append(new d(1)),this.append(new x(this.dimStyle(`\u2500\u2500 ${this.userMessageText(t)} \u2500\u2500`),1,0)),this.append(new d(1));break}const s=new $(ot(t),void 0,u());s.setExpanded(this.toolOutputExpanded),this.appendGroupMember(s)}break}case"compactionSummary":{this.closeOpenGroup(),this.append(new d(1));const s=new W(O(t),u());s.setExpanded(this.toolOutputExpanded),this.append(s);break}case"branchSummary":{this.closeOpenGroup(),this.append(new d(1));const s=new H(O(t),u());s.setExpanded(this.toolOutputExpanded),this.append(s),this.registerCopyBlock(s,"assistant",t.summary);break}case"user":{C(t)&&this.closeOpenGroup();const s=this.userMessageText(t);if(!s)break;this.pushTranscriptText(s),this.chatChildCount()>0&&this.appendUserPart(new d(1),!C(t));const i=q(s);if(i){const o=new V({...i,content:M(i.content)},u());if(o.setExpanded(this.toolOutputExpanded),this.appendUserPart(o,!C(t)),this.registerCopyBlock(o,"user",s),i.userMessage){const n=new S(i.userMessage,u(),void 0,this.markdownTransformers);this.appendUserPart(n,!C(t)),this.registerCopyBlock(n,"user",i.userMessage)}}else{const o=new S(s,u(),void 0,this.markdownTransformers);this.appendUserPart(o,!C(t)),this.registerCopyBlock(o,"user",s)}break}case"assistant":{const s=c(t).trim()!=="";s&&this.closeOpenGroup(),this.appendAssistantMessage(t,!s);break}default:break}}appendAssistantMessage(t,e=!1){const s=new B(void 0,this.hideThinking,u(),this.hiddenThinkingLabel,this.markdownTransformers),i=w(t)?{...t,stopReason:"aborted",errorMessage:"Interrupted"}:t;s.updateContent(i),this.appendAssistantPart(s,e),this.registerCopyBlock(s,"assistant",c(t));const o=this.appendAssistantSeparator(e);return this.setAssistantSeparatorContent(o,t),o}appendAssistantSeparator(t=!1){const e=new R;return t?this.appendGroupMember(e):this.append(e),e}appendAssistantPart(t,e){e?this.appendGroupMember(t):this.append(t)}appendUserPart(t,e){e?this.appendGroupMember(t):this.append(t)}appendHumanAnswer(t){this.closeOpenGroup(),this.chatChildCount()>0&&this.append(new d(1));const e=new S(t,u(),void 0,this.markdownTransformers);this.append(e),this.registerCopyBlock(e,"user",t)}isLiveGroupRegion(){return this.appendTarget===this.historyContainer}ensureGroup(){if(!this.isLiveGroupRegion())return;if(this.openGroup)return this.openGroup;const t=new at,e={members:[],recap:t,activity:new rt(this.cwd,this.nodeRoster),toolCount:0,inFlight:new Set};return this.append(t),this.historyContainer.setHidden(t,!0),this.groups.push(e),this.openGroup=e,e}closeOpenGroup(){this.openGroup=void 0}appendGroupMember(t){const e=this.ensureGroup();return this.append(t),e&&e.members.push(t),e}removeGroupMember(t){for(const e of this.groups){const s=e.members.indexOf(t);s!==-1&&e.members.splice(s,1)}this.historyContainer.setHidden(t,!1)}appendToolComponent(t,e,s){const i=this.isLiveGroupRegion()&&!this.openGroup&&this.historyContainer.children.at(-1)instanceof R?this.historyContainer.children.at(-1):void 0;i&&this.historyContainer.removeChild(i);const o=this.ensureGroup();i&&(this.append(i),o?.members.push(i));const n=this.makeToolComponent(t,e,s);return n.activityCallId=e,this.appendGroupMember(n),this.registerCopyBlock(n,"tool",""),o&&(o.key??=e,o.toolCount++,o.inFlight.add(n),o.activity.noteCall(e,t,s)),n}noteGroupTool(t,e,s){if(t.activityCallId)for(const i of this.groups)i.members.includes(t)&&i.activity.noteCall(t.activityCallId,e,s)}settleGroupTool(t,e,s=!1){for(const i of this.groups)i.inFlight.delete(t),!(!t.activityCallId||!i.members.includes(t))&&(e===void 0?i.activity.resolveWithoutResult(t.activityCallId):i.activity.settle(t.activityCallId,e,s))}promoteStreamingAssistantToBoundary(t,e=!1){!this.streamingWasGroupMember||!e&&c(t).trim()===""||(this.streamingComponent&&this.removeGroupMember(this.streamingComponent),this.streamingToolSeparator&&this.removeGroupMember(this.streamingToolSeparator),this.streamingWasGroupMember=!1,this.closeOpenGroup())}seedToolGroupSummaries(t){this.groupSummaries.clear();for(const[e,s]of Object.entries(t))this.groupSummaries.set(e,s)}applyToolGroupSummary(t,e){if(this.deferIfBuilding(()=>this.applyToolGroupSummary(t,e)))return;this.projection=xt(this.projection,t,e);const s=this.projection.toolGroupSummaryDetails[t];s!==void 0&&(this.groupSummaries.set(t,s),this.applyToolDisplay())}applyGroupDisplay(t){const e=t.key===void 0?void 0:this.groupSummaries.get(t.key),s=this.foldSettledTools&&this.showGroupSummaries&&t.toolCount>0&&t.inFlight.size===0&&e!==void 0;t.recap.setRecap(s?e:void 0,t.toolCount,t.activity.activity(),this.detailedToolRecaps,this.recapPalette),this.historyContainer.setHidden(t.recap,!s);for(const i of t.members)this.historyContainer.setHidden(i,s)}updateFoldedToolSeparators(t=new Set(this.pendingTools.values())){const e=this.historyContainer.children;for(let s=0;s<e.length;s++){const i=e[s];if(!(i instanceof R))continue;const o=e[s+1];i.setFolded(this.foldSettledTools&&!this.historyContainer.hiddenChildren.has(i)&&o instanceof G&&!this.historyContainer.hiddenChildren.has(o)&&!t.has(o)),this.historyContainer.markDirty(i)}}setAssistantSeparatorContent(t,e){const s=e.content,i=Array.isArray(s)?s:[],o=i.some(r=>typeof r=="object"&&r!==null&&r.type==="text"&&typeof r.text=="string"&&r.text.trim()!==""),n=i.some(r=>typeof r=="object"&&r!==null&&r.type==="thinking"&&typeof r.thinking=="string"&&r.thinking.trim()!=="");this.foldedToolSeparatorContents.set(t,{hasText:o,hasThinking:n}),t.setSeparatesToolGroup(o||!this.hideThinking&&n)}makeToolComponent(t,e,s){const i=new ht;let o,n;if(t==="bash"){const a=Q(s,i);a===void 0?n=lt(this.cwd,i,this.backgroundBashHint):(n=a.definition,o=a.observeResult)}else if(t==="edit"){const a=nt(this.cwd,i);n=a.definition,o=a.observeResult}else t==="read"?n=dt(this.cwd,i):t==="write"&&(n=ct(this.cwd,i));let r;return r=new G(t,e,s,{showImages:this.showImages,imageWidthCells:this.imageWidthCells},n,this.componentTui(()=>r),this.cwd),r.setToolView(n===void 0?void 0:i,o),r.setExpanded(this.toolOutputExpanded),r}append(t){this.appendTarget.addChild(t)}chatChildCount(){return this.appendTarget.children.length}resetChat(){this.setActivity(void 0),this.settleBashComponent(),this.streamingComponent=void 0,this.streamingToolSeparator=void 0,this.streamingWasGroupMember=!1,this.foldedToolSeparatorContents.clear(),this.groups.length=0,this.openGroup=void 0,this.groupSummaries.clear(),this.nodeRoster.clear(),this.pendingTools.clear(),this.lastAssistantText=void 0,this.copyBlockRecords.length=0,this.copyIndex.clear(),this.transcriptFilePaths.length=0,this.pageBlocks.clear(),this.historyContainer.clear()}maybeAppendPageBlock(t){if(!this.inlinePageBlocks||this.appendTarget!==this.historyContainer)return;const e=Y(t);if(e===void 0||this.pageBlocks.has(e.pageId))return;const s=new J(e.pageId,this.pageOpenHint);this.pageBlocks.set(e.pageId,s),this.append(s),this.loadPageBlock(s)}async loadPageBlock(t){await t.refresh()&&(this.historyContainer.markDirty(t),this.tui.requestRender())}refreshInFlightTools(){if(this.pendingTools.size!==0){for(const t of this.pendingTools.values())this.historyContainer.markDirty(t);this.tui.requestRender()}}async refreshPageBlocks(){const t=[...this.pageBlocks.values()];(await Promise.all(t.map(async s=>{const i=await s.refresh();return i&&this.historyContainer.markDirty(s),i}))).some(Boolean)&&this.tui.requestRender()}makeLoader(t){let e;const s={requestRender:p(i=>{e&&!this.onActivityChange&&this.statusContainer.markDirty(e),this.tui.requestRender(i)},"requestRender"),terminal:this.tui.terminal};return e=new F(s,this.spinnerStyle,this.dimStyle,t),e}componentTui(t){return{requestRender:p(e=>{this.historyContainer.markDirty(t()),this.tui.requestRender(e)},"requestRender"),terminal:this.tui.terminal}}settleBashComponent(t){if(!this.bashComponent)return;const e=this.bashComponent;e.setComplete(t?.exitCode,t?.cancelled??!0,t?.truncated?{truncated:!0}:void 0,t?.fullOutputPath),this.historyContainer.markDirty(e),this.bashComponent=void 0}setActivity(t){if(this.activityLoader?.stop(),this.activityLoader=t,this.onActivityChange){this.onActivityChange(t);return}this.statusContainer.clear(),t&&this.statusContainer.addChild(t)}showStatus(t){this.closeOpenGroup(),this.append(new d(1)),this.append(new x(this.dimStyle(t),1,0))}showError(t){this.deferIfBuilding(()=>this.showError(t))||(this.closeOpenGroup(),this.append(new d(1)),this.append(new x(this.errorStyle(t),1,0)),this.tui.requestRender())}crtrOutputTheme(){return{fg:p((t,e)=>t==="error"?this.errorStyle(e):t==="warning"||t==="accent"||t==="toolTitle"||t==="success"?this.spinnerStyle(e):t==="muted"?this.dimStyle(e):e,"fg"),bg:p((t,e)=>e,"bg"),bold:p(t=>this.labelStyle(t),"bold")}}assistantToolCalls(t){const e=t.content;return Array.isArray(e)?e.filter(s=>typeof s=="object"&&s!==null&&s.type==="toolCall"):[]}getTranscriptFilePathsNewestFirst(){return[...this.transcriptFilePaths]}getLastAssistantText(){const t=this.lastAssistantText?.trim();return t||void 0}blockText(t){const e=this.copyIndex.get(t);return e===void 0?void 0:this.copyBlockRecords[e]?.text}copyBlocks(){return this.copyBlockRecords}getLastToolOutputText(){for(let t=this.copyBlockRecords.length-1;t>=0;t--){const e=this.copyBlockRecords[t];if(e.kind==="tool")return e.text.trim()===""?void 0:e.text}}getTranscriptPlainText(){return this.copyBlockRecords.map(t=>t.text).filter(t=>t.trim()!=="").join(`
|
|
2
2
|
|
|
3
3
|
`)}registerCopyBlock(t,e,s){const i=this.condensedCopyBlocks.get(this.appendTarget);if(i){const n=i.findIndex(r=>r.block===t);n===-1?i.push({block:t,kind:e,text:s}):i[n].text=s;return}const o=this.copyIndex.get(t);o===void 0?(this.copyIndex.set(t,this.copyBlockRecords.length),this.copyBlockRecords.push({block:t,kind:e,text:s})):this.copyBlockRecords[o].text=s}unregisterCopyBlock(t){const e=this.condensedCopyBlocks.get(this.appendTarget);if(e){const i=e.findIndex(o=>o.block===t);i!==-1&&e.splice(i,1);return}const s=this.copyIndex.get(t);if(s!==void 0){this.copyBlockRecords.splice(s,1),this.copyIndex.delete(t);for(let i=s;i<this.copyBlockRecords.length;i++)this.copyIndex.set(this.copyBlockRecords[i].block,i)}}appendCondensedBlock({component:t,copyBlocks:e}){this.append(t),this.registerCopyBlock(t,"condensed",e.map(s=>s.text).filter(s=>s.trim()!=="").join(`
|
|
4
4
|
|
|
@@ -21,6 +21,7 @@ export interface FrameEffects {
|
|
|
21
21
|
type: 'bash_end';
|
|
22
22
|
}>) => void;
|
|
23
23
|
applyToolGroupSummary: (key: string, summary: ToolGroupSummary) => void;
|
|
24
|
+
showError: (message: string) => void;
|
|
24
25
|
};
|
|
25
26
|
setNotice: (message: string) => void;
|
|
26
27
|
/** Repaint the status line — for the frames whose footer effect is NOT
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var r=Object.defineProperty;var o=(i,t)=>r(i,"name",{value:t,configurable:!0});import{writeClipboardText as h}from"../../../core/clipboard-text.js";import{parsePreviewableCommands as k}from"../slash/prompt-preview.js";import{mark as u}from"../../../core/timing.js";function y(i,t){const{socket:d}=i,s=o(()=>{d.send({type:"get_commands"}),t.resetMemoryRefs()},"refetchInventories"),l=o(e=>{if(e.for==="get_commands"&&e.ok&&e.detail){try{t.setCommands(k(e.detail))}catch{}return}if(e.for==="navigate_tree"&&e.ok){e.detail&&t.setEditorText(e.detail);return}if(e.for==="share"){e.ok&&e.detail?(t.setNotice(`Shared: ${e.detail}`),h(e.detail)):e.ok||t.setNotice(`share failed: ${e.detail??"unknown error"}`);return}if(e.for==="clone"&&!e.ok){t.setNotice(`clone failed: ${e.detail??"unknown error"}`);return}if(!e.ok){t.setNotice(`command failed: ${e.for}${e.detail?` \u2014 ${e.detail}`:""}`);return}e.for==="reload"&&(t.reloadBindings(),t.setCommands(),s(),t.setNotice("Reloaded keybindings, extensions, skills, prompts, and themes"))},"handleAck"),c=o(e=>{t.chat.handleEvent(e),e.type==="session_info_changed"?t.refreshNodeIdentity():e.type==="thinking_level_changed"?t.setNotice(t.modelThinkingLabel()??`Thinking level: ${e.level}`):(e.type==="tool_execution_start"||e.type==="tool_execution_end")&&t.renderFooter()},"handleSessionEvent");let n=!1;return e=>{switch(t.foldState(e),e.type){case"welcome":{n||(n=!0,u("viewer.welcome")),t.chat.applySnapshot(e.snapshot),t.refreshNodeIdentity(),s(),e.pending_dialog!=null&&t.attachDialog(e.pending_dialog);break}case"tool_group_summary":t.chat.applyToolGroupSummary(e.key,e.summary);break;case"working_activity":t.chat.setWorkingActivity(e.activity);break;case"model_changed":{const a=t.modelThinkingLabel();a&&t.setNotice(a);break}case"error":
|
|
1
|
+
var r=Object.defineProperty;var o=(i,t)=>r(i,"name",{value:t,configurable:!0});import{writeClipboardText as h}from"../../../core/clipboard-text.js";import{parsePreviewableCommands as k}from"../slash/prompt-preview.js";import{mark as u}from"../../../core/timing.js";function y(i,t){const{socket:d}=i,s=o(()=>{d.send({type:"get_commands"}),t.resetMemoryRefs()},"refetchInventories"),l=o(e=>{if(e.for==="get_commands"&&e.ok&&e.detail){try{t.setCommands(k(e.detail))}catch{}return}if(e.for==="navigate_tree"&&e.ok){e.detail&&t.setEditorText(e.detail);return}if(e.for==="share"){e.ok&&e.detail?(t.setNotice(`Shared: ${e.detail}`),h(e.detail)):e.ok||t.setNotice(`share failed: ${e.detail??"unknown error"}`);return}if(e.for==="clone"&&!e.ok){t.setNotice(`clone failed: ${e.detail??"unknown error"}`);return}if(!e.ok){t.setNotice(`command failed: ${e.for}${e.detail?` \u2014 ${e.detail}`:""}`);return}e.for==="reload"&&(t.reloadBindings(),t.setCommands(),s(),t.setNotice("Reloaded keybindings, extensions, skills, prompts, and themes"))},"handleAck"),c=o(e=>{t.chat.handleEvent(e),e.type==="session_info_changed"?t.refreshNodeIdentity():e.type==="thinking_level_changed"?t.setNotice(t.modelThinkingLabel()??`Thinking level: ${e.level}`):(e.type==="tool_execution_start"||e.type==="tool_execution_end")&&t.renderFooter()},"handleSessionEvent");let n=!1;return e=>{switch(t.foldState(e),e.type){case"welcome":{n||(n=!0,u("viewer.welcome")),t.chat.applySnapshot(e.snapshot),t.refreshNodeIdentity(),s(),e.pending_dialog!=null&&t.attachDialog(e.pending_dialog);break}case"tool_group_summary":t.chat.applyToolGroupSummary(e.key,e.summary);break;case"working_activity":t.chat.setWorkingActivity(e.activity);break;case"model_changed":{const a=t.modelThinkingLabel();a&&t.setNotice(a);break}case"error":e.code==="read_only"?t.setNotice("read-only"):t.chat.showError(e.message);break;case"node_named":break;case"ack":l(e);break;case"extension_ui_request":e.method!=="setStatus"&&e.method!=="setWidget"&&e.method!=="setTitle"&&t.attachDialog(e);break;case"extension_ui_dismiss":t.dismissDialog(e.id);break;case"bash_start":t.chat.bashStart(e.command,e.excludeFromContext);break;case"bash_output":t.chat.bashOutput(e.chunk);break;case"bash_end":t.chat.bashEnd(e);break;default:c(e);break}}}o(y,"createFrameHandler");export{y as createFrameHandler};
|