@north-light/cli 0.3.530 → 0.3.531
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/dist/clients/attach/session/connection.js +1 -1
- package/dist/clients/attach/session/reconnect.js +1 -1
- package/dist/clients/attach/viewer.js +3 -3
- package/dist/core/async-array.d.ts +7 -0
- package/dist/core/async-array.js +1 -0
- package/dist/core/audit.d.ts +1 -1
- package/dist/core/audit.js +2 -2
- package/dist/core/canvas/attention.d.ts +4 -4
- package/dist/core/canvas/attention.js +1 -1
- package/dist/core/canvas/boot.d.ts +4 -4
- package/dist/core/canvas/boot.js +1 -1
- package/dist/core/canvas/canvas.d.ts +59 -59
- package/dist/core/canvas/canvas.js +19 -19
- package/dist/core/canvas/context-strip.js +2 -2
- package/dist/core/canvas/crons.d.ts +27 -27
- package/dist/core/canvas/crons.js +11 -11
- package/dist/core/canvas/daemon-actions.d.ts +10 -10
- package/dist/core/canvas/daemon-actions.js +8 -8
- package/dist/core/canvas/daemon-owner.d.ts +3 -3
- package/dist/core/canvas/daemon-owner.js +2 -2
- package/dist/core/canvas/db.d.ts +19 -30
- package/dist/core/canvas/db.js +3 -2
- package/dist/core/canvas/deliveries.d.ts +16 -16
- package/dist/core/canvas/deliveries.js +24 -24
- package/dist/core/canvas/executions.d.ts +8 -8
- package/dist/core/canvas/executions.js +1 -1
- package/dist/core/canvas/focuses.d.ts +8 -8
- package/dist/core/canvas/focuses.js +1 -1
- package/dist/core/canvas/history.d.ts +3 -3
- package/dist/core/canvas/history.js +9 -9
- package/dist/core/canvas/install-id.d.ts +1 -1
- package/dist/core/canvas/install-id.js +1 -1
- package/dist/core/canvas/managed-worktree-sweep-candidates.d.ts +1 -1
- package/dist/core/canvas/managed-worktree-sweep-candidates.js +2 -2
- package/dist/core/canvas/memory-reads.d.ts +6 -6
- package/dist/core/canvas/memory-reads.js +1 -1
- package/dist/core/canvas/nav-model.d.ts +13 -13
- package/dist/core/canvas/nav-model.js +1 -1
- package/dist/core/canvas/node-agent-paths.d.ts +6 -6
- package/dist/core/canvas/node-agent-paths.js +1 -1
- package/dist/core/canvas/node-tokens.d.ts +7 -7
- package/dist/core/canvas/node-tokens.js +3 -3
- package/dist/core/canvas/outcome-actions.d.ts +5 -5
- package/dist/core/canvas/outcome-actions.js +3 -3
- package/dist/core/canvas/recovery.d.ts +26 -26
- package/dist/core/canvas/recovery.js +2 -2
- package/dist/core/canvas/render-source.d.ts +1 -1
- package/dist/core/canvas/render-source.js +1 -1
- package/dist/core/canvas/sessions.d.ts +10 -10
- package/dist/core/canvas/sessions.js +4 -4
- package/dist/core/canvas/source.js +1 -1
- package/dist/core/canvas/structured-requests.d.ts +15 -15
- package/dist/core/canvas/structured-requests.js +5 -5
- package/dist/core/canvas/tree.d.ts +9 -9
- package/dist/core/canvas/tree.js +5 -5
- package/dist/core/canvas/waits.d.ts +13 -13
- package/dist/core/canvas/waits.js +6 -6
- package/dist/core/canvas/worktrees.d.ts +15 -15
- package/dist/core/canvas/worktrees.js +1 -1
- package/dist/core/command-hooks/transport/exec-lifecycle.js +1 -1
- package/dist/core/conversation-store/file-store.d.ts +7 -7
- package/dist/core/conversation-store/file-store.js +9 -9
- package/dist/core/conversation-store/index.d.ts +16 -14
- package/dist/core/conversation-store/index.js +1 -1
- package/dist/core/conversation-store/listener.js +5 -5
- package/dist/core/conversation-store/patch.d.ts +3 -1
- package/dist/core/conversation-store/patch.js +1 -1
- package/dist/core/feed/feed.js +3 -3
- package/dist/core/feed/inbox.d.ts +2 -2
- package/dist/core/feed/inbox.js +1 -1
- package/dist/core/feed/messages.d.ts +11 -12
- package/dist/core/feed/messages.js +5 -5
- package/dist/core/feed/reports.d.ts +4 -4
- package/dist/core/feed/reports.js +2 -2
- package/dist/core/grants/cover.d.ts +1 -1
- package/dist/core/grants/cover.js +1 -1
- package/dist/core/grants/local.d.ts +1 -1
- package/dist/core/grants/local.js +1 -1
- package/dist/core/grants/mirror.d.ts +19 -19
- package/dist/core/grants/mirror.js +2 -2
- package/dist/core/grants/on-sync.d.ts +1 -1
- package/dist/core/grants/on-sync.js +1 -1
- package/dist/core/grants/remove.js +1 -1
- package/dist/core/grants/sync.js +1 -1
- package/dist/core/graph/access.d.ts +17 -17
- package/dist/core/graph/access.js +3 -3
- package/dist/core/graph/custom.d.ts +16 -16
- package/dist/core/graph/custom.js +9 -9
- package/dist/core/graph/deletion.d.ts +3 -7
- package/dist/core/graph/deletion.js +4 -4
- package/dist/core/graph/documents.d.ts +24 -27
- package/dist/core/graph/documents.js +7 -7
- package/dist/core/graph/edges.d.ts +13 -13
- package/dist/core/graph/edges.js +1 -1
- package/dist/core/graph/events.d.ts +7 -9
- package/dist/core/graph/events.js +8 -8
- package/dist/core/graph/exposures.d.ts +6 -6
- package/dist/core/graph/exposures.js +4 -4
- package/dist/core/graph/jobs.d.ts +6 -8
- package/dist/core/graph/jobs.js +2 -2
- package/dist/core/graph/kinds/action.js +1 -1
- package/dist/core/graph/kinds/custom.js +2 -2
- package/dist/core/graph/kinds/document.d.ts +1 -0
- package/dist/core/graph/kinds/document.js +4 -4
- package/dist/core/graph/kinds/dto.d.ts +2 -2
- package/dist/core/graph/kinds/dto.js +1 -1
- package/dist/core/graph/kinds/job.js +2 -2
- package/dist/core/graph/kinds/kind.d.ts +6 -8
- package/dist/core/graph/kinds/kind.js +1 -1
- package/dist/core/graph/kinds/node.js +5 -5
- package/dist/core/graph/kinds/owner.js +2 -2
- package/dist/core/graph/kinds/registry.d.ts +6 -9
- package/dist/core/graph/kinds/registry.js +1 -1
- package/dist/core/graph/names.d.ts +6 -6
- package/dist/core/graph/names.js +3 -3
- package/dist/core/graph/object-waits.d.ts +4 -7
- package/dist/core/graph/object-waits.js +1 -1
- package/dist/core/graph/objects.d.ts +14 -14
- package/dist/core/graph/objects.js +9 -9
- package/dist/core/graph/package-docs.d.ts +2 -7
- package/dist/core/graph/package-docs.js +5 -5
- package/dist/core/graph/package-kinds.d.ts +2 -5
- package/dist/core/graph/package-kinds.js +1 -1
- package/dist/core/graph/package-reconcile.d.ts +2 -5
- package/dist/core/graph/package-reconcile.js +1 -1
- package/dist/core/graph/reader.d.ts +18 -18
- package/dist/core/graph/reader.js +3 -3
- package/dist/core/graph/receivers.d.ts +4 -4
- package/dist/core/graph/receivers.js +5 -5
- package/dist/core/graph/repo-sync/exchange.d.ts +3 -7
- package/dist/core/graph/repo-sync/exchange.js +2 -2
- package/dist/core/graph/repo-sync/repos.d.ts +7 -5
- package/dist/core/graph/repo-sync/repos.js +3 -3
- package/dist/core/graph/repo-sync/sync.d.ts +3 -6
- package/dist/core/graph/repo-sync/sync.js +2 -2
- package/dist/core/graph/rules.d.ts +5 -5
- package/dist/core/graph/rules.js +3 -3
- package/dist/core/graph/spaces/app.js +1 -1
- package/dist/core/graph/spaces/index.d.ts +4 -5
- package/dist/core/graph/spaces/index.js +1 -1
- package/dist/core/graph/spaces/own-memory.d.ts +4 -4
- package/dist/core/graph/spaces/own-memory.js +1 -1
- package/dist/core/graph/spaces/person.js +3 -3
- package/dist/core/graph/spaces/repo.d.ts +1 -1
- package/dist/core/graph/spaces/repo.js +1 -1
- package/dist/core/graph/watches.d.ts +15 -15
- package/dist/core/graph/watches.js +10 -10
- package/dist/core/human/feedback-companion.d.ts +2 -2
- package/dist/core/human/feedback-companion.js +1 -1
- package/dist/core/human/feedback.d.ts +3 -3
- package/dist/core/human/feedback.js +1 -1
- package/dist/core/human/requests.d.ts +34 -33
- package/dist/core/human/requests.js +20 -20
- package/dist/core/human/scan.d.ts +2 -2
- package/dist/core/human/scan.js +1 -1
- package/dist/core/human/tickets.d.ts +9 -9
- package/dist/core/human/tickets.js +1 -1
- package/dist/core/llm/app-rungs.d.ts +1 -1
- package/dist/core/llm/app-rungs.js +1 -1
- package/dist/core/llm/run.js +1 -1
- package/dist/core/peer/directory.d.ts +1 -1
- package/dist/core/peer/directory.js +1 -1
- package/dist/core/peer/envelope.d.ts +3 -3
- package/dist/core/peer/envelope.js +1 -1
- package/dist/core/peer/home.d.ts +7 -7
- package/dist/core/peer/home.js +2 -2
- package/dist/core/peer/ingest.d.ts +6 -6
- package/dist/core/peer/ingest.js +1 -1
- package/dist/core/peer/outbox-store.d.ts +14 -14
- package/dist/core/peer/outbox-store.js +5 -5
- package/dist/core/peer/receiver.d.ts +2 -2
- package/dist/core/peer/receiver.js +1 -1
- package/dist/core/peer/stubs.d.ts +10 -10
- package/dist/core/peer/stubs.js +1 -1
- package/dist/core/providers/approval.d.ts +2 -2
- package/dist/core/providers/approval.js +2 -2
- package/dist/core/providers/audit.d.ts +3 -3
- package/dist/core/providers/audit.js +2 -2
- package/dist/core/providers/bundles.js +2 -2
- package/dist/core/providers/call.d.ts +2 -2
- package/dist/core/providers/call.js +1 -1
- package/dist/core/providers/files.d.ts +1 -1
- package/dist/core/providers/files.js +1 -1
- package/dist/core/providers/mint.js +1 -1
- package/dist/core/providers/receipts.d.ts +1 -1
- package/dist/core/providers/receipts.js +2 -2
- package/dist/core/review/birth.js +1 -1
- package/dist/core/review/comments.d.ts +19 -19
- package/dist/core/review/comments.js +5 -5
- package/dist/core/review/companion.d.ts +1 -1
- package/dist/core/review/companion.js +1 -1
- package/dist/core/review/document.d.ts +3 -3
- package/dist/core/review/document.js +2 -2
- package/dist/core/review/fork.js +2 -2
- package/dist/core/review/realize.js +1 -1
- package/dist/core/review/remap.d.ts +2 -2
- package/dist/core/review/remap.js +4 -4
- package/dist/core/review/stage.d.ts +1 -1
- package/dist/core/review/stage.js +1 -1
- package/dist/core/review/store.d.ts +21 -21
- package/dist/core/review/store.js +1 -1
- package/dist/core/runs/activity.d.ts +1 -1
- package/dist/core/runs/activity.js +5 -5
- package/dist/core/runs/confinement.d.ts +7 -7
- package/dist/core/runs/confinement.js +2 -2
- package/dist/core/runs/events.d.ts +12 -12
- package/dist/core/runs/events.js +4 -4
- package/dist/core/runs/operations.d.ts +11 -11
- package/dist/core/runs/operations.js +5 -5
- package/dist/core/runs/questions.d.ts +10 -10
- package/dist/core/runs/questions.js +3 -3
- package/dist/core/runtime/auth-reload.js +1 -1
- package/dist/core/runtime/bearings.d.ts +5 -5
- package/dist/core/runtime/bearings.js +6 -6
- package/dist/core/runtime/broker-inventory.js +1 -1
- package/dist/core/runtime/broker-request.js +1 -1
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/close.d.ts +3 -3
- package/dist/core/runtime/close.js +1 -1
- package/dist/core/runtime/deliver-live.js +1 -1
- package/dist/core/runtime/fleet.d.ts +2 -2
- package/dist/core/runtime/host.d.ts +3 -3
- package/dist/core/runtime/host.js +3 -3
- package/dist/core/runtime/kickoff.d.ts +12 -12
- package/dist/core/runtime/kickoff.js +17 -17
- package/dist/core/runtime/launch-target.d.ts +1 -1
- package/dist/core/runtime/launch-target.js +1 -1
- package/dist/core/runtime/ledger.d.ts +3 -3
- package/dist/core/runtime/ledger.js +3 -3
- package/dist/core/runtime/lifecycle.d.ts +1 -1
- package/dist/core/runtime/lifecycle.js +2 -2
- package/dist/core/runtime/memory-admission.js +1 -1
- package/dist/core/runtime/model-swap.d.ts +2 -2
- package/dist/core/runtime/model-swap.js +1 -1
- package/dist/core/runtime/node-read.d.ts +1 -1
- package/dist/core/runtime/node-read.js +2 -2
- package/dist/core/runtime/nodes.d.ts +6 -6
- package/dist/core/runtime/nodes.js +1 -1
- package/dist/core/runtime/outcome-document.d.ts +1 -1
- package/dist/core/runtime/outcome-document.js +1 -1
- package/dist/core/runtime/persona.d.ts +3 -3
- package/dist/core/runtime/persona.js +2 -2
- package/dist/core/runtime/placement.d.ts +11 -11
- package/dist/core/runtime/placement.js +1 -1
- package/dist/core/runtime/promote.d.ts +3 -3
- package/dist/core/runtime/promote.js +1 -1
- package/dist/core/runtime/recycle.js +1 -1
- package/dist/core/runtime/reopen.d.ts +5 -5
- package/dist/core/runtime/reopen.js +1 -1
- package/dist/core/runtime/reset.d.ts +4 -4
- package/dist/core/runtime/reset.js +1 -1
- package/dist/core/runtime/revive-all.d.ts +2 -2
- package/dist/core/runtime/revive-all.js +1 -1
- package/dist/core/runtime/revive.d.ts +4 -4
- package/dist/core/runtime/revive.js +2 -2
- package/dist/core/runtime/roadmap.d.ts +6 -6
- package/dist/core/runtime/roadmap.js +5 -5
- package/dist/core/runtime/session-branch.d.ts +1 -1
- package/dist/core/runtime/session-branch.js +1 -1
- package/dist/core/runtime/session-list-cache.js +1 -1
- package/dist/core/runtime/situational-live.js +1 -1
- package/dist/core/runtime/spawn.d.ts +2 -2
- package/dist/core/runtime/spawn.js +2 -2
- package/dist/core/runtime/stop-guard.d.ts +2 -2
- package/dist/core/runtime/stop-guard.js +3 -3
- package/dist/core/runtime/warm-pool.d.ts +2 -2
- package/dist/core/runtime/warm-pool.js +1 -1
- package/dist/core/spaces/mounts.d.ts +2 -2
- package/dist/core/spaces/mounts.js +1 -1
- package/dist/core/spaces/permissions.d.ts +1 -1
- package/dist/core/spaces/permissions.js +1 -1
- package/dist/core/spaces/process.d.ts +1 -1
- package/dist/core/spaces/process.js +1 -1
- package/dist/core/spaces/space.js +1 -1
- package/dist/core/spaces/stop.d.ts +3 -3
- package/dist/core/spaces/stop.js +2 -2
- package/dist/core/spaces/users.d.ts +6 -6
- package/dist/core/spaces/users.js +1 -1
- package/dist/core/storage/attachments.d.ts +2 -2
- package/dist/core/storage/attachments.js +1 -1
- package/dist/core/storage/shares.d.ts +2 -2
- package/dist/core/storage/shares.js +1 -1
- package/dist/core/storage/tables.d.ts +21 -21
- package/dist/core/storage/tables.js +3 -3
- package/dist/core/substrate/delivery/corpus.d.ts +5 -8
- package/dist/core/substrate/delivery/corpus.js +3 -3
- package/dist/core/substrate/delivery/deliver.d.ts +10 -15
- package/dist/core/substrate/delivery/deliver.js +3 -3
- package/dist/core/substrate/delivery/plan.d.ts +2 -12
- package/dist/core/substrate/delivery/plan.js +3 -3
- package/dist/core/substrate/delivery/render-boot.d.ts +4 -4
- package/dist/core/substrate/delivery/render-boot.js +18 -18
- package/dist/core/substrate/delivery/render-event.d.ts +7 -14
- package/dist/core/substrate/delivery/render-event.js +4 -4
- package/dist/core/substrate/subject.d.ts +2 -2
- package/dist/core/substrate/subject.js +1 -1
- package/dist/core/usage/ledger.d.ts +6 -6
- package/dist/core/usage/ledger.js +4 -4
- package/dist/core/worktree-close.js +4 -4
- package/dist/core/worktree-mutation-async.js +7 -7
- package/dist/core/worktree-quarantine.js +1 -1
- package/dist/core/worktree-sweep.d.ts +1 -1
- package/dist/core/worktree-sweep.js +6 -6
- package/dist/core/worktree.d.ts +5 -5
- package/dist/core/worktree.js +13 -13
- package/dist/daemon/analytics/compute.d.ts +2 -2
- package/dist/daemon/analytics/compute.js +1 -1
- package/dist/daemon/api/app-listener.d.ts +4 -4
- package/dist/daemon/api/app-listener.js +13 -13
- package/dist/daemon/api/bridge.js +5 -5
- package/dist/daemon/api/document-listener.js +6 -6
- package/dist/daemon/api/handlers/analytics.js +1 -1
- package/dist/daemon/api/handlers/attach.js +1 -1
- package/dist/daemon/api/handlers/bash-jobs.js +1 -1
- package/dist/daemon/api/handlers/bash.js +1 -1
- package/dist/daemon/api/handlers/broker-ops.d.ts +1 -1
- package/dist/daemon/api/handlers/broker-ops.js +1 -1
- package/dist/daemon/api/handlers/broker-recovery.d.ts +1 -1
- package/dist/daemon/api/handlers/broker-recovery.js +1 -1
- package/dist/daemon/api/handlers/broker-signals.d.ts +2 -2
- package/dist/daemon/api/handlers/broker-signals.js +2 -2
- package/dist/daemon/api/handlers/canvas.d.ts +1 -1
- package/dist/daemon/api/handlers/canvas.js +4 -4
- package/dist/daemon/api/handlers/chat-inventory.js +1 -1
- package/dist/daemon/api/handlers/crons.js +1 -1
- package/dist/daemon/api/handlers/custom-objects.d.ts +4 -4
- package/dist/daemon/api/handlers/custom-objects.js +3 -3
- package/dist/daemon/api/handlers/delivery-retry.js +1 -1
- package/dist/daemon/api/handlers/delivery.js +1 -1
- package/dist/daemon/api/handlers/docs.d.ts +4 -4
- package/dist/daemon/api/handlers/docs.js +1 -1
- package/dist/daemon/api/handlers/feedback-comments.js +3 -3
- package/dist/daemon/api/handlers/files.js +1 -1
- package/dist/daemon/api/handlers/focus.js +1 -1
- package/dist/daemon/api/handlers/health.js +3 -3
- package/dist/daemon/api/handlers/hook-exec.js +1 -1
- package/dist/daemon/api/handlers/human-requests.js +1 -1
- package/dist/daemon/api/handlers/inbox-page.d.ts +1 -1
- package/dist/daemon/api/handlers/inbox-page.js +1 -1
- package/dist/daemon/api/handlers/inbox.d.ts +1 -1
- package/dist/daemon/api/handlers/inbox.js +1 -1
- package/dist/daemon/api/handlers/llm.d.ts +1 -1
- package/dist/daemon/api/handlers/llm.js +3 -3
- package/dist/daemon/api/handlers/memory-reads.js +1 -1
- package/dist/daemon/api/handlers/memory.d.ts +5 -5
- package/dist/daemon/api/handlers/memory.js +5 -5
- package/dist/daemon/api/handlers/messages.js +2 -2
- package/dist/daemon/api/handlers/node-events.d.ts +2 -2
- package/dist/daemon/api/handlers/node-events.js +3 -3
- package/dist/daemon/api/handlers/node-outcomes.js +1 -1
- package/dist/daemon/api/handlers/node-records.js +2 -2
- package/dist/daemon/api/handlers/nodes.d.ts +1 -1
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/handlers/objects.js +3 -3
- package/dist/daemon/api/handlers/package-docs.js +1 -1
- package/dist/daemon/api/handlers/plugin-app-token.d.ts +1 -1
- package/dist/daemon/api/handlers/plugin-app-token.js +1 -1
- package/dist/daemon/api/handlers/profiles.d.ts +3 -3
- package/dist/daemon/api/handlers/profiles.js +1 -1
- package/dist/daemon/api/handlers/providers.d.ts +1 -1
- package/dist/daemon/api/handlers/providers.js +1 -1
- package/dist/daemon/api/handlers/questions.js +1 -1
- package/dist/daemon/api/handlers/reports.d.ts +1 -1
- package/dist/daemon/api/handlers/reports.js +5 -5
- package/dist/daemon/api/handlers/review-comments.js +1 -1
- package/dist/daemon/api/handlers/reviews.js +1 -1
- package/dist/daemon/api/handlers/runs.js +1 -1
- package/dist/daemon/api/handlers/structured-requests.js +1 -1
- package/dist/daemon/api/handlers/subscriptions.js +1 -1
- package/dist/daemon/api/handlers/transfer.js +1 -1
- package/dist/daemon/api/map.d.ts +3 -3
- package/dist/daemon/api/map.js +1 -1
- package/dist/daemon/api/principal.d.ts +1 -1
- package/dist/daemon/api/principal.js +1 -1
- package/dist/daemon/api/reader.d.ts +5 -5
- package/dist/daemon/api/reader.js +1 -1
- package/dist/daemon/api/router.d.ts +5 -5
- package/dist/daemon/api/router.js +1 -1
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/broker-signals/bus.d.ts +1 -1
- package/dist/daemon/broker-signals/bus.js +1 -1
- package/dist/daemon/companion-retire.js +1 -1
- package/dist/daemon/cron/armed-context.d.ts +2 -2
- package/dist/daemon/cron/armed-context.js +1 -1
- package/dist/daemon/cron/authority.d.ts +2 -2
- package/dist/daemon/cron/authority.js +1 -1
- package/dist/daemon/cron/disposition.js +1 -1
- package/dist/daemon/cron/ended.d.ts +1 -1
- package/dist/daemon/cron/ended.js +2 -2
- package/dist/daemon/cron/escalation.js +3 -3
- package/dist/daemon/cron/folders.d.ts +1 -1
- package/dist/daemon/cron/folders.js +1 -1
- package/dist/daemon/cron/held.d.ts +1 -1
- package/dist/daemon/cron/held.js +1 -1
- package/dist/daemon/cron/lease-recovery.d.ts +1 -1
- package/dist/daemon/cron/lease-recovery.js +1 -1
- package/dist/daemon/cron/passes.d.ts +2 -2
- package/dist/daemon/cron/passes.js +1 -1
- package/dist/daemon/cron/run-socket.d.ts +1 -1
- package/dist/daemon/cron/run-socket.js +1 -1
- package/dist/daemon/cron/settle.js +1 -1
- package/dist/daemon/cron/sinks.d.ts +1 -1
- package/dist/daemon/cron/sinks.js +2 -2
- package/dist/daemon/cron-run.d.ts +12 -3
- package/dist/daemon/cron-run.js +2 -2
- package/dist/daemon/crtrd.js +6 -6
- package/dist/daemon/delivery/run-delivery.js +1 -1
- package/dist/daemon/due-sources.d.ts +3 -3
- package/dist/daemon/due-sources.js +1 -1
- package/dist/daemon/due.d.ts +3 -3
- package/dist/daemon/due.js +7 -7
- package/dist/daemon/fleet.d.ts +2 -2
- package/dist/daemon/fleet.js +11 -11
- package/dist/daemon/human/finish.js +3 -3
- package/dist/daemon/human/settle.d.ts +1 -1
- package/dist/daemon/human/settle.js +1 -1
- package/dist/daemon/human/sweep.js +1 -1
- package/dist/daemon/joined-owner.d.ts +2 -2
- package/dist/daemon/joined-owner.js +1 -1
- package/dist/daemon/messaging/node-message.js +1 -1
- package/dist/daemon/park-activity.d.ts +2 -2
- package/dist/daemon/park-activity.js +1 -1
- package/dist/daemon/peer/authority.js +1 -1
- package/dist/daemon/peer/forward.d.ts +6 -6
- package/dist/daemon/peer/forward.js +1 -1
- package/dist/daemon/peer/handlers.js +1 -1
- package/dist/daemon/peer/ingress.d.ts +4 -4
- package/dist/daemon/peer/ingress.js +1 -1
- package/dist/daemon/peer/outbox.d.ts +2 -2
- package/dist/daemon/peer/outbox.js +1 -1
- package/dist/daemon/peer/relay-service.js +1 -1
- package/dist/daemon/plugin-objects/read-leaf.d.ts +2 -2
- package/dist/daemon/plugin-objects/read-leaf.js +2 -2
- package/dist/daemon/profile-delete.js +1 -1
- package/dist/daemon/readiness.d.ts +2 -2
- package/dist/daemon/readiness.js +1 -1
- package/dist/daemon/reconcilers/action-lane.d.ts +1 -1
- package/dist/daemon/reconcilers/action-lane.js +1 -1
- package/dist/daemon/reconcilers/bash-deadline.js +2 -2
- package/dist/daemon/reconcilers/broker-supervision.d.ts +1 -1
- package/dist/daemon/reconcilers/broker-supervision.js +4 -4
- package/dist/daemon/reconcilers/controller-death.d.ts +1 -1
- package/dist/daemon/reconcilers/controller-death.js +1 -1
- package/dist/daemon/reconcilers/cron-lane.d.ts +1 -1
- package/dist/daemon/reconcilers/cron-lane.js +1 -1
- package/dist/daemon/reconcilers/delivery-lane.d.ts +1 -1
- package/dist/daemon/reconcilers/delivery-lane.js +2 -2
- package/dist/daemon/reconcilers/fault-retry-backstop.d.ts +3 -3
- package/dist/daemon/reconcilers/fault-retry-backstop.js +1 -1
- package/dist/daemon/reconcilers/grove-instance-sweep.d.ts +2 -2
- package/dist/daemon/reconcilers/grove-instance-sweep.js +1 -1
- package/dist/daemon/reconcilers/live-obligation.d.ts +6 -6
- package/dist/daemon/reconcilers/live-obligation.js +1 -1
- package/dist/daemon/reconcilers/managed-worktree-sweep.js +1 -1
- package/dist/daemon/reconcilers/node-deadline.d.ts +1 -1
- package/dist/daemon/reconcilers/node-deadline.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/freeze-lane.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/respawn-policy.d.ts +3 -3
- package/dist/daemon/reconcilers/node-lifecycle/respawn-policy.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/terminating.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/wants-execution.d.ts +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/wants-execution.js +1 -1
- package/dist/daemon/reconcilers/pending-review-submit.d.ts +1 -1
- package/dist/daemon/reconcilers/pending-review-submit.js +1 -1
- package/dist/daemon/reconcilers/storage-due-work.js +1 -1
- package/dist/daemon/reconcilers/storage-maintenance.d.ts +1 -1
- package/dist/daemon/reconcilers/storage-maintenance.js +2 -2
- package/dist/daemon/reconcilers/structured-request-lane.d.ts +1 -1
- package/dist/daemon/reconcilers/structured-request-lane.js +1 -1
- package/dist/daemon/review/comment-notify.js +2 -2
- package/dist/daemon/review/companion.d.ts +3 -3
- package/dist/daemon/review/companion.js +1 -1
- package/dist/daemon/review/finish.js +1 -1
- package/dist/daemon/review/sweep.js +1 -1
- package/dist/daemon/run-notices.d.ts +4 -4
- package/dist/daemon/run-notices.js +1 -1
- package/dist/daemon/runs/append-section.d.ts +2 -2
- package/dist/daemon/runs/append-section.js +2 -2
- package/dist/daemon/runs/observer.d.ts +2 -2
- package/dist/daemon/runs/observer.js +2 -2
- package/dist/daemon/structured-requests/boot.d.ts +1 -1
- package/dist/daemon/structured-requests/boot.js +1 -1
- package/dist/daemon/structured-requests/effects.js +1 -1
- package/dist/daemon/structured-requests/sidecar.d.ts +1 -1
- package/dist/daemon/structured-requests/sidecar.js +1 -1
- package/dist/migrations/004-canvas-documents/apply.d.ts +3 -3
- package/dist/migrations/004-canvas-documents/apply.js +1 -1
- package/dist/migrations/004-canvas-documents/index.d.ts +2 -2
- package/dist/migrations/004-canvas-documents/index.js +2 -2
- package/dist/migrations/activation.js +2 -2
- package/docs/public-api.md +11 -0
- package/package.json +3 -2
- package/packages/crouter-identity/package.json +1 -1
- package/runtime.lock.json +12 -12
|
@@ -1482,7 +1482,7 @@ ${r}`),e}}});function WUr(t,e){let n=Math.max(0,e-NUr),r=t.reduce((a,c)=>Math.ma
|
|
|
1482
1482
|
`)}var Upe=["rate_limit","overloaded","connection","auth","protocol","context_overflow","wedged","model_not_found","unknown"];function eAn(t){return typeof t=="object"&&t!==null?t:void 0}function T7e(t){return typeof t=="string"?t:""}function R7e(t){if(t instanceof Error){let n={type:t.name||"Error",message:t.message};return typeof t.stack=="string"&&(n.stack=t.stack),t.cause!==void 0&&(n.cause=t.cause instanceof Error?t.cause.message:String(t.cause)),n}if(typeof t=="string")return{type:"Error",message:t};let e=eAn(t);return{type:T7e(e?.name)||"Error",message:T7e(e?.message)||String(t)}}import{AsyncLocalStorage as tAn}from"node:async_hooks";import{randomBytes as nAn}from"node:crypto";var rAn=/^(?!0{32}$)[0-9a-f]{32}$/,Qpe=new tAn;function Yj(t){if(typeof t!="string"||!rAn.test(t))throw new TypeError("operation_id must be 32 lowercase non-zero hexadecimal characters");return t}function Wpe(){let t;do t=nAn(16).toString("hex");while(t==="00000000000000000000000000000000");return Yj(t)}var M7e={current:()=>Qpe.getStore(),run:(t,e)=>Qpe.run(Yj(t),e),fresh:t=>{let e=Wpe();return Qpe.run(e,()=>t(e))}};var iAn=/^[a-z][a-z0-9]*(?:[._][a-z0-9]+)*$/,oAn=new Set(["error","warn","info","debug"]),sAn=new Set(["daemon","broker","control-plane","front","sentinel"]),aAn=new Set(["succeeded","failed","skipped"]),cAn=new Set(["auto","manual","fatal"]),uAn=new Set(Upe);function lAn(t){return Buffer.byteLength(t,"utf8")}function Jj(t,e,n=128){if(typeof t!="string"||t===""||lAn(t)>n)throw new TypeError(`${e} must be a non-empty string of at most ${n} UTF-8 bytes`);return t}function dAn(t){if(typeof t!="string"||!/^\d{4}-\d{2}-\d{2}T/.test(t))throw new TypeError("ts must be an ISO 8601 timestamp");let e=new Date(t);if(Number.isNaN(e.getTime()))throw new TypeError("ts must be an ISO 8601 timestamp");return e.toISOString()}function pAn(t){if(!uAn.has(t.class))throw new TypeError("error_class.class is invalid");let e={class:t.class};if(t.status!==void 0){if(!Number.isInteger(t.status))throw new TypeError("error_class.status must be an integer");e.status=t.status}if(t.provider!==void 0&&(e.provider=Jj(t.provider,"error_class.provider")),t.retry_disposition!==void 0){if(!cAn.has(t.retry_disposition))throw new TypeError("error_class.retry_disposition is invalid");e.retry_disposition=t.retry_disposition}return e}function P7e(t){if(!oAn.has(t.level))throw new TypeError("level is invalid");if(!sAn.has(t.component))throw new TypeError("component is invalid");let e=Jj(t.event,"event");if(!iAn.test(e))throw new TypeError("event must be a lowercase dotted identifier");let n=t.operation_id===void 0?M7e.current()??Wpe():Yj(t.operation_id),r={v:1,ts:t.ts===void 0?new Date().toISOString():dAn(t.ts),level:t.level,event:e,component:t.component,operation_id:n};if(t.node_id!==void 0&&(r.node_id=Jj(t.node_id,"node_id")),t.stream_id!==void 0&&(r.stream_id=Jj(t.stream_id,"stream_id")),t.duration_ms!==void 0){if(!Number.isFinite(t.duration_ms)||t.duration_ms<0)throw new TypeError("duration_ms must be finite and non-negative");r.duration_ms=t.duration_ms}if(t.outcome!==void 0){if(!aAn.has(t.outcome))throw new TypeError("outcome is invalid");r.outcome=t.outcome}if(t.attempt!==void 0){if(!Number.isInteger(t.attempt)||t.attempt<=0)throw new TypeError("attempt must be a positive integer");r.attempt=t.attempt}return t.error_class!==void 0&&(r.error_class=pAn(t.error_class)),t.error!==void 0&&(r.error=R7e(t.error)),t.fields!==void 0&&(r.fields=t.fields),r}function Vv(t){return Buffer.byteLength(t,"utf8")}function zv(t,e){if(Vv(t)<=e)return{value:t,altered:!1};let n="\u2026",r=e-Vv(n),i=0,o="";for(let s of t){let a=Vv(s);if(i+a>r)break;o+=s,i+=a}return{value:o+n,altered:!0}}function hAn(t){return t===void 0?"[Unsupported undefined]":typeof t=="function"?`[Unsupported function${t.name?` ${t.name}`:""}]`:typeof t=="symbol"?`[Unsupported ${String(t)}]`:`[Unsupported ${t?.constructor?.name??typeof t}]`}function Hpe(t,e,n,r){if(r.remaining<=0)return{value:"[Omitted]",altered:!0,dropped:0};if(r.remaining-=1,t===null||typeof t=="boolean")return{value:t,altered:!1,dropped:0};if(typeof t=="string"){let i=zv(t,4096);return{value:i.value,altered:i.altered,dropped:0}}if(typeof t=="number")return Number.isFinite(t)?{value:t,altered:!1,dropped:0}:{value:String(t),altered:!0,dropped:0};if(typeof t=="bigint")return{value:t.toString(),altered:!0,dropped:0};if(t instanceof Date)return{value:Number.isNaN(t.getTime())?"Invalid Date":t.toISOString(),altered:!0,dropped:0};if(typeof t!="object"||t===void 0)return{value:hAn(t),altered:!0,dropped:0};if(n.has(t))return{value:"[Circular]",altered:!0,dropped:0};if(e>=4)return{value:"[Max depth]",altered:!0,dropped:0};n.add(t);try{if(Array.isArray(t)){let u=Math.min(t.length,64),l=[],d=t.length>u,p=t.length-u;for(let h=0;h<u;h+=1){if(r.remaining<=0){d=!0,p+=u-h;break}let m=Hpe(t[h],e+1,n,r);l.push(m.value),d||=m.altered,p+=m.dropped}return{value:l,altered:d,dropped:p}}let i;try{i=Object.keys(t).sort()}catch{return{value:"[Unsupported object]",altered:!0,dropped:0}}let o=i.slice(0,64),s={},a=i.length>o.length,c=i.length-o.length;for(let u=0;u<o.length;u+=1){let l=o[u];if(r.remaining<=0){a=!0,c+=o.length-u;break}let d=zv(l,128),p;try{p=Hpe(t[l],e+1,n,r)}catch{p={value:"[Unsupported property]",altered:!0,dropped:0}}if(Object.prototype.hasOwnProperty.call(s,d.value)){a=!0,c+=1;continue}s[d.value]=p.value,a||=d.altered||p.altered,c+=p.dropped}return{value:s,altered:a,dropped:c}}finally{n.delete(t)}}function mAn(t){let e=zv(String(t.type),128),n=zv(String(t.message),4096),r={type:e.value,message:n.value},i=e.altered||n.altered;if(t.stack!==void 0){let o=zv(String(t.stack),16384);r.stack=o.value,i||=o.altered}if(t.cause!==void 0){let o=zv(String(t.cause),4096);r.cause=o.value,i||=o.altered}return{value:r,altered:i}}function Xj(t){return JSON.stringify(t)}function LN(t){return Vv(Xj(t))+1}function D7e(t){let e=t.fields===void 0?void 0:Hpe(t.fields,0,new WeakSet,{remaining:5e3}),n=t.error===void 0?void 0:mAn(t.error),r={v:1,ts:t.ts,level:t.level,event:t.event,component:t.component,operation_id:t.operation_id,...t.node_id===void 0?{}:{node_id:t.node_id},...t.stream_id===void 0?{}:{stream_id:t.stream_id},...t.duration_ms===void 0?{}:{duration_ms:t.duration_ms},...t.outcome===void 0?{}:{outcome:t.outcome},...t.attempt===void 0?{}:{attempt:t.attempt},...t.error_class===void 0?{}:{error_class:t.error_class},...n===void 0?{}:{error:n.value},...e===void 0?{}:{fields:e.value}},i=LN(r),o=e?.altered===!0||n?.altered===!0||i>65536,s=e?.dropped??0;for(o&&Object.assign(r,{record_truncated:!0,original_bytes:i,dropped_fields_count:s});LN(r)>65536&&r.fields!==void 0;){let u=r.fields,l=Object.keys(u);if(l.length===0){delete r.fields;break}l.sort((d,p)=>{let h=Vv(Xj(u[p]))-Vv(Xj(u[d]));return h!==0?h:p<d?-1:p>d?1:0}),delete u[l[0]],s+=1,r.record_truncated=!0,r.original_bytes=i,r.dropped_fields_count=s}let a=r.error;LN(r)>65536&&a?.stack!==void 0&&delete a.stack,LN(r)>65536&&a?.cause!==void 0&&delete a.cause,LN(r)>65536&&a!==void 0&&(a.message=zv(a.message,64).value);let c=Xj(r);if(Vv(c)+1>65536)throw new RangeError("event record cannot fit within 64 KiB");return c}import{join as eyn}from"node:path";import{join as Hf}from"node:path";import{existsSync as NN,mkdirSync as ini,readFileSync as RAn,statSync as oni}from"node:fs";import{homedir as MAn,userInfo as PAn}from"node:os";import{basename as DAn,dirname as cni,isAbsolute as uni,join as ac,resolve as F7e}from"node:path";import{existsSync as Zj,lstatSync as Vti,mkdirSync as fAn,readdirSync as gAn,readFileSync as B7e,rmSync as AAn,statSync as yAn,symlinkSync as Kti,writeFileSync as xAn,cpSync as Yti,readlinkSync as Jti,renameSync as wAn,chmodSync as bAn,realpathSync as EAn,closeSync as Gpe,fsyncSync as jpe,openSync as zpe,linkSync as vAn,unlinkSync as SAn,writeSync as CAn}from"node:fs";import{dirname as qpe,join as _An,relative as Zti,sep as eni}from"node:path";import{homedir as IAn,platform as kAn}from"node:os";function um(t){try{return EAn(t)}catch{return t}}function L7e(t,e=IAn()){return t==="~"?e:t.startsWith("~/")||kAn()==="win32"&&t.startsWith("~\\")?_An(e,t.slice(2)):t}function e3(t){fAn(t,{recursive:!0})}function t3(t,e,n){O7e(t,JSON.stringify(e,null,2)+`
|
|
1483
1483
|
`,n)}function Vpe(t){let e=zpe(t,"r");try{jpe(e)}finally{Gpe(e)}}function ON(t){let e=zpe(t,"r");try{jpe(e)}finally{Gpe(e)}}function O7e(t,e,n){n?.createParent!==!1&&e3(qpe(t));let r=`${t}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`,i=n?.mode??(Zj(t)?yAn(t).mode&511:384);try{xAn(r,e,{mode:i}),bAn(r,i),n?.durable===!0&&Vpe(r),wAn(r,t),n?.durable===!0&&ON(qpe(t))}finally{Zj(r)&&AAn(r,{force:!0})}}function Kpe(t,e,n){let r=`${t}.${process.pid}.${Math.random().toString(16).slice(2)}.tmp`,i=zpe(r,"wx",n);try{try{let o=Buffer.from(e,"utf8");for(let s=0;s<o.length;)s+=CAn(i,o,s,o.length-s);jpe(i)}finally{Gpe(i)}try{vAn(r,t)}catch(o){if(o.code==="EEXIST")return!1;throw o}return ON(qpe(t)),!0}finally{try{SAn(r)}catch{}}}function TAn(t){return JSON.parse(B7e(t,"utf8"))}function Kv(t){try{return TAn(t)}catch(e){if(e.code==="ENOENT")return null;throw e}}function PT(t){try{return JSON.parse(B7e(t,"utf8"))}catch{return null}}function Ype(t){return Zj(t)}function Jpe(t){return Zj(t)?gAn(t,{withFileTypes:!0}).filter(e=>e.isDirectory()||e.isSymbolicLink()).map(e=>e.name):[]}var N7e="1";function $N(){let t=F7e(ay()||(process.platform==="linux"?"/":ac(MAn(),".crouter")));if(BAn()&&t===LAn())throw new Error(`refusing to use the account's real crouter root ${t} from a node --test process; point CRTR_HOME (not only HOME) at a temporary directory`);return t}function BAn(){return process.env.NODE_TEST_CONTEXT!==void 0||process.execArgv.includes("--test")}var n3;function LAn(){if(n3===void 0)try{n3=F7e(PAn().homedir,".crouter")}catch{n3=null}return n3}function uy(){return ac($N(),"runtime")}function Xpe(){return ac($N(),"apps")}function ly(){return ac(uy(),"secrets")}function FN(t,e){if(!/^[a-z0-9]+(?:-[a-z0-9]+)*-[0-9a-f]{8}$/.test(e))throw new Error(`invalid profile id: ${e}`);let n=UN(t);return{dir:ac(n.profiles,e),env:ac(ly(),"env",DAn(n.root),e),home:n.home}}function Zpe(){return process.platform==="linux"?"/run/crtr":uy()}function $7e(){return ac(uy(),"layout")}function UN(t){let e=t.startsWith("app:")?t.slice(4):t;if(!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(e)||e==="."||e==="..")throw new Error(`invalid app id: ${t}`);let n=ac(Xpe(),e);return{root:n,profiles:ac(n,"profiles"),conversations:ac(n,"conversations"),nodes:ac(n,"nodes"),files:ac(n,"files"),home:ac(n,"home"),cache:ac(n,"cache")}}function OAn(t){let e=Array.from(t.subarray(0,32),n=>n===92?"\\\\":n===34?'\\"':n===10?"\\n":n===13?"\\r":n===9?"\\t":n>=32&&n<127?String.fromCharCode(n):`\\x${n.toString(16).padStart(2,"0")}`).join("");return`${t.length} bytes, preview "${e}"${t.length>32?"\u2026":""}`}function NAn(t){let e=RAn(t);if(e.toString("utf8").trim()!==N7e)throw new Error(`unsupported runtime layout version: ${t} holds ${OAn(e)}; expected "${N7e}"`)}function U7e(){if(process.env.CRTR_LAYOUT_REFUSE==="1")return!0;if(NN($7e()))return NAn($7e()),!1;let t=$N(),e=process.platform==="linux"&&t==="/"&&NN("/volume")?"/volume":t;return NN(ac(e,"canvas"))||NN(ac(e,"canvas.db"))?!0:NN(ac(uy(),"canvas.db"))}import{chmodSync as fni,chownSync as gni,closeSync as lm,constants as r3,fchmodSync as Ani,fchownSync as yni,fstatSync as ihe,fsyncSync as xni,linkSync as wni,lstatSync as bni,mkdirSync as Q7e,openSync as the,readdirSync as $An,readFileSync as FAn,readlinkSync as Eni,readSync as vni,realpathSync as Sni,renameSync as Cni,rmdirSync as _ni,rmSync as Ini,statSync as UAn,symlinkSync as kni,unlinkSync as Tni,writeSync as Rni}from"node:fs";import{basename as Pni,dirname as Dni,join as QAn,relative as ohe,resolve as i3,sep as nhe}from"node:path";import{loadLinuxNative as WAn,O_CLOEXEC as rhe,O_PATH as s3,RESOLVE_BENEATH as HAn,RESOLVE_NO_SYMLINKS as qAn}from"../../native/linux.js";var GAn=HAn|qAn,QN=s3|r3.O_DIRECTORY|rhe,ehe=null;function a3(){return ehe===null&&(ehe=WAn()),ehe}function o3(t){return t.code}var Yv=class extends Error{};function jAn(t,e){switch(o3(t)){case"ELOOP":case"EXDEV":return new Yv(`path meets a symlink: ${e}`);case"ENXIO":return new Yv(`path is not a regular file: ${e}`);case"EAGAIN":return new Yv(`path is held by a lease: ${e}`);default:return t}}function WN(t,e,n,r,i){try{return t.openat2(e,n,r,GAn)}catch(o){throw jAn(o,i)}}function zAn(t,e,n){let r;try{r=ihe(t)}catch(i){throw lm(t),i}if(r.isFile()||n&&r.isDirectory())return t;throw lm(t),new Yv(`path is not a regular file: ${e}`)}var VAn=new Set(["ENOENT","ENOTDIR","EACCES"]);function H7e(t,e){let n=ohe(i3(t),i3(e));if(n===".."||n.startsWith(`..${nhe}`)||n.startsWith(nhe))throw new Error(`${e} is outside ${t}`);return n}function W7e(t){if(t===""||t===".."||t.includes("/"))throw new Error(`not one path component: ${t}`);return t}function she(t,e,n){if(n&r3.O_CREAT)throw new Error("openBeneath never creates; use writeFileBeneath or createFileBeneath");let r=H7e(t,e),i=a3();if(!i)return the(e,n);let o=the("/",QN),s;try{s=WN(i,o,ohe("/",i3(t))||".",QN,t)}finally{lm(o)}try{return n&s3?WN(i,s,r||".",n|rhe,e):zAn(WN(i,s,r||".",n|rhe|r3.O_NONBLOCK,e),e,!0)}finally{lm(s)}}function c3(t,e){let n=she(t,e,r3.O_RDONLY);try{return FAn(n)}finally{lm(n)}}function KAn(t,e){if(!a3())return UAn(e);let n=she(t,e,s3);try{return ihe(n)}finally{lm(n)}}function q7e(t,e){try{return KAn(t,e),!0}catch(n){if(VAn.has(o3(n)??""))return!1;throw n}}function G7e(t,e,n,r=!1){H7e(t,e);let i=a3();if(!i)return r&&Q7e(e,{recursive:!0}),n(s=>s===void 0?e:QAn(e,W7e(s)));let o=the("/",QN);try{for(let a of ohe("/",i3(e)).split(nhe).filter(Boolean)){let c;try{c=WN(i,o,a,QN,e)}catch(u){if(!r||o3(u)!=="ENOENT")throw u;try{Q7e(`/proc/self/fd/${o}/${a}`)}catch(l){if(o3(l)!=="EEXIST")throw l}c=WN(i,o,a,QN,e)}lm(o),o=c}let s=`/proc/self/fd/${o}`;return n(a=>a===void 0?s:`${s}/${W7e(a)}`)}finally{lm(o)}}function j7e(t,e){return G7e(t,e,n=>$An(n(),{withFileTypes:!0}))}function z7e(t,e){if(!a3())return{path:e,release:()=>{}};let n=she(t,e,s3),r;try{r=ihe(n)}catch(o){throw lm(n),o}if(!r.isSocket())throw lm(n),new Yv(`path is not a socket: ${e}`);let i=!0;return{path:`/proc/self/fd/${n}`,release:()=>{i&&(i=!1,lm(n))}}}function Ma(){return uy()}function V7e(){return Hf(Ma(),"on-disk-migration.lock")}function DT(t){return Hf(BT(t),"view.sock")}function YAn(){return Hf(Ma(),"nodes")}function K7e(){return Hf(Zpe(),"api.sock")}var JAn=128;function Y7e(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=JAn}function ahe(t){if(!Y7e(t))throw new TypeError("node_id must be a non-empty path segment of at most 128 UTF-8 bytes")}function XAn(t){return ahe(t),Hf(YAn(),t)}function ZAn(t,e){ahe(t);let n=e??(rpe()===t?Q6e():void 0);if(!n)throw new Error(`node ${t} has no app assignment`);return Hf(UN(n).nodes,t)}function BT(t){return ahe(t),process.platform==="linux"?Hf(Zpe(),"nodes",t):Hf(XAn(t),"run")}function u3(t,e){return Hf(ZAn(t,e),"context")}function J7e(t){return Hf(BT(t),"job")}var l3;function tyn(t,e){return t.component===e.component&&t.path===e.path&&t.node_id===e.node_id&&t.stream_id===e.stream_id}function nyn(t){if(l3===void 0){l3=t;return}if(!tyn(l3,t))throw new Error("event source is already bound for this process")}function X7e(){nyn({component:"daemon",path:eyn(Ma(),"crtrd.log")})}function d3(){return l3}import{request as pyn}from"node:http";import{homedir as hyn}from"node:os";import{join as dhe}from"node:path";var vn=class extends Error{status;code;details;headers;type;param;origin;retryable;retryAfterS;resetAt;requestId;runId;questionId;scope;userAction;constructor(e,n,r,i,o,s){super(r),this.name="APIError",this.status=e,this.code=n,this.headers=new Headers(o),i!==void 0&&(this.details=i),this.type=s?.type,this.param=s?.param,this.origin=s?.origin,this.retryable=s?.retryable,this.retryAfterS=s?.retry_after_s,this.resetAt=s?.reset_at,this.requestId=s?.request_id??this.headers.get("Request-Id")??void 0,this.runId=s?.run_id,this.questionId=s?.question_id,this.scope=s?.scope,this.userAction=s?.user_action}};function che(t){if(typeof t!="object"||t===null)return!1;let e=t.error;if(typeof e!="object"||e===null)return!1;let{code:n,message:r}=e;return typeof n=="string"&&typeof r=="string"}var me={healthz:()=>"/healthz",ready:()=>"/v1/ready",status:()=>"/v1/status",due:()=>"/v1/due",daemonRestart:()=>"/v1/daemon/restart",daemonMigrate:()=>"/v1/daemon/migrate",daemonAdmit:()=>"/v1/daemon/admit",nodes:()=>"/v1/nodes",reviveAll:()=>"/v1/nodes/revive-all",node:t=>`/v1/nodes/${t}`,nodeMemoryReads:t=>`/v1/nodes/${t}/memory-reads`,nodeOutcome:t=>`/v1/nodes/${t}/outcome`,nodeOutcomeDelivery:t=>`/v1/nodes/${t}/outcome-delivery`,nodeEvents:t=>`/v1/nodes/${t}/events`,nodeSnapshot:t=>`/v1/nodes/${t}/snapshot`,nodeSubject:t=>`/v1/nodes/${t}/subject`,nodeSession:t=>`/v1/nodes/${t}/session`,nodeChatInventory:t=>`/v1/nodes/${t}/chat-inventory`,prospectiveChatInventory:()=>"/v1/prospective-chat-inventory",nodeTranscript:t=>`/v1/nodes/${t}/transcript`,nodeContext:t=>`/v1/nodes/${t}/context`,nodeReports:t=>`/v1/nodes/${t}/reports`,nodeResult:t=>`/v1/nodes/${t}/result`,nodeJobs:t=>`/v1/nodes/${t}/jobs`,nodeJob:(t,e)=>`/v1/nodes/${t}/jobs/${e}`,nodeJobBackground:(t,e)=>`/v1/nodes/${t}/jobs/${e}/background`,nodeDelivery:t=>`/v1/nodes/${t}/delivery`,deliveryDryRun:()=>"/v1/delivery/dry-run",deliveryRetry:t=>`/v1/deliveries/${encodeURIComponent(t)}/retry`,nodeMessages:t=>`/v1/nodes/${t}/messages`,nodeInterrupt:t=>`/v1/nodes/${t}/interrupt`,nodeFork:t=>`/v1/nodes/${t}/fork`,nodeRevive:t=>`/v1/nodes/${t}/revive`,nodeRelaunchRoot:t=>`/v1/nodes/${t}/relaunch-root`,nodeBrokerSessionBound:t=>`/v1/nodes/${t}/broker/session-bound`,nodeBrokerSettle:t=>`/v1/nodes/${t}/broker/settle`,nodeBrokerParkComplete:t=>`/v1/nodes/${t}/broker/park-complete`,nodeBrokerParkActivity:t=>`/v1/nodes/${t}/broker/park-activity`,nodeBrokerTelemetry:t=>`/v1/nodes/${t}/broker/telemetry`,nodeLog:t=>`/v1/nodes/${t}/records/log`,nodeTelemetry:t=>`/v1/nodes/${t}/records/telemetry`,nodeRecap:t=>`/v1/nodes/${t}/records/recap`,nodeInboxReport:t=>`/v1/nodes/${t}/records/inbox`,nodePassiveMessage:t=>`/v1/nodes/${t}/records/passive`,nodePushedFinal:t=>`/v1/nodes/${t}/records/pushed-final`,nodeMailClaim:t=>`/v1/nodes/${t}/mail/claim`,nodeMailAcknowledge:t=>`/v1/nodes/${t}/mail/acknowledge`,nodeBrokerModel:t=>`/v1/nodes/${t}/broker/model`,nodeBrokerExtensionState:t=>`/v1/nodes/${t}/broker/extension-state`,nodeBrokerSignals:t=>`/v1/nodes/${t}/broker/signals`,nodeBrokerGeneratedName:t=>`/v1/nodes/${t}/broker/generated-name`,nodeBrokerPersonaAck:t=>`/v1/nodes/${t}/broker/persona-ack`,brokerTurn:t=>`/v1/broker/${t}/turn`,brokerProviderRetry:t=>`/v1/broker/${t}/provider-retry`,brokerFault:t=>`/v1/broker/${t}/fault`,brokerRecovery:t=>`/v1/broker/${t}/recovery`,nodeFault:t=>`/v1/nodes/${t}/fault`,nodeClose:t=>`/v1/nodes/${t}/close`,nodeRead:t=>`/v1/nodes/${t}/read`,nodeRecycle:t=>`/v1/nodes/${t}/recycle`,nodeDemote:t=>`/v1/nodes/${t}/demote`,nodePromote:t=>`/v1/nodes/${t}/promote`,nodeYield:t=>`/v1/nodes/${t}/yield`,nodeWait:t=>`/v1/nodes/${t}/wait`,nodeConfig:t=>`/v1/nodes/${t}/config`,kinds:()=>"/v1/kinds",nodeWorktreeClose:t=>`/v1/nodes/${t}/worktree/close`,nodeWorktreeAbandon:t=>`/v1/nodes/${t}/worktree/abandon`,quarantinedWorktrees:()=>"/v1/worktrees/quarantined",spaces:()=>"/v1/spaces",limits:()=>"/v1/limits",limitsApp:t=>`/v1/limits/apps/${encodeURIComponent(t)}`,nodeAttach:t=>`/v1/nodes/${t}/attach`,focuses:()=>"/v1/focuses",focusByNode:()=>"/v1/focuses/by-node",focusByPane:()=>"/v1/focuses/by-pane",focus:t=>`/v1/focuses/${t}`,nodeSubscriptions:t=>`/v1/nodes/${t}/subscriptions`,nodeSubscription:(t,e)=>`/v1/nodes/${t}/subscriptions/${e}`,crons:()=>"/v1/crons",cron:t=>`/v1/crons/${t}`,cronPause:t=>`/v1/crons/${t}/pause`,cronResume:t=>`/v1/crons/${t}/resume`,cronRun:t=>`/v1/crons/${t}/run`,cronsPoke:()=>"/v1/crons/poke",canvasAttention:()=>"/v1/canvas/attention",canvasAttentionCounts:()=>"/v1/canvas/attention/counts",canvasHistorySearch:()=>"/v1/canvas/history/search",canvasHistoryGrep:()=>"/v1/canvas/history/grep",canvasHistoryRead:()=>"/v1/canvas/history/read",canvasHistoryStats:()=>"/v1/canvas/history/stats",canvasSnapshot:()=>"/v1/canvas/snapshot",canvasLiveRoots:()=>"/v1/canvas/live-roots",canvasRoster:()=>"/v1/canvas/roster",canvasBrowse:()=>"/v1/canvas/browse",canvasAnalytics:()=>"/v1/canvas/analytics",canvasGraph:()=>"/v1/canvas/graph",canvasPrune:()=>"/v1/canvas/prune",humanReviews:()=>"/v1/human/reviews",humanReview:t=>`/v1/human/reviews/${t}`,humanReviewSubmit:t=>`/v1/human/reviews/${t}/submit`,humanReviewCancel:t=>`/v1/human/reviews/${t}/cancel`,humanReviewDocument:t=>`/v1/human/reviews/${t}/document`,humanReviewComments:t=>`/v1/human/reviews/${t}/comments`,humanReviewCommentEvents:t=>`/v1/human/reviews/${t}/comment-events`,humanReviewCommentRanges:t=>`/v1/human/reviews/${t}/comment-ranges`,humanComment:t=>`/v1/human/comments/${t}`,humanCommentEdit:t=>`/v1/human/comments/${t}/edit`,humanCommentResolve:t=>`/v1/human/comments/${t}/resolve`,humanCommentReopen:t=>`/v1/human/comments/${t}/reopen`,humanCommentDelete:t=>`/v1/human/comments/${t}/delete`,humanCommentFork:t=>`/v1/human/comments/${t}/fork`,humanInbox:()=>"/v1/human/inbox",humanInboxTicket:t=>`/v1/human/inbox/${t}`,humanInboxRespond:t=>`/v1/human/inbox/${t}/respond`,humanInboxProgress:t=>`/v1/human/inbox/${t}/progress`,humanInboxResponse:t=>`/v1/human/inbox/${t}/response`,humanInboxCancel:t=>`/v1/human/inbox/${t}/cancel`,humanInboxFeedbackResolve:(t,e)=>`/v1/human/inbox/${t}/feedback-comments/${e}/resolve`,humanRequests:()=>"/v1/human/requests",humanComponents:()=>"/v1/human/components",humanRequest:t=>`/v1/human/requests/${t}`,humanRequestReplace:t=>`/v1/human/requests/${t}/replace`,humanRequestRespond:t=>`/v1/human/requests/${t}/respond`,humanRequestDismiss:t=>`/v1/human/requests/${t}/dismiss`,humanRequestCancel:t=>`/v1/human/requests/${t}/cancel`,profiles:()=>"/v1/profiles",profile:t=>`/v1/profiles/${t}`,profilePause:t=>`/v1/profiles/${t}/pause`,profileResume:t=>`/v1/profiles/${t}/resume`,profileMetadata:t=>`/v1/profiles/${t}/metadata`,appEnv:()=>"/v1/apps/self/env",appEnvVar:t=>`/v1/apps/self/env/${encodeURIComponent(t)}`,profileEnv:t=>`/v1/profiles/${t}/env`,profileEnvVar:(t,e)=>`/v1/profiles/${t}/env/${e}`,modelAuths:()=>"/v1/model-auth",modelAuthReadiness:()=>"/v1/model-auth/readiness",modelAuth:t=>`/v1/model-auth/${t}`,modelAuthFlows:()=>"/v1/model-auth/flows",modelAuthFlow:t=>`/v1/model-auth/flows/${encodeURIComponent(t)}`,modelAuthFlowComplete:t=>`/v1/model-auth/flows/${encodeURIComponent(t)}/complete`,modelAuthFlowCancel:t=>`/v1/model-auth/flows/${encodeURIComponent(t)}/cancel`,filePeek:()=>"/v1/files/peek",fileWrite:()=>"/v1/files/write",fileList:()=>"/v1/files/list",bash:()=>"/v1/bash",objects:()=>"/v1/objects",object:t=>`/v1/objects/${encodeURIComponent(t)}`,objectsSearch:()=>"/v1/objects/search",objectWatch:t=>`/v1/objects/${encodeURIComponent(t)}/watch`,customObjects:()=>"/v1/custom-objects",customObject:t=>`/v1/custom-objects/${encodeURIComponent(t)}`,customObjectEvents:t=>`/v1/custom-objects/${encodeURIComponent(t)}/events`,customObjectDeliveries:t=>`/v1/custom-objects/${encodeURIComponent(t)}/deliveries`,customObjectAck:t=>`/v1/custom-objects/${encodeURIComponent(t)}/deliveries/ack`,objectEdges:t=>`/v1/objects/${encodeURIComponent(t)}/edges`,docs:()=>"/v1/docs",doc:t=>`/v1/docs/${encodeURIComponent(t)}`,docMove:t=>`/v1/docs/${encodeURIComponent(t)}/move`,docHistory:t=>`/v1/docs/${encodeURIComponent(t)}/history`,docsLint:()=>"/v1/docs/lint",pluginAppToken:t=>`/v1/plugins/${encodeURIComponent(t)}/app-token`,pluginCallHeaders:t=>`/v1/plugins/${encodeURIComponent(t)}/call-headers`,documentsBrowserAccess:()=>"/v1/documents/browser-access",documentsReconcilePackages:()=>"/v1/documents/reconcile-packages"};function p3(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}function Z7e(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&/^[A-Za-z0-9._~-]+$/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}function e9e(t){return typeof t=="string"&&t!==""&&t!=="."&&t!==".."&&!/[\\/\0\s?#%]/u.test(t)&&Buffer.byteLength(t,"utf8")<=128}var ryn=3e4,iyn=Symbol.for("@north-light/api/local-socket-fetch"),oyn=1e4,syn=200;async function h3({windowMs:t,probe:e,initialError:n,pollIntervalMs:r=syn,retry:i=()=>!0,now:o=Date.now,sleep:s=i9e}){let a=o()+t,c=n;for(;;){let u=a-o();if(u<=0)throw c??new Error("crtrd availability window expired without a probe failure");try{await e(u);return}catch(d){if(c=d,!i(d))throw d}let l=a-o();if(l<=0)throw c;await s(Math.min(r,l))}}var qN=2147483647;function OT(t,e="elapsed",n){let r=e==="retry_after"?`the server asked to retry after ${n}s, which is later than the call's deadline (${new Date(t).toISOString()}); not waiting`:`the call's deadline (${new Date(t).toISOString()}) passed`;return new vn(504,"deadline_exceeded",r,{deadline_at:t,reason:e,...n===void 0?{}:{retry_after_s:n}})}var HN=t=>OT(t??Date.now()),GN=class{baseUrl;fetch;headers;autostart;timeoutMs;maxRetries;localSocketTransport;onColdSocket;coldStartDiagnostic;coldStartFailure;coldStartPollWindowMs;startupFailureReported=!1;coldStartAttempted=!1;constructor(e){if(e.baseUrl==="")throw new TypeError("CrtrClient requires baseUrl");this.baseUrl=new URL(e.baseUrl),this.fetch=e.fetch??globalThis.fetch,this.headers={...e.headers},this.autostart=e.autostart??!1,this.timeoutMs=e.timeoutMs??ryn,this.maxRetries=e.maxRetries??2,this.localSocketTransport=this.fetch[iyn]===!0,e.onColdSocket!==void 0&&(this.onColdSocket=e.onColdSocket),e.coldStartDiagnostic!==void 0&&(this.coldStartDiagnostic=e.coldStartDiagnostic),e.coldStartFailure!==void 0&&(this.coldStartFailure=e.coldStartFailure),this.coldStartPollWindowMs=e.coldStartPollWindowMs??oyn}healthz(){return this.request("GET",me.healthz())}async probeHealthz(e){let n=await this.transport("GET",me.healthz(),void 0,{timeout:e});if(n.status===503)try{let r=await n.clone().json();if(typeof r.startup_blocked=="string")return r}catch{}return LT(n)}async ready(){let e=await this.transport("GET",me.ready(),void 0,{});if(e.status===503)try{let n=await e.clone().json();if(n.ready===!1)return n}catch{}return LT(e)}status(){return this.request("GET",me.status())}due(){return this.request("GET",me.due())}restartDaemon(){return this.request("POST",me.daemonRestart())}admitDaemon(){return this.request("POST",me.daemonAdmit())}migrateState(e){return this.request("POST",me.daemonMigrate(),e)}appendNodeLog(e,n){return this.request("POST",me.nodeLog(this.nodePath(e)),n)}async putNodeTelemetry(e,n){await this.request("PUT",me.nodeTelemetry(this.nodePath(e)),n)}async putNodeRecap(e,n){await this.request("PUT",me.nodeRecap(this.nodePath(e)),n)}readNodeInboxReport(e,n,r){return this.request("GET",Tr(me.nodeInboxReport(this.nodePath(e)),{ref:n,execution_id:r}))}readNodePassiveMessage(e,n){return this.request("GET",Tr(me.nodePassiveMessage(this.nodePath(e)),{ref:n}))}nodePushedFinal(e,n){return this.request("POST",me.nodePushedFinal(this.nodePath(e)),n)}createNode(e){return this.request("POST",me.nodes(),e)}listNodes(e){return this.request("GET",Tr(me.nodes(),e))}getNode(e){return this.request("GET",me.node(this.nodePath(e)))}getNodeOutcome(e,{waitSeconds:n}={}){if(n!==void 0&&(!Number.isInteger(n)||n<0||n>25))throw new RangeError("waitSeconds must be an integer between 0 and 25");return this.request("GET",Tr(me.nodeOutcome(this.nodePath(e)),{wait:n}),void 0,{timeout:(n??0)*1e3+this.timeoutMs})}getNodeEvents(e,n={},r={}){if(n.after!==void 0&&(!Number.isSafeInteger(n.after)||n.after<0))throw new RangeError("after must be a non-negative safe integer");return this.transport("GET",Tr(me.nodeEvents(this.nodePath(e)),n),void 0,{...r,headers:{accept:"text/event-stream",...r.headers??{}},timeout:0})}async*getBrokerSignals(e,n,r={}){let i=await this.send("GET",Tr(me.nodeBrokerSignals(this.nodePath(e)),{execution_id:n}),void 0,{...r,headers:{accept:"application/x-ndjson",...r.headers??{}},timeout:0});if(!i.ok){await LT(i);return}if(i.body===null)throw new vn(i.status,"invalid_response","broker signal stream has no body");let o=i.body.getReader(),s=new TextDecoder,a="";try{for(;;){let{done:c,value:u}=await o.read();if(c)break;a+=s.decode(u,{stream:!0});let l;for(;(l=a.indexOf(`
|
|
1484
1484
|
`))!==-1;){let d=a.slice(0,l);a=a.slice(l+1),d!==""&&(yield JSON.parse(d))}}if(a+=s.decode(),a.trim()!=="")throw new vn(502,"invalid_response","broker signal stream ended mid-line")}finally{await o.cancel().catch(()=>{})}}createStructuredRequest(e,n){return e.mode==="sync"?this.sendOnce("POST","/v1/structured-requests",e,n):this.request("POST","/v1/structured-requests",e,n)}getStructuredRequest(e,{wait:n=0,budgetMs:r}={}){if(!Number.isInteger(n)||n<0||n>25)throw new RangeError("wait must be an integer between 0 and 25");return this.request("GET",Tr(`/v1/structured-requests/${this.requestPath(e)}`,{wait:n}),void 0,{budgetMs:r})}cancelStructuredRequest(e,n){return this.request("POST",`/v1/structured-requests/${this.requestPath(e)}/cancel`,{},n)}registerOutcomeDelivery(e,n){return this.request("PUT",me.nodeOutcomeDelivery(this.nodePath(e)),n)}getOutcomeDelivery(e){return this.request("GET",me.nodeOutcomeDelivery(this.nodePath(e)))}async disarmOutcomeDelivery(e){await this.request("DELETE",me.nodeOutcomeDelivery(this.nodePath(e)))}listBashJobs(e){return this.request("GET",me.nodeJobs(this.nodePath(e)))}stopBashJob(e,n){return this.request("DELETE",me.nodeJob(this.nodePath(e),this.jobPath(n)))}sendMessage(e,n){return this.request("POST",me.nodeMessages(this.nodePath(e)),n)}interruptNode(e){return this.request("POST",me.nodeInterrupt(this.nodePath(e)),{})}pushReport(e,n){return this.request("POST",me.nodeReports(this.nodePath(e)),n)}submitResult(e,n){return this.request("POST",me.nodeResult(this.nodePath(e)),n)}forkNode(e){return this.request("POST",me.nodeFork(this.nodePath(e)),{})}reviveNode(e,n){return this.request("POST",me.nodeRevive(this.nodePath(e)),n??{})}relaunchRoot(e){return this.request("POST",me.nodeRelaunchRoot(this.nodePath(e)),{})}bindBrokerSession(e,n){return this.request("POST",me.nodeBrokerSessionBound(this.nodePath(e)),n)}settleBroker(e,n){return this.request("POST",me.nodeBrokerSettle(this.nodePath(e)),n)}completeBrokerPark(e,n){return this.request("POST",me.nodeBrokerParkComplete(this.nodePath(e)),n)}recordBrokerParkActivity(e,n){return this.request("POST",me.nodeBrokerParkActivity(this.nodePath(e)),n)}async recordBrokerTelemetry(e,n){await this.request("POST",me.nodeBrokerTelemetry(this.nodePath(e)),n)}claimNodeMail(e,n){return this.request("POST",me.nodeMailClaim(this.nodePath(e)),n)}acknowledgeNodeMail(e,n){return this.request("POST",me.nodeMailAcknowledge(this.nodePath(e)),n)}recordBrokerTurn(e,n){return this.request("POST",me.brokerTurn(this.nodePath(e)),n)}mutateBrokerProviderRetry(e,n){return this.request("POST",me.brokerProviderRetry(this.nodePath(e)),n)}mutateBrokerFault(e,n){return this.request("POST",me.brokerFault(this.nodePath(e)),n)}getBrokerRecovery(e,n){return this.request("GET",`${me.brokerRecovery(this.nodePath(e))}?expected_execution_id=${encodeURIComponent(n)}`)}recordNodeFault(e,n){return this.request("POST",me.nodeFault(this.nodePath(e)),n)}clearNodeFault(e,n={}){let r=new URLSearchParams;n.link!==void 0&&r.set("link",n.link),n.preserve_episode!==void 0&&r.set("preserve_episode",String(n.preserve_episode));let i=r.size===0?"":`?${r.toString()}`;return this.request("DELETE",`${me.nodeFault(this.nodePath(e))}${i}`)}commitBrokerModel(e,n){return this.request("POST",me.nodeBrokerModel(this.nodePath(e)),n)}brokerExtensionState(e){return this.request("GET",me.nodeBrokerExtensionState(this.nodePath(e)))}commitBrokerGeneratedName(e,n){return this.request("POST",me.nodeBrokerGeneratedName(this.nodePath(e)),n)}commitBrokerPersonaAck(e,n){return this.request("POST",me.nodeBrokerPersonaAck(this.nodePath(e)),n)}closeNode(e,n){return this.request("POST",me.nodeClose(this.nodePath(e)),n??{})}async markNodeRead(e){await this.request("POST",me.nodeRead(this.nodePath(e)),{})}recycleNode(e){return this.request("POST",me.nodeRecycle(this.nodePath(e)),{})}demoteNode(e){return this.request("POST",me.nodeDemote(this.nodePath(e)),{})}promoteNode(e,n){return this.request("POST",me.nodePromote(this.nodePath(e)),n)}yieldNode(e,n){return this.request("POST",me.nodeYield(this.nodePath(e)),n)}waitNode(e,n){return this.request("POST",me.nodeWait(this.nodePath(e)),n)}listKinds(){return this.request("GET",me.kinds())}patchConfig(e,n){return this.request("PATCH",me.nodeConfig(this.nodePath(e)),n,n.model!==void 0?{timeout:45e3+this.timeoutMs}:void 0)}closeWorktree(e){return this.request("POST",me.nodeWorktreeClose(this.nodePath(e)),{})}abandonWorktree(e,n){return this.request("POST",me.nodeWorktreeAbandon(this.nodePath(e)),n)}retryDelivery(e){return this.request("POST",me.deliveryRetry(e),{})}listQuarantinedWorktrees(){return this.request("GET",me.quarantinedWorktrees())}showLimits(){return this.request("GET",me.limits())}setAppLimits(e,n){return this.request("PUT",me.limitsApp(e),n)}removeAppLimits(e,n){return this.request("DELETE",Tr(me.limitsApp(e),{fields:n.join(",")}))}listSpaces(){return this.request("GET",me.spaces())}subscribe(e,n){return this.request("POST",me.nodeSubscriptions(this.nodePath(e)),n)}listFocuses(){return this.request("GET",me.focuses())}focusOf(e){return this.request("GET",Tr(me.focusByNode(),{node_id:e}))}focusByPane(e){return this.request("GET",Tr(me.focusByPane(),{pane:e}))}registerFocus(e){return this.request("POST",me.focuses(),e)}async setFocusPane(e,n){await this.request("PATCH",me.focus(e),n)}async closeFocus(e){await this.request("DELETE",me.focus(e))}async unsubscribe(e,n){await this.request("DELETE",me.nodeSubscription(this.nodePath(e),this.nodePath(n)))}armCron(e){return this.request("POST",me.crons(),e)}listCrons(e){return this.request("GET",Tr(me.crons(),e))}showCron(e,n){return this.request("GET",Tr(me.cron(this.cronPath(e)),n))}pauseCron(e,n){return this.request("POST",Tr(me.cronPause(this.cronPath(e)),n),{})}resumeCron(e,n){return this.request("POST",Tr(me.cronResume(this.cronPath(e)),n),{})}runCron(e,n){return this.request("POST",Tr(me.cronRun(this.cronPath(e)),n),{})}async cancelCron(e,n){await this.request("DELETE",Tr(me.cron(this.cronPath(e)),n))}pokeCrons(){return this.request("POST",me.cronsPoke(),{})}ensureAttach(e,n){return this.request("POST",me.nodeAttach(this.nodePath(e)),n??{})}getReports(e,n){return this.request("GET",Tr(me.nodeReports(this.nodePath(e)),n))}getTranscript(e,n){return this.request("GET",Tr(me.nodeTranscript(this.nodePath(e)),n))}getSnapshot(e){return this.request("GET",me.nodeSnapshot(this.nodePath(e)))}nodeSubject(e){return this.request("GET",me.nodeSubject(this.nodePath(e)))}getNodeMessages(e,n){return this.request("GET",Tr(me.nodeMessages(this.nodePath(e)),n))}getSession(e){return this.request("GET",me.nodeSession(this.nodePath(e)))}getChatInventory(e){return this.request("GET",me.nodeChatInventory(this.nodePath(e)))}getProspectiveChatInventory(e){return this.request("GET",Tr(me.prospectiveChatInventory(),e))}getContext(e){return this.request("GET",me.nodeContext(this.nodePath(e)))}peekFile(e,n,r){return this.request("GET",Tr(me.filePeek(),{path:e,encoding:n}),void 0,r)}writeFile(e,n,r,i){return this.request("POST",me.fileWrite(),{path:e,content:n,encoding:r},i)}listFiles(e,n,r){return this.request("GET",Tr(me.fileList(),{path:e,limit:n}),void 0,r)}runBash(e,n){return this.request("POST",me.bash(),e,n)}objects={read:(e,n)=>this.request("GET",Tr(me.object(e),n)),list:e=>this.request("GET",Tr(me.objects(),e)),search:e=>this.request("POST",me.objectsSearch(),e),watch:(e,n={})=>this.request("POST",me.objectWatch(e),n),unwatch:(e,n)=>this.request("DELETE",Tr(me.objectWatch(e),n)),edges:(e,n)=>this.request("GET",Tr(me.objectEdges(e),n))};docs={write:e=>this.request("POST",me.docs(),e),edit:(e,n)=>this.request("PATCH",me.doc(e),n),move:(e,n)=>this.request("POST",me.docMove(e),n),delete:e=>this.request("DELETE",me.doc(e)),history:(e,n)=>this.request("GET",Tr(me.docHistory(e),n)),lint:(e={})=>this.request("POST",me.docsLint(),e)};documents={browserAccess:()=>this.request("GET",me.documentsBrowserAccess()),reconcilePackages:()=>this.request("POST",me.documentsReconcilePackages())};plugins={appToken:e=>this.request("GET",me.pluginAppToken(e)),callHeaders:(e,n)=>this.request("POST",me.pluginCallHeaders(e),n)};nodeDelivery(e,n){return this.request("POST",me.nodeDelivery(this.nodePath(e)),n)}deliveryDryRun(e){return this.request("POST",me.deliveryDryRun(),e)}recordBackgroundedJob(e,n,r){return this.request("POST",me.nodeJobBackground(this.nodePath(e),this.jobPath(n)),r)}ensureProfile(e,n){return this.request("PUT",me.profile(e),n??{})}createProfile(e){return this.request("POST",me.profiles(),e)}listProfiles(){return this.request("GET",me.profiles())}updateProfile(e,n){return this.request("PATCH",me.profile(e),n)}listAppEnv(){return this.request("GET",me.appEnv())}setAppEnv(e,n){return this.request("PUT",me.appEnvVar(e),{value:n})}removeAppEnv(e){return this.request("DELETE",me.appEnvVar(e))}listProfileEnv(e){return this.request("GET",me.profileEnv(e))}setProfileEnv(e,n,r){return this.request("PUT",me.profileEnvVar(e,n),{value:r})}removeProfileEnv(e,n){return this.request("DELETE",me.profileEnvVar(e,n))}getProfile(e){return this.request("GET",me.profile(e))}pauseProfile(e){return this.request("POST",me.profilePause(e),{})}resumeProfile(e){return this.request("POST",me.profileResume(e),{})}updateProfileMetadata(e,n){return this.request("PATCH",me.profileMetadata(e),n)}deleteProfile(e,n){return this.request("DELETE",me.profile(e),n)}listModelAuth(){return this.request("GET",me.modelAuths())}getModelAuthReadiness(e){return this.request("GET",Tr(me.modelAuthReadiness(),e))}installCredential(e,n){return this.request("PUT",me.modelAuth(e),n)}removeCredential(e){return this.request("DELETE",me.modelAuth(e))}startModelAuth(e){return this.request("POST",me.modelAuthFlows(),e,{timeout:3e4+this.timeoutMs})}completeModelAuth(e,n){return this.request("POST",me.modelAuthFlowComplete(e),n,{timeout:35e3+this.timeoutMs})}cancelModelAuth(e){return this.request("POST",me.modelAuthFlowCancel(e),{})}getModelAuthFlow(e,n){return this.request("GET",Tr(me.modelAuthFlow(e),{wait:n}),void 0,{timeout:(n??0)*1e3+this.timeoutMs})}createReview(e){return this.request("POST",me.humanReviews(),e)}listReviews(e){return this.request("GET",Tr(me.humanReviews(),e))}getReview(e){return this.request("GET",me.humanReview(this.reviewPath(e)))}submitReview(e){return this.request("POST",me.humanReviewSubmit(this.reviewPath(e)),{})}cancelReview(e,n={}){return this.request("POST",me.humanReviewCancel(this.reviewPath(e)),n)}getReviewDocumentBase(e){return this.request("GET",me.humanReviewDocument(this.reviewPath(e)))}createReviewComment(e,n){let r=e===void 0?"self":this.reviewPath(e);return this.request("POST",me.humanReviewComments(r),n)}listReviewComments(e,n){let r=e===void 0?"self":this.reviewPath(e);return this.request("GET",Tr(me.humanReviewComments(r),n))}readReviewCommentEvents(e,n){return this.request("GET",Tr(me.humanReviewCommentEvents(this.reviewPath(e)),n))}updateReviewCommentRanges(e,n){return this.request("POST",me.humanReviewCommentRanges(this.reviewPath(e)),n)}getReviewComment(e){return this.request("GET",me.humanComment(this.commentPath(e)))}editReviewComment(e,n){return this.request("POST",me.humanCommentEdit(this.commentPath(e)),n)}resolveReviewComment(e,n={}){return this.request("POST",me.humanCommentResolve(this.commentPath(e)),n)}reopenReviewComment(e,n={}){return this.request("POST",me.humanCommentReopen(this.commentPath(e)),n)}deleteReviewComment(e,n={}){return this.request("POST",me.humanCommentDelete(this.commentPath(e)),n)}forkReviewComment(e){return this.request("POST",me.humanCommentFork(this.commentPath(e)),{})}listHumanInbox(){return this.request("GET",me.humanInbox())}getHumanInboxPage(e){return this.request("GET",me.humanInboxTicket(this.ticketId(e)))}getInboxHistory(e){if(e===void 0)return this.request("GET",me.humanInbox()+"/history");if(typeof e!="string"||e==="")throw new TypeError(`invalid node id: ${JSON.stringify(e)}`);return this.request("GET",Tr(me.humanInbox()+"/history",{node_id:e}))}respondHumanInboxPage(e,n){return this.request("POST",me.humanInboxRespond(this.ticketId(e)),n)}postInboxProgress(e,n){return this.request("POST",me.humanInboxProgress(this.ticketId(e)),{responses:n})}getInboxResponse(e){return this.request("GET",me.humanInboxResponse(this.ticketId(e)))}cancelHumanInboxTicket(e,n){return this.request("POST",me.humanInboxCancel(this.ticketId(e)),n??{})}createHumanRequest(e){return this.request("POST",me.humanRequests(),e)}listPageComponents(){return this.request("GET",me.humanComponents())}getHumanRequest(e){return this.request("GET",me.humanRequest(this.requestPath(e)))}replaceHumanRequest(e,n){return this.request("POST",me.humanRequestReplace(this.requestPath(e)),n)}respondHumanRequest(e,n){return this.request("POST",me.humanRequestRespond(this.requestPath(e)),n)}dismissHumanRequest(e,n={}){return this.request("POST",me.humanRequestDismiss(this.requestPath(e)),n)}cancelHumanRequest(e,n={}){return this.request("POST",me.humanRequestCancel(this.requestPath(e)),n)}resolvePageFeedbackComment(e,n,r){if(!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(n))throw new TypeError(`invalid feedback comment id: ${JSON.stringify(n)}`);return this.request("POST",me.humanInboxFeedbackResolve(this.ticketId(e),n),{node_id:r})}async dashboard(e){let n=e?.under!==void 0?{under:e.under}:void 0,[r,i]=await Promise.all([this.listNodes(n),this.status()]);return{nodes:r,counts:i.node_counts,generated_at:new Date().toISOString()}}attention(){return this.request("GET",me.canvasAttention())}attentionCounts(e){let n={node_ids:e};return this.request("POST",me.canvasAttentionCounts(),n)}historySearch(e){return this.request("POST",me.canvasHistorySearch(),e)}historyGrep(e){return this.request("POST",me.canvasHistoryGrep(),e)}historyRead(e){return this.request("GET",Tr(me.canvasHistoryRead(),e))}historyStats(e){return this.request("POST",me.canvasHistoryStats(),e)}canvasSnapshot(){return this.request("GET",me.canvasSnapshot())}analytics(e){return this.request("GET",Tr(me.canvasAnalytics(),e),void 0,{timeout:6e4})}async recordMemoryReads(e,n){await this.request("POST",me.nodeMemoryReads(this.nodePath(e)),n)}liveRoots(e={}){return this.request("GET",Tr(me.canvasLiveRoots(),e))}canvasRoster(){return this.request("GET",me.canvasRoster())}async canvasBrowseCompressed(){let e=await this.send("GET",me.canvasBrowse());return e.ok||await LT(e),new Uint8Array(await e.arrayBuffer())}canvasGraph(){return this.request("GET",me.canvasGraph())}prune(e){return this.request("POST",me.canvasPrune(),e)}async request(e,n,r,i){try{let o=i===void 0?void 0:this.resolveBudget(i),s=await this.send(e,n,r,o);return await LT(s,o?.deadlineAt)}catch(o){throw kx(o,i?.signal)}}async rawResponse(e,n,r){try{return await this.send(e,n,void 0,r)}catch(i){throw kx(i,r?.signal)}}async send(e,n,r,i={}){let o=this.resolveBudget(i),s=e==="GET"||e==="HEAD"||e==="DELETE",a=o.maxRetries??this.maxRetries;for(let c=0;;c++){let u;try{u=await this.transport(e,n,r,o)}catch(l){if(this.isColdSocketError(l))try{await this.handleColdSocket(l,o.deadlineAt),u=await this.transport(e,n,r,o)}catch(d){throw o.deadlineAt!==void 0&&Date.now()>=o.deadlineAt&&!r9e(d,o.signal)?OT(o.deadlineAt):kx(d,o.signal)}else{if(this.isInterruptedSocketError(l)&&this.localSocketTransport&&(!s||c<a))return await this.rideOutInterruptedRequest(e,n,r,o);if(s&&c<a&&!r9e(l,o.signal)&&(!this.localSocketTransport||!this.isInterruptedSocketError(l))){await lhe(n9e(c+1),o);continue}else throw kx(l,o.signal)}}if(s&&c<a&&ayn(u.status)){await t9e(u,o.deadlineAt),await lhe(n9e(c+1),o,uyn(u));continue}return u}}resolveBudget(e){let{budgetMs:n,deadlineAt:r,...i}=e;if(n===void 0&&r===void 0)return i;if(n!==void 0&&(!Number.isFinite(n)||n<=0||n>qN))throw new RangeError(`budgetMs must be a positive finite number of at most ${qN}`);if(r!==void 0&&(!Number.isFinite(r)||r-Date.now()>qN))throw new RangeError(`deadlineAt must be a finite epoch-millisecond instant at most ${qN} ms from now`);return{...i,deadlineAt:Math.min(r??1/0,n===void 0?1/0:Date.now()+n)}}async awaitWithinBudget(e,n){if(n===void 0)return e;let r=n-Date.now();if(r<=0)throw HN(n);let i;try{return await Promise.race([e,new Promise((o,s)=>{i=setTimeout(()=>s(HN(n)),r)})])}finally{i!==void 0&&clearTimeout(i)}}async sendOnce(e,n,r,i={}){let o=this.resolveBudget(i);try{return await LT(await this.transport(e,n,r,o))}catch(s){throw kx(s,o.signal)}}nodePath(e){if(!p3(e))throw new vn(400,"invalid_node_id",`invalid node id: ${JSON.stringify(e)}`);return e}jobPath(e){if(!Z7e(e))throw new vn(400,"invalid_job_id",`invalid background job id: ${JSON.stringify(e)}`);return e}cronPath(e){if(!e9e(e))throw new vn(400,"invalid_cron_id",`invalid cron id: ${JSON.stringify(e)}`);return e}requestPath(e){if(!p3(e))throw new vn(400,"invalid_request_id",`invalid request id: ${JSON.stringify(e)}`);return e}ticketId(e){if(!/^[a-f0-9]{64}$/.test(e))throw new TypeError(`invalid inbox ticket id: ${JSON.stringify(e)}`);return e}reviewPath(e){if(!p3(e))throw new vn(400,"invalid_review_id",`invalid review id: ${JSON.stringify(e)}`);return e}commentPath(e){if(!/^[a-f0-9]{32}$/.test(e))throw new vn(400,"invalid_comment_id",`invalid comment id: ${JSON.stringify(e)}`);return e}transport(e,n,r,i={}){let o=i.deadlineAt===void 0?void 0:i.deadlineAt-Date.now();if(o!==void 0&&o<=0)return Promise.reject(HN(i.deadlineAt));let s=r===void 0?void 0:JSON.stringify(r),a={accept:"application/json",...this.headers,...i.headers};s!==void 0&&(a["content-type"]="application/json");let c=i.timeout??this.timeoutMs,u=o===void 0?c:c>0?Math.min(c,o):o,l=new AbortController,d=o!==void 0&&(c<=0||o<=c),p=u>0?setTimeout(()=>l.abort(d?HN(i.deadlineAt):new DOMException("request timed out","TimeoutError")),u):void 0,h=i.signal,m=()=>l.abort(h?.reason);h!==void 0&&(h.aborted?l.abort(h.reason):h.addEventListener("abort",m,{once:!0}));let f=()=>{p!==void 0&&clearTimeout(p),h?.removeEventListener("abort",m)};return lyn(this.fetch(new URL(n,this.baseUrl),{method:e,headers:a,body:s,signal:l.signal}),l.signal).then(g=>this.retainRequestLifetime(g,f,()=>l.signal.aborted?l.signal.reason:void 0),g=>{throw f(),g})}retainRequestLifetime(e,n,r){if(e.body===null)return n(),e;let i=e.body.getReader(),o=!1,s=()=>{o||(o=!0,n())},a=new ReadableStream({async pull(c){try{let{done:u,value:l}=await i.read();u?(s(),c.close()):c.enqueue(l)}catch(u){s(),c.error(r()??u)}},async cancel(c){s(),await i.cancel(c)}});return new Response(a,{status:e.status,statusText:e.statusText,headers:e.headers})}isColdSocketError(e){let n=uhe(e);return n==="ECONNREFUSED"||n==="ENOENT"||n==="ENOTSOCK"}isInterruptedSocketError(e){let n=uhe(e);return n==="ECONNRESET"||n==="EPIPE"}async rideOutInterruptedRequest(e,n,r,i={}){try{await this.awaitAvailability(void 0,i.deadlineAt)}catch(o){throw kx(o,i.signal)}if(e!=="GET"&&e!=="HEAD")throw new vn(503,"daemon_request_interrupted",`crtrd connection ended before this ${e} response; the request may or may not have been applied.`);try{return await this.transport(e,n,r,i)}catch(o){throw kx(o,i.signal)}}async awaitAvailability(e,n){let r=n===void 0?void 0:n-Date.now();if(r!==void 0&&r<=0)throw HN(n);let i;try{await h3({windowMs:Math.min(this.coldStartPollWindowMs,r??this.coldStartPollWindowMs),initialError:e,retry:o=>o!==i,probe:async o=>{let s=this.coldStartFailure?.();if(s!==void 0)throw i=new vn(503,"daemon_unavailable",`crtrd failed to start: ${s}`),i;let a=await this.transport("GET",me.healthz(),void 0,{timeout:o});if(a.status>=200&&a.status<300){await t9e(a);return}let c=await a.text();try{if(typeof JSON.parse(c).startup_blocked=="string")return}catch{}throw new vn(a.status,"daemon_health_unavailable",`crtrd health check returned HTTP ${a.status}: ${c.slice(0,500)}`)}})}catch(o){throw o===i&&(this.startupFailureReported=!0),o}}async handleColdSocket(e,n){let r=this.autostart&&this.onColdSocket!==void 0&&!this.coldStartAttempted;r&&(this.coldStartAttempted=!0,await this.awaitWithinBudget(this.onColdSocket(),n));try{await this.awaitAvailability(e,n)}catch(i){if(r&&!this.startupFailureReported){let o=dyn(this.coldStartDiagnostic);if(o!==void 0){let s=kx(i);throw new vn(s.status,s.code,`${s.message}
|
|
1485
|
-
${o}`)}}throw i}}};function Tr(t,e){if(e===void 0)return t;let n=new URLSearchParams;for(let[i,o]of Object.entries(e))o!=null&&n.set(i,String(o));let r=n.toString();return r===""?t:`${t}?${r}`}async function LT(t,e){let n=t.status>=200&&t.status<300,r=(await cyn(t,e)).trim(),i;if(r!=="")try{i=JSON.parse(r)}catch{if(n)return;throw new vn(t.status,"invalid_response",r.slice(0,500),void 0,t.headers)}if(n)return i;throw che(i)?new vn(t.status,i.error.code,i.error.message,i.error.details,t.headers,i.error):new vn(t.status,"internal",`request failed with status ${t.status}`,void 0,t.headers)}function ayn(t){return t===429||t>=500}async function t9e(t,e){let n=(async()=>{try{await t.body?.cancel()}catch{}})();if(e===void 0)return n;let r;try{await Promise.race([n,new Promise(i=>{r=setTimeout(i,Math.max(0,e-Date.now()))})])}finally{r!==void 0&&clearTimeout(r)}}async function cyn(t,e){if(e===void 0)return t.text();let n=e-Date.now(),r=t.text();if(r.catch(()=>{}),n<=0)throw t.body?.cancel().catch(()=>{}),OT(e);let i;try{return await Promise.race([r,new Promise((o,s)=>{i=setTimeout(()=>{t.body?.cancel().catch(()=>{}),s(OT(e))},n)})])}finally{i!==void 0&&clearTimeout(i)}}function n9e(t){return Math.min(2e3,250*2**(t-1))}function uhe(t){if(typeof t!="object"||t===null)return;let e=t.code;if(typeof e=="string")return e;let n=t.cause;if(typeof n=="object"&&n!==null){let r=n.code;if(typeof r=="string")return r}}function r9e(t,e){return e?.aborted?!0:t instanceof DOMException&&(t.name==="AbortError"||t.name==="TimeoutError")}function kx(t,e){if(e?.aborted)return new vn(0,"request_aborted","request aborted by caller signal");if(t instanceof vn)return t;if(t instanceof DOMException&&t.name==="TimeoutError")return new vn(504,"request_timeout",`crtrd request timed out: ${t.message}`);if(t instanceof DOMException&&t.name==="AbortError")return new vn(0,"request_aborted","request aborted by caller signal");let n=uhe(t),r=t instanceof Error?t.message:String(t);return n==="ECONNREFUSED"||n==="ENOENT"||n==="ENOTSOCK"?new vn(503,"daemon_unavailable",`crtrd is not reachable: ${r}`):n==="ETIMEDOUT"?new vn(504,"request_timeout",`crtrd request timed out: ${r}`):new vn(503,"transport_error",r)}function uyn(t){let e=Number(t.headers.get("retry-after"));return Number.isFinite(e)&&e>0?e:void 0}async function lhe(t,e,n,r){let{deadlineAt:i,signal:o}=e;if(o?.aborted)throw new vn(0,"request_aborted","request aborted by caller signal");let s=i!==void 0&&n!==void 0?n*1e3:void 0,a=Math.max(t,s??0);if(i!==void 0&&Date.now()+a>=i){let c=OT(i,s!==void 0&&s>=t?"retry_after":"elapsed",s===void 0?void 0:n);throw r!==void 0&&Object.defineProperty(c,"cause",{value:r,configurable:!0,writable:!0}),c}if(o===void 0)return i9e(a);await new Promise((c,u)=>{let l=()=>{clearTimeout(d),o.removeEventListener("abort",l),u(new vn(0,"request_aborted","request aborted by caller signal"))},d=setTimeout(()=>{o.removeEventListener("abort",l),c()},a);o.addEventListener("abort",l,{once:!0})})}function lyn(t,e){return new Promise((n,r)=>{let i=()=>r(e.reason);e.aborted?i():e.addEventListener("abort",i,{once:!0}),t.then(o=>{e.removeEventListener("abort",i),e.aborted?o.body?.cancel().catch(()=>{}):n(o)},o=>{e.removeEventListener("abort",i),r(o)})})}function i9e(t){return new Promise(e=>setTimeout(e,t))}function dyn(t){if(t!==void 0)try{return t()}catch{return}}var myn=".crouter",fyn="api.sock",gyn=Symbol.for("@north-light/api/local-socket-fetch");function Ayn(){let t=process.env.CRTR_API_SOCKET;if(t)return t;let e=process.env.CRTR_HOME,n=e!==void 0&&e!==""?e:dhe(hyn(),myn);return dhe(process.platform==="linux"?"/run/crtr":dhe(n,"runtime"),fyn)}function yyn(t){let e=function(n,r={}){let i=n instanceof URL?n:new URL(typeof n=="string"?n:n.url),o=r.method??"GET",s={};if(r.headers!==void 0)for(let[c,u]of new Headers(r.headers).entries())s[c]=u;let a=typeof r.body=="string"?r.body:void 0;return a!==void 0&&(s["content-length"]=String(Buffer.byteLength(a))),new Promise((c,u)=>{let l=pyn({socketPath:t,path:i.pathname+i.search,method:o,headers:s},h=>{let m=new ReadableStream({start(y){h.on("data",b=>y.enqueue(new Uint8Array(b))),h.on("end",()=>y.close()),h.on("error",b=>y.error(b))},cancel(){h.destroy()}}),f=new Headers;for(let[y,b]of Object.entries(h.headers))if(b!==void 0)for(let E of Array.isArray(b)?b:[b])f.append(y,E);let g=h.statusCode??0;c(new Response(g===204?null:m,{status:g,statusText:h.statusMessage,headers:f}))});l.on("error",h=>u(new TypeError("fetch failed",{cause:h})));let d=r.signal,p=()=>{l.destroy(),u(d?.reason??new DOMException("The operation was aborted.","AbortError"))};if(d!=null){if(d.aborted){p();return}d.addEventListener("abort",p,{once:!0})}a!==void 0&&l.write(a),l.end()})};return e[gyn]=!0,e}function dy(t={}){let{socketPath:e,...n}=t;return new GN({baseUrl:"http://localhost",fetch:yyn(e??Ayn()),autostart:!0,...n})}var xyn=["description","title","icon","mode","lifecycle","status","cwd","parent","fork_from","profile_id","review_binding_json","persona_ack_json","intent"];var phe=class{dirty=new Map;subscribers=new Set;scheduled;subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}markMail(e){this.mark(e,1)}markNode(e){this.mark(e,2)}mark(e,n){this.dirty.set(e,(this.dirty.get(e)??0)|n),this.scheduled??=setImmediate(()=>this.flush())}flush(){this.scheduled=void 0;let e=[...this.dirty];this.dirty.clear();for(let[n,r]of e)for(let i of this.subscribers)try{r&1&&i(n,"mail"),r&2&&i(n,"node")}catch{}}install(e){e.function("crtr_signal",{deterministic:!1},(n,r)=>{try{typeof r=="string"&&(n==="mail"&&this.markMail(r),n==="node"&&this.markNode(r))}catch{}return null}),e.exec(`
|
|
1485
|
+
${o}`)}}throw i}}};function Tr(t,e){if(e===void 0)return t;let n=new URLSearchParams;for(let[i,o]of Object.entries(e))o!=null&&n.set(i,String(o));let r=n.toString();return r===""?t:`${t}?${r}`}async function LT(t,e){let n=t.status>=200&&t.status<300,r=(await cyn(t,e)).trim(),i;if(r!=="")try{i=JSON.parse(r)}catch{if(n)return;throw new vn(t.status,"invalid_response",r.slice(0,500),void 0,t.headers)}if(n)return i;throw che(i)?new vn(t.status,i.error.code,i.error.message,i.error.details,t.headers,i.error):new vn(t.status,"internal",`request failed with status ${t.status}`,void 0,t.headers)}function ayn(t){return t===429||t>=500}async function t9e(t,e){let n=(async()=>{try{await t.body?.cancel()}catch{}})();if(e===void 0)return n;let r;try{await Promise.race([n,new Promise(i=>{r=setTimeout(i,Math.max(0,e-Date.now()))})])}finally{r!==void 0&&clearTimeout(r)}}async function cyn(t,e){if(e===void 0)return t.text();let n=e-Date.now(),r=t.text();if(r.catch(()=>{}),n<=0)throw t.body?.cancel().catch(()=>{}),OT(e);let i;try{return await Promise.race([r,new Promise((o,s)=>{i=setTimeout(()=>{t.body?.cancel().catch(()=>{}),s(OT(e))},n)})])}finally{i!==void 0&&clearTimeout(i)}}function n9e(t){return Math.min(2e3,250*2**(t-1))}function uhe(t){if(typeof t!="object"||t===null)return;let e=t.code;if(typeof e=="string")return e;let n=t.cause;if(typeof n=="object"&&n!==null){let r=n.code;if(typeof r=="string")return r}}function r9e(t,e){return e?.aborted?!0:t instanceof DOMException&&(t.name==="AbortError"||t.name==="TimeoutError")}function kx(t,e){if(e?.aborted)return new vn(0,"request_aborted","request aborted by caller signal");if(t instanceof vn)return t;if(t instanceof DOMException&&t.name==="TimeoutError")return new vn(504,"request_timeout",`crtrd request timed out: ${t.message}`);if(t instanceof DOMException&&t.name==="AbortError")return new vn(0,"request_aborted","request aborted by caller signal");let n=uhe(t),r=t instanceof Error?t.message:String(t);return n==="ECONNREFUSED"||n==="ENOENT"||n==="ENOTSOCK"?new vn(503,"daemon_unavailable",`crtrd is not reachable: ${r}`):n==="ETIMEDOUT"?new vn(504,"request_timeout",`crtrd request timed out: ${r}`):new vn(503,"transport_error",r)}function uyn(t){let e=Number(t.headers.get("retry-after"));return Number.isFinite(e)&&e>0?e:void 0}async function lhe(t,e,n,r){let{deadlineAt:i,signal:o}=e;if(o?.aborted)throw new vn(0,"request_aborted","request aborted by caller signal");let s=i!==void 0&&n!==void 0?n*1e3:void 0,a=Math.max(t,s??0);if(i!==void 0&&Date.now()+a>=i){let c=OT(i,s!==void 0&&s>=t?"retry_after":"elapsed",s===void 0?void 0:n);throw r!==void 0&&Object.defineProperty(c,"cause",{value:r,configurable:!0,writable:!0}),c}if(o===void 0)return i9e(a);await new Promise((c,u)=>{let l=()=>{clearTimeout(d),o.removeEventListener("abort",l),u(new vn(0,"request_aborted","request aborted by caller signal"))},d=setTimeout(()=>{o.removeEventListener("abort",l),c()},a);o.addEventListener("abort",l,{once:!0})})}function lyn(t,e){return new Promise((n,r)=>{let i=()=>r(e.reason);e.aborted?i():e.addEventListener("abort",i,{once:!0}),t.then(o=>{e.removeEventListener("abort",i),e.aborted?o.body?.cancel().catch(()=>{}):n(o)},o=>{e.removeEventListener("abort",i),r(o)})})}function i9e(t){return new Promise(e=>setTimeout(e,t))}function dyn(t){if(t!==void 0)try{return t()}catch{return}}var myn=".crouter",fyn="api.sock",gyn=Symbol.for("@north-light/api/local-socket-fetch");function Ayn(){let t=process.env.CRTR_API_SOCKET;if(t)return t;let e=process.env.CRTR_HOME,n=e!==void 0&&e!==""?e:dhe(hyn(),myn);return dhe(process.platform==="linux"?"/run/crtr":dhe(n,"runtime"),fyn)}function yyn(t){let e=function(n,r={}){let i=n instanceof URL?n:new URL(typeof n=="string"?n:n.url),o=r.method??"GET",s={};if(r.headers!==void 0)for(let[c,u]of new Headers(r.headers).entries())s[c]=u;let a=typeof r.body=="string"?r.body:void 0;return a!==void 0&&(s["content-length"]=String(Buffer.byteLength(a))),new Promise((c,u)=>{let l=pyn({socketPath:t,path:i.pathname+i.search,method:o,headers:s},h=>{let m=new ReadableStream({start(y){h.on("data",b=>y.enqueue(new Uint8Array(b))),h.on("end",()=>y.close()),h.on("error",b=>y.error(b))},cancel(){h.destroy()}}),f=new Headers;for(let[y,b]of Object.entries(h.headers))if(b!==void 0)for(let E of Array.isArray(b)?b:[b])f.append(y,E);let g=h.statusCode??0;c(new Response(g===204?null:m,{status:g,statusText:h.statusMessage,headers:f}))});l.on("error",h=>u(new TypeError("fetch failed",{cause:h})));let d=r.signal,p=()=>{l.destroy(),u(d?.reason??new DOMException("The operation was aborted.","AbortError"))};if(d!=null){if(d.aborted){p();return}d.addEventListener("abort",p,{once:!0})}a!==void 0&&l.write(a),l.end()})};return e[gyn]=!0,e}function dy(t={}){let{socketPath:e,...n}=t;return new GN({baseUrl:"http://localhost",fetch:yyn(e??Ayn()),autostart:!0,...n})}var xyn=["description","title","icon","mode","lifecycle","status","cwd","parent","fork_from","profile_id","review_binding_json","persona_ack_json","intent"];var phe=class{dirty=new Map;subscribers=new Set;scheduled;async subscribe(e){return this.subscribers.add(e),()=>{this.subscribers.delete(e)}}markMail(e){this.mark(e,1)}markNode(e){this.mark(e,2)}mark(e,n){this.dirty.set(e,(this.dirty.get(e)??0)|n),this.scheduled??=setImmediate(()=>this.flush())}flush(){this.scheduled=void 0;let e=[...this.dirty];this.dirty.clear();for(let[n,r]of e)for(let i of this.subscribers)try{r&1&&i(n,"mail"),r&2&&i(n,"node")}catch{}}install(e){e.function("crtr_signal",{deterministic:!1},(n,r)=>{try{typeof r=="string"&&(n==="mail"&&this.markMail(r),n==="node"&&this.markNode(r))}catch{}return null}),e.exec(`
|
|
1486
1486
|
CREATE TEMP TRIGGER crtr_sig_deliv_ins AFTER INSERT ON main.deliveries
|
|
1487
1487
|
WHEN NEW.wake = 1 BEGIN SELECT crtr_signal('mail', NEW.destination_id); END;
|
|
1488
1488
|
CREATE TEMP TRIGGER crtr_sig_deliv_upd AFTER UPDATE OF state, canceled_at, claim_owner ON main.deliveries
|
|
@@ -1740,7 +1740,7 @@ ${u}`,"1").then(l=>{let d=a.options[Number.parseInt(l,10)-1]?.id;if(d===void 0)t
|
|
|
1740
1740
|
${m}
|
|
1741
1741
|
`)}if(h==="node-done"){process.stderr.write(`
|
|
1742
1742
|
\u2713 node ${i} finished \u2014 final report submitted.
|
|
1743
|
-
`);let m=e.tagPane()??process.env.TMUX_PANE??Vf()?.pane;!o&&m!==void 0&&Ss()&&fy(m)}u()}};return{done:l,teardown:d,isTornDown:()=>c,installSignalHandlers:()=>{let h=()=>d("signal");process.once("SIGTERM",h),process.once("SIGHUP",h),process.once("SIGINT",h)}}}import{EventEmitter as rJr}from"node:events";import{randomUUID as iJr}from"node:crypto";import{EventEmitter as eJr}from"node:events";var qYr="crtr:managed-provider-cooling";function Idn(t){let e=t?.diagnostics;return Array.isArray(e)&&e.some(n=>n?.type===qYr)}function Eze(t){return typeof t=="string"?t:""}function gp(t,e,n={}){return{kind:t,matchedOn:e,...n}}function Ff(t,e){return e.matchedOn==="text"?{...t,textKind:e.kind,textMatch:e.match,textMatches:e.textMatches}:t}var GYr=[["rate-limit",/rate.?limit|\b429\b|too many requests|usage[ _]limit|usage_not_included|usagelimiterror|insufficient_quota|quota exceeded/i],["protocol",/\b413\b|payload too large|entity too large|request too large|entity\.too\.large|body exceeds/i],["auth",/invalid_grant|refresh token|unauthori[sz]ed|invalid.?api.?key|authentication failed|\b401\b|\b403\b/i],["context-overflow",/context overflow recovery failed/i],["protocol",/websocket.*(?:closed.*\b(?:1002|1003|1007|1008|1009|1010)\b|protocol error|policy violation|unsupported data|invalid (?:frame|payload)|message too big|mandatory extension)/i],["overloaded-only",/lock file is already being held/i],["overloaded",/overloaded|temporarily unavailable/i],["service-unavailable",/service.?unavailable/i],["overloaded-only",/internal server error|api.?error|\b5\d\d\b|capacity|server.{0,3}busy/i],["connection",/connection|econnreset|etimedout|enotfound|econnrefused|network|fetch failed|socket hang|timed? out|timeout|websocket\s+(?:was\s+)?closed|websocket stream closed before response\.completed|websocket\s+error|websocket.*interrupt/i],["socket",/socket/i],["connection-only",/eai_again|epipe|ehostunreach|enetunreach|\bterminated\b|other side closed|premature close/i]];function kdn(t){let e=GYr.flatMap(([r,i])=>{let o=t.match(i);return o?[{kind:r,match:o[0]}]:[]}),n=e[0];return n===void 0?gp("other","none"):{...gp(n.kind,"text",{match:n.match}),textMatches:e}}function Tdn(t){let e=t.retryAfterMs,n=kdn(t.message??""),r=Eze(t.code)||Eze(t.errno);if(/^(ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOENT|ENOTFOUND|EAI_AGAIN|EPIPE|EHOSTUNREACH|ENETUNREACH)$/i.test(r))return Ff(gp("connection","errno",{retryAfterMs:e}),n);if(/^ELOCKED$/i.test(r))return Ff(gp("overloaded","errno",{retryAfterMs:e}),n);let i=typeof t.status=="number"?t.status:void 0;if(i!==void 0){if(i===401||i===403)return Ff(gp("auth","status",{status:i,retryAfterMs:e}),n);if(i===429)return Ff(gp("rate-limit","status",{status:i,retryAfterMs:e}),n);if(i===500||i===502||i===503||i===504)return Ff(gp("transient-http","status",{status:i,retryAfterMs:e}),n);if(i>=500&&i<=599)return Ff(gp("overloaded","status",{status:i,retryAfterMs:e}),n);if(i>=400&&i<=499)return Ff(gp("protocol","status",{status:i,retryAfterMs:e}),n)}let o=typeof t.wsCloseCode=="number"?t.wsCloseCode:void 0;if(o===1008)return Ff(gp("protocol","websocket-close",{retryAfterMs:e}),n);if(o===1006)return Ff(gp("connection","websocket-close",{retryAfterMs:e}),n);if(o===1011){let s=Eze(t.wsCloseReason),a=kdn(s);return/no running broker/i.test(s)||a.kind==="connection"||a.kind==="connection-only"?Ff(gp("connection","websocket-close",{retryAfterMs:e}),n):Ff(gp("other","websocket-close",{retryAfterMs:e}),n)}return e===void 0?n:{...n,retryAfterMs:e}}function pN(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var jYr="crtr:provider-failure";function la(t){return typeof t=="string"&&t.trim()!==""?t.trim():void 0}function sde(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function ade(t){return typeof t=="string"||typeof t=="number"?t:void 0}function hN(t){return pN(t)?t:void 0}function zYr(t){let e=la(t.errorMessage)??la(t.message)??la(t.reason)??la(t.statusText),n={...e===void 0?{}:{message:e},...sde(t.status)===void 0?{}:{status:sde(t.status)},...ade(t.code)===void 0?{}:{code:ade(t.code)},...la(t.errno)===void 0?{}:{errno:la(t.errno)},...la(t.body)===void 0?{}:{body:la(t.body)}};return Object.keys(n).length===0?void 0:n}var VYr=48,KYr=256;function Rdn(t){let e=hN(t),n=hN(e?.headers);if(e===void 0||n===void 0)return;let r={};for(let[i,o]of Object.entries(n)){if(Object.keys(r).length>=VYr)break;typeof o=="string"&&(r[i.toLowerCase()]=o.slice(0,KYr))}return{...la(e.scope)===void 0?{}:{scope:la(e.scope)},...la(e.claim)===void 0?{}:{claim:la(e.claim)},...la(e.account)===void 0?{}:{account:la(e.account)},...la(e.model)===void 0?{}:{model:la(e.model)},headers:r}}function YYr(t){let e=hN(t)?.diagnostics;if(Array.isArray(e))for(let n of e){let r=hN(n);if(r?.type!==jYr)continue;let i=hN(r.details);if(i===void 0)continue;let o=Array.isArray(i.causes)?i.causes.flatMap(s=>{let a=hN(s),c=a===void 0?void 0:zYr(a);return c===void 0?[]:[c]}):void 0;return{...sde(i.status)===void 0?{}:{status:sde(i.status)},...ade(i.code)===void 0?{}:{code:ade(i.code)},...la(i.errno)===void 0?{}:{errno:la(i.errno)},...la(i.body)===void 0?{}:{body:la(i.body)},...o===void 0||o.length===0?{}:{causes:o},...Rdn(i.ratelimit)===void 0?{}:{ratelimit:Rdn(i.ratelimit)}}}}function Mdn(t){return YYr(t)}function JYr(t){switch(t.kind){case"rate-limit":return"rate-limit";case"auth":return"auth";case"protocol":return"protocol";case"context-overflow":return"context-overflow";case"overloaded":case"overloaded-only":case"transient-http":return"overloaded";case"connection":case"connection-only":return"connection";case"socket":case"service-unavailable":case"other":return"other"}}function Pdn(t,e){return e==="auth"||e==="protocol"||e==="context-overflow"?"fatal":t==="pi\u2192provider"?e==="connection"||e==="rate-limit"||e==="overloaded"?"auto":"fatal":"manual"}function XYr(t){if(typeof t=="string")return t;if(!pN(t))return"";let e=[t.message,t.errorMessage,t.reason,t.body,t.statusText];for(let r of e)if(typeof r=="string"&&r!=="")return r;let n=t.error;if(pN(n)){let r=n.message;if(typeof r=="string"&&r!=="")return r;let i=n.reason;if(typeof i=="string"&&i!=="")return i}return""}var ZYr="upstream_model_unavailable";function cde(t,e){if(t==="pi\u2192provider"&&Idn(e))return{kind:"rate-limit",disposition:"auto"};let n=pN(e)?e:{},r=Mdn(e),i=r?.causes??[];if(r?.code===ZYr)return{kind:"connection",disposition:Pdn(t,"connection")};let o=Tdn({code:n.code??r?.code??i.find(a=>a.code!==void 0)?.code,errno:n.errno??r?.errno??i.find(a=>a.errno!==void 0)?.errno,status:n.status??r?.status,wsCloseCode:n.code,wsCloseReason:n.reason,message:[XYr(e),r?.body,...i.flatMap(a=>[a.message,a.body])].filter(a=>typeof a=="string"&&a!=="").join(" ")}),s=JYr(o);return{kind:s,disposition:Pdn(t,s)}}var ty=class extends Error{constructor(n){super(`node ${n} has no running broker \u2014 focus or revive it first`);this.nodeId=n;this.name="BrokerUnavailableError"}nodeId};var mN=class extends eJr{constructor(n,r={}){super();this.nodeId=n;this.options=r}nodeId;options;socket;decoder=new N8(y3e);closeEmitted=!1;redialFaultRecorded=!1;get socketPath(){return DT(this.nodeId)}recordSocketFault(n,r){if(this.options.recordsViewerFaults===!1)return;if(n==="redial"){if(this.redialFaultRecorded)return;this.redialFaultRecorded=!0}let i=cde("viewer\u2194broker",r);d9e(this.nodeId,{link:"viewer\u2194broker",op:n,kind:i.kind,retry:n==="redial"?{disposition:"auto",by:"client"}:{disposition:"manual"},message:r instanceof Error?r.message:String(r)}).catch(o=>{dm({event:"broker.daemon.operation.failed",level:"error",node_id:this.nodeId,error:o,fields:{operation:"viewer_fault_record"}})})}connect(){let n=vme(this.nodeId);this.socket=n,n.on("connect",()=>{this.redialFaultRecorded=!1,this.clearSocketFault(),this.emit("connect")}),n.on("data",r=>this.onData(r)),n.on("error",r=>this.onError(r,"connect")),n.on("close",()=>this.onClose())}redial(n={}){return this.destroy(),this.decoder=new N8(y3e),this.closeEmitted=!1,n.brokerUnavailableIsExpected&&(this.redialFaultRecorded=!1,this.clearSocketFault()),new Promise((r,i)=>{let o=vme(this.nodeId);this.socket=o;let s=!1;o.on("connect",()=>{s||(s=!0,this.redialFaultRecorded=!1,this.clearSocketFault(),this.emit("connect"),r())}),o.on("data",a=>this.onData(a)),o.on("error",a=>{if(s){this.onError(a,"redial");return}s=!0;let c=a.code==="ECONNREFUSED"||a.code==="ENOENT";(!n.brokerUnavailableIsExpected||!c)&&this.recordSocketFault("redial",a);try{o.destroy()}catch{}i(a)}),o.on("close",()=>this.onClose())})}send(n){let r=this.socket;if(!(r===void 0||r.destroyed))try{r.write(ble(n))}catch{}}destroy(){let n=this.socket;if(n!==void 0&&!n.destroyed)try{n.destroy()}catch{}}clearSocketFault(){this.options.recordsViewerFaults!==!1&&p9e(this.nodeId,{link:"viewer\u2194broker"}).catch(n=>{dm({event:"broker.daemon.operation.failed",level:"error",node_id:this.nodeId,error:n,fields:{operation:"viewer_fault_clear"}})})}onData(n){let r;try{r=this.decoder.push(n)}catch(i){let o=i instanceof ZO?`broker sent an oversized frame (${i.message}) \u2014 disconnecting`:`failed to decode a broker frame: ${String(i)}`;this.emitError(new Error(o)),this.destroy();return}for(let i of r)this.emit("frame",i)}onError(n,r){this.recordSocketFault(r,n),n.code==="ECONNREFUSED"||n.code==="ENOENT"?this.emitError(new ty(this.nodeId)):this.emitError(new Error(`view socket error: ${n.message}`))}onClose(){this.closeEmitted||(this.closeEmitted=!0,this.emit("close"))}emitError(n){this.listenerCount("error")>0&&this.emit("error",n)}};XDe();import{EventEmitter as tJr}from"node:events";function nJr(t,e){if("socketPath"in t)return`ws+unix://${t.socketPath}:/v1/nodes/${encodeURIComponent(e)}/attach?revive=0`;let n=new URL(t.previewEndpoint);return n.protocol=n.protocol==="http:"?"ws:":"wss:",n.pathname=`/v1/nodes/${encodeURIComponent(e)}/attach`,n.search="?wakeParked=1",n.hash="",n.toString()}var hT=class extends tJr{constructor(n,r){super();this.nodeId=n;this.target=r}nodeId;target;ws;closeEmitted=!1;get url(){return nJr(this.target,this.nodeId)}dial(){let n=new MI.default(this.url,{..."relayToken"in this.target?{headers:{authorization:`Bearer ${this.target.relayToken}`}}:{},perMessageDeflate:!1});return this.ws=n,n}connect(){let n=this.dial();n.on("open",()=>{this.emit("connect")}),n.on("message",r=>this.onMessage(r)),n.on("error",r=>this.onError(r)),n.on("close",(r,i)=>this.onClose(r,i.toString()))}redial(n){return this.destroy(),this.closeEmitted=!1,new Promise((r,i)=>{let o=this.dial(),s=!1;o.on("open",()=>{s||(s=!0,this.emit("connect"),r())}),o.on("message",a=>this.onMessage(a)),o.on("error",a=>{if(s){this.onError(a);return}s=!0;try{o.terminate()}catch{}i(a)}),o.on("close",(a,c)=>{s&&this.onClose(a,c.toString())})})}send(n){let r=this.ws;if(!(r===void 0||r.readyState!==MI.default.OPEN))try{r.send(JSON.stringify(n))}catch{}}destroy(){let n=this.ws;if(n!==void 0&&n.readyState<=MI.default.OPEN)try{n.close(1e3)}catch{}}onMessage(n){let r;try{r=JSON.parse(n.toString())}catch{return}this.emit("frame",r)}onError(n){this.emitError(new Error(`relay transport error: ${n.message}`))}onClose(n,r){if(this.closeEmitted)return;this.closeEmitted=!0;let i=cde("viewer\u2194broker",{code:n,reason:r});(n===1008||i.kind==="protocol"||n===1011&&(/^no running broker/.test(r)||/^no node /.test(r)))&&this.emitError(new ty(this.nodeId)),this.emit("close")}emitError(n){this.listenerCount("error")>0&&this.emit("error",n)}};var Ddn=1e4;function vze(t){return t===null?!0:t.lifecycle==="resident"&&t.status==="done"&&t.intent==="parked"&&t.final_report==null?!1:t.status==="done"||t.status==="dead"||t.status==="canceled"}var Z8=class extends rJr{constructor(n,r={}){super();this.nodeId=n;this.transport=r.transport??new mN(n),this.transport.on("connect",()=>{this.closeEmitted=!1,this.connected=!0,this.lastTransportError=void 0,this.emit("connect")}),this.transport.on("frame",i=>this.onFrame(i)),this.transport.on("error",i=>{this.lastTransportError=i.message,this.emitError(i)}),this.transport.on("close",()=>this.onClose())}nodeId;transport;closeEmitted=!1;connected=!1;lastTransportError;pending=new Map;request(n){let r=iJr();return new Promise((i,o)=>{if(!this.connected){o(new Error(`cannot issue '${n.type}': no live broker connection`));return}let s=setTimeout(()=>{this.pending.delete(r),o(new Error(`request '${n.type}' timed out after ${Ddn}ms`))},Ddn);typeof s.unref=="function"&&s.unref(),this.pending.set(r,{resolve:i,reject:o,timer:s}),this.send({...n,id:r})})}rejectAllPending(n){for(let{reject:r,timer:i}of this.pending.values())clearTimeout(i),r(new Error(n));this.pending.clear()}connect(){this.transport.connect()}redial(n){return this.transport.redial(n)}send(n){this.transport.send(n)}close(){this.transport.destroy()}onFrame(n){if(n.type==="data"){let r=typeof n.id=="string"?this.pending.get(n.id):void 0;r&&(this.pending.delete(n.id),clearTimeout(r.timer),r.resolve(n));return}if(n.type==="error"&&typeof n.id=="string"&&this.pending.has(n.id)){let r=this.pending.get(n.id);this.pending.delete(n.id),clearTimeout(r.timer),r.reject(new Error(n.message||`request failed: ${n.code}`));return}this.emit("frame",n)}onClose(){this.closeEmitted||(this.closeEmitted=!0,this.connected=!1,this.rejectAllPending(this.lastTransportError??"broker connection closed"),this.emit("close"))}emitError(n){this.listenerCount("error")>0&&this.emit("error",n)}};var oJr=1e3,sJr=3e3;function Bdn(t,e){let{nodeId:n,socket:r,canvasSource:i}=t,o,s=!1,a=e.initialDormant===!0,c=!1,u=!1,l=()=>{},d,p,h=new Promise(b=>{l=b}),m=b=>u?Promise.resolve(!1):new Promise(E=>{let S=_=>{d=void 0,p=void 0,E(_)};d=setTimeout(()=>S(!0),b),p=()=>{d!==void 0&&clearTimeout(d),S(!1)}}),f=()=>{r.send({type:"hello",role:e.role,client_id:e.clientId,term:{cols:process.stdout.columns??80,rows:process.stdout.rows??24}})},g=async()=>{s=!0,e.setNotice("\u21BB node refreshing \u2014 reconnecting\u2026",{sticky:!0});let b=200;try{for(;!u&&!e.isTornDown();){let E;try{E=await i.getRow(n)}catch{E=void 0}if(E!==void 0&&vze(E)){c=E?.status==="done";break}let S=E?.status==="idle"||E?.intent==="idle-release"||E?.lifecycle==="resident"&&E.status==="done"&&E.intent==="parked"&&E.final_report==null,_=S&&!a;a=S,_&&e.onEnterDormancy(),e.setNotice(S?"":"\u21BB node refreshing \u2014 reconnecting\u2026",{sticky:!S});try{if(!await Promise.race([r.redial({brokerUnavailableIsExpected:S}).then(()=>!0),h.then(()=>!1)])||u||e.isTornDown())return;f(),a=!1,e.setNotice("");return}catch{if(!await m(S?sJr:Math.min(b,oJr)))return;b*=2}}}finally{s=!1}!u&&!e.isTornDown()&&e.teardown(c?"node-done":"broker-gone")};return{sendHello:f,startDormant:()=>{s||u||e.isTornDown()||(e.onEnterDormancy(),g())},isDormant:()=>a,lastSocketError:()=>o,install:()=>{r.on("frame",e.onFrame),r.on("error",b=>{o=b.message}),r.on("close",()=>{e.isTornDown()||s||g()})},stop:()=>{u||(u=!0,p?.(),l())}}}function ude(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;try{let e=Object.getPrototypeOf(t);if(e!==Object.prototype&&e!==null||Object.getOwnPropertySymbols(t).length!==0)return!1;let n=Object.getOwnPropertyNames(t).sort();if(n.length!==3||n[0]!=="body"||n[1]!=="commandName"||n[2]!=="kind")return!1;let r=Object.getOwnPropertyDescriptors(t);if(Object.values(r).some(o=>!("value"in o)))return!1;let i=t;return i.kind!=="memory-slash"||typeof i.commandName!="string"||typeof i.body!="string"?!1:(JSON.stringify(t),!0)}catch{return!1}}function aJr(t){let e="",n=0,r=!0,i,o;for(;n<t.length;){if(r&&o===void 0){let a=t.slice(n).match(/^(?: {0,3})(`{3,}|~{3,})/);if(a!==null){let c=a[1][0],u=a[1].length;i===void 0?i={marker:c,length:u}:i.marker===c&&u>=i.length&&(i=void 0)}}if(i===void 0&&o===void 0&&t.startsWith("<!--",n)){let a=t.indexOf("-->",n+4),c=a===-1?t.length:a+3,u=t.indexOf(`
|
|
1743
|
+
`);let m=e.tagPane()??process.env.TMUX_PANE??Vf()?.pane;!o&&m!==void 0&&Ss()&&fy(m)}u()}};return{done:l,teardown:d,isTornDown:()=>c,installSignalHandlers:()=>{let h=()=>d("signal");process.once("SIGTERM",h),process.once("SIGHUP",h),process.once("SIGINT",h)}}}import{EventEmitter as rJr}from"node:events";import{randomUUID as iJr}from"node:crypto";import{EventEmitter as eJr}from"node:events";var qYr="crtr:managed-provider-cooling";function Idn(t){let e=t?.diagnostics;return Array.isArray(e)&&e.some(n=>n?.type===qYr)}function Eze(t){return typeof t=="string"?t:""}function gp(t,e,n={}){return{kind:t,matchedOn:e,...n}}function Ff(t,e){return e.matchedOn==="text"?{...t,textKind:e.kind,textMatch:e.match,textMatches:e.textMatches}:t}var GYr=[["rate-limit",/rate.?limit|\b429\b|too many requests|usage[ _]limit|usage_not_included|usagelimiterror|insufficient_quota|quota exceeded/i],["protocol",/\b413\b|payload too large|entity too large|request too large|entity\.too\.large|body exceeds/i],["auth",/invalid_grant|refresh token|unauthori[sz]ed|invalid.?api.?key|authentication failed|\b401\b|\b403\b/i],["context-overflow",/context overflow recovery failed/i],["protocol",/websocket.*(?:closed.*\b(?:1002|1003|1007|1008|1009|1010)\b|protocol error|policy violation|unsupported data|invalid (?:frame|payload)|message too big|mandatory extension)/i],["overloaded-only",/lock file is already being held/i],["overloaded",/overloaded|temporarily unavailable/i],["service-unavailable",/service.?unavailable/i],["overloaded-only",/internal server error|api.?error|\b5\d\d\b|capacity|server.{0,3}busy/i],["connection",/connection|econnreset|etimedout|enotfound|econnrefused|network|fetch failed|socket hang|timed? out|timeout|websocket\s+(?:was\s+)?closed|websocket stream closed before response\.completed|websocket\s+error|websocket.*interrupt/i],["socket",/socket/i],["connection-only",/eai_again|epipe|ehostunreach|enetunreach|\bterminated\b|other side closed|premature close/i]];function kdn(t){let e=GYr.flatMap(([r,i])=>{let o=t.match(i);return o?[{kind:r,match:o[0]}]:[]}),n=e[0];return n===void 0?gp("other","none"):{...gp(n.kind,"text",{match:n.match}),textMatches:e}}function Tdn(t){let e=t.retryAfterMs,n=kdn(t.message??""),r=Eze(t.code)||Eze(t.errno);if(/^(ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENOENT|ENOTFOUND|EAI_AGAIN|EPIPE|EHOSTUNREACH|ENETUNREACH)$/i.test(r))return Ff(gp("connection","errno",{retryAfterMs:e}),n);if(/^ELOCKED$/i.test(r))return Ff(gp("overloaded","errno",{retryAfterMs:e}),n);let i=typeof t.status=="number"?t.status:void 0;if(i!==void 0){if(i===401||i===403)return Ff(gp("auth","status",{status:i,retryAfterMs:e}),n);if(i===429)return Ff(gp("rate-limit","status",{status:i,retryAfterMs:e}),n);if(i===500||i===502||i===503||i===504)return Ff(gp("transient-http","status",{status:i,retryAfterMs:e}),n);if(i>=500&&i<=599)return Ff(gp("overloaded","status",{status:i,retryAfterMs:e}),n);if(i>=400&&i<=499)return Ff(gp("protocol","status",{status:i,retryAfterMs:e}),n)}let o=typeof t.wsCloseCode=="number"?t.wsCloseCode:void 0;if(o===1008)return Ff(gp("protocol","websocket-close",{retryAfterMs:e}),n);if(o===1006)return Ff(gp("connection","websocket-close",{retryAfterMs:e}),n);if(o===1011){let s=Eze(t.wsCloseReason),a=kdn(s);return/no running broker/i.test(s)||a.kind==="connection"||a.kind==="connection-only"?Ff(gp("connection","websocket-close",{retryAfterMs:e}),n):Ff(gp("other","websocket-close",{retryAfterMs:e}),n)}return e===void 0?n:{...n,retryAfterMs:e}}function pN(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var jYr="crtr:provider-failure";function la(t){return typeof t=="string"&&t.trim()!==""?t.trim():void 0}function sde(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function ade(t){return typeof t=="string"||typeof t=="number"?t:void 0}function hN(t){return pN(t)?t:void 0}function zYr(t){let e=la(t.errorMessage)??la(t.message)??la(t.reason)??la(t.statusText),n={...e===void 0?{}:{message:e},...sde(t.status)===void 0?{}:{status:sde(t.status)},...ade(t.code)===void 0?{}:{code:ade(t.code)},...la(t.errno)===void 0?{}:{errno:la(t.errno)},...la(t.body)===void 0?{}:{body:la(t.body)}};return Object.keys(n).length===0?void 0:n}var VYr=48,KYr=256;function Rdn(t){let e=hN(t),n=hN(e?.headers);if(e===void 0||n===void 0)return;let r={};for(let[i,o]of Object.entries(n)){if(Object.keys(r).length>=VYr)break;typeof o=="string"&&(r[i.toLowerCase()]=o.slice(0,KYr))}return{...la(e.scope)===void 0?{}:{scope:la(e.scope)},...la(e.claim)===void 0?{}:{claim:la(e.claim)},...la(e.account)===void 0?{}:{account:la(e.account)},...la(e.model)===void 0?{}:{model:la(e.model)},headers:r}}function YYr(t){let e=hN(t)?.diagnostics;if(Array.isArray(e))for(let n of e){let r=hN(n);if(r?.type!==jYr)continue;let i=hN(r.details);if(i===void 0)continue;let o=Array.isArray(i.causes)?i.causes.flatMap(s=>{let a=hN(s),c=a===void 0?void 0:zYr(a);return c===void 0?[]:[c]}):void 0;return{...sde(i.status)===void 0?{}:{status:sde(i.status)},...ade(i.code)===void 0?{}:{code:ade(i.code)},...la(i.errno)===void 0?{}:{errno:la(i.errno)},...la(i.body)===void 0?{}:{body:la(i.body)},...o===void 0||o.length===0?{}:{causes:o},...Rdn(i.ratelimit)===void 0?{}:{ratelimit:Rdn(i.ratelimit)}}}}function Mdn(t){return YYr(t)}function JYr(t){switch(t.kind){case"rate-limit":return"rate-limit";case"auth":return"auth";case"protocol":return"protocol";case"context-overflow":return"context-overflow";case"overloaded":case"overloaded-only":case"transient-http":return"overloaded";case"connection":case"connection-only":return"connection";case"socket":case"service-unavailable":case"other":return"other"}}function Pdn(t,e){return e==="auth"||e==="protocol"||e==="context-overflow"?"fatal":t==="pi\u2192provider"?e==="connection"||e==="rate-limit"||e==="overloaded"?"auto":"fatal":"manual"}function XYr(t){if(typeof t=="string")return t;if(!pN(t))return"";let e=[t.message,t.errorMessage,t.reason,t.body,t.statusText];for(let r of e)if(typeof r=="string"&&r!=="")return r;let n=t.error;if(pN(n)){let r=n.message;if(typeof r=="string"&&r!=="")return r;let i=n.reason;if(typeof i=="string"&&i!=="")return i}return""}var ZYr="upstream_model_unavailable";function cde(t,e){if(t==="pi\u2192provider"&&Idn(e))return{kind:"rate-limit",disposition:"auto"};let n=pN(e)?e:{},r=Mdn(e),i=r?.causes??[];if(r?.code===ZYr)return{kind:"connection",disposition:Pdn(t,"connection")};let o=Tdn({code:n.code??r?.code??i.find(a=>a.code!==void 0)?.code,errno:n.errno??r?.errno??i.find(a=>a.errno!==void 0)?.errno,status:n.status??r?.status,wsCloseCode:n.code,wsCloseReason:n.reason,message:[XYr(e),r?.body,...i.flatMap(a=>[a.message,a.body])].filter(a=>typeof a=="string"&&a!=="").join(" ")}),s=JYr(o);return{kind:s,disposition:Pdn(t,s)}}var ty=class extends Error{constructor(n){super(`node ${n} has no running broker \u2014 focus or revive it first`);this.nodeId=n;this.name="BrokerUnavailableError"}nodeId};var mN=class extends eJr{constructor(n,r={}){super();this.nodeId=n;this.options=r}nodeId;options;socket;decoder=new N8(y3e);closeEmitted=!1;redialFaultRecorded=!1;get socketPath(){return DT(this.nodeId)}recordSocketFault(n,r){if(this.options.recordsViewerFaults===!1)return;if(n==="redial"){if(this.redialFaultRecorded)return;this.redialFaultRecorded=!0}let i=cde("viewer\u2194broker",r);d9e(this.nodeId,{link:"viewer\u2194broker",op:n,kind:i.kind,retry:n==="redial"?{disposition:"auto",by:"client"}:{disposition:"manual"},message:r instanceof Error?r.message:String(r)}).catch(o=>{dm({event:"broker.daemon.operation.failed",level:"error",node_id:this.nodeId,error:o,fields:{operation:"viewer_fault_record"}})})}connect(){let n=vme(this.nodeId);this.socket=n,n.on("connect",()=>{this.redialFaultRecorded=!1,this.clearSocketFault(),this.emit("connect")}),n.on("data",r=>this.onData(r)),n.on("error",r=>this.onError(r,"connect")),n.on("close",()=>this.onClose())}redial(n={}){return this.destroy(),this.decoder=new N8(y3e),this.closeEmitted=!1,n.brokerUnavailableIsExpected&&(this.redialFaultRecorded=!1,this.clearSocketFault()),new Promise((r,i)=>{let o=vme(this.nodeId);this.socket=o;let s=!1;o.on("connect",()=>{s||(s=!0,this.redialFaultRecorded=!1,this.clearSocketFault(),this.emit("connect"),r())}),o.on("data",a=>this.onData(a)),o.on("error",a=>{if(s){this.onError(a,"redial");return}s=!0;let c=a.code==="ECONNREFUSED"||a.code==="ENOENT";(!n.brokerUnavailableIsExpected||!c)&&this.recordSocketFault("redial",a);try{o.destroy()}catch{}i(a)}),o.on("close",()=>this.onClose())})}send(n){let r=this.socket;if(!(r===void 0||r.destroyed))try{r.write(ble(n))}catch{}}destroy(){let n=this.socket;if(n!==void 0&&!n.destroyed)try{n.destroy()}catch{}}clearSocketFault(){this.options.recordsViewerFaults!==!1&&p9e(this.nodeId,{link:"viewer\u2194broker"}).catch(n=>{dm({event:"broker.daemon.operation.failed",level:"error",node_id:this.nodeId,error:n,fields:{operation:"viewer_fault_clear"}})})}onData(n){let r;try{r=this.decoder.push(n)}catch(i){let o=i instanceof ZO?`broker sent an oversized frame (${i.message}) \u2014 disconnecting`:`failed to decode a broker frame: ${String(i)}`;this.emitError(new Error(o)),this.destroy();return}for(let i of r)this.emit("frame",i)}onError(n,r){this.recordSocketFault(r,n),n.code==="ECONNREFUSED"||n.code==="ENOENT"?this.emitError(new ty(this.nodeId)):this.emitError(new Error(`view socket error: ${n.message}`))}onClose(){this.closeEmitted||(this.closeEmitted=!0,this.emit("close"))}emitError(n){this.listenerCount("error")>0&&this.emit("error",n)}};XDe();import{EventEmitter as tJr}from"node:events";function nJr(t,e){if("socketPath"in t)return`ws+unix://${t.socketPath}:/v1/nodes/${encodeURIComponent(e)}/attach?revive=0`;let n=new URL(t.previewEndpoint);return n.protocol=n.protocol==="http:"?"ws:":"wss:",n.pathname=`/v1/nodes/${encodeURIComponent(e)}/attach`,n.search="?wakeParked=1",n.hash="",n.toString()}var hT=class extends tJr{constructor(n,r){super();this.nodeId=n;this.target=r}nodeId;target;ws;closeEmitted=!1;get url(){return nJr(this.target,this.nodeId)}dial(){let n=new MI.default(this.url,{..."relayToken"in this.target?{headers:{authorization:`Bearer ${this.target.relayToken}`}}:{},perMessageDeflate:!1});return this.ws=n,n}connect(){let n=this.dial();n.on("open",()=>{this.emit("connect")}),n.on("message",r=>this.onMessage(r)),n.on("error",r=>this.onError(r)),n.on("close",(r,i)=>this.onClose(r,i.toString()))}redial(n){return this.destroy(),this.closeEmitted=!1,new Promise((r,i)=>{let o=this.dial(),s=!1;o.on("open",()=>{s||(s=!0,this.emit("connect"),r())}),o.on("message",a=>this.onMessage(a)),o.on("error",a=>{if(s){this.onError(a);return}s=!0;try{o.terminate()}catch{}i(a)}),o.on("close",(a,c)=>{s&&this.onClose(a,c.toString())})})}send(n){let r=this.ws;if(!(r===void 0||r.readyState!==MI.default.OPEN))try{r.send(JSON.stringify(n))}catch{}}destroy(){let n=this.ws;if(n!==void 0&&n.readyState<=MI.default.OPEN)try{n.close(1e3)}catch{}}onMessage(n){let r;try{r=JSON.parse(n.toString())}catch{return}this.emit("frame",r)}onError(n){this.emitError(new Error(`relay transport error: ${n.message}`))}onClose(n,r){if(this.closeEmitted)return;this.closeEmitted=!0;let i=cde("viewer\u2194broker",{code:n,reason:r});(n===1008||i.kind==="protocol"||n===1011&&(/^no running broker/.test(r)||/^no node /.test(r)))&&this.emitError(new ty(this.nodeId)),this.emit("close")}emitError(n){this.listenerCount("error")>0&&this.emit("error",n)}};var Ddn=1e4;function vze(t){return t===null?!0:t.lifecycle==="resident"&&t.status==="done"&&t.intent==="parked"&&t.final_report==null?!1:t.status==="done"||t.status==="dead"||t.status==="canceled"}var Z8=class extends rJr{constructor(n,r={}){super();this.nodeId=n;this.transport=r.transport??new mN(n),this.transport.on("connect",()=>{this.closeEmitted=!1,this.connected=!0,this.lastTransportError=void 0,this.emit("connect")}),this.transport.on("frame",i=>this.onFrame(i)),this.transport.on("error",i=>{this.lastTransportError=i.message,this.emitError(i)}),this.transport.on("close",()=>this.onClose())}nodeId;transport;closeEmitted=!1;connected=!1;lastTransportError;pending=new Map;request(n){let r=iJr();return new Promise((i,o)=>{if(!this.connected){o(new Error(`cannot issue '${n.type}': no live broker connection`));return}let s=setTimeout(()=>{this.pending.delete(r),o(new Error(`request '${n.type}' timed out after ${Ddn}ms`))},Ddn);typeof s.unref=="function"&&s.unref(),this.pending.set(r,{resolve:i,reject:o,timer:s}),this.send({...n,id:r})})}rejectAllPending(n){for(let{reject:r,timer:i}of this.pending.values())clearTimeout(i),r(new Error(n));this.pending.clear()}connect(){this.transport.connect()}redial(n){return this.transport.redial(n)}send(n){this.transport.send(n)}close(){this.transport.destroy()}onFrame(n){if(n.type==="data"){let r=typeof n.id=="string"?this.pending.get(n.id):void 0;r&&(this.pending.delete(n.id),clearTimeout(r.timer),r.resolve(n));return}if(n.type==="error"&&typeof n.id=="string"&&this.pending.has(n.id)){let r=this.pending.get(n.id);this.pending.delete(n.id),clearTimeout(r.timer),r.reject(new Error(n.message||`request failed: ${n.code}`));return}this.emit("frame",n)}onClose(){this.closeEmitted||(this.closeEmitted=!0,this.connected=!1,this.rejectAllPending(this.lastTransportError??"broker connection closed"),this.emit("close"))}emitError(n){this.listenerCount("error")>0&&this.emit("error",n)}};var oJr=1e3,sJr=3e3;function Bdn(t,e){let{nodeId:n,socket:r,canvasSource:i}=t,o,s=!1,a=e.initialDormant===!0,c=!1,u=!1,l=()=>{},d,p,h=new Promise(b=>{l=b}),m=b=>u?Promise.resolve(!1):new Promise(E=>{let S=_=>{d=void 0,p=void 0,E(_)};d=setTimeout(()=>S(!0),b),p=()=>{d!==void 0&&clearTimeout(d),S(!1)}}),f=()=>{r.send({type:"hello",role:e.role,client_id:e.clientId,term:{cols:process.stdout.columns??80,rows:process.stdout.rows??24}})},g=async()=>{s=!0,e.setNotice("\u21BB node refreshing \u2014 reconnecting\u2026",{sticky:!0});let b=200;try{for(;!u&&!e.isTornDown();){let E;try{E=await i.getRow(n)}catch{E=void 0}if(E!==void 0&&vze(E)){c=E?.status==="done";break}let S=E?.status==="idle"||E?.intent==="idle-release"||E?.lifecycle==="resident"&&E.status==="done"&&E.intent==="parked"&&E.final_report==null,_=S&&!a;a=S,_&&e.onEnterDormancy(),e.setNotice(S?"":"\u21BB node refreshing \u2014 reconnecting\u2026",{sticky:!S});try{if(!await Promise.race([r.redial({brokerUnavailableIsExpected:S}).then(()=>!0),h.then(()=>!1)])||u||e.isTornDown())return;f(),a=!1,e.setNotice("");return}catch{if(!await m(S?sJr:Math.min(b,oJr)))return;b*=2}}}finally{s=!1}!u&&!e.isTornDown()&&e.teardown(c?"node-done":"broker-gone")};return{sendHello:f,startDormant:()=>{s||u||e.isTornDown()||(e.onEnterDormancy(),g())},isDormant:()=>a,lastSocketError:()=>o,install:async()=>{r.on("frame",e.onFrame),r.on("error",b=>{o=b.message}),r.on("close",()=>{e.isTornDown()||s||g()})},stop:()=>{u||(u=!0,p?.(),l())}}}function ude(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;try{let e=Object.getPrototypeOf(t);if(e!==Object.prototype&&e!==null||Object.getOwnPropertySymbols(t).length!==0)return!1;let n=Object.getOwnPropertyNames(t).sort();if(n.length!==3||n[0]!=="body"||n[1]!=="commandName"||n[2]!=="kind")return!1;let r=Object.getOwnPropertyDescriptors(t);if(Object.values(r).some(o=>!("value"in o)))return!1;let i=t;return i.kind!=="memory-slash"||typeof i.commandName!="string"||typeof i.body!="string"?!1:(JSON.stringify(t),!0)}catch{return!1}}function aJr(t){let e="",n=0,r=!0,i,o;for(;n<t.length;){if(r&&o===void 0){let a=t.slice(n).match(/^(?: {0,3})(`{3,}|~{3,})/);if(a!==null){let c=a[1][0],u=a[1].length;i===void 0?i={marker:c,length:u}:i.marker===c&&u>=i.length&&(i=void 0)}}if(i===void 0&&o===void 0&&t.startsWith("<!--",n)){let a=t.indexOf("-->",n+4),c=a===-1?t.length:a+3,u=t.indexOf(`
|
|
1744
1744
|
`,c),l=t.lastIndexOf(`
|
|
1745
1745
|
`,n-1)+1,d=t.slice(l,n),p=t.slice(c,u===-1?t.length:u);if(d.trim()===""&&p.trim()===""){d.length>0&&(e=e.slice(0,-d.length)),n=u===-1?t.length:u+1,r=!0;continue}let h=t.slice(n,c);r=h.endsWith(`
|
|
1746
1746
|
`),n+=h.length;continue}if(i===void 0&&t[n]==="`"){let a=n;for(;t[a]==="`";)a++;let c=a-n;o===void 0?o=c:o===c&&(o=void 0),e+=t.slice(n,a),r=!1,n=a;continue}let s=t[n];e+=s,r=s===`
|
|
@@ -1751,7 +1751,7 @@ Follow the instructions below exactly as written \u2014 every part, including th
|
|
|
1751
1751
|
${r}`}function Odn(t){try{let e=JSON.parse(t);return Array.isArray(e)?e.flatMap(n=>{if(typeof n!="object"||n===null||Array.isArray(n))return[];let r=n;return typeof r.name!="string"||typeof r.description!="string"||typeof r.source!="string"?[]:r.source!=="builtin"&&r.source!=="command"&&r.source!=="template"?[]:r.template!==void 0&&typeof r.template!="string"?[]:r.expansion!==void 0&&!ude(r.expansion)?[]:[{name:r.name,description:r.description,source:r.source,...typeof r.template=="string"?{template:r.template}:{},...ude(r.expansion)?{expansion:r.expansion}:{}}]}):[]}catch{return[]}}function cJr(t){let e=[],n="",r=null;for(let i of t)r!==null?i===r?r=null:n+=i:i==='"'||i==="'"?r=i:/\s/.test(i)?n!==""&&(e.push(n),n=""):n+=i;return n!==""&&e.push(n),e}function uJr(t,e){let n=e.join(" ");return t.replace(/\$\{(\d+):-([^}]*)\}|\$\{@:(\d+)(?::(\d+))?\}|\$(ARGUMENTS|@|\d+)/g,(r,i,o,s,a,c)=>{if(i!==void 0)return e[Number.parseInt(i,10)-1]||o||"";if(s!==void 0){let u=Math.max(0,Number.parseInt(s,10)-1);return a!==void 0?e.slice(u,u+Number.parseInt(a,10)).join(" "):e.slice(u).join(" ")}return c==="ARGUMENTS"||c==="@"?n:e[Number.parseInt(c||"0",10)-1]??""})}function Ndn(t,e){let n=t.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(n===null)return;let r=n[1];if(e.some(c=>c.source==="builtin"&&c.name===r))return;let i=t.indexOf(" "),o=i===-1?t.slice(1):t.slice(1,i),s=e.find(c=>c.source==="command"&&c.name===o);if(s!==void 0){if(s.expansion===void 0||!ude(s.expansion))return;let c=i===-1?"":t.slice(i+1);return{name:s.name,invocation:t,content:Ldn(s.expansion,c)}}let a=e.find(c=>c.source==="template"&&c.name===r);if(typeof a?.template=="string")return{name:a.name,invocation:t,content:uJr(a.template,cJr(n[2]??""))}}var lJr="CRTR_TIMING",$dn="CRTR_TIMING_T0";function dJr(){return performance.timeOrigin+performance.now()}var Fdn=(()=>{let t=process.env[lJr];return t!==void 0&&t!==""&&t!=="0"&&t.toLowerCase()!=="false"})(),pJr=(()=>{if(!Fdn)return 0;let t=Number(process.env[$dn]);if(Number.isFinite(t)&&t>0)return t;let e=performance.timeOrigin;return process.env[$dn]=String(e),e})(),hJr=(()=>{let t=process.env.CRTR_TIMING_PROC;return t!==void 0&&t!==""?t:process.argv[2]==="surface"&&process.argv[3]==="attach"?"viewer":"cli"})(),Sze=0;function mT(t,e){if(!Fdn)return;let n=dJr(),r=n-pJr,i=Sze===0?r:n-Sze;Sze=n;let o=performance.now(),s=e===void 0?"":" "+Object.entries(e).map(([u,l])=>`${u}=${String(l)}`).join(" "),a=process.env.CRTR_TIMING_PROC??hJr,c=u=>u.toFixed(1).padStart(8);process.stderr.write(`[timing] +${c(r)}ms \u0394${c(i)}ms up=${c(o)}ms t=${n.toFixed(1)} ${a}/${process.pid} ${t}${s}
|
|
1752
1752
|
`)}function Udn(t,e){let{socket:n}=t,r=()=>{n.send({type:"get_commands"}),e.resetMemoryRefs()},i=a=>{if(a.for==="get_commands"&&a.ok&&a.detail){try{e.setCommands(Odn(a.detail))}catch{}return}if(a.for==="navigate_tree"&&a.ok){a.detail&&e.setEditorText(a.detail);return}if(a.for==="share"){a.ok&&a.detail?(e.setNotice(`Shared: ${a.detail}`),A3e(a.detail)):a.ok||e.setNotice(`share failed: ${a.detail??"unknown error"}`);return}if(a.for==="clone"&&!a.ok){e.setNotice(`clone failed: ${a.detail??"unknown error"}`);return}if(!a.ok){e.setNotice(`command failed: ${a.for}${a.detail?` \u2014 ${a.detail}`:""}`);return}a.for==="reload"&&(e.reloadBindings(),e.setCommands(),r(),e.setNotice("Reloaded keybindings, extensions, skills, prompts, and themes"))},o=a=>{e.chat.handleEvent(a),a.type==="session_info_changed"?e.refreshNodeIdentity():a.type==="thinking_level_changed"?e.setNotice(e.modelThinkingLabel()??`Thinking level: ${a.level}`):(a.type==="tool_execution_start"||a.type==="tool_execution_end")&&e.renderFooter()},s=!1;return a=>{switch(e.foldState(a),a.type){case"welcome":{s||(s=!0,mT("viewer.welcome")),e.chat.applySnapshot(a.snapshot),e.refreshNodeIdentity(),r(),a.pending_dialog!=null&&e.attachDialog(a.pending_dialog),e.onWelcome?.();break}case"tool_group_summary":e.chat.applyToolGroupSummary(a.key,a.summary);break;case"turn_reply":e.chat.applyTurnReply(a.key,a.reply);break;case"working_activity":e.chat.setWorkingActivity(a.activity);break;case"model_changed":{let c=e.modelThinkingLabel();c&&e.setNotice(c);break}case"error":a.code==="read_only"?e.setNotice("read-only"):e.chat.showError(a.message);break;case"node_named":break;case"ack":i(a);break;case"extension_ui_request":a.method!=="setStatus"&&a.method!=="setWidget"&&a.method!=="setTitle"&&e.attachDialog(a);break;case"extension_ui_dismiss":e.dismissDialog(a.id);break;case"bash_start":e.chat.bashStart(a.command,a.excludeFromContext);break;case"bash_output":e.chat.bashOutput(a.chunk);break;case"bash_end":e.chat.bashEnd(a);break;default:o(a);break}}}var mJr=1e3;function Qdn(t,e){let{tui:n,editor:r}=t,i=0,o={"crtr.attach.detach":e.detach,"crtr.attach.clear-or-detach":()=>{let s=Date.now();if(s-i<mJr){i=0,e.cancelTurn();return}i=s,r.setText(""),e.setNotice(`Editor cleared \u2014 press ${e.detachHint()} again to cancel the agent`),n.requestRender()},"crtr.attach.graph.toggle":e.toggleGraph,"crtr.attach.help.toggle":e.toggleHelp,"crtr.attach.inbox.toggle":e.toggleInbox,"crtr.attach.inbox-strip":e.toggleInboxStrip,"crtr.attach.model-ladder.next":()=>e.cycleModelLadder("forward"),"crtr.attach.model-ladder.previous":()=>e.cycleModelLadder("backward"),"crtr.attach.command.inspect":e.inspectLoadedCommand,"crtr.attach.file-review":e.openFileReview,"crtr.attach.profile-files":e.openProfileFiles,"crtr.attach.search":e.openSearch,"crtr.attach.whip":e.whip};return n.addInputListener(s=>{if(s.includes("\x1B[I")||s.includes("\x1B[O")){e.setPaneFocused(s.lastIndexOf("\x1B[I")>s.lastIndexOf("\x1B[O")),n.requestRender();let c=s.replaceAll("\x1B[I","").replaceAll("\x1B[O","");return c.length>0?{data:c}:{consume:!0}}let a=ame(s);if(a!==void 0)return m3e(a.actionId,o),a.remaining.length>0?{data:a.remaining}:{consume:!0};if(!e.hasExclusiveSurface())return e.panelHandleKey(s)?{consume:!0}:e.searchHandleKey(s)?{consume:!0}:r.focused&&Jan(e.bindings(),s,e.viewportActions())?{consume:!0}:e.stripHandleKey(s)?{consume:!0}:e.rosterHandleKey(s)?{consume:!0}:Yan(e.bindings(),s,o)?{consume:!0}:void 0})}import{spawnSync as fJr}from"node:child_process";var gJr="\x1B[?1002h\x1B[?1006h",Wdn="\x1B[?1002l\x1B[?1006l",Hdn=3;function AJr(){if(!Ss())return!1;let t=fJr("tmux",["show-options","-gv","mouse"],{encoding:"utf8"});return t.status===0&&t.stdout?.trim()==="on"}function qdn(t,e){let n=e==="on"||e==="tmux"&&AJr(),r=()=>{t(n?gJr:Wdn)},i=()=>{n=!1;try{t(Wdn)}catch{}};return process.once("exit",i),{enabled:()=>n,toggle:()=>(n=!n,r(),n),reassert:r,disable:i,install:(o,s)=>o.addInputListener(a=>{let c=!1,l=a.replace(/\x1b\[<(\d+);(\d+);(\d+)([Mm])/g,(d,p,h,m,f)=>{c=!0;let g=Number(p),y=g&-29;return y===64?s.onWheel("up",Hdn,Number(h)):y===65?s.onWheel("down",Hdn,Number(h)):y===32&&f==="M"?s.onPrimaryDrag(Number(h),Number(m)):y===0&&f==="m"?s.onPrimaryRelease(Number(h),Number(m)):g===0&&f==="M"&&s.onPrimaryPress(Number(h),Number(m)),""}).replace(/\x1b\[M[\s\S]{3}/g,()=>(c=!0,""));if(c)return l.length>0?{data:l}:{consume:!0}})}}function yJr(t,e){return t.row<e.row||t.row===e.row&&t.column<=e.column}function Gdn(t,e,n){let[r,i]=yJr(t,e)?[t,e]:[e,t],o=[];for(let s=r.row;s<=i.row;s++){let a=s===r.row?r.column-1:0,c=s===i.row?i.column:n;c>a&&o.push({row:s,from:a,to:c})}return o}function jdn(t){let e,n,r=()=>e!==void 0&&n!==void 0?{anchor:e,head:n}:void 0,i=()=>{let o=r();if(!o)return"";let s=t.frame(),a=Gdn(o.anchor,o.head,t.width()).map(c=>Fan(s[c.row-1]??"",c.from,c.to).trimEnd());for(;a.length>0&&a[a.length-1]==="";)a.pop();return a.join(`
|
|
1753
1753
|
`)};return{begin(o,s){e={row:s,column:o},n=void 0},extend(o,s){return e===void 0||n!==void 0&&n.row===s&&n.column===o?!1:(n={row:s,column:o},!0)},release(){let o=e;if(o===void 0)return;if(n===void 0)return e=void 0,{kind:"click",column:o.column,row:o.row};let s=i();if(s==="")return e=void 0,n=void 0,{kind:"selection",notice:"Nothing to copy \u2014 selection is empty"};let{system:a,tmux:c}=xle(s),u=a&&c?"clipboard + tmux buffer":a?"clipboard":c?"tmux buffer":void 0,l=s.split(`
|
|
1754
|
-
`).length;return{kind:"selection",notice:u===void 0?"Copy failed \u2014 no clipboard tool found":`Copied selection (${l} ${l===1?"line":"lines"}) \u2014 ${u}`}},clear(){let o=n!==void 0;return e=void 0,n=void 0,o},active(){return n!==void 0},apply(o){let s=r();if(!s)return o.slice();let a=t.width(),c=o.slice();for(let u of Gdn(s.anchor,s.head,a)){let l=u.row-1;l<0||l>=c.length||(c[l]=Uan(c[l],u.from,u.to,a))}return c}}}import{existsSync as xJr}from"node:fs";var zdn="\x1B_crtr-file-open;",Vdn="\x1B\\";function Kdn(t){let e=t.indexOf(zdn);if(e===-1)return;let n=e+zdn.length,r=t.indexOf(Vdn,n);return r===-1?void 0:{file:wJr(t.slice(n,r)),remaining:t.slice(0,e)+t.slice(r+Vdn.length)}}function wJr(t){let e=t.startsWith("'")?bJr(t):EJr(t);return e!==void 0&&e.startsWith("/")&&!/[\x00-\x1f\x7f]/.test(e)?e:void 0}function bJr(t){let e="",n=1;for(;;){let r=t.indexOf("'",n);if(r===-1)return;if(e+=t.slice(n,r),n=r+1,n===t.length)return e;if(t.slice(n,n+3)!=="\\''")return;e+="'",n+=3}}function EJr(t){let e="";for(let n=0;n<t.length;n++){if(t[n]!=="\\"){e+=t[n];continue}let r=t[++n];if(r===void 0)return;e+=r}return e}function Ydn(t){if(!xJr(t.file))return"missing";if(!h7e())return"no_nvim";let e=`crtr surface attach to ${un(t.nodeId)}${t.observer?" --observer":""}`,n=`${MT("edit",[t.file])} || :; exec ${e}`;return t.beforeRespawn(),bme({pane:t.pane,cwd:t.cwd,env:p$(),command:n})?"opened":"failed"}function Jdn(t){let e=new Map,n=!1,r=!1,i;t.remote||t.fetchSecret().then(a=>{i=a,X5e(),r||t.refresh()},t.onSecretError);let o=()=>{n||(n=!0,t.canvasSource.listNodes().then(a=>{for(let c of a)e.set(c.node_id,c.name);X5e(),r||t.refresh()},()=>{n=!1}))},s={selfNodeId:t.selfNodeId,nodeName:a=>{let c=e.get(a);return c===void 0&&o(),c},urlFor:a=>t.remote||i===void 0?void 0:`http://127.0.0.1:${t.port}/r/${a.split("/").map(encodeURIComponent).join("/")}?t=${i}`};return Z5e(s),{dispose(){r=!0,Z5e(void 0)}}}et();import{execFile as vJr}from"node:child_process";function Ize(t){return t==="orchestrator"?"\uF0E8":"\uF007"}function Xdn(t){let e=(t.description??"").trim(),r=[t.name&&t.name!==t.kind?t.name:"",e].filter(i=>i!=="").join(" ");return r!==""?r:t.name}function Zdn(t){return`${Ize(t.mode)} ${t.kind}`}var SJr=.72,CJr={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},_Jr=[["crtr.graph.dismiss","dismiss"],["crtr.graph.focus","focus"],["crtr.graph.revive","revive"],["crtr.graph.close-subtree","close"],["crtr.graph.focus-manager","manager"]],IJr=[["crtr.graph.dismiss","dismiss"]],kJr=[["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"]],TJr=[...["active","idle","done","dead","canceled"].map(t=>[oT(t,{}),t]),[oT("active",{streaming:!0}),"live"],[oT("active",{frozen:!0}),"frozen"],[oT("active",{hanging:{kind:"wedged"}}),"fault"]].map(([t,e])=>`${fp}${t.color}m${t.glyph}${Fr} ${Oc}${e}${Fr}`).join(" ");function RJr(t){return{node_id:t.node_id,name:t.name,kind:t.kind,description:t.description??void 0,cycles:t.cycles??void 0,status:t.status,frozen_at:t.frozen_at,pi_pid:t.pi_pid,telemetry_context_tokens:t.telemetry_context_tokens,telemetry_last_activity:t.telemetry_last_activity,fault:t.fault??null,streaming:t.streaming}}var lde=class{constructor(e,n,r,i,o,s,a="controller",c=()=>{},u=()=>{}){this.tui=e;this.self=n;this.getAsks=r;this.palette=i;this.bindings=o;this.source=s;this.role=a;this.onRefreshFailure=c;this.onNotice=u;this.remote=s instanceof wv}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;setBindings(e){this.bindings=e,this.handle!==void 0&&this.tui.requestRender()}matches(e,n){return iS(this.bindings,e,n,(r,i)=>nt(r,i))}hint(e){return e.flatMap(([n,r])=>this.bindings.gestures(n).length===0?[]:[`${$s(this.bindings,n)} ${r}`])}fitHints(e,n){let i=[],o=0;for(let s of this.hint(e)){let a=(i.length===0?0:3)+yd(s);if(o+a>n)break;i.push(s),o+=a}return i.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,CJr),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;let e=++this.snapshotSeq;this.buildSnapshot().then(n=>{e===this.snapshotSeq&&(this.snapshot=n,this.tui.requestRender())}).catch(n=>{this.onRefreshFailure(n),this.tui.requestRender()})}invalidate(){this.refresh()}async fetchInput(){if(this.remote){let i=await this.source.listNodes().catch(()=>[]);return{nodes:new Map(i.map(o=>[o.node_id,o])),subscriptions:async o=>(await this.source.subscriptionsOf(o)).map(s=>s.node_id),subscribers:async o=>(await this.source.subscribersOf(o)).map(s=>s.node_id),focused:new Set}}let e=await Ht().canvasGraph(),n=new Map,r=new Map;for(let i of e.edges){let o=n.get(i.from_id);o===void 0?n.set(i.from_id,[i.to_id]):o.push(i.to_id);let s=r.get(i.to_id);s===void 0?r.set(i.to_id,[i.from_id]):s.push(i.from_id)}return{nodes:new Map(e.nodes.map(i=>[i.node_id,RJr(i)])),subscriptions:i=>Promise.resolve(n.get(i)??[]),subscribers:i=>Promise.resolve(r.get(i)??[]),focused:new Set(e.focused_node_ids)}}async buildSnapshot(){let e=await this.fetchInput(),{nodes:n,focused:r}=e,i=new Map,o=new Map,s=new Map,a=new Map,c=async y=>{let b=i.get(y);if(b!==void 0)return b;let E;try{E=await e.subscriptions(y)}catch{E=[]}let S=E.filter(_=>n.get(_)?.kind!=="human");return i.set(y,S),S},u=async y=>{if(s.has(y))return s.get(y);let b;try{b=(await e.subscribers(y))[0]}catch{b=void 0}return s.set(y,b),b},l=async()=>{let y=this.self,b=new Set([y]);for(;;){let E=await u(y);if(E===void 0||b.has(E))break;b.add(E),y=E}return y},d=async y=>{let b=o.get(y);if(b!==void 0)return b;let E=[...await c(y)];return E.sort((S,_)=>$3e(n.get(S)?.status)-$3e(n.get(_)?.status)),o.set(y,E),E},p=new Set,h=new Set,m=async y=>{let b=n.get(y)?.status==="active";if(h.has(y))return{active:b?1:0,reveal:b||y===this.self};h.add(y);let E=0,S=!1;for(let _ of await c(y)){let I=await m(_);E+=I.active,I.reveal&&(S=!0)}return a.set(y,E),S&&p.add(y),{active:E+(b?1:0),reveal:S||b||y===this.self}},f=await l();await m(f),await Promise.all([...i.keys()].map(y=>d(y)));let g={root:f,rows:[],autoExpanded:p,activeBelow:a,nodes:n,childIds:i,sortedChildIds:o,managerOf:s,focused:r};return g.rows=this.projectRows(g),g}projectRows(e){let n=[],r=new Set,i=[{id:e.root,prefix:"",isRoot:!0,isLast:!0}];for(;i.length>0;){let{id:o,prefix:s,isRoot:a,isLast:c}=i.pop(),u=a?"":c?"\u2514\u2500 ":"\u251C\u2500 ";if(r.has(o)){n.push({id:o,hasKids:!1,isSelf:o===this.self,branch:s+u,cycle:!0,collapsed:!1});continue}r.add(o);let l=e.sortedChildIds.get(o)??[],d=this.folds.userExpanded.has(o)?!1:this.folds.userCollapsed.has(o)?!0:!e.autoExpanded.has(o);if(n.push({id:o,hasKids:l.length>0,isSelf:o===this.self,branch:s+u,cycle:!1,collapsed:d}),d)continue;let p=a?"":s+(c?" ":"\u2502 ");for(let h=l.length-1;h>=0;h--)i.push({id:l[h],prefix:p,isRoot:!1,isLast:h===l.length-1})}return n}repaintFolds(){this.snapshot!==void 0&&(this.snapshot.rows=this.projectRows(this.snapshot)),this.tui.requestRender()}renderSnapshotRow(e,n,r,i){let o=(_,I)=>r?gx(_,rm(),_v):I?gx(_,rm(),zan):fx(_);if(n.cycle){let _=`${n.branch} ${Oc}\u21BA ${Ale(n.id)}${Fr}`;return o(_,!1)}let s=e.nodes.get(n.id)??null,a=hle(s),c=aT(s,n.id),u=n.isSelf?`${L8}${c}${Fr}`:c,l=`${Oc}${s?.kind??""}${Fr}`,d=`${Oc}${mle(s,this.remote)}${Fr}`,p=n.hasKids&&n.collapsed,h=!r&&p?`${Oc}\u25B8${Fr} `:" ",m=gle(s),f=e.childIds.get(n.id)?.length??0,g=s!==null&&f>0?` ${Oc}\u2933${f}${Fr}`:"",y=s!==null&&s.status!=="active"&&(e.activeBelow.get(s.node_id)??0)>0?` ${ple}\u21E3${e.activeBelow.get(s.node_id)??0}${Fr}`:"",b=s?.fault??null,E=b!==null?` \xB7 ${Gan(b)}`:"",S=`${n.branch}${h}${a} ${u} ${l} ${d}${m}${g}${y}${yle(n.id,i)}${fle(s,this.remote)}${E}`;return o(S,Kan(n.id,s,e.focused,this.remote))}render(e){let n=this.getAsks(),r=this.snapshot?.rows??[],i=r.findIndex(E=>E.id===this.cursorId);i<0&&(i=r.findIndex(E=>E.id===this.self),i<0&&(i=0)),this.cursorId=r[i]?.id??this.self;let o=process.stdout.rows??jan,s=Math.max(3,Math.min(Math.floor(o*SJr),o-2)),a=Math.min(s-2,1+Math.max(1,r.length)),c=a-1,u=c>=3,l=c;for(let E=0;c>0&&E<4;E++){i<this.scrollTop&&(this.scrollTop=i),i>=this.scrollTop+l&&(this.scrollTop=i-l+1),this.scrollTop=Math.max(0,Math.min(this.scrollTop,Math.max(0,r.length-l)));let S=c-(u&&this.scrollTop>0?1:0)-(u&&this.scrollTop+l<r.length?1:0);if(S===l)break;l=Math.max(1,S)}let d=Math.min(r.length,this.scrollTop+l),p=[];u&&this.scrollTop>0&&p.push(`${Oc} \u2191 ${this.scrollTop} more${Fr}`);for(let E=this.scrollTop;E<d;E++){let S=this.snapshot;p.push(S!==void 0?this.renderSnapshotRow(S,r[E],E===i,n):"")}for(u&&d<r.length&&p.push(`${Oc} \u2193 ${r.length-d} more${Fr}`),p.unshift(TJr);p.length<a;)p.push("");let h=r.length>0?`${L8}\u2317 canvas graph${Fr} ${Oc}(${i+1}/${r.length})${Fr}`:`${L8}\u2317 canvas graph${Fr} ${Oc}(loading)${Fr}`,m=this.pendingConfirm!==void 0?`${O8}${this.pendingConfirm.label} ${L8}${this.hint([["crtr.graph.confirm.accept","accept"],["crtr.graph.confirm.cancel","cancel"]]).join(" \xB7 ")}${Fr}`:`${Oc}${this.fitHints([...this.remote||this.role!=="controller"?IJr:_Jr,...kJr],Math.max(1,e-5))}${Fr}`,f=this.palette.border,g=Math.max(1,e-4),y=p.map(E=>`${f("\u2502")} ${ot(E,g,"",!0)} ${f("\u2502")}`),b=this.palette.surface;return[this.borderRow("\u256D","\u256E",h,e),...y,this.borderRow("\u2570","\u256F",m,e)].map(b)}borderRow(e,n,r,i){let o=this.palette.border,s=Math.max(1,i-5),a=ot(r,s,"\u2026"),c=Math.max(0,i-5-yd(a));return`${o(`${e}\u2500`)} ${a} ${o("\u2500".repeat(c)+n)}`}handleInput(e){try{this.dispatch(e)}catch{}}dispatch(e){if(this.pendingConfirm!==void 0){if(this.matches("crtr.graph.confirm.accept",e)){let u=this.pendingConfirm.action;this.pendingConfirm=void 0,u()}else this.pendingConfirm=void 0;this.tui.requestRender();return}if(this.matches("crtr.graph.dismiss",e)){this.close();return}let n=this.snapshot,r=n?.rows??[],i=r.findIndex(u=>u.id===this.cursorId);i<0&&(i=Math.max(0,r.findIndex(u=>u.id===this.self)));let o=r[i],s=u=>u!==void 0&&!u.cycle,a=(u,l)=>{for(let d=u+l;d>=0&&d<r.length;d+=l)if(s(r[d]))return d;return u},c=u=>{let l=u===1?0:r.length-1;for(let d=l;d>=0&&d<r.length;d+=u)if(s(r[d]))return d;return i};if(this.matches("crtr.graph.down",e)){i=a(i,1),this.cursorId=r[i]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.up",e)){i=a(i,-1),this.cursorId=r[i]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.first",e)){this.cursorId=r[c(1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.last",e)){this.cursorId=r[c(-1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.collapse-or-manager",e)){if(o!==void 0&&o.hasKids&&!o.collapsed)this.userCollapsed.add(o.id),this.userExpanded.delete(o.id),this.repaintFolds();else{let u=n?.managerOf.get(this.cursorId??this.self);u!==void 0&&r.some(l=>l.id===u)&&(this.cursorId=u),this.tui.requestRender()}return}if(this.matches("crtr.graph.expand-or-child",e)){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){let u=n?.sortedChildIds.get(o.id)?.[0];u!==void 0&&(this.cursorId=u),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}let u=this.cursorId,l=u===void 0?null:n?.nodes.get(u)??null;u!==void 0&&l!==null&&l.status!=="active"&&l.status!=="idle"&&(this.reviveTarget(u),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}let u=n?.managerOf.get(this.self);u!==void 0&&(this.focusTarget(u),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}let u=this.cursorId??this.self,l=n?.nodes.get(u)??null,d=l!==null?Xdn(l):Ale(u);this.pendingConfirm={label:`kill ${d}?`,action:()=>this.shellCrtr(["node","lifecycle","close","--node",u])},this.tui.requestRender();return}}focusTarget(e){let n=process.env.TMUX_PANE;if(n===void 0||n===""){this.onNotice("Focusing a node needs a local viewer in tmux");return}(async()=>{let r=Ht(),i=await r.getNode(e);(await Tle(r,i,{pane:n})).focused||this.onNotice("Could not open that node\u2019s viewer")})().catch(r=>this.onNotice(Nc(r)))}reviveTarget(e){this.shellCrtr(["node","lifecycle","revive",e],()=>this.focusTarget(e))}shellCrtr(e,n){try{vJr("crtr",e,i=>{i==null&&n?.()}).stdin?.end()}catch{}}};et();var MJr=.72,PJr={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},dde=class{constructor(e,n){this.tui=e;this.pal=n}tui;pal;handle;bindings;scrollTop=0;lastContentRows=1;setBindings(e){this.bindings=e,this.handle!==void 0&&this.tui.requestRender()}toggle(){this.handle===void 0?this.open():this.close()}close(){this.handle!==void 0&&(this.handle.hide(),this.handle=void 0,this.tui.requestRender())}isOpen(){return this.handle!==void 0}invalidate(){this.handle!==void 0&&this.tui.requestRender()}render(e){let n=Math.max(1,e);if(n<5)return this.renderNarrow(n);let r=n-4,i=this.body(r),o=Math.max(1,this.tui.terminal.rows),s=Math.max(3,Math.min(Math.floor(o*MJr),Math.max(3,o-2))),a=Math.max(1,s-2),c=i.length>a,u=c&&a>=3?a-2:1;this.lastContentRows=u,this.scrollTop=Math.max(0,Math.min(this.scrollTop,Math.max(0,i.length-u)));let l=Math.min(i.length,this.scrollTop+u),d=[];for(c&&a>=3&&d.push(this.scrollTop>0?this.pal.muted(`\u2191 ${this.scrollTop} more`):""),d.push(...i.slice(this.scrollTop,l)),c&&a>=3?d.push(l<i.length?this.pal.muted(`\u2193 ${i.length-l} more`):""):c&&a===2&&d.push(l<i.length?this.pal.muted(`\u2193 ${i.length-l} more`):"");d.length<a;)d.push("");let p=this.pal.bold(this.pal.accent("\u2328 attach help")),h=this.pal.muted("esc dismiss \xB7 \u2191\u2193 scroll");return[this.borderRow("\u256D","\u256E",p,n),...d.map(m=>this.boxRow(m,n)),this.borderRow("\u2570","\u256F",h,n)].map(this.pal.surface)}handleInput(e){return nt(e,"escape")||nt(e,"q")?(this.close(),!0):nt(e,"up")||this.matchesBinding("crtr.attach.scroll.up",e)?this.scrollBy(-1):nt(e,"down")||this.matchesBinding("crtr.attach.scroll.down",e)?this.scrollBy(1):nt(e,"pageUp")||this.matchesBinding("crtr.attach.scroll.page-up",e)?this.scrollBy(-this.pageSize()):nt(e,"pageDown")||this.matchesBinding("crtr.attach.scroll.page-down",e)?this.scrollBy(this.pageSize()):!0}open(){this.scrollTop=0,this.handle=this.tui.showOverlay(this,PJr)}matchesBinding(e,n){return this.bindings!==void 0&&iS(this.bindings,e,n,(r,i)=>nt(r,i))}scrollBy(e){let n=this.body(Math.max(1,this.tui.terminal.columns-4)).length,r=Math.max(0,n-this.lastContentRows),i=Math.max(0,Math.min(r,this.scrollTop+e));return i!==this.scrollTop&&(this.scrollTop=i,this.tui.requestRender()),!0}pageSize(){return Math.max(1,this.lastContentRows-1)}body(e){return this.lines().flatMap(n=>this.wrap(n.text,e).map(r=>this.style(r,n.style)))}lines(){let e=(s,a)=>({text:`${this.binding(s)} ${a}`,style:"plain"}),n=s=>({text:s,style:"heading"}),r=s=>({text:s,style:"muted"}),i={text:"",style:"plain"},o=zf.map(({actionId:s})=>{let a=bd.find(c=>c.id===s)?.name??s;return e(s,a)});return[n("Learning crouter"),{text:"/tutorial the guided crouter tutorial \u2014 your agent teaches it, one lesson at a time",style:"plain"},i,n("Scrolling"),e("crtr.attach.scroll.up","scroll one line up"),e("crtr.attach.scroll.down","scroll one line down"),e("crtr.attach.scroll.page-up","scroll one page up"),e("crtr.attach.scroll.page-down","scroll one page down"),e("crtr.attach.scroll.live","return to the live bottom"),r("mouse wheel (when reporting is on)"),i,n("Searching the transcript"),{text:`${this.binding("crtr.attach.search")} search what the transcript is currently showing. Type to jump as you go, enter to browse the matches.`,style:"plain"},{text:`${this.binding("crtr.attach.search.next")} / ${this.binding("crtr.attach.search.previous")} next and previous match \xB7 ${this.binding("crtr.attach.search.edit")} edit the query \xB7 ${this.binding("crtr.attach.search.close")} close. Typing anything else closes search and returns to the editor.`,style:"plain"},{text:"A lowercase query ignores case; any uppercase letter makes it case-sensitive.",style:"plain"},{text:"Folded tool output is not on screen, so it is not searched \u2014 unfold it to include it.",style:"muted"},i,n("Selection and copy"),{text:"Drag with the mouse to select; releasing copies the selection to the clipboard (and the tmux buffer). Any key clears the highlight.",style:"plain"},{text:"prefix + [ tmux copy-mode selects and copies the visible screenful; it works even while mouse reporting is on.",style:"plain"},{text:"Option-drag (iTerm2, Terminal.app) or Shift-drag (Ghostty, Alacritty, xterm) makes a true terminal selection that bypasses mouse reporting.",style:"plain"},{text:"Block-copy commands copy transcript content and are not capped at one screenful.",style:"plain"},i,n("Copy commands"),{text:"/copy last assistant message.",style:"plain"},{text:`/copy-message (${this.binding("crtr.attach.copy.message")}) newest copyable block entirely visible in the viewport; otherwise the newest one that intersects it.`,style:"plain"},{text:"/copy-tool newest tool call's result text.",style:"plain"},{text:"/copy-transcript every copyable block's text, oldest to newest, joined by blank lines.",style:"plain"},i,n("Mouse"),{text:`/mouse or ${this.binding("crtr.attach.mouse.toggle")} toggle mouse reporting \u2014 wheel scrolling and viewer drag-select. Turning it off restores tmux drag-select and copy-mode mouse.`,style:"plain"},i,n("Other attach keys"),...o]}binding(e){return this.bindings===void 0?"Loading\u2026":$s(this.bindings,e)}wrap(e,n){if(e==="")return[""];let r=Math.max(1,n),i=e.split(/\s+/),o=[],s="";for(let a of i){let c=s===""?a:`${s} ${a}`;s!==""&&_e(c)>r?(o.push(ot(s,r,"",!0)),s=` ${a}`):s=c}return s!==""&&o.push(ot(s,r,"",!0)),o}style(e,n){switch(n){case"heading":return this.pal.bold(this.pal.accent(e));case"muted":return this.pal.muted(e);case"plain":return e}}boxRow(e,n){let r=n-4,i=ot(e,r,"",!0),o=" ".repeat(Math.max(0,r-_e(i)));return`${this.pal.border("\u2502")} ${i}${o} ${this.pal.border("\u2502")}`}borderRow(e,n,r,i){if(i<6)return ot(`${this.pal.border(e)}${r}${this.pal.border(n)}`,i,"",!0);let o=i-5,s=ot(r,o,"\u2026"),a=Math.max(0,i-5-_e(s));return`${this.pal.border(`${e}\u2500`)} ${s} ${this.pal.border("\u2500".repeat(a)+n)}`}renderNarrow(e){let n=ot(this.pal.bold(this.pal.accent("help")),e,"",!0);return[this.pal.surface(n)]}};et();import{join as DJr}from"node:path";function fN(t,e){let n=`${new Date().toISOString()} ${t} ${e}`.replaceAll(/[\r\n]/g," ");Kj(DJr(Ma(),"attach-invariants.log"),n)}et();var pde=class{constructor(e,n,r){this.surface=e;this.focusTarget=n;this.getRows=r}surface;focusTarget;getRows;_focused=!1;get focused(){return this._focused}set focused(e){this._focused=e,R$(this.focusTarget)&&(this.focusTarget.focused=e)}get wantsKeyRelease(){return this.focusTarget.wantsKeyRelease??this.surface.wantsKeyRelease??!1}render(e){let n=Math.max(0,Math.floor(this.getRows())),r=Math.max(0,Math.floor(e));this.surface.setRows(n);let i=this.surface.render(r);i.length!==n&&kze(`surface rendered ${i.length} rows; expected ${n}`);let o=i.slice(0,n).map(a=>_e(a)>r?(kze(`surface row is ${_e(a)} cells wide; expected at most ${r}`),epn($i(a,0,r,!0),r)):epn(a,r));for(;o.length<n;)o.push(" ".repeat(r));let s=BJr(o);return s>1?(kze(`surface frame contains ${s} CURSOR_MARKER sequences; expected at most one`),o.map(LJr)):o}handleInput(e){(this.focusTarget.handleInput??this.surface.handleInput)?.call(this.focusTarget.handleInput===void 0?this.surface:this.focusTarget,e)}invalidate(){this.surface.invalidate()}};function epn(t,e){return ot(t,e,"",!0)}function BJr(t){return t.reduce((e,n)=>e+n.split(Kr).length-1,0)}function LJr(t){return t.split(Kr).join("")}function kze(t){fN("surface-frame",t)}var OJr={anchor:"top-left",width:"100%",maxHeight:"100%",margin:0},NJr={anchor:"top-left",width:"100%",margin:0,nonCapturing:!0},mde=class{capabilities;tui;mouse;getRows;statusNotice;formatNotice;noticeMs;selfPane;stack=[];noticeOverlay;noticeTimer;constructor(e){this.tui=e.tui,this.mouse=e.mouse,this.getRows=e.rows,this.statusNotice=e.statusNotice,this.formatNotice=e.formatNotice,this.noticeMs=e.noticeMs,this.selfPane=e.selfPane,this.capabilities={...e.capabilities,selfPane:e.selfPane}}mount(e,n){this.disposeNotice();let r=new pde(e,n?.focus??e,this.getRows),i=this.tui.showOverlay(r,OJr),o={component:e,frame:r,overlay:i,cleanup:[],closed:!1,closing:!1},s=this.stack[this.stack.length-1];return s&&s.overlay.setHidden(!0),this.stack.push(o),{close:()=>this.closeEntry(o,!0),invalidate:()=>{!o.closed&&this.stack[this.stack.length-1]===o&&this.tui.requestRender()},onClose:a=>{if(o.closed||o.closing){hde("onClose registered after surface close");return}o.cleanup.push(a)}}}notice(e,n){if(this.disposeNotice(),this.stack.length===0){this.statusNotice(e,n);return}if(e==="")return;let r=new Rze(()=>this.formatNotice(e));this.noticeOverlay=this.tui.showOverlay(r,NJr),n?.sticky!==!0&&this.noticeMs>0&&(this.noticeTimer=setTimeout(()=>{this.noticeTimer=void 0,this.disposeNoticeOverlay()},this.noticeMs))}suspendForChild(){return this.tui.stop(),()=>{this.tui.start(),this.mouse.reassert(),this.tui.invalidate(),this.tui.requestRender(!0)}}async focusNode(e){if(!this.capabilities.canFocusNode||this.selfPane===void 0||this.selfPane==="")return this.notice("Focusing a node needs a local viewer in tmux"),!1;try{let n=Ht(),r=await n.getNode(e),i=await kle(n,e,{pane:this.selfPane,cwd:r.cwd,name:r.name});return i.focused||this.notice("Could not open that node\u2019s viewer"),i.focused}catch(n){return this.notice(Nc(n)),!1}}pickReviewFile(e){return new Promise(n=>{let r,i=!1,o=a=>{i||(i=!0,n(a),r.close())},s=jle(e.candidates,e.cwd,a=>o(a),()=>o(null),a=>this.notice(a));r=this.mount($Jr(s.component,e.title),{focus:s.focus}),r.onClose(()=>o(null))})}handleWheel(e,n){return this.stack[this.stack.length-1]?.component.handleWheel?.(e,n)??!1}hasFullPaneSurface(){return this.stack.length>0}closeAll(){let e=this.stack[0];e&&this.closeEntry(e,!1),this.disposeNotice()}closeEntry(e,n){if(e.closed||e.closing)return;if(this.stack.indexOf(e)===-1){e.closed=!0;return}for(e.closing=!0;this.stack.indexOf(e)!==-1;){let o=this.stack.indexOf(e),s=this.stack[o+1];if(!s)break;this.closeEntry(s,!1)}try{e.overlay.hide()}catch(o){hde(`surface overlay hide failed: ${Tze(o)}`)}for(let o of e.cleanup)try{let s=o();s&&typeof s.then=="function"&&s.catch(a=>hde(`surface cleanup failed: ${Tze(a)}`))}catch(s){hde(`surface cleanup failed: ${Tze(s)}`)}e.cleanup.length=0,e.closed=!0,e.closing=!1;let i=this.stack.indexOf(e);if(i!==-1&&this.stack.splice(i,1),n){this.disposeNotice();let o=this.stack[this.stack.length-1];o&&o.overlay.setHidden(!1)}}disposeNotice(){this.disposeNoticeOverlay(),this.noticeTimer!==void 0&&(clearTimeout(this.noticeTimer),this.noticeTimer=void 0)}disposeNoticeOverlay(){this.noticeOverlay?.hide(),this.noticeOverlay=void 0}},Rze=class{constructor(e){this.text=e}text;render(e){return[ot(this.text(),Math.max(0,e),"",!0)]}invalidate(){}};function $Jr(t,e){let n=0;return{setRows:r=>{n=Math.max(0,Math.floor(r))},render:r=>{let i=t.render(r),s=(e===void 0?i:[ot(e,Math.max(0,r),"",!0),...i.slice(1)]).slice(0,n);for(;s.length<n;)s.push("");return s},invalidate:()=>t.invalidate()}}function hde(t){fN("surface-host",t)}function Tze(t){return t instanceof Error?t.message:String(t)}et();import{existsSync as zJr,watch as VJr}from"node:fs";function FJr(t,e){switch(e){case"gray":return`${Wue}${t}${Oe}`;case"cyan":return`${ss}${t}${Oe}`;case"red":return`${vsn}${t}${Oe}`;case"yellow":return`${Ns}${t}${Oe}`;default:return t}}var UJr={notify:"\u2709",decision:"\u25C6",context:"\u270E",error:"\u26A0",review:"\u25A4",display:"\u2709",rich:"\u25A3",interactive:"\u25C6"},QJr={notify:"gray",decision:"cyan",context:"cyan",error:"red",review:"yellow",display:"gray",rich:"cyan",interactive:"cyan"};function WJr(t){let e=Math.floor((Date.now()-new Date(t).getTime())/6e4);return e>=60?`${Math.floor(e/60)}h ago`:e>0?`${e}m ago`:"just now"}function tpn(t,e,n,r,i=Number.MAX_SAFE_INTEGER){let o=[` ${os}${t.length} pending${Oe} ${ut}\xB7 ${r.label}${Oe}`];if(r.hint!==void 0&&o.push(` ${ut}${r.hint}${Oe}`),o.push(""),t.length===0)return[...o,` ${ut}${Esn}No pending interactions${Oe}`];let s=e-4,a=t.map((l,d)=>HJr(l,d,n,s)),c=qJr(a,n,Math.max(1,i-o.length)),u=[...o];c.start>0&&u.push(` ${ut}\u2191 ${c.start} above${Oe}`);for(let l=c.start;l<c.end;l++)u.push(...a[l]);return c.end<t.length&&u.push(` ${ut}\u2193 ${t.length-c.end} below${Oe}`),u}function HJr(t,e,n,r){let i=t.kind==="page"?t.awaitsResponse===!1?"display":"rich":t.kind,o=UJr[i]??"\xB7",s=WJr(t.kind==="page"?t.emittedAt:t.blockedSince),a=e===n?`${ss}\u25B8${Oe} `:" ",c=Math.max(1,r-s.length-6),u=`${a}${FJr(o,QJr[i]??"cyan")} ${os}${Hue(t.title||`(${t.id.slice(0,8)})`,c)}${Oe} ${ut}${s}${Oe}`,l=t.claim?`claimed by ${t.claim.owner} \xB7 ${t.subtitle}`:t.subtitle,d=[u,` ${ut}${Hue(l,r-6)}${Oe}`],p=Mze(t);return p!==void 0&&d.push(` ${ut}Recommended: ${Hue(p,Math.max(1,r-19))}${Oe}`),d}function Mze(t){if(!(t.kind!=="page"||t.recommendedOptions.length===0))return t.recommendedOptions.map(e=>e.label).join(" \xB7 ")}function qJr(t,e,n){let r=Math.max(0,Math.min(e,t.length-1)),i=r+1,o=!0;for(;;){let s=i<t.length?{start:r,end:i+1}:void 0,a=r>0?{start:r-1,end:i}:void 0,u=(o?[s,a]:[a,s]).find(l=>l!==void 0&&GJr(t,l.start,l.end)<=n);if(u===void 0)break;r=u.start,i=u.end,o=!o}return{start:r,end:i}}function GJr(t,e,n){let r=e>0?1:0;for(let i=e;i<n;i++)r+=t[i].length;return n<t.length&&r++,r}function fde(t,e,n="list"){if(t<60||e<18)return{mode:"minimum",listWidth:t,detailWidth:0,height:e};if(t<96)return{mode:n,listWidth:t,detailWidth:t,height:e};let r=Math.max(30,Math.min(44,Math.floor(t/3)));return{mode:"two-column",listWidth:r,detailWidth:t-r-1,height:e}}var gde=class{constructor(e){this.opts=e}opts;running=null;stopped=!1;start(){return this.running!==null?this.running:(this.running=this.run(),this.running)}async stop(){this.stopped=!0,this.running!==null&&await this.running}async run(){if(this.opts.host.capabilities.remote)return this.opts.host.notice("The review is unavailable in a remote attach \u2014 the file and companion live on the host."),!1;let e;try{e=await Ax().byId(this.opts.reviewId)}catch(n){return this.opts.host.notice(jJr(n)),!1}return!this.stopped&&qle(this.opts.host,e)}};function jJr(t){return t instanceof ZA?cN(t):t instanceof Error?t.message:String(t)}var yde=class{options;host;scan;items=[];visible=[];profile;filter;pendingSeat;selectedDir;selectedIndex=0;screen="list";adapter;reviewAdapter;focusingSource=!1;claim;submittingDir;cancelConfirmation;cols;rows;status;refreshError;watchers=[];selectedWatcher;heartbeat;started=!1;closed=!1;preview;previewFailed;previewFetching;previewStale=!1;openRevision;constructor(e){this.options=e,this.host=e.host,this.scan=e.scan??KJr,this.cols=e.cols??80,this.rows=e.rows??24,this.profile=e.profile,this.filter=e.profile===void 0?"all":"profile",this.selectedDir=e.initialSelection,this.pendingSeat=e.initialSelection,this.rescan()}snapshot(){return{items:[...this.items],selectedDir:this.selectedDir,screen:this.screen,inputBuffer:this.adapter?.inputBuffer()}}async rescan(){let e=this.selectedDir,n=this.claim;try{this.items=await this.scan()}catch(i){if(this.closed)return;this.status=Nc(i),this.markDirty();return}if(this.closed)return;if(this.recomputeVisible(),this.pendingSeat!==void 0){let i=this.pendingSeat;this.pendingSeat=void 0,this.seatOn(i)}if(!(e!==void 0&&this.items.some(i=>i.dir===e))&&this.adapter!==void 0&&e!==void 0&&n!==void 0){let i=(await this.requestOrNull(n.id))?.state==="canceled";if(this.closed)return;i&&odn(e),e!==this.submittingDir&&(this.status=i?"canceled by requester":"ticket resolved elsewhere"),this.leaveDetail(e!==this.submittingDir)}this.reseatSelection()}recomputeVisible(){if(this.filter==="all"||this.profile===void 0){this.visible=this.items;return}let e=this.profile.members();this.visible=this.items.filter(n=>{let r=n.source.nodeId;return r!==void 0&&e.has(r)})}reseatSelection(){let e=this.selectedDir===void 0?-1:this.visible.findIndex(n=>n.dir===this.selectedDir);if(e>=0){this.selectedIndex=e;return}if(!(this.adapter!==void 0&&this.selectedDir!==void 0&&this.items.some(n=>n.dir===this.selectedDir))){if(this.visible.length===0){this.selectedIndex=0,this.selectedDir=void 0;return}this.selectedIndex=Math.min(Math.max(0,this.selectedIndex),this.visible.length-1),this.selectedDir=this.visible[this.selectedIndex].dir}}highlightIndex(){return this.selectedDir===void 0?-1:this.visible.findIndex(e=>e.dir===this.selectedDir)}currentRow(){let e=this.highlightIndex();return e>=0?this.visible[e]:void 0}scopeHeading(){return this.profile===void 0?{label:"all profiles"}:this.filter==="profile"?{label:this.profile.label,hint:"P all profiles"}:{label:"all profiles",hint:`P ${this.profile.label} only`}}refreshOutcome(e){if(this.refreshError=e,e===void 0){this.invalidate();return}this.markDirty()}start(){this.started||this.closed||(this.started=!0,this.watchRoots(),this.heartbeat=setInterval(()=>{this.claim!==void 0&&ede(this.claim.dir,this.claim.token)},1e4))}async invalidate(){if(this.previewStale=!0,await this.rescan(),!this.closed){if(this.adapter!==void 0&&this.claim!==void 0){await this.reloadSelectedPage();return}this.markDirty()}}resize(e,n){this.cols=e,this.rows=n,this.adapter?.resize(this.detailSize().cols,this.detailSize().rows),this.markDirty()}render(){let e=fde(this.cols,this.rows,this.screen);if(e.mode==="minimum")return[`${Ns}Resize terminal to at least 60\xD718 to use inbox.${Oe}`];let n=tpn(this.visible,e.listWidth,this.highlightIndex(),this.scopeHeading(),e.height),r=this.detailLines(e.detailWidth,e.height);if(e.mode==="list")return this.withStatus(n);if(e.mode==="detail")return this.withStatus(r);let i=[],o=`${Wue}\u2502${Oe}`;for(let s=0;s<e.height;s++){let a=ca(n[s]??"",e.listWidth),c=ca(r[s]??"",e.detailWidth),u=" ".repeat(Math.max(0,e.listWidth-_e(a)));i.push(`${a}${u}${o}${c}`)}return this.withStatus(i)}handleKey(e,n){if(n.ctrl&&e==="c"){this.close();return}if(this.screen==="detail"&&this.adapter!==void 0){if((e==="g"||e==="G")&&this.adapter.canAcceptHostKeys()){this.focusSelectedSource();return}this.adapter.handleKey(e,n),this.markDirty();return}if(this.cancelConfirmation!==void 0){if(e==="y"||e==="Y"){let r=this.cancelConfirmation.item;this.cancelConfirmation=void 0,this.status="canceling\u2026",this.cancelFromInbox(r)}else(e==="n"||e==="N"||n.escape)&&(this.cancelConfirmation=void 0,this.status=void 0);this.markDirty();return}if(e==="P"&&this.profile!==void 0){this.toggleProfileFilter(),this.markDirty();return}if(e==="x"||e==="X"){let r=this.currentRow();r!==void 0&&(this.cancelConfirmation={item:r},this.status=void 0),this.markDirty();return}if(e==="s"||e==="S"){this.sendFastAction(),this.markDirty();return}if(n.escape||e==="q"){this.close();return}e==="j"||n.downArrow?this.select(this.selectedIndex+1):e==="k"||n.upArrow?this.select(this.selectedIndex-1):e==="g"||e==="G"?this.focusSelectedSource():(n.return||e==="a")&&this.activate(),this.markDirty()}toggleProfileFilter(){this.filter=this.filter==="profile"?"all":"profile",this.recomputeVisible(),this.reseatSelection()}async sendFastAction(){let e=this.currentRow();if(e===void 0)return;if(e.kind!=="page"||e.fastAction===void 0){this.status="no recommended answer on this ticket \u2014 Enter opens it";return}let n=await this.requestOrNull(e.id);if(Pze(n)){this.status=Ade(n),await this.rescan();return}let r=J8(e.dir);if(r===null){this.status="ticket is being edited by another inbox";return}let i=e.fastAction.kind==="acknowledge"?"acknowledged":`sent: ${Mze(e)??"recommended answer"}`;this.submittingDir=e.dir;try{await K8(e.id,e.fastAction.responses),this.status=i}catch(o){this.status=Y8(o)==="already_settled"?Ade(await this.requestOrNull(e.id)):Nc(o)}finally{$f(e.dir,r.token),this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async cancelFromInbox(e){this.submittingDir=e.dir;try{e.kind==="review"?await Ax().cancel(e.id,"Canceled from the inbox."):await jln(e.id,{reason:"Canceled from the inbox.",actor:"human"}),this.status="canceled"}catch(n){this.status=Nc(n)}finally{this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async activate(){let e=this.currentRow();if(e===void 0)return;if(e.kind==="review"){await this.activateReview(e);return}let n=await this.requestOrNull(e.id);if(this.closed)return;if(Pze(n)){this.status=Ade(n),await this.rescan();return}let r=J8(e.dir);if(r===null){this.status="ticket is being edited by another inbox";return}let i,o;try{let s=await Ht().getHumanInboxPage(e.inboxTicketId);if(s.state==="resolved"||s.state==="canceled"){$f(e.dir,r.token),this.status=qO(s),await this.rescan();return}i=eT(s),o=s.revision}catch{$f(e.dir,r.token),this.status="page could not be read",await this.invalidate();return}if(this.closed||this.claim!==void 0||this.adapter!==void 0){$f(e.dir,r.token);return}this.claim={dir:e.dir,id:e.id,ticketId:e.inboxTicketId,token:r.token},this.screen="detail",this.adapter=new dN({ticketId:e.inboxTicketId,page:i,productKinds:$3(),cols:this.detailSize().cols,rows:this.detailSize().rows,onDirty:()=>this.markDirty(),onEditorRequest:()=>this.editActivePageInput(),onBack:()=>{this.leaveDetail(),this.markDirty()},onComplete:s=>{this.complete(s)}}),this.openRevision=o,this.watchSelected(e.dir),this.markDirty()}async activateReview(e){this.reviewAdapter=new gde({reviewId:e.id,host:this.host});let n=!1;try{n=await this.reviewAdapter.start()}catch(r){this.status=Nc(r)}finally{this.reviewAdapter=void 0}if(n){this.close();return}await this.rescan(),this.markDirty()}selectDir(e){this.seatOn(e)&&this.markDirty()}seatOn(e){let n=this.visible.findIndex(r=>r.dir===e);return n<0&&this.items.some(r=>r.dir===e)&&(this.filter="all",this.recomputeVisible(),n=this.visible.findIndex(r=>r.dir===e)),n<0?!1:(this.select(n),!0)}async reloadSelectedPage(){let e=this.claim;if(this.adapter===void 0||e===void 0){this.markDirty();return}try{let n=await Ht().getHumanInboxPage(e.ticketId);if(this.closed||this.claim!==e||this.adapter===void 0)return;n.revision!==this.openRevision&&(this.openRevision=n.revision,this.adapter.reload(eT(n)))}catch{this.status="page could not be read"}this.markDirty()}close(){if(!this.closed){this.closed=!0,this.started=!1,this.heartbeat!==void 0&&clearInterval(this.heartbeat),this.heartbeat=void 0,this.reviewAdapter?.stop(),this.leaveDetail(this.claim?.dir!==this.submittingDir);for(let e of this.watchers)e.close();this.watchers=[],this.selectedWatcher?.close(),this.selectedWatcher=void 0,this.options.onClosed()}}async complete(e){let n=this.claim;if(n===void 0)return;this.submittingDir=n.dir;try{await K8(n.id,e)}catch(i){this.submittingDir=void 0,this.status=Nc(i);let o=Y8(i);if(o==="unreachable"||o==="other"){this.markDirty();return}o==="already_settled"&&(this.status=Ade(await this.requestOrNull(n.id))),this.leaveDetail(!1),await this.rescan(),this.markDirty();return}this.submittingDir=void 0,this.leaveDetail(!1),await this.rescan();let r=this.items.some(i=>i.dir===n.dir);dm({level:r?"warn":"info",event:"inbox.page.resolved",fields:{ticket_id:n.id,request_settled:Pze(await this.requestOrNull(n.id)),still_listed:r,claim_left_behind:zJr(Rv(n.dir))}}),this.markDirty()}editActivePageInput(){let e=this.adapter?.inputBuffer();if(e===void 0)return;let n=this.host.suspendForChild(),r={text:e};try{r=ide(e)}finally{n(),this.adapter?.setInputBuffer(r.text),r.error!==void 0&&(this.status=r.error),this.markDirty()}}leaveDetail(e=!0){this.adapter?.close(),this.adapter=void 0,this.selectedWatcher?.close(),this.selectedWatcher=void 0,e&&this.claim!==void 0&&$f(this.claim.dir,this.claim.token),this.claim=void 0,this.openRevision=void 0,this.screen="list",this.reseatSelection()}select(e){this.visible.length!==0&&(this.selectedIndex=Math.max(0,Math.min(e,this.visible.length-1)),this.selectedDir=this.visible[this.selectedIndex].dir)}detailSize(){let e=fde(this.cols,this.rows,this.screen);return{cols:Math.max(1,e.detailWidth-2),rows:e.height}}detailLines(e,n){if(this.adapter!==void 0)return this.adapter.render();let r=this.currentRow();if(r===void 0)return this.passiveDetailLines(e,n);let i=this.focusAvailable(r.dir)?` ${ut}g${Oe} chat`:"",o=r.kind==="page"&&r.fastAction!==void 0?` ${ut}s${Oe} ${r.fastAction.kind==="acknowledge"?"acknowledge":"send recommended"}`:"",s=r.kind==="page"?[` ${ut}Enter${Oe} opens the full page ${ut}\u2191\u2193/jk${Oe} select${o} ${ut}x${Oe} cancel`,` ${ut}Page:${Oe} c comment u/d scroll${i} ${ut}q${Oe} close`]:[` ${ut}Enter${Oe} opens the full review ${ut}\u2191\u2193/jk${Oe} select ${ut}x${Oe} cancel`,` ${i} ${ut}q${Oe} close`],a=Math.max(0,n-s.length),c=this.passiveDetailLines(e,a);for(;c.length<a;)c.push("");return[...c,...s.map(u=>ca(u,e))]}focusAvailable(e){return this.host.capabilities.canFocusNode}async focusSelectedSource(){let e=this.screen==="detail"?this.claim?.dir:this.currentRow()?.dir,n=e===void 0?void 0:this.items.find(i=>i.dir===e);if(n===void 0||this.focusingSource)return;let r=n.source.nodeId;if(r===void 0){this.status="This request was not raised by a canvas node",this.markDirty();return}this.focusingSource=!0;try{await this.host.focusNode(r)?this.close():(this.status="Could not open that node\u2019s viewer",this.markDirty())}finally{this.focusingSource=!1}}pagePreviewBody(e,n){let r=this.preview;if(r!==void 0&&r.dir===e.dir){if(this.previewStale&&this.schedulePreview(e),r.width===n&&r.links===fae())return r.lines;let i=npn(r.view,n);return this.preview={...r,width:n,links:fae(),lines:i},i}return this.schedulePreview(e),this.previewFailed===e.dir?[`${ut}page could not be read${Oe}`]:[]}schedulePreview(e){this.previewFetching!==e.dir&&(this.previewFetching=e.dir,this.previewStale=!1,Ht().getHumanInboxPage(e.inboxTicketId).then(n=>{if(this.closed||this.previewFetching!==e.dir||(this.previewFetching=void 0,this.previewFailed=void 0,this.preview?.dir===e.dir&&this.preview.revision===n.revision))return;let r=eT(n),i=this.preview?.width??fde(this.cols,this.rows,this.screen).detailWidth;this.preview={dir:e.dir,revision:n.revision,view:r,width:i,links:fae(),lines:npn(r,i)},this.markDirty()},()=>{this.closed||this.previewFetching!==e.dir||(this.previewFetching=void 0,this.previewFailed=e.dir,this.preview?.dir===e.dir&&(this.preview=void 0),this.markDirty())}))}async requestOrNull(e){try{return await Ht().getHumanRequest(e)}catch{return}}passiveDetailLines(e,n){let r=this.currentRow();if(r===void 0)return[` ${ut}Select a pending interaction.${Oe}`];let i=[...fl(ml(r.title),Math.max(10,e-2)).map(s=>` ${os}${ss}${s}${Oe}`),""];for(let s of pae(r.subtitle,Math.max(1,e-2)))i.push(` ${s}`);let o=r.kind==="page"?this.pagePreviewBody(r,e):[`${ut}1 file to review${Oe}`];if(o.length>0){i.push("");let s=Math.max(0,n-i.length),a=o.length<=s?o:o.slice(0,Math.max(0,s-1));for(let c of a)i.push(` ${c}`);a.length<o.length&&i.push(` ${ut}\u2026 +${o.length-a.length} more lines${Oe}`)}return i.map(s=>ca(s,e)).slice(0,Math.max(1,n))}withStatus(e){let n=this.cancelConfirmation===void 0?this.refreshError??this.status:`cancel \u201C${this.cancelConfirmation.item.title}\u201D? y yes \xB7 n/Esc no`;if(n===void 0||this.rows<1)return e;let r=[...e];for(;r.length<this.rows;)r.push("");return r[this.rows-1]=`${Ns}${n}${Oe}`,r}markDirty(){this.options.onDirty()}watchRoots(){let e=lN(this.options.onInboxActivity??(()=>{this.invalidate()}));this.watchers.push({close:e})}watchSelected(e){this.selectedWatcher?.close();try{this.selectedWatcher=VJr(e,()=>{this.invalidate()})}catch{this.selectedWatcher=void 0}}};async function KJr(){let{tickets:t}=await Ht().listHumanInbox();return t.map(Lf).sort(bv)}function npn(t,e){let n=t.manifest.dialect==="html"?$O(t.document):NO(t.document,t.manifest);return Gue(t.manifest,n,Math.min(Math.max(20,e-4),100),Math.max(20,e-4))}function Pze(t){return t!==void 0&&t.state!=="pending"}function Ade(t){return t?.page===void 0?"ticket was already resolved":qO(t.page)}var Dze=class{constructor(e){this.controller=e}controller;focused=!1;rows=0;width=-1;height=-1;handle;setRows(e){this.rows=e}render(e){let n=this.rows;return(e!==this.width||n!==this.height)&&(this.width=e,this.height=n,this.controller.resize(e,n)),YJr(this.controller.render(),e,n)}handleInput(e){let{input:n,key:r}=rde(e);this.controller.handleKey(n,r)}invalidate(){this.handle?.invalidate()}setHandle(e){this.handle=e}};function YJr(t,e,n){let r=t.slice(0,n);for(;r.length<n;)r.push("");return r.map(i=>{let o=ca(i,e);return o+" ".repeat(Math.max(0,e-qo(o)))})}async function JJr(t){if(t.scan!==void 0)return t.scan();let{tickets:e}=await Ht().listHumanInbox();return e.map(Lf).sort(bv)}async function rpn(t,e){try{return await e()}catch(n){throw new Error(`Could not load ${t}: ${n instanceof Error?n.message:String(n)}`)}}function ipn(t){let e,n=()=>{let c=e;c===void 0||c.closed||(c.closed=!0,e=void 0,c.controller?.close(),c.handle?.close(),c.controller=void 0,c.handle=void 0)},r=c=>{if(c.closed||e!==c)return;let u=new yde({host:t.host,onDirty:()=>c.handle?.invalidate(),onClosed:n,...t.scan===void 0?{}:{scan:t.scan},onInboxActivity:()=>o(c),...c.preselectDir===void 0?{}:{initialSelection:c.preselectDir},...t.profile===void 0?{}:{profile:{id:t.profile.id,label:t.profile.label,members:()=>c.profileMembers}}}),l=new Dze(u);c.controller=u;try{let d=t.host.mount(l);c.handle=d,l.setHandle(d),d.onClose(()=>{c.handle===d&&(c.handle=void 0),u.close()}),u.start()}catch(d){throw n(),d}},i=async c=>{let u=t.profile,l=c?rpn("inbox visibility",()=>JJr(t)):void 0,d=u===void 0?void 0:rpn("profile membership",()=>Ht().listNodes({profile_id:u.id})),[,p]=await Promise.all([l,d]);return p===void 0?void 0:new Set(p.map(h=>h.node_id))},o=(c,u=!1)=>{if(!u&&c.controller!==void 0&&t.profile===void 0){c.controller.invalidate();return}let l=++c.refreshGeneration;i(c.controller===void 0).then(d=>{c.closed||e!==c||l!==c.refreshGeneration||(d!==void 0&&(c.profileMembers=d),c.controller===void 0?r(c):c.controller.refreshOutcome())},d=>{if(c.closed||e!==c||l!==c.refreshGeneration)return;let p=d instanceof Error?d.message:String(d);if(u){n(),t.host.notice(p);return}c.controller?.refreshOutcome(p)})},s=c=>{if(e!==void 0){c!==void 0&&e.controller?.selectDir(c);return}if(t.host.capabilities.remote){t.host.notice("The inbox is unavailable in a remote attach.");return}let u={closed:!1,refreshGeneration:0,profileMembers:new Set,...c===void 0?{}:{preselectDir:c}};e=u,o(u,!0)};return{toggle:()=>{if(e!==void 0){n();return}s()},open:s,close:n,isOpen:()=>e!==void 0}}import{homedir as sXr}from"node:os";import{fileURLToPath as tXr}from"node:url";import{join as apn,dirname as nXr}from"node:path";import{readFileSync as XJr}from"node:fs";import{dirname as ZJr,join as opn}from"node:path";import{fileURLToPath as eXr}from"node:url";var xde=null;function spn(){if(xde!==null)return xde;let t=opn(ZJr(eXr(import.meta.url)),"..","..");return xde=JSON.parse(XJr(opn(t,"package.json"),"utf8")).version,xde}var rXr=tXr(import.meta.url),iXr=nXr(rXr),oXr=apn(iXr,"..",".."),qPs=apn(oXr,"scripts","self-update.mjs");function cpn(){return spn()}var aXr="Ctrl+B d leaves \u2014 the agent keeps running \xB7 Ctrl+B n / p switches windows";function upn(t){let e;try{e=cpn()}catch{}let n;try{t.profile_id&&(n=Px(t.profile_id).manifest.name)}catch{}let r=t.cwd;if(r){let o=sXr();r===o?r="~":r.startsWith(o+"/")&&(r="~"+r.slice(o.length))}let i=process.env.CRTR_TMUX_STARTED==="1"?aXr:void 0;return{version:e,profile:n,cwd:r,...i!==void 0?{hint:i}:{}}}import{createConnection as cXr}from"node:net";function lpn(t,e){return t||e?"observer":"controller"}async function uXr(t){let e=Number(process.env.CRTR_ATTACH_WAIT_MS??"");if(!Number.isFinite(e)||e<=0)return;let n=DT(t),r=Date.now()+e;for(;Date.now()<r;){if(await new Promise(o=>{let s=cXr(n),a=c=>{s.destroy(),o(c)};s.once("connect",()=>a(!0)),s.once("error",()=>a(!1))}))return;await new Promise(o=>setTimeout(o,100))}}async function dpn(t,e,n=!0){let r=e!==void 0,i=r?ysn({canvasName:e}):new HO,o,s,a,c,u;if(r)o={cwd:process.cwd()},a=new hT(t,Nue(e));else{let h=await i.getNode(t);if(h===null)throw new Xh({error:"not_found",message:`no node: ${t}`,received:t,next:"List nodes with `crtr node inspect list`."});o=h,s=h;try{if((await Ht().ensureAttach(t,{resume:!0,revive:!0,wakeParked:n})).parked){let f=await Ht().getSnapshot(t);c=f.snapshot,u=f.commands}}catch(m){Hje(m,"The node may be finalized or otherwise not attachable.")}c===void 0&&await uXr(t),a=new hT(t,{socketPath:K7e()})}let l=new Z8(t,{transport:a}),d=h=>h instanceof ty?new Xh({error:"no_broker",message:h.message,received:t,next:"Focus or revive the node first \u2014 attach needs a running headless broker."}):new Xh({error:"socket_error",message:`could not attach to node ${t}: ${String(h?.message??h)}`,received:t,next:"Check the node has a running headless broker."}),p;return l.on("error",h=>{p===void 0&&(p=h)}),c===void 0&&await new Promise((h,m)=>{let f=()=>{y(),h()},g=b=>{y(),m(b)},y=()=>{l.off("connect",f),l.off("error",g)};l.on("connect",f),l.on("error",g),l.connect()}).catch(h=>{throw d(h)}),{remote:r,canvasSource:i,meta:o,nodeIdentity:s,socket:l,...c===void 0?{}:{initialSnapshot:c,initialCommands:u},assertConnected:()=>{if(c===void 0&&p!==void 0)throw d(p)}}}import{basename as jXr}from"node:path";aa();et();bfe();import{statSync as EXr}from"node:fs";et();import{mkdirSync as lXr,readFileSync as dXr,writeFileSync as pXr}from"node:fs";import{dirname as hXr,join as mXr}from"node:path";var fXr="completion-frecency.json",gXr=336*60*60*1e3,AXr=8,yXr=1e3;function xXr(t,e){if(!t)return 0;let n=Math.max(0,e-t.t),r=Math.pow(.5,n/gXr),i=1-Math.exp(-t.n/3);return AXr*r*i}function wXr(t){let e={};try{let n=JSON.parse(dXr(t,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))return e;for(let[r,i]of Object.entries(n)){if(!i||typeof i!="object")continue;let{n:o,t:s}=i;typeof o!="number"||!Number.isFinite(o)||o<=0||typeof s!="number"||!Number.isFinite(s)||(e[r]={n:o,t:s})}}catch{}return e}function bXr(t,e){try{lXr(hXr(t),{recursive:!0}),pXr(t,JSON.stringify(e),"utf8")}catch{}}function ppn(t=mXr(Wc(),fXr)){let e=wXr(t),n,r=()=>{n||(n=setTimeout(()=>{n=void 0,bXr(t,e)},yXr),n.unref?.())};return{record:i=>{let o=e[i];e[i]={n:(o?.n??0)+1,t:Date.now()},r()},bonus:(i,o=Date.now())=>xXr(e[i],o)}}function Bze(t,e,n){let r=n.now??Date.now(),i=[];for(let o of t){let s=rR(e,n.searchableOf(o));s.matches&&i.push({item:o,score:s.score-n.store.bonus(n.idOf(o),r)})}return i.sort((o,s)=>o.score-s.score),i.map(o=>o.item)}function Lze(t){let e=Math.max(t.lastIndexOf("/"),t.lastIndexOf(":"));return e<0?t:`${t.slice(e+1)} ${t}`}function hpn(t){return t.replace(/:/g,"")}function ej(t,e,n){let r=t.join(`
|
|
1754
|
+
`).length;return{kind:"selection",notice:u===void 0?"Copy failed \u2014 no clipboard tool found":`Copied selection (${l} ${l===1?"line":"lines"}) \u2014 ${u}`}},clear(){let o=n!==void 0;return e=void 0,n=void 0,o},active(){return n!==void 0},apply(o){let s=r();if(!s)return o.slice();let a=t.width(),c=o.slice();for(let u of Gdn(s.anchor,s.head,a)){let l=u.row-1;l<0||l>=c.length||(c[l]=Uan(c[l],u.from,u.to,a))}return c}}}import{existsSync as xJr}from"node:fs";var zdn="\x1B_crtr-file-open;",Vdn="\x1B\\";function Kdn(t){let e=t.indexOf(zdn);if(e===-1)return;let n=e+zdn.length,r=t.indexOf(Vdn,n);return r===-1?void 0:{file:wJr(t.slice(n,r)),remaining:t.slice(0,e)+t.slice(r+Vdn.length)}}function wJr(t){let e=t.startsWith("'")?bJr(t):EJr(t);return e!==void 0&&e.startsWith("/")&&!/[\x00-\x1f\x7f]/.test(e)?e:void 0}function bJr(t){let e="",n=1;for(;;){let r=t.indexOf("'",n);if(r===-1)return;if(e+=t.slice(n,r),n=r+1,n===t.length)return e;if(t.slice(n,n+3)!=="\\''")return;e+="'",n+=3}}function EJr(t){let e="";for(let n=0;n<t.length;n++){if(t[n]!=="\\"){e+=t[n];continue}let r=t[++n];if(r===void 0)return;e+=r}return e}function Ydn(t){if(!xJr(t.file))return"missing";if(!h7e())return"no_nvim";let e=`crtr surface attach to ${un(t.nodeId)}${t.observer?" --observer":""}`,n=`${MT("edit",[t.file])} || :; exec ${e}`;return t.beforeRespawn(),bme({pane:t.pane,cwd:t.cwd,env:p$(),command:n})?"opened":"failed"}function Jdn(t){let e=new Map,n=!1,r=!1,i;t.remote||t.fetchSecret().then(a=>{i=a,X5e(),r||t.refresh()},t.onSecretError);let o=()=>{n||(n=!0,t.canvasSource.listNodes().then(a=>{for(let c of a)e.set(c.node_id,c.name);X5e(),r||t.refresh()},()=>{n=!1}))},s={selfNodeId:t.selfNodeId,nodeName:a=>{let c=e.get(a);return c===void 0&&o(),c},urlFor:a=>t.remote||i===void 0?void 0:`http://127.0.0.1:${t.port}/r/${a.split("/").map(encodeURIComponent).join("/")}?t=${i}`};return Z5e(s),{dispose(){r=!0,Z5e(void 0)}}}et();import{execFile as vJr}from"node:child_process";function Ize(t){return t==="orchestrator"?"\uF0E8":"\uF007"}function Xdn(t){let e=(t.description??"").trim(),r=[t.name&&t.name!==t.kind?t.name:"",e].filter(i=>i!=="").join(" ");return r!==""?r:t.name}function Zdn(t){return`${Ize(t.mode)} ${t.kind}`}var SJr=.72,CJr={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},_Jr=[["crtr.graph.dismiss","dismiss"],["crtr.graph.focus","focus"],["crtr.graph.revive","revive"],["crtr.graph.close-subtree","close"],["crtr.graph.focus-manager","manager"]],IJr=[["crtr.graph.dismiss","dismiss"]],kJr=[["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"]],TJr=[...["active","idle","done","dead","canceled"].map(t=>[oT(t,{}),t]),[oT("active",{streaming:!0}),"live"],[oT("active",{frozen:!0}),"frozen"],[oT("active",{hanging:{kind:"wedged"}}),"fault"]].map(([t,e])=>`${fp}${t.color}m${t.glyph}${Fr} ${Oc}${e}${Fr}`).join(" ");function RJr(t){return{node_id:t.node_id,name:t.name,kind:t.kind,description:t.description??void 0,cycles:t.cycles??void 0,status:t.status,frozen_at:t.frozen_at,pi_pid:t.pi_pid,telemetry_context_tokens:t.telemetry_context_tokens,telemetry_last_activity:t.telemetry_last_activity,fault:t.fault??null,streaming:t.streaming}}var lde=class{constructor(e,n,r,i,o,s,a="controller",c=()=>{},u=()=>{}){this.tui=e;this.self=n;this.getAsks=r;this.palette=i;this.bindings=o;this.source=s;this.role=a;this.onRefreshFailure=c;this.onNotice=u;this.remote=s instanceof wv}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;setBindings(e){this.bindings=e,this.handle!==void 0&&this.tui.requestRender()}matches(e,n){return iS(this.bindings,e,n,(r,i)=>nt(r,i))}hint(e){return e.flatMap(([n,r])=>this.bindings.gestures(n).length===0?[]:[`${$s(this.bindings,n)} ${r}`])}fitHints(e,n){let i=[],o=0;for(let s of this.hint(e)){let a=(i.length===0?0:3)+yd(s);if(o+a>n)break;i.push(s),o+=a}return i.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,CJr),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;let e=++this.snapshotSeq;this.buildSnapshot().then(n=>{e===this.snapshotSeq&&(this.snapshot=n,this.tui.requestRender())}).catch(n=>{this.onRefreshFailure(n),this.tui.requestRender()})}invalidate(){this.refresh()}async fetchInput(){if(this.remote){let i=await this.source.listNodes().catch(()=>[]);return{nodes:new Map(i.map(o=>[o.node_id,o])),subscriptions:async o=>(await this.source.subscriptionsOf(o)).map(s=>s.node_id),subscribers:async o=>(await this.source.subscribersOf(o)).map(s=>s.node_id),focused:new Set}}let e=await Ht().canvasGraph(),n=new Map,r=new Map;for(let i of e.edges){let o=n.get(i.from_id);o===void 0?n.set(i.from_id,[i.to_id]):o.push(i.to_id);let s=r.get(i.to_id);s===void 0?r.set(i.to_id,[i.from_id]):s.push(i.from_id)}return{nodes:new Map(e.nodes.map(i=>[i.node_id,RJr(i)])),subscriptions:i=>Promise.resolve(n.get(i)??[]),subscribers:i=>Promise.resolve(r.get(i)??[]),focused:new Set(e.focused_node_ids)}}async buildSnapshot(){let e=await this.fetchInput(),{nodes:n,focused:r}=e,i=new Map,o=new Map,s=new Map,a=new Map,c=async y=>{let b=i.get(y);if(b!==void 0)return b;let E;try{E=await e.subscriptions(y)}catch{E=[]}let S=E.filter(_=>n.get(_)?.kind!=="human");return i.set(y,S),S},u=async y=>{if(s.has(y))return s.get(y);let b;try{b=(await e.subscribers(y))[0]}catch{b=void 0}return s.set(y,b),b},l=async()=>{let y=this.self,b=new Set([y]);for(;;){let E=await u(y);if(E===void 0||b.has(E))break;b.add(E),y=E}return y},d=async y=>{let b=o.get(y);if(b!==void 0)return b;let E=[...await c(y)];return E.sort((S,_)=>$3e(n.get(S)?.status)-$3e(n.get(_)?.status)),o.set(y,E),E},p=new Set,h=new Set,m=async y=>{let b=n.get(y)?.status==="active";if(h.has(y))return{active:b?1:0,reveal:b||y===this.self};h.add(y);let E=0,S=!1;for(let _ of await c(y)){let I=await m(_);E+=I.active,I.reveal&&(S=!0)}return a.set(y,E),S&&p.add(y),{active:E+(b?1:0),reveal:S||b||y===this.self}},f=await l();await m(f),await Promise.all([...i.keys()].map(y=>d(y)));let g={root:f,rows:[],autoExpanded:p,activeBelow:a,nodes:n,childIds:i,sortedChildIds:o,managerOf:s,focused:r};return g.rows=this.projectRows(g),g}projectRows(e){let n=[],r=new Set,i=[{id:e.root,prefix:"",isRoot:!0,isLast:!0}];for(;i.length>0;){let{id:o,prefix:s,isRoot:a,isLast:c}=i.pop(),u=a?"":c?"\u2514\u2500 ":"\u251C\u2500 ";if(r.has(o)){n.push({id:o,hasKids:!1,isSelf:o===this.self,branch:s+u,cycle:!0,collapsed:!1});continue}r.add(o);let l=e.sortedChildIds.get(o)??[],d=this.folds.userExpanded.has(o)?!1:this.folds.userCollapsed.has(o)?!0:!e.autoExpanded.has(o);if(n.push({id:o,hasKids:l.length>0,isSelf:o===this.self,branch:s+u,cycle:!1,collapsed:d}),d)continue;let p=a?"":s+(c?" ":"\u2502 ");for(let h=l.length-1;h>=0;h--)i.push({id:l[h],prefix:p,isRoot:!1,isLast:h===l.length-1})}return n}repaintFolds(){this.snapshot!==void 0&&(this.snapshot.rows=this.projectRows(this.snapshot)),this.tui.requestRender()}renderSnapshotRow(e,n,r,i){let o=(_,I)=>r?gx(_,rm(),_v):I?gx(_,rm(),zan):fx(_);if(n.cycle){let _=`${n.branch} ${Oc}\u21BA ${Ale(n.id)}${Fr}`;return o(_,!1)}let s=e.nodes.get(n.id)??null,a=hle(s),c=aT(s,n.id),u=n.isSelf?`${L8}${c}${Fr}`:c,l=`${Oc}${s?.kind??""}${Fr}`,d=`${Oc}${mle(s,this.remote)}${Fr}`,p=n.hasKids&&n.collapsed,h=!r&&p?`${Oc}\u25B8${Fr} `:" ",m=gle(s),f=e.childIds.get(n.id)?.length??0,g=s!==null&&f>0?` ${Oc}\u2933${f}${Fr}`:"",y=s!==null&&s.status!=="active"&&(e.activeBelow.get(s.node_id)??0)>0?` ${ple}\u21E3${e.activeBelow.get(s.node_id)??0}${Fr}`:"",b=s?.fault??null,E=b!==null?` \xB7 ${Gan(b)}`:"",S=`${n.branch}${h}${a} ${u} ${l} ${d}${m}${g}${y}${yle(n.id,i)}${fle(s,this.remote)}${E}`;return o(S,Kan(n.id,s,e.focused,this.remote))}render(e){let n=this.getAsks(),r=this.snapshot?.rows??[],i=r.findIndex(E=>E.id===this.cursorId);i<0&&(i=r.findIndex(E=>E.id===this.self),i<0&&(i=0)),this.cursorId=r[i]?.id??this.self;let o=process.stdout.rows??jan,s=Math.max(3,Math.min(Math.floor(o*SJr),o-2)),a=Math.min(s-2,1+Math.max(1,r.length)),c=a-1,u=c>=3,l=c;for(let E=0;c>0&&E<4;E++){i<this.scrollTop&&(this.scrollTop=i),i>=this.scrollTop+l&&(this.scrollTop=i-l+1),this.scrollTop=Math.max(0,Math.min(this.scrollTop,Math.max(0,r.length-l)));let S=c-(u&&this.scrollTop>0?1:0)-(u&&this.scrollTop+l<r.length?1:0);if(S===l)break;l=Math.max(1,S)}let d=Math.min(r.length,this.scrollTop+l),p=[];u&&this.scrollTop>0&&p.push(`${Oc} \u2191 ${this.scrollTop} more${Fr}`);for(let E=this.scrollTop;E<d;E++){let S=this.snapshot;p.push(S!==void 0?this.renderSnapshotRow(S,r[E],E===i,n):"")}for(u&&d<r.length&&p.push(`${Oc} \u2193 ${r.length-d} more${Fr}`),p.unshift(TJr);p.length<a;)p.push("");let h=r.length>0?`${L8}\u2317 canvas graph${Fr} ${Oc}(${i+1}/${r.length})${Fr}`:`${L8}\u2317 canvas graph${Fr} ${Oc}(loading)${Fr}`,m=this.pendingConfirm!==void 0?`${O8}${this.pendingConfirm.label} ${L8}${this.hint([["crtr.graph.confirm.accept","accept"],["crtr.graph.confirm.cancel","cancel"]]).join(" \xB7 ")}${Fr}`:`${Oc}${this.fitHints([...this.remote||this.role!=="controller"?IJr:_Jr,...kJr],Math.max(1,e-5))}${Fr}`,f=this.palette.border,g=Math.max(1,e-4),y=p.map(E=>`${f("\u2502")} ${ot(E,g,"",!0)} ${f("\u2502")}`),b=this.palette.surface;return[this.borderRow("\u256D","\u256E",h,e),...y,this.borderRow("\u2570","\u256F",m,e)].map(b)}borderRow(e,n,r,i){let o=this.palette.border,s=Math.max(1,i-5),a=ot(r,s,"\u2026"),c=Math.max(0,i-5-yd(a));return`${o(`${e}\u2500`)} ${a} ${o("\u2500".repeat(c)+n)}`}handleInput(e){try{this.dispatch(e)}catch{}}dispatch(e){if(this.pendingConfirm!==void 0){if(this.matches("crtr.graph.confirm.accept",e)){let u=this.pendingConfirm.action;this.pendingConfirm=void 0,u()}else this.pendingConfirm=void 0;this.tui.requestRender();return}if(this.matches("crtr.graph.dismiss",e)){this.close();return}let n=this.snapshot,r=n?.rows??[],i=r.findIndex(u=>u.id===this.cursorId);i<0&&(i=Math.max(0,r.findIndex(u=>u.id===this.self)));let o=r[i],s=u=>u!==void 0&&!u.cycle,a=(u,l)=>{for(let d=u+l;d>=0&&d<r.length;d+=l)if(s(r[d]))return d;return u},c=u=>{let l=u===1?0:r.length-1;for(let d=l;d>=0&&d<r.length;d+=u)if(s(r[d]))return d;return i};if(this.matches("crtr.graph.down",e)){i=a(i,1),this.cursorId=r[i]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.up",e)){i=a(i,-1),this.cursorId=r[i]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.first",e)){this.cursorId=r[c(1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.last",e)){this.cursorId=r[c(-1)]?.id??this.cursorId,this.tui.requestRender();return}if(this.matches("crtr.graph.collapse-or-manager",e)){if(o!==void 0&&o.hasKids&&!o.collapsed)this.userCollapsed.add(o.id),this.userExpanded.delete(o.id),this.repaintFolds();else{let u=n?.managerOf.get(this.cursorId??this.self);u!==void 0&&r.some(l=>l.id===u)&&(this.cursorId=u),this.tui.requestRender()}return}if(this.matches("crtr.graph.expand-or-child",e)){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){let u=n?.sortedChildIds.get(o.id)?.[0];u!==void 0&&(this.cursorId=u),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}let u=this.cursorId,l=u===void 0?null:n?.nodes.get(u)??null;u!==void 0&&l!==null&&l.status!=="active"&&l.status!=="idle"&&(this.reviveTarget(u),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}let u=n?.managerOf.get(this.self);u!==void 0&&(this.focusTarget(u),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}let u=this.cursorId??this.self,l=n?.nodes.get(u)??null,d=l!==null?Xdn(l):Ale(u);this.pendingConfirm={label:`kill ${d}?`,action:()=>this.shellCrtr(["node","lifecycle","close","--node",u])},this.tui.requestRender();return}}focusTarget(e){let n=process.env.TMUX_PANE;if(n===void 0||n===""){this.onNotice("Focusing a node needs a local viewer in tmux");return}(async()=>{let r=Ht(),i=await r.getNode(e);(await Tle(r,i,{pane:n})).focused||this.onNotice("Could not open that node\u2019s viewer")})().catch(r=>this.onNotice(Nc(r)))}reviveTarget(e){this.shellCrtr(["node","lifecycle","revive",e],()=>this.focusTarget(e))}shellCrtr(e,n){try{vJr("crtr",e,i=>{i==null&&n?.()}).stdin?.end()}catch{}}};et();var MJr=.72,PJr={anchor:"center",width:"72%",minWidth:48,maxHeight:"72%",margin:1},dde=class{constructor(e,n){this.tui=e;this.pal=n}tui;pal;handle;bindings;scrollTop=0;lastContentRows=1;setBindings(e){this.bindings=e,this.handle!==void 0&&this.tui.requestRender()}toggle(){this.handle===void 0?this.open():this.close()}close(){this.handle!==void 0&&(this.handle.hide(),this.handle=void 0,this.tui.requestRender())}isOpen(){return this.handle!==void 0}invalidate(){this.handle!==void 0&&this.tui.requestRender()}render(e){let n=Math.max(1,e);if(n<5)return this.renderNarrow(n);let r=n-4,i=this.body(r),o=Math.max(1,this.tui.terminal.rows),s=Math.max(3,Math.min(Math.floor(o*MJr),Math.max(3,o-2))),a=Math.max(1,s-2),c=i.length>a,u=c&&a>=3?a-2:1;this.lastContentRows=u,this.scrollTop=Math.max(0,Math.min(this.scrollTop,Math.max(0,i.length-u)));let l=Math.min(i.length,this.scrollTop+u),d=[];for(c&&a>=3&&d.push(this.scrollTop>0?this.pal.muted(`\u2191 ${this.scrollTop} more`):""),d.push(...i.slice(this.scrollTop,l)),c&&a>=3?d.push(l<i.length?this.pal.muted(`\u2193 ${i.length-l} more`):""):c&&a===2&&d.push(l<i.length?this.pal.muted(`\u2193 ${i.length-l} more`):"");d.length<a;)d.push("");let p=this.pal.bold(this.pal.accent("\u2328 attach help")),h=this.pal.muted("esc dismiss \xB7 \u2191\u2193 scroll");return[this.borderRow("\u256D","\u256E",p,n),...d.map(m=>this.boxRow(m,n)),this.borderRow("\u2570","\u256F",h,n)].map(this.pal.surface)}handleInput(e){return nt(e,"escape")||nt(e,"q")?(this.close(),!0):nt(e,"up")||this.matchesBinding("crtr.attach.scroll.up",e)?this.scrollBy(-1):nt(e,"down")||this.matchesBinding("crtr.attach.scroll.down",e)?this.scrollBy(1):nt(e,"pageUp")||this.matchesBinding("crtr.attach.scroll.page-up",e)?this.scrollBy(-this.pageSize()):nt(e,"pageDown")||this.matchesBinding("crtr.attach.scroll.page-down",e)?this.scrollBy(this.pageSize()):!0}open(){this.scrollTop=0,this.handle=this.tui.showOverlay(this,PJr)}matchesBinding(e,n){return this.bindings!==void 0&&iS(this.bindings,e,n,(r,i)=>nt(r,i))}scrollBy(e){let n=this.body(Math.max(1,this.tui.terminal.columns-4)).length,r=Math.max(0,n-this.lastContentRows),i=Math.max(0,Math.min(r,this.scrollTop+e));return i!==this.scrollTop&&(this.scrollTop=i,this.tui.requestRender()),!0}pageSize(){return Math.max(1,this.lastContentRows-1)}body(e){return this.lines().flatMap(n=>this.wrap(n.text,e).map(r=>this.style(r,n.style)))}lines(){let e=(s,a)=>({text:`${this.binding(s)} ${a}`,style:"plain"}),n=s=>({text:s,style:"heading"}),r=s=>({text:s,style:"muted"}),i={text:"",style:"plain"},o=zf.map(({actionId:s})=>{let a=bd.find(c=>c.id===s)?.name??s;return e(s,a)});return[n("Learning crouter"),{text:"/tutorial the guided crouter tutorial \u2014 your agent teaches it, one lesson at a time",style:"plain"},i,n("Scrolling"),e("crtr.attach.scroll.up","scroll one line up"),e("crtr.attach.scroll.down","scroll one line down"),e("crtr.attach.scroll.page-up","scroll one page up"),e("crtr.attach.scroll.page-down","scroll one page down"),e("crtr.attach.scroll.live","return to the live bottom"),r("mouse wheel (when reporting is on)"),i,n("Searching the transcript"),{text:`${this.binding("crtr.attach.search")} search what the transcript is currently showing. Type to jump as you go, enter to browse the matches.`,style:"plain"},{text:`${this.binding("crtr.attach.search.next")} / ${this.binding("crtr.attach.search.previous")} next and previous match \xB7 ${this.binding("crtr.attach.search.edit")} edit the query \xB7 ${this.binding("crtr.attach.search.close")} close. Typing anything else closes search and returns to the editor.`,style:"plain"},{text:"A lowercase query ignores case; any uppercase letter makes it case-sensitive.",style:"plain"},{text:"Folded tool output is not on screen, so it is not searched \u2014 unfold it to include it.",style:"muted"},i,n("Selection and copy"),{text:"Drag with the mouse to select; releasing copies the selection to the clipboard (and the tmux buffer). Any key clears the highlight.",style:"plain"},{text:"prefix + [ tmux copy-mode selects and copies the visible screenful; it works even while mouse reporting is on.",style:"plain"},{text:"Option-drag (iTerm2, Terminal.app) or Shift-drag (Ghostty, Alacritty, xterm) makes a true terminal selection that bypasses mouse reporting.",style:"plain"},{text:"Block-copy commands copy transcript content and are not capped at one screenful.",style:"plain"},i,n("Copy commands"),{text:"/copy last assistant message.",style:"plain"},{text:`/copy-message (${this.binding("crtr.attach.copy.message")}) newest copyable block entirely visible in the viewport; otherwise the newest one that intersects it.`,style:"plain"},{text:"/copy-tool newest tool call's result text.",style:"plain"},{text:"/copy-transcript every copyable block's text, oldest to newest, joined by blank lines.",style:"plain"},i,n("Mouse"),{text:`/mouse or ${this.binding("crtr.attach.mouse.toggle")} toggle mouse reporting \u2014 wheel scrolling and viewer drag-select. Turning it off restores tmux drag-select and copy-mode mouse.`,style:"plain"},i,n("Other attach keys"),...o]}binding(e){return this.bindings===void 0?"Loading\u2026":$s(this.bindings,e)}wrap(e,n){if(e==="")return[""];let r=Math.max(1,n),i=e.split(/\s+/),o=[],s="";for(let a of i){let c=s===""?a:`${s} ${a}`;s!==""&&_e(c)>r?(o.push(ot(s,r,"",!0)),s=` ${a}`):s=c}return s!==""&&o.push(ot(s,r,"",!0)),o}style(e,n){switch(n){case"heading":return this.pal.bold(this.pal.accent(e));case"muted":return this.pal.muted(e);case"plain":return e}}boxRow(e,n){let r=n-4,i=ot(e,r,"",!0),o=" ".repeat(Math.max(0,r-_e(i)));return`${this.pal.border("\u2502")} ${i}${o} ${this.pal.border("\u2502")}`}borderRow(e,n,r,i){if(i<6)return ot(`${this.pal.border(e)}${r}${this.pal.border(n)}`,i,"",!0);let o=i-5,s=ot(r,o,"\u2026"),a=Math.max(0,i-5-_e(s));return`${this.pal.border(`${e}\u2500`)} ${s} ${this.pal.border("\u2500".repeat(a)+n)}`}renderNarrow(e){let n=ot(this.pal.bold(this.pal.accent("help")),e,"",!0);return[this.pal.surface(n)]}};et();import{join as DJr}from"node:path";function fN(t,e){let n=`${new Date().toISOString()} ${t} ${e}`.replaceAll(/[\r\n]/g," ");Kj(DJr(Ma(),"attach-invariants.log"),n)}et();var pde=class{constructor(e,n,r){this.surface=e;this.focusTarget=n;this.getRows=r}surface;focusTarget;getRows;_focused=!1;get focused(){return this._focused}set focused(e){this._focused=e,R$(this.focusTarget)&&(this.focusTarget.focused=e)}get wantsKeyRelease(){return this.focusTarget.wantsKeyRelease??this.surface.wantsKeyRelease??!1}render(e){let n=Math.max(0,Math.floor(this.getRows())),r=Math.max(0,Math.floor(e));this.surface.setRows(n);let i=this.surface.render(r);i.length!==n&&kze(`surface rendered ${i.length} rows; expected ${n}`);let o=i.slice(0,n).map(a=>_e(a)>r?(kze(`surface row is ${_e(a)} cells wide; expected at most ${r}`),epn($i(a,0,r,!0),r)):epn(a,r));for(;o.length<n;)o.push(" ".repeat(r));let s=BJr(o);return s>1?(kze(`surface frame contains ${s} CURSOR_MARKER sequences; expected at most one`),o.map(LJr)):o}handleInput(e){(this.focusTarget.handleInput??this.surface.handleInput)?.call(this.focusTarget.handleInput===void 0?this.surface:this.focusTarget,e)}invalidate(){this.surface.invalidate()}};function epn(t,e){return ot(t,e,"",!0)}function BJr(t){return t.reduce((e,n)=>e+n.split(Kr).length-1,0)}function LJr(t){return t.split(Kr).join("")}function kze(t){fN("surface-frame",t)}var OJr={anchor:"top-left",width:"100%",maxHeight:"100%",margin:0},NJr={anchor:"top-left",width:"100%",margin:0,nonCapturing:!0},mde=class{capabilities;tui;mouse;getRows;statusNotice;formatNotice;noticeMs;selfPane;stack=[];noticeOverlay;noticeTimer;constructor(e){this.tui=e.tui,this.mouse=e.mouse,this.getRows=e.rows,this.statusNotice=e.statusNotice,this.formatNotice=e.formatNotice,this.noticeMs=e.noticeMs,this.selfPane=e.selfPane,this.capabilities={...e.capabilities,selfPane:e.selfPane}}mount(e,n){this.disposeNotice();let r=new pde(e,n?.focus??e,this.getRows),i=this.tui.showOverlay(r,OJr),o={component:e,frame:r,overlay:i,cleanup:[],closed:!1,closing:!1},s=this.stack[this.stack.length-1];return s&&s.overlay.setHidden(!0),this.stack.push(o),{close:()=>this.closeEntry(o,!0),invalidate:()=>{!o.closed&&this.stack[this.stack.length-1]===o&&this.tui.requestRender()},onClose:a=>{if(o.closed||o.closing){hde("onClose registered after surface close");return}o.cleanup.push(a)}}}notice(e,n){if(this.disposeNotice(),this.stack.length===0){this.statusNotice(e,n);return}if(e==="")return;let r=new Rze(()=>this.formatNotice(e));this.noticeOverlay=this.tui.showOverlay(r,NJr),n?.sticky!==!0&&this.noticeMs>0&&(this.noticeTimer=setTimeout(()=>{this.noticeTimer=void 0,this.disposeNoticeOverlay()},this.noticeMs))}suspendForChild(){return this.tui.stop(),()=>{this.tui.start(),this.mouse.reassert(),this.tui.invalidate(),this.tui.requestRender(!0)}}async focusNode(e){if(!this.capabilities.canFocusNode||this.selfPane===void 0||this.selfPane==="")return this.notice("Focusing a node needs a local viewer in tmux"),!1;try{let n=Ht(),r=await n.getNode(e),i=await kle(n,e,{pane:this.selfPane,cwd:r.cwd,name:r.name});return i.focused||this.notice("Could not open that node\u2019s viewer"),i.focused}catch(n){return this.notice(Nc(n)),!1}}pickReviewFile(e){return new Promise(n=>{let r,i=!1,o=a=>{i||(i=!0,n(a),r.close())},s=jle(e.candidates,e.cwd,a=>o(a),()=>o(null),a=>this.notice(a));r=this.mount($Jr(s.component,e.title),{focus:s.focus}),r.onClose(()=>o(null))})}handleWheel(e,n){return this.stack[this.stack.length-1]?.component.handleWheel?.(e,n)??!1}hasFullPaneSurface(){return this.stack.length>0}closeAll(){let e=this.stack[0];e&&this.closeEntry(e,!1),this.disposeNotice()}closeEntry(e,n){if(e.closed||e.closing)return;if(this.stack.indexOf(e)===-1){e.closed=!0;return}for(e.closing=!0;this.stack.indexOf(e)!==-1;){let o=this.stack.indexOf(e),s=this.stack[o+1];if(!s)break;this.closeEntry(s,!1)}try{e.overlay.hide()}catch(o){hde(`surface overlay hide failed: ${Tze(o)}`)}for(let o of e.cleanup)try{let s=o();s&&typeof s.then=="function"&&s.catch(a=>hde(`surface cleanup failed: ${Tze(a)}`))}catch(s){hde(`surface cleanup failed: ${Tze(s)}`)}e.cleanup.length=0,e.closed=!0,e.closing=!1;let i=this.stack.indexOf(e);if(i!==-1&&this.stack.splice(i,1),n){this.disposeNotice();let o=this.stack[this.stack.length-1];o&&o.overlay.setHidden(!1)}}disposeNotice(){this.disposeNoticeOverlay(),this.noticeTimer!==void 0&&(clearTimeout(this.noticeTimer),this.noticeTimer=void 0)}disposeNoticeOverlay(){this.noticeOverlay?.hide(),this.noticeOverlay=void 0}},Rze=class{constructor(e){this.text=e}text;render(e){return[ot(this.text(),Math.max(0,e),"",!0)]}invalidate(){}};function $Jr(t,e){let n=0;return{setRows:r=>{n=Math.max(0,Math.floor(r))},render:r=>{let i=t.render(r),s=(e===void 0?i:[ot(e,Math.max(0,r),"",!0),...i.slice(1)]).slice(0,n);for(;s.length<n;)s.push("");return s},invalidate:()=>t.invalidate()}}function hde(t){fN("surface-host",t)}function Tze(t){return t instanceof Error?t.message:String(t)}et();import{existsSync as zJr,watch as VJr}from"node:fs";function FJr(t,e){switch(e){case"gray":return`${Wue}${t}${Oe}`;case"cyan":return`${ss}${t}${Oe}`;case"red":return`${vsn}${t}${Oe}`;case"yellow":return`${Ns}${t}${Oe}`;default:return t}}var UJr={notify:"\u2709",decision:"\u25C6",context:"\u270E",error:"\u26A0",review:"\u25A4",display:"\u2709",rich:"\u25A3",interactive:"\u25C6"},QJr={notify:"gray",decision:"cyan",context:"cyan",error:"red",review:"yellow",display:"gray",rich:"cyan",interactive:"cyan"};function WJr(t){let e=Math.floor((Date.now()-new Date(t).getTime())/6e4);return e>=60?`${Math.floor(e/60)}h ago`:e>0?`${e}m ago`:"just now"}function tpn(t,e,n,r,i=Number.MAX_SAFE_INTEGER){let o=[` ${os}${t.length} pending${Oe} ${ut}\xB7 ${r.label}${Oe}`];if(r.hint!==void 0&&o.push(` ${ut}${r.hint}${Oe}`),o.push(""),t.length===0)return[...o,` ${ut}${Esn}No pending interactions${Oe}`];let s=e-4,a=t.map((l,d)=>HJr(l,d,n,s)),c=qJr(a,n,Math.max(1,i-o.length)),u=[...o];c.start>0&&u.push(` ${ut}\u2191 ${c.start} above${Oe}`);for(let l=c.start;l<c.end;l++)u.push(...a[l]);return c.end<t.length&&u.push(` ${ut}\u2193 ${t.length-c.end} below${Oe}`),u}function HJr(t,e,n,r){let i=t.kind==="page"?t.awaitsResponse===!1?"display":"rich":t.kind,o=UJr[i]??"\xB7",s=WJr(t.kind==="page"?t.emittedAt:t.blockedSince),a=e===n?`${ss}\u25B8${Oe} `:" ",c=Math.max(1,r-s.length-6),u=`${a}${FJr(o,QJr[i]??"cyan")} ${os}${Hue(t.title||`(${t.id.slice(0,8)})`,c)}${Oe} ${ut}${s}${Oe}`,l=t.claim?`claimed by ${t.claim.owner} \xB7 ${t.subtitle}`:t.subtitle,d=[u,` ${ut}${Hue(l,r-6)}${Oe}`],p=Mze(t);return p!==void 0&&d.push(` ${ut}Recommended: ${Hue(p,Math.max(1,r-19))}${Oe}`),d}function Mze(t){if(!(t.kind!=="page"||t.recommendedOptions.length===0))return t.recommendedOptions.map(e=>e.label).join(" \xB7 ")}function qJr(t,e,n){let r=Math.max(0,Math.min(e,t.length-1)),i=r+1,o=!0;for(;;){let s=i<t.length?{start:r,end:i+1}:void 0,a=r>0?{start:r-1,end:i}:void 0,u=(o?[s,a]:[a,s]).find(l=>l!==void 0&&GJr(t,l.start,l.end)<=n);if(u===void 0)break;r=u.start,i=u.end,o=!o}return{start:r,end:i}}function GJr(t,e,n){let r=e>0?1:0;for(let i=e;i<n;i++)r+=t[i].length;return n<t.length&&r++,r}function fde(t,e,n="list"){if(t<60||e<18)return{mode:"minimum",listWidth:t,detailWidth:0,height:e};if(t<96)return{mode:n,listWidth:t,detailWidth:t,height:e};let r=Math.max(30,Math.min(44,Math.floor(t/3)));return{mode:"two-column",listWidth:r,detailWidth:t-r-1,height:e}}var gde=class{constructor(e){this.opts=e}opts;running=null;stopped=!1;start(){return this.running!==null?this.running:(this.running=this.run(),this.running)}async stop(){this.stopped=!0,this.running!==null&&await this.running}async run(){if(this.opts.host.capabilities.remote)return this.opts.host.notice("The review is unavailable in a remote attach \u2014 the file and companion live on the host."),!1;let e;try{e=await Ax().byId(this.opts.reviewId)}catch(n){return this.opts.host.notice(jJr(n)),!1}return!this.stopped&&qle(this.opts.host,e)}};function jJr(t){return t instanceof ZA?cN(t):t instanceof Error?t.message:String(t)}var yde=class{options;host;scan;items=[];visible=[];profile;filter;pendingSeat;selectedDir;selectedIndex=0;screen="list";adapter;reviewAdapter;focusingSource=!1;claim;submittingDir;cancelConfirmation;cols;rows;status;refreshError;watchers=[];selectedWatcher;heartbeat;started=!1;closed=!1;preview;previewFailed;previewFetching;previewStale=!1;openRevision;constructor(e){this.options=e,this.host=e.host,this.scan=e.scan??KJr,this.cols=e.cols??80,this.rows=e.rows??24,this.profile=e.profile,this.filter=e.profile===void 0?"all":"profile",this.selectedDir=e.initialSelection,this.pendingSeat=e.initialSelection,this.rescan()}snapshot(){return{items:[...this.items],selectedDir:this.selectedDir,screen:this.screen,inputBuffer:this.adapter?.inputBuffer()}}async rescan(){let e=this.selectedDir,n=this.claim;try{this.items=await this.scan()}catch(i){if(this.closed)return;this.status=Nc(i),this.markDirty();return}if(this.closed)return;if(this.recomputeVisible(),this.pendingSeat!==void 0){let i=this.pendingSeat;this.pendingSeat=void 0,this.seatOn(i)}if(!(e!==void 0&&this.items.some(i=>i.dir===e))&&this.adapter!==void 0&&e!==void 0&&n!==void 0){let i=(await this.requestOrNull(n.id))?.state==="canceled";if(this.closed)return;i&&odn(e),e!==this.submittingDir&&(this.status=i?"canceled by requester":"ticket resolved elsewhere"),this.leaveDetail(e!==this.submittingDir)}this.reseatSelection()}recomputeVisible(){if(this.filter==="all"||this.profile===void 0){this.visible=this.items;return}let e=this.profile.members();this.visible=this.items.filter(n=>{let r=n.source.nodeId;return r!==void 0&&e.has(r)})}reseatSelection(){let e=this.selectedDir===void 0?-1:this.visible.findIndex(n=>n.dir===this.selectedDir);if(e>=0){this.selectedIndex=e;return}if(!(this.adapter!==void 0&&this.selectedDir!==void 0&&this.items.some(n=>n.dir===this.selectedDir))){if(this.visible.length===0){this.selectedIndex=0,this.selectedDir=void 0;return}this.selectedIndex=Math.min(Math.max(0,this.selectedIndex),this.visible.length-1),this.selectedDir=this.visible[this.selectedIndex].dir}}highlightIndex(){return this.selectedDir===void 0?-1:this.visible.findIndex(e=>e.dir===this.selectedDir)}currentRow(){let e=this.highlightIndex();return e>=0?this.visible[e]:void 0}scopeHeading(){return this.profile===void 0?{label:"all profiles"}:this.filter==="profile"?{label:this.profile.label,hint:"P all profiles"}:{label:"all profiles",hint:`P ${this.profile.label} only`}}refreshOutcome(e){if(this.refreshError=e,e===void 0){this.invalidate();return}this.markDirty()}start(){this.started||this.closed||(this.started=!0,this.watchRoots(),this.heartbeat=setInterval(()=>{this.claim!==void 0&&ede(this.claim.dir,this.claim.token)},1e4))}async invalidate(){if(this.previewStale=!0,await this.rescan(),!this.closed){if(this.adapter!==void 0&&this.claim!==void 0){await this.reloadSelectedPage();return}this.markDirty()}}resize(e,n){this.cols=e,this.rows=n,this.adapter?.resize(this.detailSize().cols,this.detailSize().rows),this.markDirty()}render(){let e=fde(this.cols,this.rows,this.screen);if(e.mode==="minimum")return[`${Ns}Resize terminal to at least 60\xD718 to use inbox.${Oe}`];let n=tpn(this.visible,e.listWidth,this.highlightIndex(),this.scopeHeading(),e.height),r=this.detailLines(e.detailWidth,e.height);if(e.mode==="list")return this.withStatus(n);if(e.mode==="detail")return this.withStatus(r);let i=[],o=`${Wue}\u2502${Oe}`;for(let s=0;s<e.height;s++){let a=ca(n[s]??"",e.listWidth),c=ca(r[s]??"",e.detailWidth),u=" ".repeat(Math.max(0,e.listWidth-_e(a)));i.push(`${a}${u}${o}${c}`)}return this.withStatus(i)}handleKey(e,n){if(n.ctrl&&e==="c"){this.close();return}if(this.screen==="detail"&&this.adapter!==void 0){if((e==="g"||e==="G")&&this.adapter.canAcceptHostKeys()){this.focusSelectedSource();return}this.adapter.handleKey(e,n),this.markDirty();return}if(this.cancelConfirmation!==void 0){if(e==="y"||e==="Y"){let r=this.cancelConfirmation.item;this.cancelConfirmation=void 0,this.status="canceling\u2026",this.cancelFromInbox(r)}else(e==="n"||e==="N"||n.escape)&&(this.cancelConfirmation=void 0,this.status=void 0);this.markDirty();return}if(e==="P"&&this.profile!==void 0){this.toggleProfileFilter(),this.markDirty();return}if(e==="x"||e==="X"){let r=this.currentRow();r!==void 0&&(this.cancelConfirmation={item:r},this.status=void 0),this.markDirty();return}if(e==="s"||e==="S"){this.sendFastAction(),this.markDirty();return}if(n.escape||e==="q"){this.close();return}e==="j"||n.downArrow?this.select(this.selectedIndex+1):e==="k"||n.upArrow?this.select(this.selectedIndex-1):e==="g"||e==="G"?this.focusSelectedSource():(n.return||e==="a")&&this.activate(),this.markDirty()}toggleProfileFilter(){this.filter=this.filter==="profile"?"all":"profile",this.recomputeVisible(),this.reseatSelection()}async sendFastAction(){let e=this.currentRow();if(e===void 0)return;if(e.kind!=="page"||e.fastAction===void 0){this.status="no recommended answer on this ticket \u2014 Enter opens it";return}let n=await this.requestOrNull(e.id);if(Pze(n)){this.status=Ade(n),await this.rescan();return}let r=J8(e.dir);if(r===null){this.status="ticket is being edited by another inbox";return}let i=e.fastAction.kind==="acknowledge"?"acknowledged":`sent: ${Mze(e)??"recommended answer"}`;this.submittingDir=e.dir;try{await K8(e.id,e.fastAction.responses),this.status=i}catch(o){this.status=Y8(o)==="already_settled"?Ade(await this.requestOrNull(e.id)):Nc(o)}finally{$f(e.dir,r.token),this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async cancelFromInbox(e){this.submittingDir=e.dir;try{e.kind==="review"?await Ax().cancel(e.id,"Canceled from the inbox."):await jln(e.id,{reason:"Canceled from the inbox.",actor:"human"}),this.status="canceled"}catch(n){this.status=Nc(n)}finally{this.submittingDir=void 0,await this.rescan(),this.markDirty()}}async activate(){let e=this.currentRow();if(e===void 0)return;if(e.kind==="review"){await this.activateReview(e);return}let n=await this.requestOrNull(e.id);if(this.closed)return;if(Pze(n)){this.status=Ade(n),await this.rescan();return}let r=J8(e.dir);if(r===null){this.status="ticket is being edited by another inbox";return}let i,o;try{let s=await Ht().getHumanInboxPage(e.inboxTicketId);if(s.state==="resolved"||s.state==="canceled"){$f(e.dir,r.token),this.status=qO(s),await this.rescan();return}i=eT(s),o=s.revision}catch{$f(e.dir,r.token),this.status="page could not be read",await this.invalidate();return}if(this.closed||this.claim!==void 0||this.adapter!==void 0){$f(e.dir,r.token);return}this.claim={dir:e.dir,id:e.id,ticketId:e.inboxTicketId,token:r.token},this.screen="detail",this.adapter=new dN({ticketId:e.inboxTicketId,page:i,productKinds:$3(),cols:this.detailSize().cols,rows:this.detailSize().rows,onDirty:()=>this.markDirty(),onEditorRequest:()=>this.editActivePageInput(),onBack:()=>{this.leaveDetail(),this.markDirty()},onComplete:s=>{this.complete(s)}}),this.openRevision=o,this.watchSelected(e.dir),this.markDirty()}async activateReview(e){this.reviewAdapter=new gde({reviewId:e.id,host:this.host});let n=!1;try{n=await this.reviewAdapter.start()}catch(r){this.status=Nc(r)}finally{this.reviewAdapter=void 0}if(n){this.close();return}await this.rescan(),this.markDirty()}selectDir(e){this.seatOn(e)&&this.markDirty()}seatOn(e){let n=this.visible.findIndex(r=>r.dir===e);return n<0&&this.items.some(r=>r.dir===e)&&(this.filter="all",this.recomputeVisible(),n=this.visible.findIndex(r=>r.dir===e)),n<0?!1:(this.select(n),!0)}async reloadSelectedPage(){let e=this.claim;if(this.adapter===void 0||e===void 0){this.markDirty();return}try{let n=await Ht().getHumanInboxPage(e.ticketId);if(this.closed||this.claim!==e||this.adapter===void 0)return;n.revision!==this.openRevision&&(this.openRevision=n.revision,this.adapter.reload(eT(n)))}catch{this.status="page could not be read"}this.markDirty()}close(){if(!this.closed){this.closed=!0,this.started=!1,this.heartbeat!==void 0&&clearInterval(this.heartbeat),this.heartbeat=void 0,this.reviewAdapter?.stop(),this.leaveDetail(this.claim?.dir!==this.submittingDir);for(let e of this.watchers)e.close();this.watchers=[],this.selectedWatcher?.close(),this.selectedWatcher=void 0,this.options.onClosed()}}async complete(e){let n=this.claim;if(n===void 0)return;this.submittingDir=n.dir;try{await K8(n.id,e)}catch(i){this.submittingDir=void 0,this.status=Nc(i);let o=Y8(i);if(o==="unreachable"||o==="other"){this.markDirty();return}o==="already_settled"&&(this.status=Ade(await this.requestOrNull(n.id))),this.leaveDetail(!1),await this.rescan(),this.markDirty();return}this.submittingDir=void 0,this.leaveDetail(!1),await this.rescan();let r=this.items.some(i=>i.dir===n.dir);dm({level:r?"warn":"info",event:"inbox.page.resolved",fields:{ticket_id:n.id,request_settled:Pze(await this.requestOrNull(n.id)),still_listed:r,claim_left_behind:zJr(Rv(n.dir))}}),this.markDirty()}editActivePageInput(){let e=this.adapter?.inputBuffer();if(e===void 0)return;let n=this.host.suspendForChild(),r={text:e};try{r=ide(e)}finally{n(),this.adapter?.setInputBuffer(r.text),r.error!==void 0&&(this.status=r.error),this.markDirty()}}leaveDetail(e=!0){this.adapter?.close(),this.adapter=void 0,this.selectedWatcher?.close(),this.selectedWatcher=void 0,e&&this.claim!==void 0&&$f(this.claim.dir,this.claim.token),this.claim=void 0,this.openRevision=void 0,this.screen="list",this.reseatSelection()}select(e){this.visible.length!==0&&(this.selectedIndex=Math.max(0,Math.min(e,this.visible.length-1)),this.selectedDir=this.visible[this.selectedIndex].dir)}detailSize(){let e=fde(this.cols,this.rows,this.screen);return{cols:Math.max(1,e.detailWidth-2),rows:e.height}}detailLines(e,n){if(this.adapter!==void 0)return this.adapter.render();let r=this.currentRow();if(r===void 0)return this.passiveDetailLines(e,n);let i=this.focusAvailable(r.dir)?` ${ut}g${Oe} chat`:"",o=r.kind==="page"&&r.fastAction!==void 0?` ${ut}s${Oe} ${r.fastAction.kind==="acknowledge"?"acknowledge":"send recommended"}`:"",s=r.kind==="page"?[` ${ut}Enter${Oe} opens the full page ${ut}\u2191\u2193/jk${Oe} select${o} ${ut}x${Oe} cancel`,` ${ut}Page:${Oe} c comment u/d scroll${i} ${ut}q${Oe} close`]:[` ${ut}Enter${Oe} opens the full review ${ut}\u2191\u2193/jk${Oe} select ${ut}x${Oe} cancel`,` ${i} ${ut}q${Oe} close`],a=Math.max(0,n-s.length),c=this.passiveDetailLines(e,a);for(;c.length<a;)c.push("");return[...c,...s.map(u=>ca(u,e))]}focusAvailable(e){return this.host.capabilities.canFocusNode}async focusSelectedSource(){let e=this.screen==="detail"?this.claim?.dir:this.currentRow()?.dir,n=e===void 0?void 0:this.items.find(i=>i.dir===e);if(n===void 0||this.focusingSource)return;let r=n.source.nodeId;if(r===void 0){this.status="This request was not raised by a canvas node",this.markDirty();return}this.focusingSource=!0;try{await this.host.focusNode(r)?this.close():(this.status="Could not open that node\u2019s viewer",this.markDirty())}finally{this.focusingSource=!1}}pagePreviewBody(e,n){let r=this.preview;if(r!==void 0&&r.dir===e.dir){if(this.previewStale&&this.schedulePreview(e),r.width===n&&r.links===fae())return r.lines;let i=npn(r.view,n);return this.preview={...r,width:n,links:fae(),lines:i},i}return this.schedulePreview(e),this.previewFailed===e.dir?[`${ut}page could not be read${Oe}`]:[]}schedulePreview(e){this.previewFetching!==e.dir&&(this.previewFetching=e.dir,this.previewStale=!1,Ht().getHumanInboxPage(e.inboxTicketId).then(n=>{if(this.closed||this.previewFetching!==e.dir||(this.previewFetching=void 0,this.previewFailed=void 0,this.preview?.dir===e.dir&&this.preview.revision===n.revision))return;let r=eT(n),i=this.preview?.width??fde(this.cols,this.rows,this.screen).detailWidth;this.preview={dir:e.dir,revision:n.revision,view:r,width:i,links:fae(),lines:npn(r,i)},this.markDirty()},()=>{this.closed||this.previewFetching!==e.dir||(this.previewFetching=void 0,this.previewFailed=e.dir,this.preview?.dir===e.dir&&(this.preview=void 0),this.markDirty())}))}async requestOrNull(e){try{return await Ht().getHumanRequest(e)}catch{return}}passiveDetailLines(e,n){let r=this.currentRow();if(r===void 0)return[` ${ut}Select a pending interaction.${Oe}`];let i=[...fl(ml(r.title),Math.max(10,e-2)).map(s=>` ${os}${ss}${s}${Oe}`),""];for(let s of pae(r.subtitle,Math.max(1,e-2)))i.push(` ${s}`);let o=r.kind==="page"?this.pagePreviewBody(r,e):[`${ut}1 file to review${Oe}`];if(o.length>0){i.push("");let s=Math.max(0,n-i.length),a=o.length<=s?o:o.slice(0,Math.max(0,s-1));for(let c of a)i.push(` ${c}`);a.length<o.length&&i.push(` ${ut}\u2026 +${o.length-a.length} more lines${Oe}`)}return i.map(s=>ca(s,e)).slice(0,Math.max(1,n))}withStatus(e){let n=this.cancelConfirmation===void 0?this.refreshError??this.status:`cancel \u201C${this.cancelConfirmation.item.title}\u201D? y yes \xB7 n/Esc no`;if(n===void 0||this.rows<1)return e;let r=[...e];for(;r.length<this.rows;)r.push("");return r[this.rows-1]=`${Ns}${n}${Oe}`,r}markDirty(){this.options.onDirty()}watchRoots(){let e=lN(this.options.onInboxActivity??(()=>{this.invalidate()}));this.watchers.push({close:e})}watchSelected(e){this.selectedWatcher?.close();try{this.selectedWatcher=VJr(e,()=>{this.invalidate()})}catch{this.selectedWatcher=void 0}}};async function KJr(){let{tickets:t}=await Ht().listHumanInbox();return t.map(Lf).sort(bv)}function npn(t,e){let n=t.manifest.dialect==="html"?$O(t.document):NO(t.document,t.manifest);return Gue(t.manifest,n,Math.min(Math.max(20,e-4),100),Math.max(20,e-4))}function Pze(t){return t!==void 0&&t.state!=="pending"}function Ade(t){return t?.page===void 0?"ticket was already resolved":qO(t.page)}var Dze=class{constructor(e){this.controller=e}controller;focused=!1;rows=0;width=-1;height=-1;handle;setRows(e){this.rows=e}render(e){let n=this.rows;return(e!==this.width||n!==this.height)&&(this.width=e,this.height=n,this.controller.resize(e,n)),YJr(this.controller.render(),e,n)}handleInput(e){let{input:n,key:r}=rde(e);this.controller.handleKey(n,r)}invalidate(){this.handle?.invalidate()}setHandle(e){this.handle=e}};function YJr(t,e,n){let r=t.slice(0,n);for(;r.length<n;)r.push("");return r.map(i=>{let o=ca(i,e);return o+" ".repeat(Math.max(0,e-qo(o)))})}async function JJr(t){if(t.scan!==void 0)return t.scan();let{tickets:e}=await Ht().listHumanInbox();return e.map(Lf).sort(bv)}async function rpn(t,e){try{return await e()}catch(n){throw new Error(`Could not load ${t}: ${n instanceof Error?n.message:String(n)}`)}}function ipn(t){let e,n=()=>{let c=e;c===void 0||c.closed||(c.closed=!0,e=void 0,c.controller?.close(),c.handle?.close(),c.controller=void 0,c.handle=void 0)},r=c=>{if(c.closed||e!==c)return;let u=new yde({host:t.host,onDirty:()=>c.handle?.invalidate(),onClosed:n,...t.scan===void 0?{}:{scan:t.scan},onInboxActivity:()=>o(c),...c.preselectDir===void 0?{}:{initialSelection:c.preselectDir},...t.profile===void 0?{}:{profile:{id:t.profile.id,label:t.profile.label,members:()=>c.profileMembers}}}),l=new Dze(u);c.controller=u;try{let d=t.host.mount(l);c.handle=d,l.setHandle(d),d.onClose(()=>{c.handle===d&&(c.handle=void 0),u.close()}),u.start()}catch(d){throw n(),d}},i=async c=>{let u=t.profile,l=c?rpn("inbox visibility",()=>JJr(t)):void 0,d=u===void 0?void 0:rpn("profile membership",()=>Ht().listNodes({profile_id:u.id})),[,p]=await Promise.all([l,d]);return p===void 0?void 0:new Set(p.map(h=>h.node_id))},o=(c,u=!1)=>{if(!u&&c.controller!==void 0&&t.profile===void 0){c.controller.invalidate();return}let l=++c.refreshGeneration;i(c.controller===void 0).then(d=>{c.closed||e!==c||l!==c.refreshGeneration||(d!==void 0&&(c.profileMembers=d),c.controller===void 0?r(c):c.controller.refreshOutcome())},d=>{if(c.closed||e!==c||l!==c.refreshGeneration)return;let p=d instanceof Error?d.message:String(d);if(u){n(),t.host.notice(p);return}c.controller?.refreshOutcome(p)})},s=c=>{if(e!==void 0){c!==void 0&&e.controller?.selectDir(c);return}if(t.host.capabilities.remote){t.host.notice("The inbox is unavailable in a remote attach.");return}let u={closed:!1,refreshGeneration:0,profileMembers:new Set,...c===void 0?{}:{preselectDir:c}};e=u,o(u,!0)};return{toggle:()=>{if(e!==void 0){n();return}s()},open:s,close:n,isOpen:()=>e!==void 0}}import{homedir as sXr}from"node:os";import{fileURLToPath as tXr}from"node:url";import{join as apn,dirname as nXr}from"node:path";import{readFileSync as XJr}from"node:fs";import{dirname as ZJr,join as opn}from"node:path";import{fileURLToPath as eXr}from"node:url";var xde=null;function spn(){if(xde!==null)return xde;let t=opn(ZJr(eXr(import.meta.url)),"..","..");return xde=JSON.parse(XJr(opn(t,"package.json"),"utf8")).version,xde}var rXr=tXr(import.meta.url),iXr=nXr(rXr),oXr=apn(iXr,"..",".."),qPs=apn(oXr,"scripts","self-update.mjs");function cpn(){return spn()}var aXr="Ctrl+B d leaves \u2014 the agent keeps running \xB7 Ctrl+B n / p switches windows";function upn(t){let e;try{e=cpn()}catch{}let n;try{t.profile_id&&(n=Px(t.profile_id).manifest.name)}catch{}let r=t.cwd;if(r){let o=sXr();r===o?r="~":r.startsWith(o+"/")&&(r="~"+r.slice(o.length))}let i=process.env.CRTR_TMUX_STARTED==="1"?aXr:void 0;return{version:e,profile:n,cwd:r,...i!==void 0?{hint:i}:{}}}import{createConnection as cXr}from"node:net";function lpn(t,e){return t||e?"observer":"controller"}async function uXr(t){let e=Number(process.env.CRTR_ATTACH_WAIT_MS??"");if(!Number.isFinite(e)||e<=0)return;let n=DT(t),r=Date.now()+e;for(;Date.now()<r;){if(await new Promise(o=>{let s=cXr(n),a=c=>{s.destroy(),o(c)};s.once("connect",()=>a(!0)),s.once("error",()=>a(!1))}))return;await new Promise(o=>setTimeout(o,100))}}async function dpn(t,e,n=!0){let r=e!==void 0,i=r?ysn({canvasName:e}):new HO,o,s,a,c,u;if(r)o={cwd:process.cwd()},a=new hT(t,Nue(e));else{let h=await i.getNode(t);if(h===null)throw new Xh({error:"not_found",message:`no node: ${t}`,received:t,next:"List nodes with `crtr node inspect list`."});o=h,s=h;try{if((await Ht().ensureAttach(t,{resume:!0,revive:!0,wakeParked:n})).parked){let f=await Ht().getSnapshot(t);c=f.snapshot,u=f.commands}}catch(m){Hje(m,"The node may be finalized or otherwise not attachable.")}c===void 0&&await uXr(t),a=new hT(t,{socketPath:K7e()})}let l=new Z8(t,{transport:a}),d=h=>h instanceof ty?new Xh({error:"no_broker",message:h.message,received:t,next:"Focus or revive the node first \u2014 attach needs a running headless broker."}):new Xh({error:"socket_error",message:`could not attach to node ${t}: ${String(h?.message??h)}`,received:t,next:"Check the node has a running headless broker."}),p;return l.on("error",h=>{p===void 0&&(p=h)}),c===void 0&&await new Promise(async(h,m)=>{let f=()=>{y(),h()},g=b=>{y(),m(b)},y=()=>{l.off("connect",f),l.off("error",g)};l.on("connect",f),l.on("error",g),l.connect()}).catch(h=>{throw d(h)}),{remote:r,canvasSource:i,meta:o,nodeIdentity:s,socket:l,...c===void 0?{}:{initialSnapshot:c,initialCommands:u},assertConnected:()=>{if(c===void 0&&p!==void 0)throw d(p)}}}import{basename as jXr}from"node:path";aa();et();bfe();import{statSync as EXr}from"node:fs";et();import{mkdirSync as lXr,readFileSync as dXr,writeFileSync as pXr}from"node:fs";import{dirname as hXr,join as mXr}from"node:path";var fXr="completion-frecency.json",gXr=336*60*60*1e3,AXr=8,yXr=1e3;function xXr(t,e){if(!t)return 0;let n=Math.max(0,e-t.t),r=Math.pow(.5,n/gXr),i=1-Math.exp(-t.n/3);return AXr*r*i}function wXr(t){let e={};try{let n=JSON.parse(dXr(t,"utf8"));if(!n||typeof n!="object"||Array.isArray(n))return e;for(let[r,i]of Object.entries(n)){if(!i||typeof i!="object")continue;let{n:o,t:s}=i;typeof o!="number"||!Number.isFinite(o)||o<=0||typeof s!="number"||!Number.isFinite(s)||(e[r]={n:o,t:s})}}catch{}return e}function bXr(t,e){try{lXr(hXr(t),{recursive:!0}),pXr(t,JSON.stringify(e),"utf8")}catch{}}function ppn(t=mXr(Wc(),fXr)){let e=wXr(t),n,r=()=>{n||(n=setTimeout(()=>{n=void 0,bXr(t,e)},yXr),n.unref?.())};return{record:i=>{let o=e[i];e[i]={n:(o?.n??0)+1,t:Date.now()},r()},bonus:(i,o=Date.now())=>xXr(e[i],o)}}function Bze(t,e,n){let r=n.now??Date.now(),i=[];for(let o of t){let s=rR(e,n.searchableOf(o));s.matches&&i.push({item:o,score:s.score-n.store.bonus(n.idOf(o),r)})}return i.sort((o,s)=>o.score-s.score),i.map(o=>o.item)}function Lze(t){let e=Math.max(t.lastIndexOf("/"),t.lastIndexOf(":"));return e<0?t:`${t.slice(e+1)} ${t}`}function hpn(t){return t.replace(/:/g,"")}function ej(t,e,n){let r=t.join(`
|
|
1755
1755
|
`),i=0;for(let l=0;l<e&&l<t.length;l++)i+=t[l].length+1;let o=i+n,s=lcn(r,o);if(!s)return null;let a=s.start-i,c=s.end-i;return{kind:s.start===0?"leading":"ref",startCol:a,endCol:c,prefix:s.surfacePrefix}}var wde=class{refs;refNames;delegate;frecency;constructor(e,n,r){this.refs=e,this.refNames=new Set(e.map(i=>i.name)),this.delegate=n,this.frecency=r}get triggerCharacters(){return this.delegate.triggerCharacters}async getSuggestions(e,n,r,i){let o=ej(e,n,r);if(!o)return this.delegate.getSuggestions(e,n,r,i);if(o.kind==="leading"){if(i.force)return this.delegate.getSuggestions(e,n,r,i);let c=(e[n]??"").slice(0,r),u=await this.delegate.getSuggestions(["/"],0,1,i);if(!u)return null;let l=Bze(u.items,c.slice(1),{searchableOf:d=>Lze(d.value),idOf:d=>`command:${d.value}`,store:this.frecency});return l.length===0?null:{items:l,prefix:c}}let s=Bze(this.refs,hpn(o.prefix.slice(1)),{searchableOf:c=>Lze(c.name),idOf:c=>`ref:${c.name}`,store:this.frecency});return s.length===0?null:{items:s.map(c=>({value:c.name,label:w3e(c.name),description:c.shortForm||void 0})),prefix:o.prefix.slice(1)}}applyCompletion(e,n,r,i,o){let s=ej(e,n,r);if(s&&s.kind==="ref"&&this.refNames.has(i.value)){let a=w3e(i.value),c=e[n]??"",u=c.slice(0,s.startCol)+a+c.slice(s.endCol),l=e.slice();return l[n]=u,{lines:l,cursorLine:n,cursorCol:s.startCol+a.length}}return this.delegate.applyCompletion(e,n,r,i,o)}shouldTriggerFileCompletion(e,n,r){let i=ej(e,n,r);return i&&i.kind==="ref"?!0:this.delegate.shouldTriggerFileCompletion?this.delegate.shouldTriggerFileCompletion(e,n,r):!1}};var Oze=8,vXr=24,SXr=8192;function CXr(t,e){let n=t.slice(0,e),r=t.length>e;return{text:n.replace(/\x1b\](?:[^\x07\x1b]*)(?:\x07|\x1b\\)?/g,"").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\x00-\x09\x0b-\x1f\x7f-\x9f]/g,""),truncated:r}}function _Xr(t,e){if(e<vXr)return[];let n=Math.min(SXr,Math.max(256,e*Oze*4)),r=CXr(t,n),i=Po(r.text,e);if(!r.truncated&&i.length<=Oze)return i;let o=i.slice(0,Oze-1);return o.push(ot("\u2026 truncated \xB7 inspect for full prompt",e)),o}var tj=[46,92,190],nj=[166,98,24],IXr=[0,145,170];function rj(t,e,n){return[Math.round(t[0]+(e[0]-t[0])*n),Math.round(t[1]+(e[1]-t[1])*n),Math.round(t[2]+(e[2]-t[2])*n)]}var mpn={off:void 0,minimal:rj(tj,nj,0/4),low:rj(tj,nj,1/4),medium:rj(tj,nj,2/4),high:rj(tj,nj,3/4),xhigh:rj(tj,nj,4/4),max:IXr},kXr={black:[0,0,0],red:[205,49,49],green:[13,188,121],yellow:[229,229,16],blue:[36,114,200],magenta:[188,63,188],cyan:[17,168,205],white:[229,229,229],orange:[228,152,68],grey:[128,128,128],gray:[128,128,128],brightred:[241,76,76],brightgreen:[35,209,139],brightyellow:[245,245,67],brightblue:[59,142,234],brightmagenta:[214,112,214],brightcyan:[41,184,219]};function fpn(t){let e=t.trim().toLowerCase(),n=/^colour(\d{1,3})$/.exec(e);if(n!==null)return l=>`\x1B[48;5;${n[1]}m\x1B[97m\x1B[1m ${l} \x1B[0m`;let r,i=/^#([0-9a-f]{6})$/.exec(e);if(i!==null){let l=i[1];r=[parseInt(l.slice(0,2),16),parseInt(l.slice(2,4),16),parseInt(l.slice(4,6),16)]}else r=kXr[e];if(r===void 0)return;let[o,s,a]=r,u=.299*o+.587*s+.114*a>160?"\x1B[30m":"\x1B[97m";return l=>`\x1B[48;2;${o};${s};${a}m${u}\x1B[1m ${l} \x1B[0m`}var bde=t=>`\x1B[7m ${t} \x1B[27m`;function gpn(t,e){let n=t===void 0?void 0:mpn[t];if(n===void 0)return e;let[r,i,o]=n;return s=>`\x1B[38;2;${r};${i};${o}m${s}\x1B[39m`}function Apn(t,e){let n=t===void 0?void 0:mpn[t];if(n===void 0)return e;let[r,i,o]=n;return s=>`\x1B[48;2;${r};${i};${o}m\x1B[97m\x1B[1m ${s} \x1B[0m`}function TXr(t,e,n,r,i){let o=e?r(ot(e,Math.max(1,t-4),"\u2026")):"",s=_e(o),a=t-s,c="";n&&a>4&&(c=_e(n)<=a?n:ot(n,a,"\u2026"));let u=Math.max(0,t-s-_e(c));return o+i("\u2500".repeat(u))+c}var Ede="\x1B[7m",vde="\x1B[0m",Nze="\x1B[48;5;240m";function RXr(t){let e=t.indexOf(Kr);if(e===-1)return;let n=e+Kr.length;if(!t.startsWith(Ede,n))return;let r=n+Ede.length,i=t.indexOf(vde,r);if(i===-1)return;let o=t.slice(r,i),s=`${Nze}${o}\x1B[0m`;return t.slice(0,n)+s+t.slice(i+vde.length)}var MXr=/\.(png|jpe?g|gif|webp|bmp)$/i;function PXr(t){let e=t.match(/\x1b\[200~([\s\S]*?)\x1b\[201~/),n=(e?e[1]:t).trim();if(n.length<2||/[\u0000-\u0008\u000e-\u001f]/.test(n))return null;(n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))&&(n=n.slice(1,-1));let r=n.replace(/\\(.)/g,"$1");if(/\n/.test(r)||!MXr.test(r))return null;try{if(!EXr(r).isFile())return null}catch{return null}return r}function DXr(t,e,n,r){let i=[];if(t.length===0||t.length===1&&t[0]==="")return i.push({logicalLine:0,startIndex:0,endIndex:0,text:"",hasCursor:!0,cursorPos:0}),i;for(let o=0;o<t.length;o++){let s=t[o]??"",a=o===n;if(_e(s)<=e){i.push({logicalLine:o,startIndex:0,endIndex:s.length,text:s,hasCursor:a,cursorPos:a?r:0});continue}let c=M$(s,e);for(let u=0;u<c.length;u++){let l=c[u];if(!l)continue;let d=u===c.length-1,p=!1,h=0;a&&(d?(p=r>=l.startIndex,h=r-l.startIndex):(p=r>=l.startIndex&&r<l.endIndex,p&&(h=r-l.startIndex,h>l.text.length&&(h=l.text.length)))),i.push({logicalLine:o,startIndex:l.startIndex,endIndex:l.endIndex,text:l.text,hasCursor:p,cursorPos:h})}}return i}function BXr(t,e){return Ele(t).filter(n=>e.has(n.candidate)).map(n=>({start:n.start,end:n.end}))}var LXr="\x1B[4m\x1B[2m",OXr="\x1B[24m\x1B[22m",NXr=new Intl.Segmenter(void 0,{granularity:"grapheme"});function $Xr(t){for(let e of NXr.segment(t))return e.segment.length;return 0}function FXr(t){let e=t.indexOf(Kr),n=e===-1?0:e+Kr.length,r=t.indexOf(Ede,n),i=Ede.length;if(r===-1&&(r=t.indexOf(Nze,n),i=Nze.length),r===-1)return null;let o=t.indexOf(vde,r+i);return o===-1?null:{start:e!==-1?e:r,end:o+vde.length}}function UXr(t,e,n,r,i){let o=[];if(e.hasCursor){let a=FXr(t);if(a===null)return t;let c=e.text.slice(e.cursorPos),u=c.length===0?0:$Xr(c),l=e.cursorPos+u;for(let d of n){let p=d.start-e.startIndex,h=d.end-e.startIndex;if(h<=e.cursorPos){let m=i+p,f=i+h;f<=a.start&&t.slice(m,f)===r.slice(d.start,d.end)&&o.push({absStart:m,absEnd:f})}else if(p>=l){let m=a.end+(p-l),f=a.end+(h-l);m>=a.end&&t.slice(m,f)===r.slice(d.start,d.end)&&o.push({absStart:m,absEnd:f})}}}else for(let a of n){let c=i+(a.start-e.startIndex),u=i+(a.end-e.startIndex);t.slice(c,u)===r.slice(a.start,a.end)&&o.push({absStart:c,absEnd:u})}if(o.length===0)return t;o.sort((a,c)=>c.absStart-a.absStart);let s=t;for(let a of o)s=s.slice(0,a.absStart)+LXr+s.slice(a.absStart,a.absEnd)+OXr+s.slice(a.absEnd);return s}function QXr(t){let e=/^\/(\S+)\s*([\s\S]*)$/.exec(t.trim());return e?e[1]:null}function WXr(t,e){if(!t.startsWith("/"))return!1;let n=t.indexOf(" "),r=n===-1?t.slice(1):t.slice(1,n);if(e.has(r))return!0;if(t.startsWith("/skill:")){let i=n===-1?t.slice(7):t.slice(7,n);if(e.has(`skill:${i}`))return!0}return!1}var Sde=class t extends xk{km;pendingRawSubmitText;realOnSubmit;pendingReturn;static PASTE_BURST_MS=10;constructor(e,n,r,i){super(e,n,r,i),this.km=r;let o=this.submitValue.bind(this);this.submitValue=()=>{let s=this;this.pendingRawSubmitText=s.getExpandedText(),o()},Object.defineProperty(this,"onSubmit",{configurable:!0,get:()=>s=>{let a=this.pendingRawSubmitText??s;this.pendingRawSubmitText=void 0,this.realOnSubmit?.(a)},set:s=>{this.realOnSubmit=s}})}onPasteImagePath;settleHeldReturn(e){let n=this.pendingReturn;if(n!==void 0){if(clearTimeout(n.timer),this.pendingReturn=void 0,e==="newline"){this.insertTextAtCursor(`
|
|
1756
1756
|
`);return}super.handleInput(n.data),this.tui.requestRender()}}imageTokenWidthBeforeCursor(){let{line:e,col:n}=this.getCursor(),r=this.getLines()[e];if(r===void 0)return 0;let i=r.slice(0,n).match(/\[Image #\d+\]$/);return i?i[0].length:0}imageTokenWidthAfterCursor(){let{line:e,col:n}=this.getCursor(),r=this.getLines()[e];if(r===void 0)return 0;let i=r.slice(n).match(/^\[Image #\d+\]/);return i?i[0].length:0}handleInput(e){if(this.settleHeldReturn("newline"),!this.isShowingAutocomplete()&&this.km.matches(e,"tui.editor.cursorDown")){let s=this,a=this.getCursor(),c=s.historyIndex;super.handleInput(e);let u=this.getCursor();s.historyIndex===c&&u.line===a.line&&u.col===a.col&&this.onCursorDownAtBottom?.();return}if(!this.isShowingAutocomplete()&&this.km.matches(e,"tui.input.newLine")){this.insertTextAtCursor(`
|
|
1757
1757
|
`);return}if(!this.isShowingAutocomplete()&&this.km.matches(e,"tui.editor.deleteCharBackward")){let s=this.imageTokenWidthBeforeCursor();if(s>1){for(let a=0;a<s;a++)super.handleInput(e);return}}if(!this.isShowingAutocomplete()&&this.km.matches(e,"tui.editor.cursorLeft")){let s=this.imageTokenWidthBeforeCursor();if(s>1){for(let a=0;a<s;a++)super.handleInput(e);return}}if(!this.isShowingAutocomplete()&&this.km.matches(e,"tui.editor.cursorRight")){let s=this.imageTokenWidthAfterCursor();if(s>1){for(let a=0;a<s;a++)super.handleInput(e);return}}let n=PXr(e);if(n&&this.onPasteImagePath?.(n))return;if((e==="\r"||e===`
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export declare function mapAsync<T, U>(items: readonly T[], fn: (item: T, index: number, items: readonly T[]) => Promise<U>): Promise<U[]>;
|
|
2
|
+
export declare function flatMapAsync<T, U>(items: readonly T[], fn: (item: T, index: number, items: readonly T[]) => Promise<U | readonly U[]>): Promise<U[]>;
|
|
3
|
+
export declare function filterAsync<T>(items: readonly T[], fn: (item: T, index: number, items: readonly T[]) => Promise<unknown>): Promise<T[]>;
|
|
4
|
+
export declare function someAsync<T>(items: readonly T[], fn: (item: T, index: number, items: readonly T[]) => Promise<unknown>): Promise<boolean>;
|
|
5
|
+
export declare function everyAsync<T>(items: readonly T[], fn: (item: T, index: number, items: readonly T[]) => Promise<unknown>): Promise<boolean>;
|
|
6
|
+
export declare function findAsync<T>(items: readonly T[], fn: (item: T, index: number, items: readonly T[]) => Promise<unknown>): Promise<T | undefined>;
|
|
7
|
+
export declare function forEachAsync<T>(items: readonly T[], fn: (item: T, index: number, items: readonly T[]) => Promise<unknown>): Promise<void>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=Object.defineProperty;var a=(n,t)=>e(n,"name",{value:t,configurable:!0});async function u(n,t){const r=[];for(let o=0;o<n.length;o++)r.push(await t(n[o],o,n));return r}a(u,"mapAsync");async function l(n,t){const r=[];for(let o=0;o<n.length;o++){const c=await t(n[o],o,n);Array.isArray(c)?r.push(...c):r.push(c)}return r}a(l,"flatMapAsync");async function y(n,t){const r=[];for(let o=0;o<n.length;o++)await t(n[o],o,n)&&r.push(n[o]);return r}a(y,"filterAsync");async function i(n,t){for(let r=0;r<n.length;r++)if(await t(n[r],r,n))return!0;return!1}a(i,"someAsync");async function p(n,t){for(let r=0;r<n.length;r++)if(!await t(n[r],r,n))return!1;return!0}a(p,"everyAsync");async function h(n,t){for(let r=0;r<n.length;r++)if(await t(n[r],r,n))return n[r]}a(h,"findAsync");async function s(n,t){for(let r=0;r<n.length;r++)await t(n[r],r,n)}a(s,"forEachAsync");export{p as everyAsync,y as filterAsync,h as findAsync,l as flatMapAsync,s as forEachAsync,u as mapAsync,i as someAsync};
|
package/dist/core/audit.d.ts
CHANGED
|
@@ -18,6 +18,6 @@ export interface PeerAuditRow {
|
|
|
18
18
|
resource?: string | null;
|
|
19
19
|
}
|
|
20
20
|
/** Write one audit row. A failure to write is logged by the caller's wrapper and never changes the answer. */
|
|
21
|
-
export declare function writePeerAudit(row: PeerAuditRow): void
|
|
21
|
+
export declare function writePeerAudit(row: PeerAuditRow): Promise<void>;
|
|
22
22
|
/** The outcome string for an HTTP status. */
|
|
23
23
|
export declare const auditOutcome: (status: number) => string;
|