@north-light/crouter 0.3.349 → 0.3.351
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/crtr-launcher +4 -0
- package/bin/runtime-generation-manifest.mjs +12 -2
- package/dist/api/client.d.ts +50 -7
- package/dist/api/client.js +2 -2
- package/dist/api/dto/analytics.d.ts +184 -0
- package/dist/api/dto/analytics.js +0 -0
- package/dist/api/dto/broker-ops.d.ts +43 -1
- package/dist/api/dto/config.d.ts +11 -0
- package/dist/api/dto/grants.d.ts +14 -0
- package/dist/api/dto/grants.js +0 -0
- package/dist/api/dto/human-requests.d.ts +14 -0
- package/dist/api/dto/memory.d.ts +6 -0
- package/dist/api/dto/modelauth.d.ts +35 -0
- package/dist/api/dto/node-records.d.ts +35 -0
- package/dist/api/dto/node-records.js +0 -0
- package/dist/api/dto/nodes.d.ts +5 -0
- package/dist/api/dto/profiles.d.ts +38 -3
- package/dist/api/dto/worktree.d.ts +11 -0
- package/dist/api/errors.d.ts +23 -1
- package/dist/api/errors.js +1 -1
- package/dist/api/index.d.ts +2 -0
- package/dist/api/index.js +1 -1
- package/dist/api/node-transport.js +1 -1
- package/dist/api/routes.d.ts +22 -0
- package/dist/api/routes.js +1 -1
- package/dist/build-root.d.ts +6 -1
- package/dist/build-root.js +1 -1
- package/dist/builtin-memory/crouter-sdk/client.md +34 -0
- package/dist/builtin-memory/crouter-sdk/errors.md +2 -0
- package/dist/builtin-memory/crouter-sdk/memory.md +2 -2
- package/dist/builtin-memory/crouter-sdk/streaming.md +21 -0
- package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/claude-plugin-commands.ts +8 -4
- package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/memory-slash-commands.ts +39 -118
- package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/provider-rotation.d.ts +6 -1
- package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/provider-rotation.js +41 -27
- package/dist/builtin-pi-packages/pi-crtr-extensions/extensions/provider-rotation.ts +52 -29
- package/dist/cli.js +9 -8
- package/dist/clients/attach/chrome/inbox-strip.js +1 -1
- package/dist/clients/attach/chrome/roster.js +1 -1
- package/dist/clients/attach/config.js +1 -1
- package/dist/clients/attach/overlays/auth.js +2 -2
- package/dist/clients/attach/overlays/graph.js +1 -1
- package/dist/clients/attach/render/tool-calls.js +3 -3
- package/dist/clients/attach/session/connection.js +1 -1
- package/dist/clients/attach/session/profile-files.js +1 -1
- package/dist/clients/attach/viewer.js +1569 -816
- package/dist/commands/api-client.js +3 -3
- package/dist/commands/broker-permissions.d.ts +2 -0
- package/dist/commands/broker-permissions.js +1 -0
- package/dist/commands/canvas-analytics/chart.d.ts +52 -0
- package/dist/commands/canvas-analytics/chart.js +1 -0
- package/dist/commands/canvas-analytics/drilldown.d.ts +34 -0
- package/dist/commands/canvas-analytics/drilldown.js +1 -0
- package/dist/commands/canvas-analytics/format.d.ts +29 -0
- package/dist/commands/canvas-analytics/format.js +1 -0
- package/dist/commands/canvas-analytics/graph-detail.d.ts +2 -0
- package/dist/commands/canvas-analytics/graph-detail.js +2 -0
- package/dist/commands/canvas-analytics/graphs.d.ts +9 -0
- package/dist/commands/canvas-analytics/graphs.js +1 -0
- package/dist/commands/canvas-analytics/memory.d.ts +2 -0
- package/dist/commands/canvas-analytics/memory.js +1 -0
- package/dist/commands/canvas-analytics/overview.d.ts +2 -0
- package/dist/commands/canvas-analytics/overview.js +1 -0
- package/dist/commands/canvas-analytics/shell.d.ts +60 -0
- package/dist/commands/canvas-analytics/shell.js +2 -0
- package/dist/commands/canvas-analytics/time.d.ts +2 -0
- package/dist/commands/canvas-analytics/time.js +1 -0
- package/dist/commands/canvas-analytics/usage.d.ts +2 -0
- package/dist/commands/canvas-analytics/usage.js +1 -0
- package/dist/commands/canvas-analytics/view.d.ts +85 -0
- package/dist/commands/canvas-analytics/view.js +1 -0
- package/dist/commands/canvas-analytics.d.ts +2 -0
- package/dist/commands/canvas-analytics.js +1 -0
- package/dist/commands/canvas-prune.js +1 -1
- package/dist/commands/canvas.js +1 -1
- package/dist/commands/cron.js +5 -5
- package/dist/commands/human/components.d.ts +2 -0
- package/dist/commands/human/components.js +2 -2
- package/dist/commands/human/prompts.js +1 -1
- package/dist/commands/human/queue.js +1 -1
- package/dist/commands/memory/client.d.ts +11 -0
- package/dist/commands/memory/client.js +1 -0
- package/dist/commands/memory/delete.js +1 -1
- package/dist/commands/memory/edit.js +3 -3
- package/dist/commands/memory/find.js +1 -1
- package/dist/commands/memory/history.js +4 -4
- package/dist/commands/memory/lint.js +1 -1
- package/dist/commands/memory/list.d.ts +0 -2
- package/dist/commands/memory/list.js +1 -1
- package/dist/commands/memory/move.js +1 -1
- package/dist/commands/memory/origin.js +1 -1
- package/dist/commands/memory/read.d.ts +0 -5
- package/dist/commands/memory/read.js +3 -3
- package/dist/commands/memory/shared.d.ts +0 -178
- package/dist/commands/memory/shared.js +1 -12
- package/dist/commands/memory/write.js +5 -5
- package/dist/commands/node/bash.js +5 -5
- package/dist/commands/node/create.d.ts +0 -17
- package/dist/commands/node/create.js +2 -3
- package/dist/commands/node/inspect.js +6 -6
- package/dist/commands/node/lifecycle.js +2 -2
- package/dist/commands/node-context.js +2 -2
- package/dist/commands/node-inspect-artifacts.js +6 -6
- package/dist/commands/pkg/browse/catalog.js +1 -1
- package/dist/commands/pkg/browse/model.d.ts +1 -1
- package/dist/commands/pkg/market-manage.js +1 -1
- package/dist/commands/pkg/plugin-manage.js +10 -10
- package/dist/commands/profile/daemon-profiles.d.ts +13 -0
- package/dist/commands/profile/daemon-profiles.js +4 -0
- package/dist/commands/profile/delete.js +1 -1
- package/dist/commands/profile/env.d.ts +6 -0
- package/dist/commands/profile/env.js +2 -2
- package/dist/commands/profile/kind.js +1 -2
- package/dist/commands/profile/list.js +1 -1
- package/dist/commands/profile/meta.js +1 -1
- package/dist/commands/profile/new.js +1 -1
- package/dist/commands/profile/pause.js +1 -1
- package/dist/commands/profile/project.js +1 -1
- package/dist/commands/profile/rename.js +1 -1
- package/dist/commands/profile/show.js +1 -1
- package/dist/commands/profile.js +1 -1
- package/dist/commands/push.js +3 -3
- package/dist/commands/surface-inspect.js +1 -1
- package/dist/commands/sys/branch.js +1 -1
- package/dist/commands/sys/config.js +1 -1
- package/dist/commands/sys/connect.js +3 -3
- package/dist/commands/sys/context/admin/actions.js +1 -1
- package/dist/commands/sys/context/admin/model.d.ts +1 -0
- package/dist/commands/sys/context/admin/model.js +1 -1
- package/dist/commands/sys/context/admin.js +1 -1
- package/dist/commands/sys/context/expose.js +2 -1
- package/dist/commands/sys/context/prompt-review.js +2 -2
- package/dist/commands/sys/context/resolve.js +7 -7
- package/dist/commands/sys/context/sysprompt.js +1 -1
- package/dist/commands/sys/join.d.ts +1 -0
- package/dist/commands/sys/join.js +1 -0
- package/dist/commands/sys/migrate.js +1 -1
- package/dist/commands/sys/panels/models-panel.js +1 -1
- package/dist/commands/sys/panels/profiles-panel.d.ts +0 -1
- package/dist/commands/sys/panels/profiles-panel.js +1 -1
- package/dist/commands/sys/provider-login.js +6 -6
- package/dist/commands/sys/setup-core.d.ts +1 -1
- package/dist/commands/sys/setup-core.js +6 -6
- package/dist/commands/sys/setup-settings-runner.js +1 -1
- package/dist/commands/sys/setup.js +1 -1
- package/dist/commands/sys/spaces.d.ts +1 -0
- package/dist/commands/sys/spaces.js +2 -0
- package/dist/commands/sys/sync-deps.js +2 -2
- package/dist/commands/sys/sync-project-guidance.js +4 -4
- package/dist/commands/sys/sync-skills.js +2 -2
- package/dist/commands/sys/worktrees.d.ts +1 -0
- package/dist/commands/sys/worktrees.js +1 -1
- package/dist/commands/sys.js +1 -1
- package/dist/core/auth-file.js +2 -2
- package/dist/core/bash-job-supervisor.d.ts +6 -0
- package/dist/core/bash-job-supervisor.js +4 -0
- package/dist/core/bash-jobs.d.ts +13 -6
- package/dist/core/bash-jobs.js +8 -7
- package/dist/core/broker-client/transport-relay.d.ts +6 -3
- package/dist/core/broker-client/transport-relay.js +1 -1
- package/dist/core/broker-client/transport-socket.d.ts +6 -1
- package/dist/core/broker-client/transport-socket.js +1 -1
- package/dist/core/canvas/canvas.d.ts +39 -18
- package/dist/core/canvas/canvas.js +21 -20
- package/dist/core/canvas/context-strip.d.ts +20 -0
- package/dist/core/canvas/context-strip.js +5 -0
- package/dist/core/canvas/crons.d.ts +12 -20
- package/dist/core/canvas/crons.js +15 -13
- package/dist/core/canvas/db.js +2 -2
- package/dist/core/canvas/deliveries.d.ts +4 -1
- package/dist/core/canvas/deliveries.js +1 -1
- package/dist/core/canvas/executions.js +1 -1
- package/dist/core/canvas/history.d.ts +2 -1
- package/dist/core/canvas/history.js +17 -18
- package/dist/core/canvas/memory-reads.d.ts +19 -0
- package/dist/core/canvas/memory-reads.js +1 -0
- package/dist/core/canvas/migrations.d.ts +0 -4
- package/dist/core/canvas/migrations.js +99 -32
- package/dist/core/canvas/nav-render.js +1 -1
- package/dist/core/canvas/node-agent-paths.d.ts +8 -0
- package/dist/core/canvas/node-agent-paths.js +1 -0
- package/dist/core/canvas/node-recap.d.ts +2 -2
- package/dist/core/canvas/node-recap.js +2 -2
- package/dist/core/canvas/node-tokens.d.ts +24 -0
- package/dist/core/canvas/node-tokens.js +5 -0
- package/dist/core/canvas/paths.d.ts +16 -19
- package/dist/core/canvas/paths.js +1 -1
- package/dist/core/canvas/render-source.d.ts +2 -2
- package/dist/core/canvas/render-source.js +6 -9
- package/dist/core/canvas/sessions.d.ts +18 -0
- package/dist/core/canvas/sessions.js +4 -1
- package/dist/core/canvas/types.d.ts +22 -6
- package/dist/core/command-hooks/compose.js +1 -1
- package/dist/core/command-hooks/discovery.d.ts +15 -1
- package/dist/core/command-hooks/discovery.js +1 -1
- package/dist/core/command-hooks/help.d.ts +2 -2
- package/dist/core/command-hooks/lifecycle-create.d.ts +1 -1
- package/dist/core/command-hooks/lifecycle-create.js +1 -1
- package/dist/core/command-hooks/transport/exec-invoke.d.ts +2 -0
- package/dist/core/command-hooks/transport/exec-invoke.js +1 -1
- package/dist/core/command-hooks/transport/exec-lifecycle.d.ts +1 -0
- package/dist/core/command-hooks/transport/exec-lifecycle.js +1 -1
- package/dist/core/command-hooks/transport/plan.d.ts +3 -0
- package/dist/core/command-hooks/transport/plan.js +1 -0
- package/dist/core/command-plugins/discovery.js +1 -1
- package/dist/core/command.d.ts +6 -2
- package/dist/core/command.js +6 -6
- package/dist/core/config.d.ts +8 -5
- package/dist/core/config.js +1 -1
- package/dist/core/conversation-store/client-worker.d.ts +1 -0
- package/dist/core/conversation-store/client-worker.js +1 -0
- package/dist/core/conversation-store/client.d.ts +2 -0
- package/dist/core/conversation-store/client.js +2 -0
- package/dist/core/conversation-store/file-store.d.ts +37 -0
- package/dist/core/conversation-store/file-store.js +9 -0
- package/dist/core/conversation-store/index.d.ts +50 -0
- package/dist/core/conversation-store/index.js +1 -0
- package/dist/core/conversation-store/listener.d.ts +4 -0
- package/dist/core/conversation-store/listener.js +3 -0
- package/dist/core/conversation-store/patch.d.ts +1 -0
- package/dist/core/conversation-store/patch.js +1 -0
- package/dist/core/directory/join.d.ts +27 -0
- package/dist/core/directory/join.js +1 -0
- package/dist/core/disk-usage.d.ts +4 -0
- package/dist/core/disk-usage.js +1 -0
- package/dist/core/events/emit.d.ts +2 -0
- package/dist/core/events/emit.js +3 -1
- package/dist/core/feed/feed.js +4 -4
- package/dist/core/feed/messages.d.ts +3 -0
- package/dist/core/feed/messages.js +6 -6
- package/dist/core/fs-utils.d.ts +2 -0
- package/dist/core/fs-utils.js +3 -3
- package/dist/core/grants/local.d.ts +4 -0
- package/dist/core/grants/local.js +1 -0
- package/dist/core/grants/mirror.d.ts +44 -0
- package/dist/core/grants/mirror.js +4 -0
- package/dist/core/grants/on-sync.d.ts +22 -0
- package/dist/core/grants/on-sync.js +1 -0
- package/dist/core/grants/remove.d.ts +7 -0
- package/dist/core/grants/remove.js +1 -0
- package/dist/core/grants/sandboxes.d.ts +7 -0
- package/dist/core/grants/sandboxes.js +1 -0
- package/dist/core/grants/sync.d.ts +12 -0
- package/dist/core/grants/sync.js +1 -0
- package/dist/core/help/memory-extensions.d.ts +3 -0
- package/dist/core/help/memory-extensions.js +2 -0
- package/dist/core/help.d.ts +14 -0
- package/dist/core/help.js +7 -7
- package/dist/core/host-exports/builtins.js +3 -3
- package/dist/core/host-exports/export.js +3 -3
- package/dist/core/human/action-binding.d.ts +2 -0
- package/dist/core/human/action-binding.js +1 -1
- package/dist/core/human/feedback-companion.d.ts +0 -1
- package/dist/core/human/feedback-companion.js +1 -1
- package/dist/core/human/page-schema.d.ts +1 -1
- package/dist/core/inspector/core.d.ts +2 -0
- package/dist/core/inspector/core.js +1 -1
- package/dist/core/inspector/tui.js +2 -2
- package/dist/core/installed-plugins.js +1 -1
- package/dist/core/io.js +6 -6
- package/dist/core/keybindings/catalog.d.ts +1 -1
- package/dist/core/keybindings/catalog.js +1 -1
- package/dist/core/layout-migrate/index.d.ts +15 -0
- package/dist/core/layout-migrate/index.js +4 -0
- package/dist/core/layout-migrate/paths.d.ts +26 -0
- package/dist/core/layout-migrate/paths.js +1 -0
- package/dist/core/layout-migrate/stored-paths.d.ts +2 -0
- package/dist/core/layout-migrate/stored-paths.js +11 -0
- package/dist/core/layout-migrate/stores.d.ts +17 -0
- package/dist/core/layout-migrate/stores.js +4 -0
- package/dist/core/layout.d.ts +26 -0
- package/dist/core/layout.js +2 -0
- package/dist/core/llm/run.d.ts +60 -0
- package/dist/core/llm/run.js +4 -0
- package/dist/core/memory/cli-selector.d.ts +13 -0
- package/dist/core/memory/cli-selector.js +1 -0
- package/dist/core/memory/history.d.ts +5 -4
- package/dist/core/memory/history.js +6 -6
- package/dist/core/memory/inline-ref-inventory.d.ts +2 -1
- package/dist/core/memory/inline-ref-inventory.js +1 -1
- package/dist/core/memory/lint.js +2 -2
- package/dist/core/memory/mutation-domain.d.ts +2 -2
- package/dist/core/memory/mutation-domain.js +8 -7
- package/dist/core/memory/mutations.js +1 -1
- package/dist/core/memory/service.d.ts +5 -0
- package/dist/core/memory/service.js +2 -2
- package/dist/core/memory-resolver.d.ts +11 -7
- package/dist/core/memory-resolver.js +2 -2
- package/dist/core/model-auth/daemon-login.d.ts +13 -0
- package/dist/core/model-auth/daemon-login.js +1 -0
- package/dist/core/model-auth/flows.d.ts +45 -0
- package/dist/core/model-auth/flows.js +1 -0
- package/dist/core/model-auth/handoff-jti.d.ts +4 -0
- package/dist/core/model-auth/handoff-jti.js +1 -0
- package/dist/core/model-routes.js +1 -1
- package/dist/core/nested-stores.d.ts +2 -1
- package/dist/core/nested-stores.js +1 -2
- package/dist/core/preview-registry.js +2 -2
- package/dist/core/profiles/env-store.js +2 -2
- package/dist/core/profiles/manifest.d.ts +16 -5
- package/dist/core/profiles/manifest.js +1 -1
- package/dist/core/provider-management.js +1 -1
- package/dist/core/review/birth.js +1 -1
- package/dist/core/review/companion.d.ts +0 -2
- package/dist/core/review/companion.js +1 -1
- package/dist/core/review/fork.js +2 -2
- package/dist/core/review/realize.js +1 -1
- package/dist/core/review/stage.d.ts +1 -1
- package/dist/core/review/stage.js +1 -1
- package/dist/core/review/types.d.ts +1 -1
- package/dist/core/runs/events.d.ts +34 -0
- package/dist/core/runs/events.js +1 -0
- package/dist/core/runs/operations.d.ts +43 -0
- package/dist/core/runs/operations.js +12 -0
- package/dist/core/runtime/bearings-render.d.ts +2 -2
- package/dist/core/runtime/bearings-render.js +11 -11
- package/dist/core/runtime/bearings.js +2 -2
- package/dist/core/runtime/broker/cli-relay.d.ts +5 -0
- package/dist/core/runtime/broker/cli-relay.js +1 -0
- package/dist/core/runtime/broker/client-registry.d.ts +0 -5
- package/dist/core/runtime/broker/client-registry.js +1 -1
- package/dist/core/runtime/broker/daemon-ops.d.ts +28 -1
- package/dist/core/runtime/broker/daemon-ops.js +1 -1
- package/dist/core/runtime/broker/engine-drive.d.ts +0 -2
- package/dist/core/runtime/broker/engine-drive.js +1 -1
- package/dist/core/runtime/broker/fault-retry.d.ts +9 -0
- package/dist/core/runtime/broker/fault-retry.js +1 -1
- package/dist/core/runtime/broker/frame-dispatch.d.ts +5 -9
- package/dist/core/runtime/broker/frame-dispatch.js +1 -1
- package/dist/core/runtime/broker/frame-engine-control.d.ts +3 -2
- package/dist/core/runtime/broker/frame-engine-control.js +1 -1
- package/dist/core/runtime/broker/frame-memory-refs.d.ts +4 -3
- package/dist/core/runtime/broker/frame-memory-refs.js +1 -1
- package/dist/core/runtime/broker/frame-read.js +1 -1
- package/dist/core/runtime/broker/frame-session.js +1 -1
- package/dist/core/runtime/broker/held-deferred-inbox.d.ts +3 -1
- package/dist/core/runtime/broker/held-deferred-inbox.js +1 -1
- package/dist/core/runtime/broker/inbox.d.ts +1 -2
- package/dist/core/runtime/broker/inbox.js +7 -10
- package/dist/core/runtime/broker/model-adapter.d.ts +9 -0
- package/dist/core/runtime/broker/model-adapter.js +2 -0
- package/dist/core/runtime/broker/node-token.d.ts +3 -0
- package/dist/core/runtime/broker/node-token.js +1 -0
- package/dist/core/runtime/broker/read-ops.js +1 -1
- package/dist/core/runtime/broker/rebind.d.ts +2 -0
- package/dist/core/runtime/broker/rebind.js +1 -1
- package/dist/core/runtime/broker/tool-groups.js +1 -1
- package/dist/core/runtime/broker/turn-ignition.d.ts +3 -3
- package/dist/core/runtime/broker/turn-ignition.js +1 -1
- package/dist/core/runtime/broker-cli.js +3 -3
- package/dist/core/runtime/broker-extension-render.d.ts +2 -5
- package/dist/core/runtime/broker-extension-render.js +4 -4
- package/dist/core/runtime/broker-persona-guidance.js +3 -3
- package/dist/core/runtime/broker-protocol.d.ts +7 -8
- package/dist/core/runtime/broker.js +1 -1
- package/dist/core/runtime/canvas-extensions.d.ts +1 -0
- package/dist/core/runtime/canvas-extensions.js +1 -1
- package/dist/core/runtime/close.d.ts +9 -0
- package/dist/core/runtime/close.js +1 -1
- package/dist/core/runtime/deliver-live.js +1 -1
- package/dist/core/runtime/fleet.d.ts +1 -1
- package/dist/core/runtime/front-door-login.js +1 -1
- package/dist/core/runtime/front-door.js +2 -2
- package/dist/core/runtime/headless-pi.d.ts +1 -1
- package/dist/core/runtime/headless-pi.js +1 -1
- package/dist/core/runtime/host.d.ts +1 -1
- package/dist/core/runtime/host.js +3 -1
- package/dist/core/runtime/invocation.d.ts +3 -0
- package/dist/core/runtime/kickoff.d.ts +1 -0
- package/dist/core/runtime/kickoff.js +16 -16
- package/dist/core/runtime/launch-target.d.ts +1 -1
- package/dist/core/runtime/launch-target.js +1 -1
- package/dist/core/runtime/launch.d.ts +10 -35
- package/dist/core/runtime/launch.js +1 -1
- package/dist/core/runtime/lifecycle.js +2 -2
- package/dist/core/runtime/memory.d.ts +1 -1
- package/dist/core/runtime/memory.js +1 -1
- package/dist/core/runtime/model-registry.js +1 -1
- package/dist/core/runtime/model-swap.d.ts +17 -19
- package/dist/core/runtime/model-swap.js +1 -1
- package/dist/core/runtime/node-read.js +3 -2
- package/dist/core/runtime/nodes.d.ts +7 -0
- package/dist/core/runtime/nodes.js +1 -1
- package/dist/core/runtime/outcome-document.js +1 -1
- package/dist/core/runtime/package-health.js +2 -2
- package/dist/core/runtime/persona.js +2 -2
- package/dist/core/runtime/pi-vendored.js +1 -1
- package/dist/core/runtime/placement-tmux.d.ts +1 -1
- package/dist/core/runtime/placement-tmux.js +1 -1
- package/dist/core/runtime/placement.js +1 -1
- package/dist/core/runtime/promote.js +1 -1
- package/dist/core/runtime/provider-credential-gate.js +2 -2
- package/dist/core/runtime/recovery-hold.d.ts +2 -0
- package/dist/core/runtime/recovery-hold.js +1 -0
- package/dist/core/runtime/recycle.js +1 -1
- package/dist/core/runtime/reopen.js +1 -1
- package/dist/core/runtime/reset.js +1 -1
- package/dist/core/runtime/revive.d.ts +1 -1
- package/dist/core/runtime/revive.js +2 -3
- package/dist/core/runtime/roadmap.js +4 -4
- package/dist/core/runtime/run-command.d.ts +6 -0
- package/dist/core/runtime/run-command.js +1 -1
- package/dist/core/runtime/session-branch.d.ts +2 -8
- package/dist/core/runtime/session-branch.js +1 -1
- package/dist/core/runtime/session-list-cache.d.ts +6 -22
- package/dist/core/runtime/session-list-cache.js +1 -1
- package/dist/core/runtime/situational-context.js +2 -2
- package/dist/core/runtime/spawn-env.d.ts +6 -6
- package/dist/core/runtime/spawn-env.js +1 -1
- package/dist/core/runtime/spawn.d.ts +5 -0
- package/dist/core/runtime/spawn.js +2 -2
- package/dist/core/runtime/stop-guard.js +2 -2
- package/dist/core/runtime/stop-signals.d.ts +2 -2
- package/dist/core/runtime/stop-signals.js +1 -1
- package/dist/core/runtime/structured-output.d.ts +10 -4
- package/dist/core/runtime/structured-output.js +4 -4
- package/dist/core/runtime/tmux-bindings.js +3 -3
- package/dist/core/runtime/tmux-driver.d.ts +4 -0
- package/dist/core/runtime/tmux-driver.js +7 -7
- package/dist/core/runtime/view-socket.d.ts +9 -2
- package/dist/core/runtime/view-socket.js +1 -1
- package/dist/core/runtime/warm-pool.js +1 -1
- package/dist/core/scope.d.ts +3 -2
- package/dist/core/scope.js +1 -1
- package/dist/core/scoped-state/db.js +1 -1
- package/dist/core/scoped-state/migrate.js +3 -3
- package/dist/core/scoped-state/profiles.d.ts +2 -1
- package/dist/core/scoped-state/profiles.js +1 -1
- package/dist/core/scoped-state/schema.d.ts +2 -1
- package/dist/core/scoped-state/schema.js +4 -4
- package/dist/core/scopes.d.ts +2 -2
- package/dist/core/scopes.js +1 -1
- package/dist/core/secrets.d.ts +1 -0
- package/dist/core/secrets.js +2 -2
- package/dist/core/spaces/mounts.d.ts +32 -0
- package/dist/core/spaces/mounts.js +1 -0
- package/dist/core/spaces/open-beneath.d.ts +71 -0
- package/dist/core/spaces/open-beneath.js +1 -0
- package/dist/core/spaces/permissions.d.ts +46 -0
- package/dist/core/spaces/permissions.js +1 -0
- package/dist/core/spaces/process.d.ts +27 -0
- package/dist/core/spaces/process.js +1 -0
- package/dist/core/spaces/space.d.ts +8 -0
- package/dist/core/spaces/space.js +2 -0
- package/dist/core/spaces/stop.d.ts +8 -0
- package/dist/core/spaces/stop.js +2 -0
- package/dist/core/spaces/users.d.ts +19 -0
- package/dist/core/spaces/users.js +1 -0
- package/dist/core/subscription-state.d.ts +2 -0
- package/dist/core/subscription-state.js +3 -3
- package/dist/core/substrate/frontmatter-validation.js +1 -1
- package/dist/core/substrate/injected-store.d.ts +28 -3
- package/dist/core/substrate/injected-store.js +2 -1
- package/dist/core/substrate/listings.js +1 -1
- package/dist/core/substrate/memory-events.d.ts +6 -0
- package/dist/core/substrate/memory-events.js +1 -0
- package/dist/core/substrate/on-read-node.js +1 -1
- package/dist/core/substrate/on-read.d.ts +6 -6
- package/dist/core/substrate/on-read.js +5 -5
- package/dist/core/substrate/plan.js +1 -1
- package/dist/core/substrate/render-node.js +1 -1
- package/dist/core/substrate/render.d.ts +4 -3
- package/dist/core/substrate/render.js +38 -38
- package/dist/core/substrate/schema.d.ts +6 -0
- package/dist/core/substrate/schema.js +1 -1
- package/dist/core/tui/panel.js +1 -1
- package/dist/core/user-settings.d.ts +12 -0
- package/dist/core/user-settings.js +1 -1
- package/dist/core/worktree-mutation-async.js +5 -5
- package/dist/core/worktree-quarantine.js +1 -1
- package/dist/core/worktree-remove.d.ts +15 -0
- package/dist/core/worktree-remove.js +1 -0
- package/dist/core/worktree-sweep.js +6 -6
- package/dist/daemon/analytics/compute.d.ts +37 -0
- package/dist/daemon/analytics/compute.js +1 -0
- package/dist/daemon/analytics/scan-worker.d.ts +1 -0
- package/dist/daemon/analytics/scan-worker.js +2 -0
- package/dist/daemon/analytics/scan.d.ts +37 -0
- package/dist/daemon/analytics/scan.js +1 -0
- package/dist/daemon/api/app-listener.d.ts +11 -0
- package/dist/daemon/api/app-listener.js +21 -0
- package/dist/daemon/api/bridge.js +5 -5
- package/dist/daemon/api/handlers/analytics.d.ts +2 -0
- package/dist/daemon/api/handlers/analytics.js +1 -0
- package/dist/daemon/api/handlers/attach.js +1 -1
- package/dist/daemon/api/handlers/bash-jobs.js +2 -2
- package/dist/daemon/api/handlers/bash.js +1 -1
- package/dist/daemon/api/handlers/broker-ops.js +1 -1
- package/dist/daemon/api/handlers/canvas.d.ts +1 -1
- package/dist/daemon/api/handlers/canvas.js +6 -6
- package/dist/daemon/api/handlers/crons.js +1 -1
- package/dist/daemon/api/handlers/files.d.ts +1 -1
- package/dist/daemon/api/handlers/files.js +1 -1
- package/dist/daemon/api/handlers/health.js +2 -2
- package/dist/daemon/api/handlers/hook-exec.d.ts +2 -0
- package/dist/daemon/api/handlers/hook-exec.js +1 -0
- package/dist/daemon/api/handlers/human-requests.js +1 -1
- package/dist/daemon/api/handlers/inbox.js +1 -1
- package/dist/daemon/api/handlers/llm.d.ts +2 -0
- package/dist/daemon/api/handlers/llm.js +3 -0
- package/dist/daemon/api/handlers/memory-reads.d.ts +4 -0
- package/dist/daemon/api/handlers/memory-reads.js +1 -0
- package/dist/daemon/api/handlers/memory.js +5 -1
- package/dist/daemon/api/handlers/messages.js +2 -2
- package/dist/daemon/api/handlers/modelauth.js +1 -1
- package/dist/daemon/api/handlers/node-outcomes.js +1 -1
- package/dist/daemon/api/handlers/node-records.d.ts +2 -0
- package/dist/daemon/api/handlers/node-records.js +3 -0
- package/dist/daemon/api/handlers/nodes.d.ts +1 -1
- package/dist/daemon/api/handlers/nodes.js +1 -1
- package/dist/daemon/api/handlers/profiles.d.ts +4 -1
- package/dist/daemon/api/handlers/profiles.js +1 -1
- package/dist/daemon/api/handlers/reports.js +5 -3
- package/dist/daemon/api/handlers/reviews.d.ts +1 -1
- package/dist/daemon/api/handlers/reviews.js +1 -1
- package/dist/daemon/api/handlers/run-routes.d.ts +2 -0
- package/dist/daemon/api/handlers/run-routes.js +1 -0
- package/dist/daemon/api/handlers/runs.d.ts +9 -0
- package/dist/daemon/api/handlers/runs.js +1 -0
- package/dist/daemon/api/handlers/subscriptions.js +1 -1
- package/dist/daemon/api/handlers/worktree.js +1 -1
- package/dist/daemon/api/map.d.ts +10 -4
- package/dist/daemon/api/map.js +2 -2
- package/dist/daemon/api/operations.d.ts +18 -0
- package/dist/daemon/api/operations.js +1 -0
- package/dist/daemon/api/principal.d.ts +42 -0
- package/dist/daemon/api/principal.js +1 -0
- package/dist/daemon/api/router.d.ts +27 -3
- package/dist/daemon/api/router.js +1 -1
- package/dist/daemon/api/server.d.ts +4 -0
- package/dist/daemon/api/server.js +1 -1
- package/dist/daemon/api/vendor-signin.d.ts +7 -0
- package/dist/daemon/api/vendor-signin.js +77 -0
- package/dist/daemon/api/viewer-presence.d.ts +3 -0
- package/dist/daemon/api/viewer-presence.js +1 -0
- package/dist/daemon/cron/armed-context.d.ts +4 -0
- package/dist/daemon/cron/armed-context.js +1 -1
- package/dist/daemon/cron/escalation.js +3 -3
- package/dist/daemon/cron/lease-recovery.js +1 -1
- package/dist/daemon/cron/sinks.js +2 -2
- package/dist/daemon/cron-run.d.ts +5 -5
- package/dist/daemon/cron-run.js +1 -1
- package/dist/daemon/crtrd.js +8 -7
- package/dist/daemon/delivery/run-delivery.d.ts +4 -0
- package/dist/daemon/delivery/run-delivery.js +1 -1
- package/dist/daemon/fleet.d.ts +1 -1
- package/dist/daemon/fleet.js +6 -6
- package/dist/daemon/human/finish.js +7 -7
- package/dist/daemon/joined-owner.d.ts +5 -0
- package/dist/daemon/joined-owner.js +1 -0
- package/dist/daemon/manage.js +2 -2
- package/dist/daemon/messaging/node-message.js +1 -1
- package/dist/daemon/park-activity.js +1 -1
- package/dist/daemon/reconcilers/bash-deadline.js +1 -1
- package/dist/daemon/reconcilers/broker-supervision.d.ts +1 -1
- package/dist/daemon/reconcilers/broker-supervision.js +4 -4
- package/dist/daemon/reconcilers/delivery-lane.js +1 -1
- package/dist/daemon/reconcilers/live-obligation.d.ts +7 -0
- package/dist/daemon/reconcilers/live-obligation.js +1 -1
- package/dist/daemon/reconcilers/node-lifecycle/tick.js +1 -1
- package/dist/daemon/reconcilers/storage-maintenance.d.ts +20 -1
- package/dist/daemon/reconcilers/storage-maintenance.js +1 -1
- package/dist/daemon/runs/append-section.d.ts +6 -0
- package/dist/daemon/runs/append-section.js +2 -0
- package/dist/daemon/runs/observer.d.ts +5 -0
- package/dist/daemon/runs/observer.js +4 -0
- package/dist/launcher/bwrap.d.ts +4 -0
- package/dist/launcher/bwrap.js +2 -0
- package/dist/launcher/client.d.ts +2 -0
- package/dist/launcher/client.js +3 -0
- package/dist/launcher/main.d.ts +1 -0
- package/dist/launcher/main.js +3 -0
- package/dist/launcher/netrule.d.ts +1 -0
- package/dist/launcher/netrule.js +1 -0
- package/dist/launcher/seccomp.d.ts +1 -0
- package/dist/launcher/seccomp.js +1 -0
- package/dist/launcher/spec.d.ts +88 -0
- package/dist/launcher/spec.js +1 -0
- package/dist/launcher/users.d.ts +18 -0
- package/dist/launcher/users.js +7 -0
- package/dist/launcher/validate.d.ts +22 -0
- package/dist/launcher/validate.js +1 -0
- package/dist/migrations/corpus.js +3 -3
- package/dist/migrations/runner.js +1 -1
- package/dist/native/linux/addon.node +0 -0
- package/dist/native/linux.d.ts +29 -0
- package/dist/native/linux.js +1 -0
- package/dist/pi-extensions/broker-local.js +2 -2
- package/dist/pi-extensions/canvas-bash-valve.d.ts +1 -3
- package/dist/pi-extensions/canvas-bash-valve.js +4 -7
- package/dist/pi-extensions/canvas-context-intro.d.ts +1 -2
- package/dist/pi-extensions/canvas-context-intro.js +2 -2
- package/dist/pi-extensions/canvas-doc-substrate.js +6 -6
- package/dist/pi-extensions/canvas-inbox-watcher.d.ts +2 -1
- package/dist/pi-extensions/canvas-inbox-watcher.js +2 -1
- package/dist/pi-extensions/canvas-passive-context.d.ts +1 -1
- package/dist/pi-extensions/canvas-passive-context.js +11 -11
- package/dist/pi-extensions/canvas-recap.js +6 -6
- package/dist/pi-extensions/canvas-stophook.js +1 -1
- package/dist/pi-extensions/canvas-structured-output.js +4 -4
- package/dist/pi-extensions/canvas-tool-guide.js +1 -1
- package/dist/pi-extensions/system-prompt-entry.d.ts +15 -0
- package/dist/pi-extensions/system-prompt-entry.js +1 -0
- package/dist/shared/env.d.ts +5 -1
- package/dist/shared/env.js +1 -1
- package/dist/shared/strip-cd-prefix.d.ts +1 -0
- package/dist/shared/strip-cd-prefix.js +1 -0
- package/dist/types.d.ts +31 -15
- package/docs/cli/memory-and-preferences.md +3 -1
- package/docs/sdk/client.md +34 -0
- package/docs/sdk/errors.md +2 -0
- package/docs/sdk/memory.md +2 -2
- package/docs/sdk/streaming.md +21 -0
- package/package.json +18 -4
- package/packages/crouter-identity/dist/index.d.ts +54 -0
- package/packages/crouter-identity/dist/index.js +166 -0
- package/packages/crouter-identity/package.json +33 -0
- package/runtime.lock.json +34 -8
- package/scripts/build-native-linux.mjs +16 -0
- package/scripts/install-runtime.mjs +9 -7
- package/scripts/lib/isolation-env.mjs +42 -0
- package/scripts/runtime-smoke.mjs +49 -0
- package/src/native/linux/addon.c +249 -0
- package/dist/core/profiles/state-block.d.ts +0 -4
- package/dist/core/profiles/state-block.js +0 -3
- package/dist/core/runtime/broker/auth-reload.d.ts +0 -41
- package/dist/core/runtime/broker/auth-reload.js +0 -1
- package/dist/core/substrate/cli-context-delivery.d.ts +0 -22
- package/dist/core/substrate/cli-context-delivery.js +0 -1
|
@@ -1 +1,5 @@
|
|
|
1
|
-
var Y=Object.defineProperty;var a=(e,n)=>Y(e,"name",{value:n,configurable:!0});import{getNode as N}from"../../../core/canvas/canvas.js";import{ApiError as m}from"../../../api/errors.js";import{assertScope as J}from"../../../core/scopes.js";import{CrtrError as X}from"../../../core/errors.js";import{memoryDir as x}from"../../../core/runtime/memory.js";import{NEUTRAL_PROJECT_MEMORY as K,projectScopeRoots as L,scopeMemoryDir as Q}from"../../../core/scope.js";import{profileMemoryDir as F}from"../../../core/profiles/manifest.js";import{openProjectMemoryStore as V}from"../../../core/memory-resolver.js";import{candidateLocation as ee,createDoc as te,deleteDoc as ne,listDocs as oe,moveDoc as re,readDoc as ie,readHistory as se,searchDocs as de,updateDoc as ae}from"../../../core/memory/service.js";import{MEMORY_SCOPES as z,isMemoryDocName as S}from"../../../api/dto/memory.js";import{invalidRequest as b,isRecord as R,objectBody as j,optionalString as h,requiredString as w}from"./validate.js";const _="memory:read",I="memory:write",E=100,G=100;function q(e){const n=e.params.name;if(n===void 0||!S(n))throw new m(400,"invalid_memory_doc_name","memory document name must be slash-joined [A-Za-z0-9_-] segments");return n}a(q,"requireName");function k(e){return Object.fromEntries(e.query.entries())}a(k,"queryObject");function $(e,n){return{scope:e,storeRoot:n,namespace:"",mountStatus:"ready",projectMemory:K}}a($,"nativeStore");function p(e,n){const t=[];for(const c of Object.keys(e))n.includes(c)||t.push({field:c,problem:"is not allowed",received:e[c]});const r=h(e,"node",t),i=h(e,"cwd",t),o=h(e,"profile",t),s=h(e,"store",t);s!==void 0&&!z.includes(s)&&t.push({field:"store",problem:`must be one of ${z.join(", ")}`,received:s}),r!==void 0&&(i!==void 0||o!==void 0)&&t.push({field:"node",problem:"derives cwd and profile and cannot be combined with either"}),t.length>0&&b("memory scope",t);let d,l;if(r!==void 0){const c=N(r);if(c===null)throw new m(404,"node_not_found",`unknown node: ${r}`);d={cwd:c.cwd,profileId:c.profile_id??null,nodeId:c.node_id},l=c.node_id}else d={cwd:i??"/",profileId:o??null,nodeId:null};const u=s;if(u==="node"&&l===void 0)throw new m(400,"invalid_request","store node requires node");if(u==="profile"&&d.profileId===null)throw new m(400,"invalid_request","store profile requires profile or node with a profile");return{target:d,...u===void 0?{}:{scope:u},...l===void 0?{}:{nodeId:l}}}a(p,"resolveScope");function y(e,n){if(e.nodeId===void 0)return;const t=N(e.nodeId);if(t===null)throw new m(404,"node_not_found",`unknown node: ${e.nodeId}`);J(t,n)}a(y,"requireScope");function f(e,n){const t=e.scope;if(!n)return{...t===void 0?{}:{scope:t}};const r=t??(L(e.target.cwd,e.target.profileId).length>0?"project":"user");if(r==="builtin")throw new m(400,"invalid_request","builtin memory is read-only");if(r==="node")return{scope:r,store:$("node",x(e.target.nodeId)),memoryDir:x(e.target.nodeId)};if(r==="profile")return{scope:r,store:$("profile",F(e.target.profileId)),memoryDir:F(e.target.profileId)};if(r==="project"){const o=L(e.target.cwd,e.target.profileId)[0];if(o===void 0)throw new m(400,"invalid_request","store project requires a project memory store in cwd or profile");const s=V(o.slice(0,-8).replace(/\/$/,""));return{scope:r,store:s,memoryDir:s.storeRoot}}const i=Q("user");if(i===null)throw new Error("user memory directory unavailable");return{scope:"user",store:$("user",i),memoryDir:i}}a(f,"selection");function Z(e,n){return e.length>1?e.map(t=>ee(t,n)):void 0}a(Z,"candidates");function B(e){return{name:e.name,short_form:e.shortForm,kind:e.kind,scope:e.scope,extensions:e.extensions,path:e.path,store_root:e.storeRoot,physical_relative_path:e.physicalRelativePath,...Z(e.candidates,e.candidates[0])===void 0?{}:{candidates:Z(e.candidates,e.candidates[0])}}}a(B,"summary");function H(e){try{const n=ie(e);if(n.kind==="document")return n}catch(n){if(!(n instanceof X)||n.code!=="not_found")throw n}throw new m(404,"memory_document_not_found",`memory document not found: ${e.name}`)}a(H,"requestedDocument");function A(e,n,t=f(n,!1),r=!1){const i=H({target:n.target,...t,name:e,frontmatter:r,interpolateNodePaths:!1}),o=i.doc;return{...B({name:o.name,kind:String(o.frontmatter?.kind??""),scope:o.scope,path:o.path,storeRoot:o.root,physicalRelativePath:o.physicalRelativePath,shortForm:String(o.frontmatter?.["short-form"]??""),slash:o.frontmatter?.slash===!0,extensions:o.frontmatter?.extensions??{},candidates:i.candidates}),body:i.content,frontmatter:o.frontmatter,representation:o.representation,links:[...i.links]}}a(A,"document");function T(e,n,t){if(e===void 0)return t;const r=typeof e=="number"?e:Number(e);if(!Number.isInteger(r)||r<1||r>G)throw new m(400,"invalid_request",`${n} must be an integer from 1 through ${G}`);return r}a(T,"number");function U(e,n){const t=typeof e=="number"?e:Number(e);if(!Number.isFinite(t)||t<1)throw new m(400,"invalid_request",`${n} must be a finite number of at least 1`);return t}a(U,"positiveNumber");function D(e,n){const t=e[n];if(t!==void 0){if(t===!0||t==="true")return!0;if(t===!1||t==="false")return!1;throw new m(400,"invalid_request",`${n} must be a boolean`)}}a(D,"optionalBoolean");function W(e,n,t=[]){if(e!==void 0&&!R(e))throw new m(400,"invalid_request","frontmatter must be an object");const r=e===void 0?{}:e;for(const s of t)if(s in r)throw new m(400,"invalid_request",`frontmatter.${s} cannot be set directly`);const i={},o={"short-form":"shortForm","when-and-why-to-read":"whenAndWhyToRead","lint-ignore":"lintIgnore",rationale:"docRationale",kind:"kind",unlisted:"unlisted",surfaces:"surface",gate:"gate",slash:"slash"};for(const[s,d]of Object.entries(r)){const l=o[s];if(l===void 0)throw new m(400,"invalid_request",`frontmatter.${s} is not writable through this route`);if(s==="unlisted"||s==="slash"){if(d!==!0)throw new m(400,"invalid_request",`frontmatter.${s} must be true; remove it with unset`)}else if(s==="surfaces"){if(!Array.isArray(d)||!d.every(u=>typeof u=="string"))throw new m(400,"invalid_request","frontmatter.surfaces must be a string array")}else if(s==="lint-ignore"){if(!Array.isArray(d)||!d.every(u=>typeof u=="string"))throw new m(400,"invalid_request","frontmatter.lint-ignore must be a string array")}else if(typeof d!="string"||d.trim()==="")throw new m(400,"invalid_request",`frontmatter.${s} must be a non-empty string`);i[l]=d}if(n!==void 0){if(!R(n))throw new m(400,"invalid_request","extensions must be an object");const s=[];for(const[d,l]of Object.entries(n)){if(!R(l))throw new m(400,"invalid_request",`extensions.${d} must be an object`);for(const[u,c]of Object.entries(l))s.push(`extensions.${d}.${u}=${String(c)}`)}i.extension=s}return i}a(W,"frontmatterFields");function me(e){const n=k(e),t=[],r=h(n,"kind",t),i=h(n,"after",t);t.length>0&&b("memory list query",t);const o=p(n,["node","cwd","profile","store","kind","limit","after"]);y(o,_);const s=oe({target:o.target,...f(o,!1),...r===void 0?{}:{kind:r}}).sort((c,g)=>c.name.localeCompare(g.name)),d=i===void 0?s:s.filter(c=>c.name.localeCompare(i)>0),l=d.slice(0,T(n.limit,"limit",E)).map(B);return{status:200,body:{object:"list",data:l,has_more:d.length>l.length}}}a(me,"handleList");function le(e){const n=k(e),t=p(n,["node","cwd","profile","store","frontmatter"]);return y(t,_),{status:200,body:A(q(e),t,f(t,!1),D(n,"frontmatter")===!0)}}a(le,"handleRetrieve");function ce(e){const n=[],t=j(e.body,["name","kind","when_and_why_to_read","body","frontmatter","extensions","node","cwd","profile","store"],n),r=w(t,"name",n),i=w(t,"kind",n),o=w(t,"when_and_why_to_read",n),s=w(t,"body",n);if(n.length>0&&b("memory create request",n),!S(r))throw new m(400,"invalid_memory_doc_name","memory document name must be slash-joined [A-Za-z0-9_-] segments");const d=p(t,["name","kind","when_and_why_to_read","body","frontmatter","extensions","node","cwd","profile","store"]);y(d,I);const l=f(d,!0),u={name:r,kind:i,whenAndWhyToRead:o,body:s,...W(t.frontmatter,t.extensions,["kind","when-and-why-to-read","origin","last-updated"])},c=te({target:d.target,scope:l.scope,memoryDir:l.memoryDir,store:l.store,isExplicitProjectStore:!1,origin:{created:new Date().toISOString(),cwd:d.target.cwd,...d.target.nodeId===null?{}:{node:d.target.nodeId}},fields:u}),g=A(c.name,d,l);return{status:200,body:c.findings===void 0?g:{...g,findings:c.findings}}}a(ce,"handleCreate");function ue(e){const n=[],t=j(e.body,["rationale","body","frontmatter","extensions","unset","node","cwd","profile","store"],n),r=w(t,"rationale",n);t.body!==void 0&&typeof t.body!="string"&&n.push({field:"body",problem:"must be a string",received:t.body}),t.unset!==void 0&&(!Array.isArray(t.unset)||!t.unset.every(d=>typeof d=="string"))&&n.push({field:"unset",problem:"must be a string array",received:t.unset}),n.length>0&&b("memory update request",n);const i=q(e),o=p(t,["rationale","body","frontmatter","extensions","unset","node","cwd","profile","store"]);y(o,I);const s=W(t.frontmatter,t.extensions,["kind","when-and-why-to-read","origin","last-updated"]);return ae({target:o.target,selection:{target:o.target,...f(o,!1)},fields:{name:i,rationale:r,...t.body===void 0?{}:{body:t.body},...t.unset===void 0?{}:{unset:t.unset},...s}}),{status:200,body:A(i,o)}}a(ue,"handleUpdate");function fe(e){const n=p(k(e),["node","cwd","profile","store"]);y(n,I);const t=q(e);return{status:200,body:{...ne({target:n.target,selection:{target:n.target,...f(n,!1)},fields:{name:t}}),deleted:!0}}}a(fe,"handleDelete");function pe(e){const n=[],t=j(e.body,["to","node","cwd","profile","store"],n),r=w(t,"to",n);if(n.length>0&&b("memory move request",n),!S(r))throw new m(400,"invalid_memory_doc_name","memory document name must be slash-joined [A-Za-z0-9_-] segments");const i=p(t,["to","node","cwd","profile","store"]);y(i,I);const o=q(e);return{status:200,body:re({target:i.target,selection:{target:i.target,...f(i,!1)},fields:{name:o,to:r}})}}a(pe,"handleMove");function O(e){return"line"in e?`${e.name}\0${e.scope}\0${e.physical_relative_path}\0${String(e.line).padStart(10,"0")}`:e.name}a(O,"grepCursor");function ye(e){const n=[],t=j(e.body,["query","kind","grep","body","limit","after","min_score","node","cwd","profile","store"],n),r=w(t,"query",n),i=h(t,"kind",n),o=h(t,"after",n);n.length>0&&b("memory search request",n);const s=p(t,["query","kind","grep","body","limit","after","min_score","node","cwd","profile","store"]);y(s,_);const d=D(t,"grep"),l=D(t,"body"),u=t.min_score===void 0?void 0:U(t.min_score,"min_score");if(d===!0&&l===!0)throw new m(400,"invalid_request","grep and body cannot both be true");if(d===!0&&u!==void 0)throw new m(400,"invalid_request","min_score is only available in ranked mode");const g=[...de({target:s.target,...f(s,!1),query:r,...i===void 0?{}:{kind:i},...d===void 0?{}:{grep:d},...l===void 0?{}:{body:l},...u===void 0?{}:{minScore:u}}).hits].sort((v,C)=>d===!0?O(v).localeCompare(O(C)):v.name.localeCompare(C.name)),P=o===void 0?g:g.filter(v=>(d===!0?O(v):v.name).localeCompare(o)>0),M=P.slice(0,T(t.limit,"limit",E));return{status:200,body:{object:"list",data:M,has_more:P.length>M.length}}}a(ye,"handleSearch");function he(e){const n=k(e),t=p(n,["node","cwd","profile","store","limit","revision","diff"]);y(t,_);const r=n.revision===void 0?void 0:U(n.revision,"revision"),i=D(n,"diff"),o=se({target:t.target,...f(t,!1),name:q(e),limit:T(n.limit,"limit",E),...r===void 0?{}:{revision:r},...i===void 0?{}:{diff:i}});return{status:200,body:{name:o.name,scope:o.scope,log_path:o.logPath,total:o.total,...o.deleted===void 0?{}:{deleted:o.deleted},..."record"in o?{record:o.record}:{revisions:[...o.revisions]}}}}a(he,"handleHistory");function ge(e){const n=k(e),t=e.query.get("name");if(t===null||!S(t))throw new m(400,"invalid_memory_doc_name","memory document name must be slash-joined [A-Za-z0-9_-] segments");const r=p(n,["name","node","cwd","profile","store"]);y(r,_);const i=H({target:r.target,...f(r,!1),name:t});return{status:200,body:{name:i.doc.name,scope:i.doc.scope,path:i.doc.path,store_root:i.doc.root,physical_relative_path:i.doc.physicalRelativePath,...i.doc.plugin===void 0?{}:{plugin:i.doc.plugin}}}}a(ge,"handleResolve");const $e=[{method:"GET",pattern:"/v1/memory/docs",scope:"memory:read",handler:me},{method:"GET",pattern:"/v1/memory/docs/:name",scope:"memory:read",handler:le},{method:"POST",pattern:"/v1/memory/docs",scope:"memory:write",handler:ce},{method:"PATCH",pattern:"/v1/memory/docs/:name",scope:"memory:write",handler:ue},{method:"DELETE",pattern:"/v1/memory/docs/:name",scope:"memory:write",handler:fe},{method:"POST",pattern:"/v1/memory/docs/:name/move",scope:"memory:write",handler:pe},{method:"POST",pattern:"/v1/memory/search",scope:"memory:read",handler:ye},{method:"GET",pattern:"/v1/memory/docs/:name/history",scope:"memory:read",handler:he},{method:"GET",pattern:"/v1/memory/resolve",scope:"memory:read",handler:ge}];export{$e as memoryRoutes};
|
|
1
|
+
var Fe=Object.defineProperty;var m=(e,t)=>Fe(e,"name",{value:t,configurable:!0});import{createHash as We}from"node:crypto";import{getNode as Z,findNodeBySessionFile as Be}from"../../../core/canvas/canvas.js";import{interpolateNodePaths as ce}from"../../../core/canvas/paths.js";import{existsSync as Ge,readFileSync as ue,realpathSync as ze,statSync as Ue}from"node:fs";import{join as K,resolve as Ze}from"node:path";import{loadProfileManifest as Ke,resolveProfileOperand as He}from"../../../core/profiles/manifest.js";import{conversationStore as Ve,ConversationNotFoundError as Ye}from"../../../core/conversation-store/index.js";import{ApiError as l}from"../../../api/errors.js";import{paginate as H}from"../../../core/pagination.js";import{appSpace as V}from"../../../core/layout.js";import{memoryPermission as fe,readableProjectForScopes as Je}from"../../../core/spaces/permissions.js";import{canReadRun as Xe,resolvedScopes as Y}from"../router.js";import{CrtrError as J}from"../../../core/errors.js";import{memoryDir as Qe}from"../../../core/runtime/memory.js";import{NEUTRAL_PROJECT_MEMORY as xe,projectScopeRoot as X,projectScopeRootsWithMemory as et,scopeMemoryDir as pe,ensureProjectScopeRoot as tt}from"../../../core/scope.js";import{descendantStoreDiscoveryWarnings as ot}from"../../../core/nested-stores.js";import{profileMemoryDir as nt}from"../../../core/profiles/manifest.js";import{openProjectMemoryStore as Q}from"../../../core/memory-resolver.js";import{effectivePrivacy as x,PRIVACY_LEVELS as B}from"../../../core/substrate/schema.js";import{lintMemoryStore as he,lintMemoryTarget as rt,lintOrphans as it,resolvableCanonicalNames as st}from"../../../core/memory/lint.js";import{createMemoryDocSnapshot as ye,loadMemoryTargetView as ge,memoryStoresInPrecedence as ee}from"../../../core/memory-resolver.js";import{parseSubstrateDoc as we}from"../../../core/substrate/schema.js";import{parseFrontmatterGeneric as be}from"../../../core/frontmatter.js";import{dirDedupKey as at,docsByName as dt,renderDirListing as lt}from"../../../core/substrate/listings.js";import{memoryExtensionEffectiveCatalog as mt,memoryExtensionValidationCatalog as ct,projectEffectiveMemoryExtensions as ut}from"../../../core/memory/extensions.js";import{effectiveDocKind as ft}from"../../../core/substrate/schema.js";import{requireUnambiguousDoc as pt}from"../../../core/memory/mutation-domain.js";import{contentReadAttachments as ve}from"../../../core/substrate/on-read.js";import{assembleNodeSubject as _e}from"../../../core/substrate/subject.js";import{emptyContextExposureState as ht,exposureTarget as G,loadContextExposureState as te,registerDocumentExposure as Se,registerExposure as ke,saveContextExposureState as z}from"../../../core/substrate/injected-store.js";import{insertMemoryReads as yt}from"../../../core/canvas/memory-reads.js";import{emitEvent as gt}from"../../../core/events/emit.js";import{memoryEvents as oe}from"../../../core/substrate/memory-events.js";import{candidateLocation as qe,compareMemoryListKeys as wt,memoryListKey as bt,createDoc as je,deleteDoc as De,listDocs as vt,moveDoc as Re,readDoc as Ee,readHistory as _t,searchDocs as St,updateDoc as $e}from"../../../core/memory/service.js";import{MEMORY_SCOPES as Ie,isMemoryDocName as M}from"../../../api/dto/memory.js";import{invalidRequest as N,isRecord as E,objectBody as C,optionalString as I,requiredString as $}from"./validate.js";const P="read",q="rw",ne=100,Pe=100;function A(e){const t=e.params.name;if(t===void 0||!M(t))throw new l(400,"invalid_memory_doc_name","memory document name must be slash-joined [A-Za-z0-9_-] segments");return t}m(A,"requireName");function O(e){return Object.fromEntries(e.query.entries())}m(O,"queryObject");function F(e,t,o,i){return{scope:e,storeRoot:t,namespace:"",mountStatus:"ready",projectMemory:xe,ownerApp:o,profileId:i}}m(F,"nativeStore");function T(e,t){if(e.principal.class==="person")return!0;const o=e.principal.app;return process.platform!=="linux"&&o==="app:terminal"?!0:Je(t,o,Y(e.principal),e.principal.class==="broker"?e.principal.scopes:null)}m(T,"projectReadable");function v(e,t,o,i="read"){const s=[];for(const u of Object.keys(t))o.includes(u)||s.push({field:u,problem:"is not allowed",received:t[u]});const n=I(t,"node",s),r=I(t,"cwd",s),a=I(t,"profile",s),d=I(t,"store",s),f=I(t,"dir",s),c=I(t,"select_profile",s);if(f!==void 0&&(d!==void 0||c!==void 0)&&s.push({field:"dir",problem:"selects the project store itself and cannot combine with store or select_profile"}),c!==void 0&&d!=="profile"&&s.push({field:"select_profile",problem:"requires store profile"}),d!==void 0&&!Ie.includes(d)&&!/^app:[A-Za-z0-9_-]{1,64}$/.test(d)&&s.push({field:"store",problem:`must be one of ${Ie.join(", ")} or app:<id>`,received:d}),e.principal.class==="app"&&(n!==void 0||r!==void 0||a!==void 0||f!==void 0||c!==void 0||t.mode==="cli"))throw new l(403,"scope_missing","an app server cannot select a node, cwd or profile");if(e.principal.class==="broker"&&(n!==void 0&&n!==e.principal.node||r!==void 0||a!==void 0||f!==void 0||c!==void 0))throw new l(403,"scope_missing","a broker can select only its own node and mounted memory");n!==void 0&&a!==void 0&&s.push({field:"node",problem:"derives profile and cannot be combined with it"}),s.length>0&&N("memory scope",s);let g,k;if(n!==void 0){const u=Z(n);if(u===null)throw new l(404,"node_not_found",`unknown node: ${n}`);g={cwd:r??u.cwd,profileId:u.profile_id??null,nodeId:u.node_id,grantee:u.grantee},k=u.node_id}else g={cwd:r??(e.principal.class==="broker"?Z(e.principal.node)?.cwd??"/":e.principal.class==="app"?V(e.principal.app).files:"/"),profileId:a??(e.principal.class==="broker"?Z(e.principal.node)?.profile_id??null:null),nodeId:e.principal.class==="broker"?e.principal.node:null,grantee:e.principal.class==="person"?void 0:e.principal.app},e.principal.class==="broker"&&(k=e.principal.node);const b=d;if(b==="node"&&k===void 0)throw new l(400,"invalid_request","store node requires node");if(b==="profile"&&g.profileId===null&&c===void 0)throw new l(400,"invalid_request","store profile requires profile or node with a profile");if(c!==void 0&&(g={...g,profileId:He(c).profileId}),f!==void 0){const u=Ze(g.cwd,f);if(!Ge(u)||!Ue(u).isDirectory())throw new l(400,"invalid_request",`--dir does not exist or is not a directory: ${f}`);const R=Q(ze(u));if(!T(e,R.repositoryRoot??R.ownerDir??u))throw new l(403,"scope_missing","project memory is outside the run mounts");return g={...g,allowsStore:m((y,me)=>y.scope==="project"&&T(e,y.repositoryRoot??y.ownerDir??y.storeRoot),"allowsStore"),allowsProject:m(y=>T(e,y),"allowsProject")},{target:g,nodeId:k,store:R,access:i,permitted:m(y=>y.scope==="project"&&T(e,y.repositoryRoot??y.ownerDir??y.storeRoot),"permitted")}}const h=e.principal,w=h.class==="person"?[]:Y(h),p=h.class==="broker"?h.scopes:null,S=h.class==="person"?null:h.app,D=m((u,R)=>h.class==="person"?!0:u.scope==="project"?T(e,u.repositoryRoot??u.ownerDir??u.storeRoot):fe(S,w,p,u,i,R),"permitted");if(g={...g,allowsStore:D,allowsProject:m(u=>T(e,u),"allowsProject")},d?.startsWith("app:")||h.class==="app"&&d===void 0){const u=d??(h.class==="person"?"app:terminal":h.app),R=F("profile",V(u).memory,u);if(!D(R))throw new l(403,"scope_missing",`missing memory permission for ${u}`);return{target:g,nodeId:k,store:R,access:i,permitted:D}}if(b!==void 0&&h.class!=="person"){const u=ee({...g,allowsStore:void 0,allowsProject:void 0},b);if(u.length===0||!u.some(R=>D(R)))throw new l(403,"scope_missing",`missing memory permission for ${b}`)}return{target:g,...b===void 0?{}:{scope:b},...k===void 0?{}:{nodeId:k},access:i,permitted:D}}m(v,"resolveScope");function _(e,t){if(e.access!==t)throw new Error("memory route access mismatch");if(e.store!==void 0&&!e.permitted(e.store))throw new l(403,"scope_missing","memory store is not permitted")}m(_,"requireScope");function U(e,t,o){if(!e.permitted(t,o))throw new l(403,"scope_missing",`missing memory write permission for ${o}`)}m(U,"requireWrite");function j(e,t){const o=e.scope;if(!t)return{...o===void 0?{}:{scope:o},...e.store===void 0?{}:{store:e.store}};if(e.store!==void 0)return{scope:e.store.scope,store:e.store,memoryDir:e.store.storeRoot};const i=o??(e.target.nodeId?"node":X(e.target.cwd)!==null?"project":"user");if(i==="builtin")throw new l(400,"invalid_request","builtin memory is read-only");if(i==="node"){const r=Qe(e.target.nodeId,e.target.grantee),a=F("node",r,e.target.grantee);if(!e.permitted(a))throw new l(403,"scope_missing","node memory is not permitted");return{scope:i,store:a,memoryDir:r}}if(i==="profile"){const{profileId:r,manifest:a}=Ke(e.target.profileId),d=a.grantee?.startsWith("app:")?K(V(a.grantee).memory,"profiles",r):nt(r),f=F("profile",d,a.grantee,r);if(!e.permitted(f))throw new l(403,"scope_missing","profile memory is not permitted");return{scope:i,store:f,memoryDir:d}}if(i==="project"){const r=o==="project"?tt(e.target.cwd):X(e.target.cwd);if(r===null)throw new l(400,"invalid_request","store project requires a project memory store in cwd");const a=Q(r.slice(0,-8).replace(/\/$/,""));if(!e.permitted(a))throw new l(403,"scope_missing","project memory is outside the run mounts");return{scope:i,store:a,memoryDir:a.storeRoot}}const s=pe("user");if(s===null)throw new Error("user memory directory unavailable");const n=F("user",s);if(!e.permitted(n))throw new l(403,"scope_missing","user memory is not permitted");return{scope:"user",store:n,memoryDir:s}}m(j,"selection");function Ae(e,t){return e.length>1?e.map(o=>qe(o,t)):void 0}m(Ae,"candidates");function Te(e){return{name:e.name,short_form:e.shortForm,kind:e.kind,privacy:e.privacy,scope:e.scope,extensions:e.extensions,path:e.path,store_root:e.storeRoot,physical_relative_path:e.physicalRelativePath,...Ae(e.candidates,e.candidates[0])===void 0?{}:{candidates:Ae(e.candidates,e.candidates[0])}}}m(Te,"summary");function re(e){try{const t=Ee(e);if(t.kind==="document")return t}catch(t){if(!(t instanceof J)||t.code!=="not_found")throw t}throw new l(404,"memory_document_not_found",`memory document not found: ${e.name}`)}m(re,"requestedDocument");function ie(e,t,o=j(t,!1),i=!1){const s=re({target:t.target,...o,name:e,frontmatter:i,interpolateNodePaths:!1}),n=s.doc;return{...Te({name:n.name,kind:String(n.frontmatter?.kind??""),privacy:x(n.frontmatter),scope:n.scope,path:n.path,storeRoot:n.root,physicalRelativePath:n.physicalRelativePath,shortForm:String(n.frontmatter?.["short-form"]??""),slash:n.frontmatter?.slash===!0,extensions:n.frontmatter?.extensions??{},candidates:s.candidates}),body:s.content,frontmatter:n.frontmatter===null?null:{...n.frontmatter,privacy:x(n.frontmatter)},representation:n.representation,links:[...s.links]}}m(ie,"document");function se(e,t,o){if(e===void 0)return o;const i=typeof e=="number"?e:Number(e);if(!Number.isInteger(i)||i<1||i>Pe)throw new l(400,"invalid_request",`${t} must be an integer from 1 through ${Pe}`);return i}m(se,"number");function ae(e,t,o){if(e===void 0)return t;const i=typeof e=="number"||typeof e=="string"&&e.trim()!==""?Number(e):NaN;if(!Number.isInteger(i)||i<1||o!==void 0&&i>o)throw new l(400,"invalid_request",`limit must be ${o===void 0?"a positive integer":`an integer from 1 through ${o}`}`);return i}m(ae,"cliLimit");function Oe(e,t){const o=typeof e=="number"?e:Number(e);if(!Number.isFinite(o)||o<1)throw new l(400,"invalid_request",`${t} must be a finite number of at least 1`);return o}m(Oe,"positiveNumber");function W(e,t){const o=e[t];if(o!==void 0){if(o===!0||o==="true")return!0;if(o===!1||o==="false")return!1;throw new l(400,"invalid_request",`${t} must be a boolean`)}}m(W,"optionalBoolean");function Ne(e,t,o=[]){if(e!==void 0&&!E(e))throw new l(400,"invalid_request","frontmatter must be an object");const i=e===void 0?{}:e;for(const r of o)if(r in i)throw new l(400,"invalid_request",`frontmatter.${r} cannot be set directly`);const s={},n={"short-form":"shortForm","when-and-why-to-read":"whenAndWhyToRead","lint-ignore":"lintIgnore",rationale:"docRationale",kind:"kind",privacy:"privacy",unlisted:"unlisted",surfaces:"surface",gate:"gate",slash:"slash"};for(const[r,a]of Object.entries(i)){const d=n[r];if(d===void 0)throw new l(400,"invalid_request",`frontmatter.${r} is not writable through this route`);if(r==="privacy"){if(!B.includes(a))throw new l(400,"invalid_request",`frontmatter.privacy must be one of ${B.join(", ")}`)}else if(r==="unlisted"||r==="slash"){if(a!==!0)throw new l(400,"invalid_request",`frontmatter.${r} must be true; remove it with unset`)}else if(r==="surfaces"){if(!Array.isArray(a)||!a.every(f=>typeof f=="string"))throw new l(400,"invalid_request","frontmatter.surfaces must be a string array")}else if(r==="lint-ignore"){if(!Array.isArray(a)||!a.every(f=>typeof f=="string"))throw new l(400,"invalid_request","frontmatter.lint-ignore must be a string array")}else if(typeof a!="string"||a.trim()==="")throw new l(400,"invalid_request",`frontmatter.${r} must be a non-empty string`);s[d]=a}if(t!==void 0){if(!E(t))throw new l(400,"invalid_request","extensions must be an object");const r=[];for(const[a,d]of Object.entries(t)){if(!E(d))throw new l(400,"invalid_request",`extensions.${a} must be an object`);for(const[f,c]of Object.entries(d))r.push(`extensions.${a}.${f}=${String(c)}`)}s.extension=r}return s}m(Ne,"frontmatterFields");function de(e,t){if(t.nodeId!==void 0&&e.principal.class!=="app"){if(e.principal.class==="broker"&&e.principal.node!==t.nodeId)throw new l(403,"other_app_run","memory exposure can only be recorded for the calling node");return t.nodeId}}m(de,"ledgerNode");function Ce(e,t,o,i){const s=de(e,t);if(s===void 0||i.length===0)return;const n=te(s),r=We("sha256").update(JSON.stringify(i)).digest("hex");ke(G(n,"transcript"),`listing:memory-${o}:${r}`,"content"),z(s,n)}m(Ce,"listingExposure");function Me(e,t){if(t.length!==0)try{yt(e,t)}catch(o){gt({level:"warn",event:"memory_reads.insert_failed",error:o,fields:{node_id:e}})}}m(Me,"recordMemoryReads");function kt(e){const t=O(e),o=[],i=I(t,"kind",o),s=I(t,"after",o);o.length>0&&N("memory list query",o);const n=v(e,t,["node","cwd","profile","store","dir","select_profile","mode","kind","limit","cursor","after"]);_(n,P);const r=vt({target:n.target,...j(n,!1),...i===void 0?{}:{kind:i}});if(t.mode==="cli"){const c=H(r,{limit:ae(t.limit,50,200),cursor:t.cursor},{defaultLimit:50,maxLimit:200,keyOf:bt,compareKeys:wt,total:"count"});return Ce(e,n,"list",c.items),{status:200,body:c}}r.sort((c,g)=>c.name.localeCompare(g.name));const a=s===void 0?r:r.filter(c=>c.name.localeCompare(s)>0),d=a.slice(0,se(t.limit,"limit",ne)).map(Te);return{status:200,body:{object:"list",data:d,has_more:a.length>d.length}}}m(kt,"handleList");function qt(e){const t=O(e);if(t.mode==="cli"){const i=v(e,t,["node","cwd","profile","store","dir","mode","kind","frontmatter"]);_(i,P);const s=A(e),n=Ee({target:i.target,...j(i,!1),name:s,...t.kind===void 0?{}:{kind:String(t.kind)},frontmatter:W(t,"frontmatter")===!0}),r=de(e,i),a=r===void 0?ht():te(r),d=[],f=G(a,"transcript",d);if(n.kind==="directory"){const u=lt(n.listingByName,n.name,r===void 0?null:f,!1);return r!==void 0&&(ke(f,at(n.name),"preview"),z(r,a)),{status:200,body:{name:n.name,listing:u,follow_up:"Each line is readable with `crtr memory read <name>` \u2014 a `[[name]]: <line>` entry is a doc, a bare `[[name]]` is a subdirectory whose read browses deeper. Browse the whole inventory with `crtr memory list`."}}}const{doc:c,candidates:g,content:k,links:b,listingByName:h}=n;Se(G(a,"transcript"),c,"content");const w=ve(c,{subject:i.nodeId===void 0?null:_e(i.nodeId),target:f,byName:h,memoryTarget:i.target,listings:"blocks",explicit:!0});if(r!==void 0){z(r,a);const u=new Date().toISOString();Me(r,[...oe([{name:c.name,scope:c.scope}],"read",u),...oe(d,"loaded",u)])}const p=w.listing,S=p!==void 0&&p.length>0,D=S?b.length>0?"Each `[[name]]` line in `listing` is one of this directory\u2019s immediate members, and the `[[name]]` links in the body are further reading \u2014 follow either with `crtr memory read <name>` only when the task needs that depth.":"Each `[[name]]` line in `listing` is one of this directory\u2019s immediate members, readable with `crtr memory read <name>` \u2014 follow one only when the task needs that depth.":b.length>0?"The `[[name]]` links in the body are further reading \u2014 follow one with `crtr memory read <name>` only when the task needs that depth.":null;return{status:200,body:{name:c.name,local_name:c.localName,kind:ft(c),privacy:x(c.frontmatter),scope:c.scope,path:c.path,store_root:c.root,physical_relative_path:c.physicalRelativePath,representation:c.representation,...g.length>1?{candidates:g.map(u=>qe(u,c))}:{},content:k,attachment_blocks:w.blocks,...S?{listing:p}:{},extensions:ut(c.frontmatter?.extensions,mt(c)),...b.length>0?{links:b}:{},...D===null?{}:{follow_up:D}}}}const o=v(e,t,["node","cwd","profile","store","frontmatter"]);return _(o,P),{status:200,body:ie(A(e),o,j(o,!1),W(t,"frontmatter")===!0)}}m(qt,"handleRetrieve");function jt(e){if(E(e.body)&&e.body.mode==="cli"){const{mode:k,...b}=e.body,h=v(e,e.body,["node","cwd","profile","store","dir","select_profile","fields","mode"],q);_(h,q);const w=[],p=C(b.fields,["name","kind","whenAndWhyToRead","body","privacy","shortForm","unlisted","surface","gate","lintIgnore","slash","rationale","extension"],w),S=$(p,"name",w),D=$(p,"kind",w);$(p,"whenAndWhyToRead",w),$(p,"body",w),D!==void 0&&D!=="knowledge"&&D!=="preference"&&w.push({field:"kind",problem:"must be knowledge or preference",received:D});for(const y of["privacy","shortForm","gate","rationale"])p[y]!==void 0&&(typeof p[y]!="string"||p[y].trim()==="")&&w.push({field:y,problem:"must be a non-empty string",received:p[y]});p.privacy!==void 0&&!B.includes(p.privacy)&&w.push({field:"privacy",problem:`must be one of ${B.join(", ")}`,received:p.privacy});for(const y of["unlisted","slash"])p[y]!==void 0&&typeof p[y]!="boolean"&&w.push({field:y,problem:"must be a boolean",received:p[y]});for(const y of["surface","extension"])p[y]!==void 0&&(!Array.isArray(p[y])||!p[y].every(me=>typeof me=="string"))&&w.push({field:y,problem:"must be a string array",received:p[y]});if(p.lintIgnore!==void 0&&typeof p.lintIgnore!="string"&&(!Array.isArray(p.lintIgnore)||!p.lintIgnore.every(y=>typeof y=="string"))&&w.push({field:"lintIgnore",problem:"must be a string or string array",received:p.lintIgnore}),w.length>0&&N("memory create request",w),!M(S))throw new l(400,"invalid_memory_doc_name","memory document name must be slash-joined [A-Za-z0-9_-] segments");const u=j(h,!0);U(h,u.store,S);const R={created:new Date().toISOString(),cwd:h.target.cwd,...h.target.nodeId===null?{}:{node:h.target.nodeId}};return{status:200,body:je({target:h.target,scope:u.scope,store:u.store,memoryDir:u.memoryDir,isExplicitProjectStore:b.dir!==void 0||b.store==="project",origin:R,fields:p})}}const t=[],o=C(e.body,["name","kind","when_and_why_to_read","body","frontmatter","extensions","node","cwd","profile","store"],t),i=$(o,"name",t),s=$(o,"kind",t),n=$(o,"when_and_why_to_read",t),r=$(o,"body",t);if(t.length>0&&N("memory create request",t),!M(i))throw new l(400,"invalid_memory_doc_name","memory document name must be slash-joined [A-Za-z0-9_-] segments");const a=v(e,o,["name","kind","when_and_why_to_read","body","frontmatter","extensions","node","cwd","profile","store"],q);_(a,q);const d=j(a,!0);U(a,d.store,i);const f={name:i,kind:s,whenAndWhyToRead:n,body:r,...Ne(o.frontmatter,o.extensions,["kind","when-and-why-to-read","origin","last-updated"])},c=je({target:a.target,scope:d.scope,memoryDir:d.memoryDir,store:d.store,isExplicitProjectStore:!1,origin:{created:new Date().toISOString(),cwd:a.target.cwd,...a.target.nodeId===null?{}:{node:a.target.nodeId}},fields:f}),g=ie(c.name,a,d);return{status:200,body:c.findings===void 0?g:{...g,findings:c.findings}}}m(jt,"handleCreate");function Dt(e){if(E(e.body)&&e.body.mode==="cli"){const{mode:a,...d}=e.body,f=v(e,e.body,["node","cwd","profile","store","dir","select_profile","fields","mode"],q);if(_(f,q),!E(d.fields))throw new l(400,"invalid_request","fields must be an object");return{status:200,body:$e({target:f.target,selection:{target:f.target,...j(f,!1)},fields:{...d.fields,name:A(e)}})}}const t=[],o=C(e.body,["rationale","body","frontmatter","extensions","unset","node","cwd","profile","store"],t),i=$(o,"rationale",t);o.body!==void 0&&typeof o.body!="string"&&t.push({field:"body",problem:"must be a string",received:o.body}),o.unset!==void 0&&(!Array.isArray(o.unset)||!o.unset.every(a=>typeof a=="string"))&&t.push({field:"unset",problem:"must be a string array",received:o.unset}),t.length>0&&N("memory update request",t);const s=A(e),n=v(e,o,["rationale","body","frontmatter","extensions","unset","node","cwd","profile","store"],q);_(n,q);const r=Ne(o.frontmatter,o.extensions,["kind","when-and-why-to-read","origin","last-updated"]);return $e({target:n.target,selection:{target:n.target,...j(n,!1)},fields:{name:s,rationale:i,...o.body===void 0?{}:{body:o.body},...o.unset===void 0?{}:{unset:o.unset},...r}}),{status:200,body:ie(s,n)}}m(Dt,"handleUpdate");function Rt(e){if(E(e.body)&&e.body.mode==="cli"){const{mode:s,...n}=e.body,r=v(e,e.body,["node","cwd","profile","store","dir","fields","mode"],q);return _(r,q),{status:200,body:De({target:r.target,selection:{target:r.target,...j(r,!1)},fields:{name:A(e)}})}}const t=v(e,O(e),["node","cwd","profile","store"],q);_(t,q);const o=A(e);return{status:200,body:{...De({target:t.target,selection:{target:t.target,...j(t,!1)},fields:{name:o}}),deleted:!0}}}m(Rt,"handleDelete");function Et(e){if(E(e.body)&&e.body.mode==="cli"){const{mode:a,...d}=e.body,f=v(e,e.body,["node","cwd","profile","store","dir","fields","mode"],q);if(_(f,q),!E(d.fields))throw new l(400,"invalid_request","fields must be an object");if(typeof d.fields.to!="string"||!M(d.fields.to))throw new l(400,"invalid_memory_doc_name","move destination must be a memory document name");return Le(f,A(e),d.fields.to),{status:200,body:Re({target:f.target,selection:{target:f.target,...j(f,!1)},fields:{...d.fields,name:A(e)}})}}const t=[],o=C(e.body,["to","node","cwd","profile","store"],t),i=$(o,"to",t);if(t.length>0&&N("memory move request",t),!M(i))throw new l(400,"invalid_memory_doc_name","memory document name must be slash-joined [A-Za-z0-9_-] segments");const s=v(e,o,["to","node","cwd","profile","store"],q);_(s,q);const n=A(e);return Le(s,n,i),{status:200,body:Re({target:s.target,selection:{target:s.target,...j(s,!1)},fields:{name:n,to:i}})}}m(Et,"handleMove");function Le(e,t,o){const i=re({target:e.target,...j(e,!1),name:t}).doc;U(e,i.store,t),U(e,i.store,o)}m(Le,"requireMoveDestination");function le(e){return"line"in e?`${e.name}\0${e.scope}\0${e.physical_relative_path}\0${String(e.line).padStart(10,"0")}`:e.name}m(le,"grepCursor");function $t(e){const t=[],o=C(e.body,["query","kind","grep","body","limit","cursor","after","min_score","node","cwd","profile","store","dir","mode"],t),i=$(o,"query",t),s=I(o,"kind",t),n=I(o,"after",t);t.length>0&&N("memory search request",t);const r=v(e,o,["query","kind","grep","body","limit","cursor","after","min_score","node","cwd","profile","store","dir","mode"]);_(r,P);const a=W(o,"grep"),d=W(o,"body"),f=o.min_score===void 0?void 0:Oe(o.min_score,"min_score");if(a===!0&&d===!0)throw new l(400,"invalid_request","grep and body cannot both be true");if(a===!0&&f!==void 0)throw new l(400,"invalid_request","min_score is only available in ranked mode");const c=St({target:r.target,...j(r,!1),query:i,...s===void 0?{}:{kind:s},...a===void 0?{}:{grep:a},...d===void 0?{}:{body:d},...f===void 0?{}:{minScore:f}});if(o.mode==="cli"){const h=ae(o.limit,10,100),w=o.cursor,p=c.mode==="grep"?H([...c.hits],{limit:h,cursor:w},{defaultLimit:10,maxLimit:100,keyOf:m(S=>`${S.name}:${S.scope}:${S.physical_relative_path}:${String(S.line).padStart(7,"0")}`,"keyOf"),total:"omit"}):H([...c.hits],{limit:h,cursor:w},{defaultLimit:10,maxLimit:100,keyOf:m(S=>`${String(1e6-S.score).padStart(7,"0")}:${S.scope}:${S.name}:${S.physical_relative_path}`,"keyOf"),total:"omit"});return Ce(e,r,"find",p.items),{status:200,body:{mode:c.mode,matches:c.matches,hits:p.items,next_cursor:p.next_cursor}}}const g=[...c.hits].sort((h,w)=>a===!0?le(h).localeCompare(le(w)):h.name.localeCompare(w.name)),k=n===void 0?g:g.filter(h=>(a===!0?le(h):h.name).localeCompare(n)>0),b=k.slice(0,se(o.limit,"limit",ne));return{status:200,body:{object:"list",data:b,has_more:k.length>b.length}}}m($t,"handleSearch");function It(e){const t=O(e),o=v(e,t,["node","cwd","profile","store","dir","select_profile","mode","limit","revision","diff"]);_(o,P);const i=t.revision===void 0?void 0:Oe(t.revision,"revision"),s=W(t,"diff"),n=_t({target:o.target,...j(o,!1),name:A(e),limit:t.mode==="cli"?ae(t.limit,10):se(t.limit,"limit",ne),...i===void 0?{}:{revision:i},...s===void 0?{}:{diff:s}});return t.mode==="cli"?{status:200,body:n}:{status:200,body:{name:n.name,scope:n.scope,log_path:n.logPath,total:n.total,...n.deleted===void 0?{}:{deleted:n.deleted},..."record"in n?{record:n.record}:{revisions:[...n.revisions]}}}}m(It,"handleHistory");function Pt(e){const t=O(e),o=e.query.get("name");if(o===null||!M(o))throw new l(400,"invalid_memory_doc_name","memory document name must be slash-joined [A-Za-z0-9_-] segments");const i=v(e,t,["name","node","cwd","profile","store","dir","select_profile","mode"]);_(i,P);const s=re({target:i.target,...j(i,!1),name:o});if(t.mode==="cli"){const n=pt({name:o,winner:s.doc,candidates:s.candidates});return{status:200,body:{name:n.name,path:n.path,scope:n.scope,local_name:n.localName,store_root:n.root,physical_relative_path:n.physicalRelativePath,representation:n.representation,origin:n.frontmatter?.origin??null}}}return{status:200,body:{name:s.doc.name,scope:s.doc.scope,path:s.doc.path,store_root:s.doc.root,physical_relative_path:s.doc.physicalRelativePath,...s.doc.plugin===void 0?{}:{plugin:s.doc.plugin}}}}m(Pt,"handleResolve");function At(e){const t=v(e,O(e),["node","cwd","profile"]);_(t,P);const o=ye(t.target),i=new Set,s=[];for(const n of o.docs){if(i.has(n.name))continue;i.add(n.name);const r=we(n);if(r?.slash===!0)try{const a=ue(n.path,"utf8"),d=be(a).body;s.push({name:n.name,short_form:r.shortForm,path:n.path,canonical_body:n.body,execution_body:t.nodeId===void 0?d:ce(d,t.nodeId,t.target.grantee)})}catch(a){s.push({name:n.name,short_form:r.shortForm,path:n.path,canonical_body:n.body,error:a instanceof Error?a.message:String(a)})}}return{status:200,body:s}}m(At,"handleSlashDocs");async function Tt(e){const t=C(e.body,["node","name"],[]),o=v(e,t,["node","name"]);if(_(o,P),o.nodeId===void 0)throw new l(400,"invalid_request","slash attachments require a node");const i=$(t,"name",[]);if(i===void 0)throw new l(400,"invalid_request","slash document name required");const n=ye(o.target).resolve([i]).get(i);if(n===void 0)throw new l(404,"not_found",`memory slash document not found: ${i}`);const r=de(e,o);if(r===void 0)throw new l(403,"permission_error","slash attachments require the calling node");const a=be(ue(n.path,"utf8")),d={...n,frontmatter:a.data,body:a.body};if(we(d)?.slash!==!0)throw new l(404,"not_found",`memory slash document not found: ${i}`);const f=ce(d.body,r,o.target.grantee),c=te(r),g=[],k=G(c,"transcript",g);Se(k,d,"content");const b=ge(o.target,{quiet:!0,includeDescendants:!0}),h=ve(d,{subject:_e(o.nodeId),target:k,byName:dt(b.docs),memoryTarget:o.target,listings:"blocks"}).blocks;return z(r,c),Me(r,oe(g,"loaded")),{status:200,body:{blocks:h,execution_body:f}}}m(Tt,"handleSlashAttachments");function Ot(e){const t=C(e.body,["node","cwd","profile","store","dir","mode"],[]),o=v(e,t,["node","cwd","profile","store","dir","mode"]);if(_(o,P),t.dir!==void 0&&(typeof t.dir!="string"||t.dir===""))throw new l(400,"invalid_request","dir must be a nonempty directory path");if(t.dir!==void 0&&t.store!==void 0)throw new l(400,"invalid_request","dir selects one store and cannot combine with store");if(e.principal.class!=="person"){const n=o.store??(o.scope===void 0?void 0:ee(o.target,o.scope).find(d=>d.mountStatus==="ready"));if(n===void 0||(n.scope==="project"?!T(e,n.repositoryRoot??n.ownerDir??n.storeRoot):!fe(e.principal.app,Y(e.principal),e.principal.class==="broker"?e.principal.scopes:null,n,"read",void 0,!0)))throw new l(403,"scope_missing","memory lint requires a whole-store read grant and an explicit store");const r=he(n),a=m(d=>({rule:d.rule,path:d.path,message:d.message}),"row");return{status:200,body:{checked:r.checked,stores:r.storesLinted,findings:r.errors.map(a),warnings:r.warnings.map(a),notices:r.notices.map(a)}}}const i=t.dir===void 0?rt({target:o.target,...o.scope===void 0?{}:{scope:o.scope}}):(()=>{const n=o.store,r=ge({...o.target,cwd:n.ownerDir??n.storeRoot,nodeId:null},{quiet:!0,includeDescendants:!0}),a=he(n,{resolvable:st(r.docs),frontDoor:"advisory"}),d=it(r.docs,{flagStoreRoot:n.storeRoot});return{...a,findings:[...a.findings,...d],warnings:[...a.warnings,...d]}})(),s=m(n=>({rule:n.rule,path:n.path,message:n.message,...n.name===void 0?{}:{name:n.name},...n.scope===void 0?{}:{scope:n.scope},...n.storeRoot===void 0?{}:{store_root:n.storeRoot},...n.paths===void 0?{}:{paths:[...n.paths]}}),"row");return{status:200,body:{checked:i.checked,stores:i.storesLinted,..."profileProjects"in i?{profile_projects:i.profileProjects}:{},findings:i.errors.map(s),warnings:i.warnings.map(s),notices:i.notices.map(s)}}}m(Ot,"handleLint");function Nt(e){const t=v(e,O(e),["node","cwd","profile"]);_(t,P);const o=X(t.target.cwd),i=o!==null&&T(e,t.target.cwd)?"project":"user",s=i==="user"?pe("user"):K(o,"memory");if(e.principal.class!=="person"&&!t.permitted(i==="user"?F("user",s):Q(t.target.cwd)))throw new l(403,"scope_missing","memory extensions are not permitted");if(s===null)throw new Error("user memory directory unavailable");return{status:200,body:ct({scope:i,path:K(s,".extension-help.md")})}}m(Nt,"handleExtensionCatalog");function L(e,t){const o=E(e.body)&&e.body.mode==="cli"?e.body:O(e);if(!E(o)||o.mode!=="cli")return t(e);const i=Object.fromEntries(["node","cwd","profile","store","dir","select_profile"].filter(r=>o[r]!==void 0).map(r=>[r,o[r]])),s=v(e,i,Object.keys(i)),n=(s.store===void 0?ee(s.target,s.scope,!0,!1):[s.store]).filter(r=>r.mountStatus!=="ready"&&r.mountStatus!=="absent"&&r.diagnostic!==void 0).map(r=>`memory store not mounted: ${r.diagnostic}`);s.store===void 0&&(s.scope===void 0||s.scope==="project")&&n.push(...ot(et(s.target.cwd,s.target.profileId).map(({root:r})=>r).filter(r=>T(e,r))));try{const r=t(e);return n.length===0||!E(r.body)?r:{...r,body:{...r.body,diagnostics:n}}}catch(r){throw n.length>0&&r instanceof l&&r.status===404?new l(r.status,r.code,`${r.message}
|
|
2
|
+
${n.join(`
|
|
3
|
+
`)}`,r.details):n.length>0&&r instanceof J&&r.code==="not_found"?new J(r.code,`${r.message}
|
|
4
|
+
${n.join(`
|
|
5
|
+
`)}`,r.exitCode,r.details):r}}m(L,"withCliDiscovery");function Ct(e){const t=e.query.get("conversation_id");if(t===null||!/^[0-9a-f-]{36}$/i.test(t)||e.query.size!==1)throw new l(400,"invalid_request","conversation_id must be a single conversation UUID");try{const o=Ve().header(t),i=Be(o.path);if(e.principal.class!=="person"&&(i===null||!Xe(e.principal,i.grantee??"app:terminal")))throw new l(404,"not_found",`conversation not found: ${t}`);return{status:200,body:{session_file:o.path}}}catch(o){throw o instanceof Ye?new l(404,"not_found",`conversation not found: ${t}`):o}}m(Ct,"handleOriginConversation");const _o=[{method:"GET",pattern:"/v1/memory/docs",handler:m(e=>L(e,kt),"handler")},{method:"GET",pattern:"/v1/memory/docs/:name",handler:m(e=>L(e,qt),"handler")},{method:"POST",pattern:"/v1/memory/docs",handler:jt},{method:"PATCH",pattern:"/v1/memory/docs/:name",handler:Dt},{method:"DELETE",pattern:"/v1/memory/docs/:name",handler:Rt},{method:"POST",pattern:"/v1/memory/docs/:name/move",handler:Et},{method:"POST",pattern:"/v1/memory/search",handler:m(e=>L(e,$t),"handler")},{method:"GET",pattern:"/v1/memory/docs/:name/history",handler:m(e=>L(e,It),"handler")},{method:"GET",pattern:"/v1/memory/resolve",handler:m(e=>L(e,Pt),"handler")},{method:"GET",pattern:"/v1/memory/origin",handler:Ct},{method:"GET",pattern:"/v1/memory/extensions",handler:Nt},{method:"POST",pattern:"/v1/memory/lint",handler:m(e=>L(e,Ot),"handler")},{method:"GET",pattern:"/v1/memory/slash",handler:At},{method:"POST",pattern:"/v1/memory/slash/attachments",handler:Tt}];export{_o as memoryRoutes};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var E=Object.defineProperty;var c=(r,e)=>E(r,"name",{value:e,configurable:!0});import{join as J}from"node:path";import{claimNodeMail as W,acknowledgeNodeMail as D}from"../../../core/canvas/deliveries.js";import{nodeMailEntry as L}from"../../../core/feed/inbox.js";import{enqueueNodeMail as q,cancelPendingNodeMail as G}from"../../../core/feed/messages.js";import{reviveNode as O}from"../../../core/runtime/revive.js";import{BrokerUnreachableError as F}from"../../../core/runtime/broker-request.js";import{isBrokerLive as C}from"../../../core/runtime/model-swap.js";import{deliverLive as U,interruptLive as H}from"../../../core/runtime/interactive-deliver.js";import{isProfilePaused as K}from"../../../core/profiles/manifest.js";import{getNode as x,withFreshTerminalGuard as Q}from"../../../core/canvas/canvas.js";import{reportsDir as V}from"../../../core/canvas/paths.js";import{withCanvasWrite as X}from"../../../core/canvas/db.js";import{cancelCronsOnWake as I}from"../../../core/canvas/crons.js";import{assertNotFinalized as N,assertFinalizedForReopen as Y,commitReopenResident as A}from"../../../core/runtime/reopen.js";import{writeOutputSchema as Z}from"../../../core/runtime/structured-output.js";import{appendSituationalContext as j,formatSituationalProse as ee}from"../../../core/runtime/situational-context.js";import{formatDataCard as P}from"../../../shared/generated-context.js";import{hasNoNaturalCycle as te}from"../../../core/runtime/revive-all.js";import{recordPendingParkActivity as re}from"../../park-pending.js";import{wantsExecution as ne}from"../../reconcilers/node-lifecycle/wants-execution.js";import{hasFreshGroundState as oe}from"../../../core/runtime/revive.js";import{notFound as S,usage as a}from"../../../core/errors.js";import{assertScope as ie}from"../../../core/scopes.js";import{InputError as ae}from"../../../core/io.js";import{ApiError as se}from"../../../api/index.js";import{ownerOnly as de}from"../router.js";const ce=["critical","urgent","normal","deferred"];function M(r,e){if(typeof r!="object"||r===null||Array.isArray(r))throw a(`${e} must be an object { kind, facts?, body? }`);const i=r,t=i.kind;if(typeof t!="string"||t.trim()==="")throw a(`${e}.kind is required`);if(!t.includes(":"))throw a(`${e}.kind must be namespaced (contain ':'): ${t}`);const s={kind:t},n=i.facts;if(n!==void 0){if(typeof n!="object"||n===null||Array.isArray(n))throw a(`${e}.facts must be an object of string or number values`);const y={};for(const[m,f]of Object.entries(n)){if(typeof f!="string"&&typeof f!="number")throw a(`${e}.facts.${m} must be a string or number`);y[m]=f}s.facts=y}const o=i.body;if(o!==void 0){if(typeof o!="string")throw a(`${e}.body must be a string`);s.body=o}return s}c(M,"parseCardRequest");function T(r,e){try{return P(r.kind,r.facts??{},r.body??"")}catch(i){throw a(`${e}: ${i instanceof Error?i.message:String(i)}`)}}c(T,"renderCard");function ue(r){if(typeof r!="object"||r===null)throw a("a message requires a JSON body { body, tier?, fresh? }");const e=r,i=e.body,t=e.fresh===!0,s=e.tier,n=e.situational_context,o=e.output_schema,y=typeof i=="string"&&i.trim()!=="",m=typeof n=="string"&&n.trim()!=="",f=typeof o=="string"&&o.trim()!=="",g=e.situational_card,h=e.context_cards,b=g===void 0?void 0:M(g,"situational_card");if(h!==void 0&&!Array.isArray(h))throw a("context_cards must be an array of { kind, facts?, body? }");const l=h?.map((v,k)=>M(v,`context_cards[${k}]`));if(b!==void 0&&typeof n=="string"&&n!=="")throw a("situational_card and situational_context are mutually exclusive");const _=b!==void 0||l!==void 0&&l.length>0;if(!t&&!y&&!m&&!f&&!_)throw a("a message requires a non-empty body (or fresh: true, situational_context, a runtime card, or output_schema)");if(t&&l!==void 0&&l.length>0)throw a("context_cards cannot ride a fresh revive (no inbox entry carries them)");if(s!==void 0&&!ce.includes(s))throw a(`invalid tier: ${String(s)} (expected critical|urgent|normal|deferred)`);const u={body:typeof i=="string"?i:""};s!==void 0&&(u.tier=s),t&&(u.fresh=!0),e.reopen===!0&&(u.reopen=!0),typeof n=="string"&&(u.situational_context=n),b!==void 0&&(u.situational_card=b),l!==void 0&&(u.context_cards=l),typeof o=="string"&&(u.output_schema=o),typeof e.from=="string"&&(u.from=e.from);const p=e.delivery;if(p!==void 0&&p!=="interactive")throw a(`invalid delivery: ${String(p)} (expected interactive)`);if(p==="interactive"){if(t||u.situational_context!==void 0||u.output_schema!==void 0)throw a("interactive delivery supports a body, runtime cards, and reopen only (no fresh, situational_context, or output_schema)");if(!y)throw a("interactive delivery requires a non-empty body");if(u.tier==="deferred")throw a("interactive delivery cannot be deferred");u.delivery="interactive"}return u}c(ue,"parseSendBody");function fe(r){try{return JSON.parse(r)}catch{throw a("output_schema must be a JSON schema string")}}c(fe,"parseSchema");function le(r){return r.split(`
|
|
2
|
-
`)[0].slice(0,120)}c(le,"label");function z(r,e){if(e===null)return"";const i=J(V(r),e);return P("reopen-final-report",{path:i},"This node previously completed work. Read this final report before acting on the new instruction.")}c(z,"previousFinalReportCard");function me(r,e){return new ae({error:"deferred_no_natural_cycle",message:`${r} is ${e} with no natural next cycle ahead of it \u2014 a deferred message would never be delivered.`,next:"Use --tier normal, urgent, or critical to wake it now, or --reopen (with a body or --fresh) to re-task it first."})}c(me,"deferredNoNaturalCycle");function pe(r){if(!oe(r))throw new se(422,"unprocessable",`node ${r} has no goal/roadmap on disk \u2014 a fresh revive would resume amnesiac.`)}c(pe,"assertRecoverableForFresh");async function ye(r){const e=r.params.id,i=x(e);if(i===null)throw S(`unknown node: ${e}`,{received:e});const t=ue(r.body),s=t.tier??"normal",n=K(i.profile_id),o=t.from??null;if(o!==null){const d=x(o);d!==null&&ie(d,"act")}const y=t.body.trim()!=="",m=t.situational_card!==void 0?T(t.situational_card,"situational_card"):t.situational_context!==void 0?ee(t.situational_context.trim()):"",f=m!=="",g=(t.context_cards??[]).map((d,w)=>T(d,`context_cards[${w}]`)),h=t.output_schema!==void 0&&t.output_schema.trim()!==""?fe(t.output_schema):null;if(t.fresh){const d=t.reopen?Y(e):null;t.reopen||N(e),pe(e),f&&j(e,m),t.reopen&&A(e,d);const w=await O(e,{resume:!1,capacity:"refuse"});return{status:201,body:{node_id:e,delivered:!1,revived:w.launch!==void 0}}}t.delivery==="interactive"&&!t.reopen&&N(e);let b=!1,l="";if(t.delivery==="interactive"&&t.reopen&&(l=z(e,A(e)),b=!0),t.delivery==="interactive"&&!n&&C(i))try{return f&&j(e,m),await U(e,t.body,{cards:[...l===""?[]:[l],...f?[m]:[],...g],origin:o==="human"?{type:"human"}:{type:"runtime",kind:"inbox",entries:[{...o===null?{}:{from:o},kind:"message",tier:s}]}}),I(e),{status:201,body:{node_id:e,delivered:!0,revived:!1,delivered_via:"engine"}}}catch(d){if(!(d instanceof F))throw d}const _=c(()=>{t.reopen||N(e),h!==null&&Z(e,"oneoff",h),f&&j(e,m),t.reopen&&!b&&(l=z(e,A(e)));const d=[...l===""?[]:[l],...g],w=d.length>0?{cards:d}:{};if(y||h!==null){const $=y?t.body:"A one-off structured-output request has been granted. Submit a result matching the requested schema with `crtr push result` before you stop; after it is accepted, continue normally.";return q(e,{senderNodeId:o,urgency:s,wake:1,kind:"message",label:le($),bodyJson:{body:$,...f?{situational:!0}:{},...w}})}return q(e,{senderNodeId:o,urgency:s,wake:1,kind:"message",label:f?"(ambient context updated)":"(context delivered)",bodyJson:{...f?{situational:!0}:{},situationalOnly:!0,...w}})},"deliverImmediate"),p=c(()=>{if(s==="deferred"){const d=Q(e,te,_);if(d.kind==="missing")throw S(`unknown node: ${e}`,{received:e});if(d.kind==="terminal")throw me(e,d.status);return d.result}return _()},"deliver")();p.urgency!=="deferred"&&X(()=>re(e));const v=x(e);if(v===null)throw S(`unknown node: ${e}`,{received:e});i.frozen_at!==null&&I(e);let k=!1,R=!1;if((t.reopen||v.lifecycle==="terminal"||!ne(v))&&p.urgency!=="deferred"&&!n&&!C(v))try{const d=await O(e,{resume:!0,capacity:"freeze"});k=d.launch!==void 0,R=d.outcome==="frozen"}catch{}return{status:201,body:{node_id:e,delivered:!0,revived:k,...R?{not_revived_reason:"capacity_frozen"}:{},delivered_at:p.createdAt,...p.urgency===s?{}:{delivered_tier:p.urgency},...t.delivery==="interactive"?{delivered_via:"inbox"}:{}}}}c(ye,"handleMessage");async function he(r){const e=r.params.id,i=x(e);if(i===null)throw S(`unknown node: ${e}`,{received:e});const t=G(e,{senderNodeId:"human",kind:"message"});let s=!1;if(C(i))try{s=await H(e)!=="idle"}catch(o){if(!(o instanceof F))throw o}return{status:200,body:{node_id:e,outcome:s?"aborted_turn":t.length>0?"canceled_pending":"idle",aborted_turn:s,canceled_pending:t.length}}}c(he,"handleInterrupt");function B(r){if(typeof r.body!="object"||r.body===null||Array.isArray(r.body))throw a("mail requires an object body");const e=r.body;if(typeof e.execution_id!="string"||e.execution_id.trim()==="")throw a("execution_id is required");return e}c(B,"mailBody");function be(r){const e=B(r),i=e.channel;if(i!=="wake"&&i!=="passive")throw a("channel must be wake or passive");const t=W(r.params.id,e.execution_id,i);return{status:200,body:{action:t.action,deliveries:t.deliveries.map(n=>({delivery_id:n.deliveryId,attempts:n.attempts,handoff:n.handoff,entry:L(n)}))}}}c(be,"handleMailClaim");function ve(r){const e=B(r);if(!Array.isArray(e.deliveries))throw a("deliveries must be an array");const i=e.deliveries.map(n=>{if(typeof n!="object"||n===null||Array.isArray(n))throw a("each delivery must be an object");const o=n;if(typeof o.delivery_id!="string"||o.delivery_id==="")throw a("delivery_id is required");if(!Number.isSafeInteger(o.attempts)||o.attempts<1)throw a("attempts must be a positive integer");if(o.disposition!=="acknowledged"&&o.disposition!=="released")throw a("disposition must be acknowledged or released");return{delivery_id:o.delivery_id,attempts:o.attempts,disposition:o.disposition}}),t=D(r.params.id,e.execution_id,i.map(n=>({deliveryId:n.delivery_id,attempts:n.attempts,disposition:n.disposition})));return{status:200,body:{action:t.action,results:t.results.map(n=>({delivery_id:n.deliveryId,outcome:n.outcome}))}}}c(ve,"handleMailAcknowledge");const Ke=de([{method:"POST",pattern:"/v1/nodes/:id/mail/claim",handler:be},{method:"POST",pattern:"/v1/nodes/:id/mail/acknowledge",handler:ve}]),Qe=[{method:"POST",pattern:"/v1/nodes/:id/messages",scope:"act",handler:ye},{method:"POST",pattern:"/v1/nodes/:id/interrupt",scope:"act",handler:he}];export{Ke as brokerMailRoutes,Qe as messageRoutes};
|
|
1
|
+
var E=Object.defineProperty;var c=(r,e)=>E(r,"name",{value:e,configurable:!0});import{join as J}from"node:path";import{claimNodeMail as W,acknowledgeNodeMail as D}from"../../../core/canvas/deliveries.js";import{nodeMailEntry as L}from"../../../core/feed/inbox.js";import{enqueueNodeMail as q,cancelPendingNodeMail as G}from"../../../core/feed/messages.js";import{reviveNode as O}from"../../../core/runtime/revive.js";import{BrokerUnreachableError as F}from"../../../core/runtime/broker-request.js";import{isBrokerLive as C}from"../../../core/runtime/model-swap.js";import{deliverLive as U,interruptLive as H}from"../../../core/runtime/interactive-deliver.js";import{isProfilePaused as K}from"../../../core/profiles/manifest.js";import{getNode as x,withFreshTerminalGuard as Q}from"../../../core/canvas/canvas.js";import{reportsDir as V}from"../../../core/canvas/node-agent-paths.js";import{withCanvasWrite as X}from"../../../core/canvas/db.js";import{cancelCronsOnWake as I}from"../../../core/canvas/crons.js";import{assertNotFinalized as N,assertFinalizedForReopen as Y,commitReopenResident as A}from"../../../core/runtime/reopen.js";import{writeOutputSchema as Z}from"../../../core/runtime/structured-output.js";import{appendSituationalContext as j,formatSituationalProse as ee}from"../../../core/runtime/situational-context.js";import{formatDataCard as P}from"../../../shared/generated-context.js";import{hasNoNaturalCycle as te}from"../../../core/runtime/revive-all.js";import{recordPendingParkActivity as re}from"../../park-pending.js";import{wantsExecution as ne}from"../../reconcilers/node-lifecycle/wants-execution.js";import{hasFreshGroundState as oe}from"../../../core/runtime/revive.js";import{notFound as S,usage as a}from"../../../core/errors.js";import{assertScope as ie}from"../../../core/scopes.js";import{InputError as ae}from"../../../core/io.js";import{ApiError as se}from"../../../api/index.js";import{ownerOnly as de}from"../router.js";const ce=["critical","urgent","normal","deferred"];function M(r,e){if(typeof r!="object"||r===null||Array.isArray(r))throw a(`${e} must be an object { kind, facts?, body? }`);const i=r,t=i.kind;if(typeof t!="string"||t.trim()==="")throw a(`${e}.kind is required`);if(!t.includes(":"))throw a(`${e}.kind must be namespaced (contain ':'): ${t}`);const s={kind:t},n=i.facts;if(n!==void 0){if(typeof n!="object"||n===null||Array.isArray(n))throw a(`${e}.facts must be an object of string or number values`);const y={};for(const[m,f]of Object.entries(n)){if(typeof f!="string"&&typeof f!="number")throw a(`${e}.facts.${m} must be a string or number`);y[m]=f}s.facts=y}const o=i.body;if(o!==void 0){if(typeof o!="string")throw a(`${e}.body must be a string`);s.body=o}return s}c(M,"parseCardRequest");function T(r,e){try{return P(r.kind,r.facts??{},r.body??"")}catch(i){throw a(`${e}: ${i instanceof Error?i.message:String(i)}`)}}c(T,"renderCard");function ue(r){if(typeof r!="object"||r===null)throw a("a message requires a JSON body { body, tier?, fresh? }");const e=r,i=e.body,t=e.fresh===!0,s=e.tier,n=e.situational_context,o=e.output_schema,y=typeof i=="string"&&i.trim()!=="",m=typeof n=="string"&&n.trim()!=="",f=typeof o=="string"&&o.trim()!=="",g=e.situational_card,h=e.context_cards,b=g===void 0?void 0:M(g,"situational_card");if(h!==void 0&&!Array.isArray(h))throw a("context_cards must be an array of { kind, facts?, body? }");const l=h?.map((v,k)=>M(v,`context_cards[${k}]`));if(b!==void 0&&typeof n=="string"&&n!=="")throw a("situational_card and situational_context are mutually exclusive");const _=b!==void 0||l!==void 0&&l.length>0;if(!t&&!y&&!m&&!f&&!_)throw a("a message requires a non-empty body (or fresh: true, situational_context, a runtime card, or output_schema)");if(t&&l!==void 0&&l.length>0)throw a("context_cards cannot ride a fresh revive (no inbox entry carries them)");if(s!==void 0&&!ce.includes(s))throw a(`invalid tier: ${String(s)} (expected critical|urgent|normal|deferred)`);const u={body:typeof i=="string"?i:""};s!==void 0&&(u.tier=s),t&&(u.fresh=!0),e.reopen===!0&&(u.reopen=!0),typeof n=="string"&&(u.situational_context=n),b!==void 0&&(u.situational_card=b),l!==void 0&&(u.context_cards=l),typeof o=="string"&&(u.output_schema=o),typeof e.from=="string"&&(u.from=e.from);const p=e.delivery;if(p!==void 0&&p!=="interactive")throw a(`invalid delivery: ${String(p)} (expected interactive)`);if(p==="interactive"){if(t||u.situational_context!==void 0||u.output_schema!==void 0)throw a("interactive delivery supports a body, runtime cards, and reopen only (no fresh, situational_context, or output_schema)");if(!y)throw a("interactive delivery requires a non-empty body");if(u.tier==="deferred")throw a("interactive delivery cannot be deferred");u.delivery="interactive"}return u}c(ue,"parseSendBody");function fe(r){try{return JSON.parse(r)}catch{throw a("output_schema must be a JSON schema string")}}c(fe,"parseSchema");function le(r){return r.split(`
|
|
2
|
+
`)[0].slice(0,120)}c(le,"label");function z(r,e){if(e===null)return"";const i=J(V(r),e);return P("reopen-final-report",{path:i},"This node previously completed work. Read this final report before acting on the new instruction.")}c(z,"previousFinalReportCard");function me(r,e){return new ae({error:"deferred_no_natural_cycle",message:`${r} is ${e} with no natural next cycle ahead of it \u2014 a deferred message would never be delivered.`,next:"Use --tier normal, urgent, or critical to wake it now, or --reopen (with a body or --fresh) to re-task it first."})}c(me,"deferredNoNaturalCycle");function pe(r){if(!oe(r))throw new se(422,"unprocessable",`node ${r} has no goal/roadmap on disk \u2014 a fresh revive would resume amnesiac.`)}c(pe,"assertRecoverableForFresh");async function ye(r){const e=r.params.id,i=x(e);if(i===null)throw S(`unknown node: ${e}`,{received:e});const t=ue(r.body),s=t.tier??"normal",n=K(i.profile_id),o=t.from??null;if(o!==null){const d=x(o);d!==null&&ie(d,"crtr:act")}const y=t.body.trim()!=="",m=t.situational_card!==void 0?T(t.situational_card,"situational_card"):t.situational_context!==void 0?ee(t.situational_context.trim()):"",f=m!=="",g=(t.context_cards??[]).map((d,w)=>T(d,`context_cards[${w}]`)),h=t.output_schema!==void 0&&t.output_schema.trim()!==""?fe(t.output_schema):null;if(t.fresh){const d=t.reopen?Y(e):null;t.reopen||N(e),pe(e),f&&j(e,m),t.reopen&&A(e,d);const w=await O(e,{resume:!1,capacity:"refuse"});return{status:201,body:{node_id:e,delivered:!1,revived:w.launch!==void 0}}}t.delivery==="interactive"&&!t.reopen&&N(e);let b=!1,l="";if(t.delivery==="interactive"&&t.reopen&&(l=z(e,A(e)),b=!0),t.delivery==="interactive"&&!n&&!i.run_id&&C(i))try{return f&&j(e,m),await U(e,t.body,{cards:[...l===""?[]:[l],...f?[m]:[],...g],origin:o==="human"?{type:"human"}:{type:"runtime",kind:"inbox",entries:[{...o===null?{}:{from:o},kind:"message",tier:s}]}}),I(e),{status:201,body:{node_id:e,delivered:!0,revived:!1,delivered_via:"engine"}}}catch(d){if(!(d instanceof F))throw d}const _=c(()=>{t.reopen||N(e),h!==null&&Z(e,"oneoff",h),f&&j(e,m),t.reopen&&!b&&(l=z(e,A(e)));const d=[...l===""?[]:[l],...g],w=d.length>0?{cards:d}:{};if(y||h!==null){const $=y?t.body:"A one-off structured-output request has been granted. Submit a result matching the requested schema with `crtr push result` before you stop; after it is accepted, continue normally.";return q(e,{senderNodeId:o,urgency:s,wake:1,kind:"message",label:le($),bodyJson:{body:$,...f?{situational:!0}:{},...w}})}return q(e,{senderNodeId:o,urgency:s,wake:1,kind:"message",label:f?"(ambient context updated)":"(context delivered)",bodyJson:{...f?{situational:!0}:{},situationalOnly:!0,...w}})},"deliverImmediate"),p=c(()=>{if(s==="deferred"){const d=Q(e,te,_);if(d.kind==="missing")throw S(`unknown node: ${e}`,{received:e});if(d.kind==="terminal")throw me(e,d.status);return d.result}return _()},"deliver")();p.urgency!=="deferred"&&X(()=>re(e));const v=x(e);if(v===null)throw S(`unknown node: ${e}`,{received:e});i.frozen_at!==null&&I(e);let k=!1,R=!1;if((t.reopen||v.lifecycle==="terminal"||!ne(v))&&p.urgency!=="deferred"&&!n&&!C(v))try{const d=await O(e,{resume:!0,capacity:"freeze"});k=d.launch!==void 0,R=d.outcome==="frozen"}catch{}return{status:201,body:{node_id:e,delivered:!0,revived:k,...R?{not_revived_reason:"capacity_frozen"}:{},delivered_at:p.createdAt,...p.urgency===s?{}:{delivered_tier:p.urgency},...t.delivery==="interactive"?{delivered_via:"inbox"}:{}}}}c(ye,"handleMessage");async function he(r){const e=r.params.id,i=x(e);if(i===null)throw S(`unknown node: ${e}`,{received:e});const t=G(e,{senderNodeId:"human",kind:"message"});let s=!1;if(C(i))try{s=await H(e)!=="idle"}catch(o){if(!(o instanceof F))throw o}return{status:200,body:{node_id:e,outcome:s?"aborted_turn":t.length>0?"canceled_pending":"idle",aborted_turn:s,canceled_pending:t.length}}}c(he,"handleInterrupt");function B(r){if(typeof r.body!="object"||r.body===null||Array.isArray(r.body))throw a("mail requires an object body");const e=r.body;if(typeof e.execution_id!="string"||e.execution_id.trim()==="")throw a("execution_id is required");return e}c(B,"mailBody");function be(r){const e=B(r),i=e.channel;if(i!=="wake"&&i!=="passive")throw a("channel must be wake or passive");const t=W(r.params.id,e.execution_id,i);return{status:200,body:{action:t.action,deliveries:t.deliveries.map(n=>({delivery_id:n.deliveryId,attempts:n.attempts,handoff:n.handoff,entry:L(n)}))}}}c(be,"handleMailClaim");function ve(r){const e=B(r);if(!Array.isArray(e.deliveries))throw a("deliveries must be an array");const i=e.deliveries.map(n=>{if(typeof n!="object"||n===null||Array.isArray(n))throw a("each delivery must be an object");const o=n;if(typeof o.delivery_id!="string"||o.delivery_id==="")throw a("delivery_id is required");if(!Number.isSafeInteger(o.attempts)||o.attempts<1)throw a("attempts must be a positive integer");if(o.disposition!=="acknowledged"&&o.disposition!=="released")throw a("disposition must be acknowledged or released");return{delivery_id:o.delivery_id,attempts:o.attempts,disposition:o.disposition}}),t=D(r.params.id,e.execution_id,i.map(n=>({deliveryId:n.delivery_id,attempts:n.attempts,disposition:n.disposition})));return{status:200,body:{action:t.action,results:t.results.map(n=>({delivery_id:n.deliveryId,outcome:n.outcome}))}}}c(ve,"handleMailAcknowledge");const Ke=de([{method:"POST",pattern:"/v1/nodes/:id/mail/claim",handler:be},{method:"POST",pattern:"/v1/nodes/:id/mail/acknowledge",handler:ve}]),Qe=[{method:"POST",pattern:"/v1/nodes/:id/messages",scope:"crtr:act",handler:ye},{method:"POST",pattern:"/v1/nodes/:id/interrupt",scope:"crtr:act",handler:he}];export{Ke as brokerMailRoutes,Qe as messageRoutes};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var P=Object.defineProperty;var r=(n,e)=>P(n,"name",{value:e,configurable:!0});import{join as j}from"node:path";import{deleteAuthCredential as k,readAuthCredentials as M,setAuthCredential as A}from"../../../core/auth-file.js";import{PoolCredentialStore as $}from"../../../core/pool-credential-store.js";import{secretsDir as L}from"../../../core/layout.js";import{ApiError as d}from"../../../api/index.js";import{RunError as q}from"../../../core/runs/operations.js";import{usage as h}from"../../../core/errors.js";import{resolveLaunchTarget as N}from"../../../core/runtime/launch-target.js";import{ANTHROPIC_PROVIDER_ID as O,OPENAI_CODEX_PROVIDER_ID as S,commitManagedLogin as R,readSubscriptionPool as b,removeAllManagedAccounts as T}from"../../../core/subscription-state.js";import{cancelModelAuthFlow as C,completeModelAuthFlow as x,startModelAuthFlow as G,waitModelAuthFlow as U}from"../../../core/model-auth/flows.js";function c(){return j(L(),"auth.json")}r(c,"authPath");function p(n){return n===O||n===S}r(p,"isManagedProvider");function I(n,e){if(typeof e!="string"||e==="")throw new d(400,"invalid_request",`oauth credential requires \`${n}\``);const t=Date.parse(e);if(Number.isNaN(t))throw new d(400,"invalid_request",`\`${n}\` is not a valid ISO timestamp`);return t}r(I,"parseExpiry");function w(n,e,t){if(typeof t!="string"||t==="")throw new d(400,"invalid_request",`${n} credential requires \`${e}\``);return t}r(w,"requireField");function V(n){return{label:n.label,expires_at:new Date(n.expires).toISOString(),rate_limited_until:new Date(n.rateLimitedUntil).toISOString(),...n.authFailure?{auth_failure:n.authFailure}:{},...n.accountId?{account_id:n.accountId}:{}}}r(V,"toManagedAccountStatus");function D(n){const e=b(n).map(V);return{provider:n,managed:!0,configured:e.length>0,accounts:e}}r(D,"managedStatus");function _(n,e){const t=n.query.getAll(e);if(t.length>1)throw h(`${e} must appear at most once`);return t[0]}r(_,"singleQueryValue");function B(n){const e=n.indexOf("/"),t=e>0?n.slice(0,e):"";if(t==="")throw new d(422,"unresolved_model","the selected launch has no concrete model provider");return t}r(B,"providerFromModel");async function H(){const n=await M(c()),e=[D(O),D(S)];for(const[t,o]of Object.entries(n))p(t)||o.type!=="api_key"&&o.type!=="oauth"||e.push({provider:t,managed:!1,configured:!0,kind:o.type});return{status:200,body:{providers:e}}}r(H,"handleList");async function J(n){for(const[l]of n.query)if(l!=="profile"&&l!=="cwd"&&l!=="kind"&&l!=="model")throw h(`unknown model-auth readiness query parameter: ${l}`);const e=_(n,"profile"),t=_(n,"cwd"),o=_(n,"kind"),a=_(n,"model");if(o!==void 0&&o.trim()==="")throw h("kind must be a non-empty string when provided");if(a!==void 0&&a.trim()==="")throw h("model must be a non-empty string when provided");const u=await N({root:!0,...e!==void 0?{profile:e}:{},...t!==void 0?{cwd:t}:{},...o!==void 0?{kind:o}:{},...a!==void 0?{model:a}:{}},{readOnlyProfileSelection:!0});if(u.launch.model===void 0)throw new d(422,"unresolved_model","the selected launch has no concrete model");const i=B(u.launch.model);if(p(i)){const l=b(i);if(l.length>0){const m=l.filter(f=>f.authFailure===void 0);if(m.length===0)return{status:200,body:{provider:i,model:u.launch.model,credential:"unusable",reason:"invalid_grant"}};const g=Date.now(),F=m.some(f=>f.rateLimitedUntil<=g),v=Math.min(...m.map(f=>f.rateLimitedUntil));return{status:200,body:{provider:i,model:u.launch.model,credential:"ready",...!F&&v>g?{rate_limited_until:new Date(v).toISOString()}:{}}}}}const s=await new $(c()).read(i),y=s?.type==="oauth"||s?.type==="api_key"&&!!s.key;return{status:200,body:{provider:i,model:u.launch.model,credential:y?"ready":"missing"}}}r(J,"handleReadiness");async function K(n){const e=n.params.provider,t=n.body;if(t===void 0||typeof t!="object"||typeof t.kind!="string")throw new d(400,"invalid_request","a credential `kind` is required");switch(t.kind){case"api_key":{const o=w("api_key","api_key",t.api_key);return await A(e,{type:"api_key",key:o},c()),{status:200,body:{provider:e,installed:!0,managed:!1}}}case"oauth":{if(p(e))throw new d(422,"unprocessable",`provider ${e} stores oauth credentials as managed accounts \u2014 use kind \`managed_account\``);const o=w("oauth","access_token",t.access_token),a=w("oauth","refresh_token",t.refresh_token),u=I("expires_at",t.expires_at),i=t.extra??{};await A(e,{type:"oauth",...i,access:o,refresh:a,expires:u},c());const s={provider:e,installed:!0,managed:!1};return typeof t.account_id=="string"&&t.account_id!==""&&(s.account_id=t.account_id),{status:200,body:s}}case"managed_account":{if(!p(e))throw new d(422,"unprocessable",`provider ${e} does not support managed accounts`);const o=typeof t.label=="string"&&t.label.trim()?t.label.trim():void 0;if(!o&&t.auto_label!==!0)throw new d(400,"invalid_request","managed_account credential requires `label` or `auto_label`");const a=typeof t.account_id=="string"&&t.account_id!==""?t.account_id:void 0,u=w("managed_account","access_token",t.access_token),i=w("managed_account","refresh_token",t.refresh_token),s=I("expires_at",t.expires_at),y=typeof t.last_rate_limited_at=="number"?t.last_rate_limited_at:Math.max(0,...b(e).map(m=>m.lastRateLimitedAt));await R(e,o,{refresh:i,access:u,expires:s,...a?{accountId:a}:{},lastRateLimitedAt:y,autoLabel:t.auto_label===!0});const l={provider:e,installed:!0,managed:!0};return a&&(l.account_id=a),{status:200,body:l}}default:throw new d(400,"invalid_request",`unknown credential kind: ${String(t.kind)}`)}}r(K,"handleInstall");async function Q(n){const e=n.params.provider;if(p(e)){const o=await T(e),a=await k(e,c());return{status:200,body:{provider:e,removed_accounts:o+(a?1:0)}}}const t=await k(e,c())?1:0;return{status:200,body:{provider:e,removed_accounts:t}}}r(Q,"handleDelete");function E(n){const e=n.body;if(e===void 0)return{};if(typeof e!="object"||e===null||Array.isArray(e))throw new d(400,"invalid_request","request body must be a JSON object");return e}r(E,"bodyObject");async function X(n){const e=E(n);return{status:200,body:await G({provider:e.provider,...e.redirect!==void 0?{redirect:e.redirect}:{},...e.label!==void 0?{label:e.label}:{}})}}r(X,"handleFlowStart");async function z(n){const e=E(n);return{status:200,body:await x(n.params.flow_id,e.input)}}r(z,"handleFlowComplete");async function W(n){const e=C(n.params.flow_id);if(!e)throw new q(400,"invalid_request","no sign-in has this flow_id","flow_id");const{jti:t,...o}=e;return{status:200,body:o}}r(W,"handleFlowCancel");async function Y(n){for(const[s]of n.query)if(s!=="wait")throw h(`unknown model-auth flow query parameter: ${s}`);const e=_(n,"wait");let t=0;if(e!==void 0&&(t=/^\d+$/.test(e)?Number(e):NaN,!Number.isInteger(t)||t<1||t>25))throw new d(400,"invalid_request","wait must be an integer from 1 to 25");const o=new AbortController;n.res.once("close",()=>o.abort());const a=await U(n.params.flow_id,t*1e3,o.signal);if(!a)throw new q(404,"not_found","no sign-in has this flow_id","flow_id");const{jti:u,...i}=a;return{status:200,body:i}}r(Y,"handleFlowGet");const ue=[{method:"POST",pattern:"/v1/model-auth/flows",ownerOnly:!0,handler:X},{method:"POST",pattern:"/v1/model-auth/flows/:flow_id/complete",ownerOnly:!0,handler:z},{method:"POST",pattern:"/v1/model-auth/flows/:flow_id/cancel",ownerOnly:!0,handler:W},{method:"GET",pattern:"/v1/model-auth/flows/:flow_id",ownerOnly:!0,handler:Y},{method:"GET",pattern:"/v1/model-auth",handler:H},{method:"GET",pattern:"/v1/model-auth/readiness",handler:J},{method:"PUT",pattern:"/v1/model-auth/:provider",ownerOnly:!0,handler:K},{method:"DELETE",pattern:"/v1/model-auth/:provider",ownerOnly:!0,handler:Q}];export{ue as modelAuthRoutes};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var v=Object.defineProperty;var i=(e,t)=>v(e,"name",{value:t,configurable:!0});import{setTimeout as w}from"node:timers/promises";import{ApiError as r}from"../../../api/errors.js";import{getNode as h}from"../../../core/canvas/canvas.js";import{armExternalActionDelivery as g,activateArmedExternalActionDelivery as A,readExternalActionDelivery as s}from"../../../core/canvas/deliveries.js";import{withCanvasWrite as u}from"../../../core/canvas/db.js";import{OUTCOME_PAYLOAD_MAX_BYTES as m}from"../../../core/canvas/types.js";import{composeNodeOutcomeDocument as O}from"../../../core/runtime/outcome-document.js";import{HUMAN_ACTION_NAME_PATTERN as E}from"../../../core/human/action-binding.js";import{resolveHumanAction as b}from"../../../core/human-actions.js";import{toNodeOutcomeDTO as f,toOutcomeDeliveryDTO as p}from"../map.js";const D=250,N=25;function c(e){const t=h(e);if(t===null)throw new r(404,"node_not_found",`no node ${e}`);return t}i(c,"requireNode");function T(e){const t=e.query.get("wait");if(t===null||t==="")return 0;if(!/^(?:0|[1-9]\d*)$/.test(t))throw new r(400,"invalid_request","`wait` must be an integer between 0 and 25");const n=Number(t);if(n<0||n>N)throw new r(400,"invalid_request","`wait` must be an integer between 0 and 25");return n}i(T,"parseWait");function k(e){const t=f(e);return{node_id:e.node_id,state:t===null?"pending":"settled",outcome:t,node_status:e.status,deadline_at:e.deadline_at??null}}i(k,"responseFor");async function $(e){const t=e.params.id??"",n=T(e),o=Date.now()+n*1e3;let a=c(t);for(;f(a)===null&&Date.now()<o;)await w(Math.min(D,o-Date.now())),a=c(t);return{status:200,body:k(a)}}i($,"handleGetOutcome");function q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(q,"isPlainObject");function x(e){let t;try{t=JSON.stringify(e)}catch{throw new r(400,"invalid_request","`payload` must be JSON-serializable")}if(t===void 0)throw new r(400,"invalid_request","`payload` must be JSON-serializable");return Buffer.byteLength(t,"utf8")}i(x,"payloadBytes");function S(e){if(!q(e))throw new r(400,"invalid_request","request body must be an object");for(const n of Object.keys(e))if(n!=="action"&&n!=="payload")throw new r(400,"invalid_request",`unexpected field in request body: ${n}`);const t=e.action;if(typeof t!="string"||!E.test(t))throw new r(400,"invalid_request","`action` must be a declared action name");if(e.payload!==void 0&&x(e.payload)>m)throw new r(413,"payload_too_large",`serialized payload exceeds ${m} bytes`);return e.payload===void 0?{action:t}:{action:t,payload:e.payload}}i(S,"parseRegistration");function d(e){return`node-outcome:${e}`}i(d,"outcomeKey");function y(e){const t=e.adapter;if(t?.adapter!=="subprocess"||!Array.isArray(t.argv)||!t.argv.every(n=>typeof n=="string")||typeof t.cwd!="string")throw new Error(`outcome delivery ${e.deliveryId} has an invalid subprocess adapter`);return{nodeId:e.idempotencyKey?.slice(13)??"",state:e.state==="handed_off"?"running":e.state==="acknowledged"?"accepted":e.state,attempt:e.attempts,actionName:e.destinationId,argv:t.argv,cwd:t.cwd,configOrigin:typeof t.config_origin=="string"?t.config_origin:"",payload:t.payload??null,document:null,nextAttemptAt:e.nextAttemptAt??0,claimedAt:e.claimedAt,claimOwner:e.claimOwner,acceptedAt:e.acknowledgedAt,permanentFailedAt:e.failedAt,lastFailure:e.lastFailure,createdAt:e.createdAt,updatedAt:e.updatedAt}}i(y,"outcomeView");function I(e){const t=e.outcome_reason;let n,o;return e.outcome_kind==="result"||t==="finished"||t==="declined"?(n="done",o="done"):t==="parked"?(n="done",o="parked"):t==="closed"||t==="retired"||t==="stranded"||t==="deadline_exceeded"?(n="canceled",o=null):(n="dead",o=null),{...e,status:n,intent:o,terminal_reason:t}}i(I,"nodeAtOutcome");function M(e,t,n){return u(o=>{const a=s(d(e.node_id));if(a!==null&&a.state!=="armed")return null;if(g(o,{destinationId:t.action,adapter:{adapter:"subprocess",argv:t.argv,cwd:t.cwd,config_origin:t.configOrigin,payload:n??null},idempotencyKey:d(e.node_id)}),e.outcome_at!==null){if(e.outcome_kind===null||e.outcome_reason===null)throw new Error(`outcome latch is incomplete for node ${e.node_id}`);const _=JSON.stringify(O({node:I(e),outcome:{kind:e.outcome_kind,reason:e.outcome_reason,at:e.outcome_at,revision:e.outcome_revision,detailJson:e.outcome_detail_json??null},action:{name:t.action,payload:n??null},finalReport:e.final_report}));A(o,{idempotencyKey:d(e.node_id),label:e.node_id,bodyJson:_,supersede:!1})}const l=s(d(e.node_id));if(l===null)throw new Error(`outcome delivery was not registered for ${e.node_id}`);return y(l)})}i(M,"armOutcomeExternalAction");function L(e,t){const n=b(e,t);if(!("kind"in n))return n;throw n.kind==="unknown_action"?new r(422,"unknown_action",`no action named ${e} is declared from ${t}`):new r(422,"invalid_action",`${e} is declared in ${n.configOrigin} but unusable: ${n.reason}`,{reason:n.reason,configOrigin:n.configOrigin})}i(L,"resolveAction");function R(e){const t=e.params.id??"",n=c(t),o=S(e.body),a=L(o.action,n.cwd),l=M(n,{action:o.action,...a},o.payload);if(l===null)throw new r(409,"outcome_delivery_settled","outcome delivery has already started or settled");return{status:200,body:p(l)}}i(R,"handlePutDelivery");function J(e){const t=e.params.id??"",n=s(d(t));if(n===null)throw new r(404,"outcome_delivery_not_found",`no outcome delivery for node ${t}`);return{status:200,body:p(y(n))}}i(J,"handleGetDelivery");function P(e){const t=e.params.id??"",n=s(d(t));if(n!==null&&n.state!=="armed")throw new r(409,"outcome_delivery_settled","outcome delivery has already started or settled");return n!==null&&u(o=>{o.prepare("DELETE FROM deliveries WHERE delivery_id = ? AND state = 'armed'").run(n.deliveryId)}),{status:204}}i(P,"handleDeleteDelivery");const X=[{method:"GET",pattern:"/v1/nodes/:id/outcome",handler:$},{method:"PUT",pattern:"/v1/nodes/:id/outcome-delivery",handler:R},{method:"GET",pattern:"/v1/nodes/:id/outcome-delivery",handler:J},{method:"DELETE",pattern:"/v1/nodes/:id/outcome-delivery",handler:P}];export{X as nodeOutcomeRoutes};
|
|
1
|
+
var v=Object.defineProperty;var i=(e,t)=>v(e,"name",{value:t,configurable:!0});import{setTimeout as w}from"node:timers/promises";import{ApiError as r}from"../../../api/errors.js";import{getNode as h}from"../../../core/canvas/canvas.js";import{armExternalActionDelivery as g,activateArmedExternalActionDelivery as A,readExternalActionDelivery as s}from"../../../core/canvas/deliveries.js";import{withCanvasWrite as u}from"../../../core/canvas/db.js";import{OUTCOME_PAYLOAD_MAX_BYTES as m}from"../../../core/canvas/types.js";import{composeNodeOutcomeDocument as O}from"../../../core/runtime/outcome-document.js";import{HUMAN_ACTION_NAME_PATTERN as E}from"../../../core/human/action-binding.js";import{resolveHumanAction as b}from"../../../core/human-actions.js";import{toNodeOutcomeDTO as f,toOutcomeDeliveryDTO as p}from"../map.js";const D=250,N=25;function c(e){const t=h(e);if(t===null)throw new r(404,"node_not_found",`no node ${e}`);return t}i(c,"requireNode");function T(e){const t=e.query.get("wait");if(t===null||t==="")return 0;if(!/^(?:0|[1-9]\d*)$/.test(t))throw new r(400,"invalid_request","`wait` must be an integer between 0 and 25");const n=Number(t);if(n<0||n>N)throw new r(400,"invalid_request","`wait` must be an integer between 0 and 25");return n}i(T,"parseWait");function k(e){const t=f(e);return{node_id:e.node_id,state:t===null?"pending":"settled",outcome:t,node_status:e.status,deadline_at:e.deadline_at??null}}i(k,"responseFor");async function $(e){const t=e.params.id??"",n=T(e),o=Date.now()+n*1e3;let a=c(t);for(;f(a)===null&&Date.now()<o;)await w(Math.min(D,o-Date.now())),a=c(t);return{status:200,body:k(a)}}i($,"handleGetOutcome");function q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(q,"isPlainObject");function x(e){let t;try{t=JSON.stringify(e)}catch{throw new r(400,"invalid_request","`payload` must be JSON-serializable")}if(t===void 0)throw new r(400,"invalid_request","`payload` must be JSON-serializable");return Buffer.byteLength(t,"utf8")}i(x,"payloadBytes");function S(e){if(!q(e))throw new r(400,"invalid_request","request body must be an object");for(const n of Object.keys(e))if(n!=="action"&&n!=="payload")throw new r(400,"invalid_request",`unexpected field in request body: ${n}`);const t=e.action;if(typeof t!="string"||!E.test(t))throw new r(400,"invalid_request","`action` must be a declared action name");if(e.payload!==void 0&&x(e.payload)>m)throw new r(413,"payload_too_large",`serialized payload exceeds ${m} bytes`);return e.payload===void 0?{action:t}:{action:t,payload:e.payload}}i(S,"parseRegistration");function d(e){return`node-outcome:${e}`}i(d,"outcomeKey");function y(e){const t=e.adapter;if(t?.adapter!=="subprocess"||!Array.isArray(t.argv)||!t.argv.every(n=>typeof n=="string")||typeof t.cwd!="string")throw new Error(`outcome delivery ${e.deliveryId} has an invalid subprocess adapter`);return{nodeId:e.idempotencyKey?.slice(13)??"",state:e.state==="handed_off"?"running":e.state==="acknowledged"?"accepted":e.state,attempt:e.attempts,actionName:e.destinationId,argv:t.argv,cwd:t.cwd,configOrigin:typeof t.config_origin=="string"?t.config_origin:"",payload:t.payload??null,document:null,nextAttemptAt:e.nextAttemptAt??0,claimedAt:e.claimedAt,claimOwner:e.claimOwner,acceptedAt:e.acknowledgedAt,permanentFailedAt:e.failedAt,lastFailure:e.lastFailure,createdAt:e.createdAt,updatedAt:e.updatedAt}}i(y,"outcomeView");function I(e){const t=e.outcome_reason;let n,o;return e.outcome_kind==="result"||t==="finished"||t==="declined"?(n="done",o="done"):t==="parked"?(n="done",o="parked"):t==="closed"||t==="retired"||t==="stranded"||t==="deadline_exceeded"?(n="canceled",o=null):(n="dead",o=null),{...e,status:n,intent:o,terminal_reason:t}}i(I,"nodeAtOutcome");function M(e,t,n){return u(o=>{const a=s(d(e.node_id));if(a!==null&&a.state!=="armed")return null;if(g(o,{destinationId:t.action,adapter:{adapter:"subprocess",argv:t.argv,cwd:t.cwd,node_id:e.node_id,app:e.grantee??"app:terminal",config_origin:t.configOrigin,payload:n??null},idempotencyKey:d(e.node_id)}),e.outcome_at!==null){if(e.outcome_kind===null||e.outcome_reason===null)throw new Error(`outcome latch is incomplete for node ${e.node_id}`);const _=JSON.stringify(O({node:I(e),outcome:{kind:e.outcome_kind,reason:e.outcome_reason,at:e.outcome_at,revision:e.outcome_revision,detailJson:e.outcome_detail_json??null},action:{name:t.action,payload:n??null},finalReport:e.final_report}));A(o,{idempotencyKey:d(e.node_id),label:e.node_id,bodyJson:_,supersede:!1})}const l=s(d(e.node_id));if(l===null)throw new Error(`outcome delivery was not registered for ${e.node_id}`);return y(l)})}i(M,"armOutcomeExternalAction");function L(e,t){const n=b(e,t);if(!("kind"in n))return n;throw n.kind==="unknown_action"?new r(422,"unknown_action",`no action named ${e} is declared from ${t}`):new r(422,"invalid_action",`${e} is declared in ${n.configOrigin} but unusable: ${n.reason}`,{reason:n.reason,configOrigin:n.configOrigin})}i(L,"resolveAction");function R(e){const t=e.params.id??"",n=c(t),o=S(e.body),a=L(o.action,n.cwd),l=M(n,{action:o.action,...a},o.payload);if(l===null)throw new r(409,"outcome_delivery_settled","outcome delivery has already started or settled");return{status:200,body:p(l)}}i(R,"handlePutDelivery");function J(e){const t=e.params.id??"",n=s(d(t));if(n===null)throw new r(404,"outcome_delivery_not_found",`no outcome delivery for node ${t}`);return{status:200,body:p(y(n))}}i(J,"handleGetDelivery");function P(e){const t=e.params.id??"",n=s(d(t));if(n!==null&&n.state!=="armed")throw new r(409,"outcome_delivery_settled","outcome delivery has already started or settled");return n!==null&&u(o=>{o.prepare("DELETE FROM deliveries WHERE delivery_id = ? AND state = 'armed'").run(n.deliveryId)}),{status:204}}i(P,"handleDeleteDelivery");const X=[{method:"GET",pattern:"/v1/nodes/:id/outcome",handler:$},{method:"PUT",pattern:"/v1/nodes/:id/outcome-delivery",handler:R},{method:"GET",pattern:"/v1/nodes/:id/outcome-delivery",handler:J},{method:"DELETE",pattern:"/v1/nodes/:id/outcome-delivery",handler:P}];export{X as nodeOutcomeRoutes};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
var g=Object.defineProperty;var n=(e,t)=>g(e,"name",{value:t,configurable:!0});import{mkdirSync as v,readFileSync as N,writeFileSync as S}from"node:fs";import{dirname as w,isAbsolute as k,join as h,resolve as E}from"node:path";import{appendRotatingRecord as O}from"../../../core/log.js";import{jobDir as c,messagesDir as T}from"../../../core/canvas/paths.js";import{openDb as F}from"../../../core/canvas/db.js";import{resolveRef as A}from"../../../core/canvas/history.js";import{writeNodeRecap as D}from"../../../core/canvas/node-recap.js";import{markStopSignal as R,consumeStopSignals as x,clearStopSignals as j}from"../../../core/runtime/stop-signals.js";import{notFound as l,usage as s}from"../../../core/errors.js";import{isBeneathRefusal as q,readFileBeneath as I}from"../../../core/spaces/open-beneath.js";import{requireCurrentExecution as _}from"./broker-recovery.js";function m(e){if(e.body===null||typeof e.body!="object"||Array.isArray(e.body))throw s("node record requires a JSON object");const t=e.body;return _(e.params.id,t.expected_execution_id),t}n(m,"body");function d(e,t){if(typeof e!="string")throw s(`${t} must be a string`);return e}n(d,"text");const K=[{method:"POST",pattern:"/v1/nodes/:id/records/log",handler:n(e=>{const t=d(m(e).record,"record");return{status:200,body:{appended:O(h(c(e.params.id),"log.jsonl"),t)}}},"handler")},{method:"PUT",pattern:"/v1/nodes/:id/records/telemetry",handler:n(e=>{const t=m(e),r=t.tokens_in,o=t.tokens_out,i=t.context_tokens,u=t.last_activity,b=d(t.model,"model"),f=d(t.updated_at,"updated_at");if(typeof r!="number"||!Number.isFinite(r)||r<0||typeof o!="number"||!Number.isFinite(o)||o<0||i!==null&&(typeof i!="number"||!Number.isFinite(i)||i<0)||u!==null&&typeof u!="string"||Number.isNaN(Date.parse(f)))throw s("invalid telemetry");const y=h(c(e.params.id),"telemetry.json");let a={};try{a=JSON.parse(N(y,"utf8"))}catch(p){if(!(p instanceof SyntaxError)&&p.code!=="ENOENT")throw p}return v(c(e.params.id),{recursive:!0}),S(y,JSON.stringify({tokens_in:r,tokens_out:o,context_tokens:i??a.context_tokens,last_activity:u??a.last_activity,model:b||a.model||"",updated_at:f},null,2),"utf8"),{status:204}},"handler")},{method:"PUT",pattern:"/v1/nodes/:id/records/recap",handler:n(e=>(D(e.params.id,d(m(e).briefing,"briefing")),{status:204}),"handler")},{method:"GET",pattern:"/v1/nodes/:id/records/inbox",handler:n(e=>{const t=e.params.id,r=e.query.get("ref");if(_(t,e.query.get("execution_id")),r===null||!/^[a-z0-9-]+:reports\/[^/]+\.md$/.test(r))throw s("ref must be a report handle");if(F().prepare(`SELECT 1 FROM deliveries d JOIN messages m ON m.message_id = d.message_id
|
|
2
|
+
WHERE d.destination_kind = 'node_inbox' AND d.destination_id = ? AND d.state = 'handed_off'
|
|
3
|
+
AND d.claim_owner = ? AND d.canceled_at IS NULL AND m.body_ref = ? LIMIT 1`).get(t,e.query.get("execution_id"),r)===void 0)throw l("report was not delivered to this node");const i=A(r);if(i?.source!=="report")throw l("report not found");return{status:200,body:{content:i.body}}},"handler")},{method:"GET",pattern:"/v1/nodes/:id/records/passive",handler:n(e=>{const t=e.query.get("ref"),r=T(e.params.id);if(t===null||!k(t)||w(E(t))!==r||!t.endsWith(".md"))throw s("ref must be a direct-message spill path for this node");try{return{status:200,body:{content:I(r,t).toString("utf8")}}}catch(o){throw o.code==="ENOENT"?l("passive message not found"):q(o)?s("ref meets a symlink or is not a regular file; only the node's own message files are served"):o}},"handler")},{method:"POST",pattern:"/v1/nodes/:id/records/pushed-final",handler:n(e=>{const t=m(e);if(t.action==="mark")R(e.params.id,"pushedFinal",d(t.expected_execution_id,"expected_execution_id"));else if(t.action==="clear")j(e.params.id);else{if(t.action==="consume")return{status:200,body:x(e.params.id,d(t.expected_execution_id,"expected_execution_id"))};throw s("action must be mark, clear or consume")}return{status:200,body:{pushedFinal:!1}}},"handler")}];export{K as nodeRecordRoutes};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type ModelRegistryLike } from '../../../core/model-routes.js';
|
|
2
|
-
import type
|
|
2
|
+
import { type HandlerResult, type RequestContext, type RouteTable } from '../router.js';
|
|
3
3
|
interface NodeHandlerDeps {
|
|
4
4
|
modelRegistry?: ModelRegistryLike;
|
|
5
5
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var X=Object.defineProperty;var s=(e,t)=>X(e,"name",{value:t,configurable:!0});import{envProfileId as Z}from"../../../shared/env.js";import{existsSync as D,readdirSync as q,statSync as ee}from"node:fs";import{basename as ne,isAbsolute as te,resolve as I}from"node:path";import{appendSituationalContext as oe,formatSituationalProse as ie}from"../../../core/runtime/situational-context.js";import{closeNode as re}from"../../../core/runtime/close.js";import{reviveNode as de}from"../../../core/runtime/revive.js";import{nowIso as T}from"../../../core/fs-utils.js";import{assertLaunchModelRegistered as $,forkNode as se,spawnChildPrepared as ae}from"../../../core/runtime/spawn.js";import{childrenOf as le,getNode as b,listNodes as M,subscribersOf as ce,subscriptionsOf as E,setMessageWait as ue,updateNode as A}from"../../../core/canvas/canvas.js";import{subtreeIds as fe}from"../../../core/canvas/nav-model.js";import{withCanvasWrite as me}from"../../../core/canvas/db.js";import{unbindSession as pe}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as he}from"../../../core/canvas/attention.js";import{contextDir as P,reportsDir as we}from"../../../core/canvas/paths.js";import{nodeArtifacts as ye}from"../../../core/canvas/history.js";import{readNodeMessagesPage as ge,readNodeSession as _e,readNodeSnapshot as be,transcriptMarkdown as ve}from"../../../core/runtime/node-read.js";import{assembleNodeSubject as ke}from"../../../core/substrate/subject.js";import{reviveAll as Se}from"../../../core/runtime/revive-all.js";import{promoteAsync as Oe,requestYieldAsync as Ne,reshapeNodeAsync as L}from"../../../core/runtime/promote.js";import{recycleNode as Te}from"../../../core/runtime/recycle.js";import{relaunchRoot as $e}from"../../../core/runtime/reset.js";import{assertReopenGate as Ae}from"../../../core/runtime/reopen.js";import{writeYieldMessage as Pe,readGoal as Re}from"../../../core/runtime/kickoff.js";import{hasRoadmap as xe,seedRoadmap as Ce}from"../../../core/runtime/roadmap.js";import{renameWindow as De}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as Ie,isProviderPinnedModelToken as Me,normalizeModel as Ee,readMergedLaunchConfigAsync as j}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as Le}from"../../../core/model-routes.js";import{BrokerUnreachableError as je}from"../../../core/runtime/broker-request.js";import{isBrokerLive as Fe,persistDormantModel as Ge,setModelLive as ze}from"../../../core/runtime/model-swap.js";import{boundFleet as We}from"../../../core/runtime/fleet.js";import{writeOutputSchema as F}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as G}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as Be}from"../../../core/human/action-binding.js";import{resolveHumanAction as Je}from"../../../core/human-actions.js";import{parseDurationMs as Ve}from"../../../core/wake.js";import{claimWarmNode as Ke,refillWarmPool as z,warmPoolEnabled as Ye}from"../../../core/runtime/warm-pool.js";import{resolveLaunchTarget as He}from"../../../core/runtime/launch-target.js";import{fullName as Qe}from"../../../core/canvas/labels.js";import{reportsForNode as Ue}from"./reports.js";import{getCron as Xe}from"../../../core/canvas/crons.js";import{cronWakeOrigin as Ze}from"../../../core/runtime/bearings.js";import{boundDaemonControl as qe}from"../../control.js";import{notFound as R,usage as u}from"../../../core/errors.js";import{assertScope as en,validateScopes as W}from"../../../core/scopes.js";import{scopeAllowed as B}from"../../../shared/env.js";import{toCloseResultDTO as nn,toNodeDetailDTO as x,toNodeSummaryDTO as tn,toReviveResultDTO as on}from"../map.js";import{ApiError as h}from"../../../api/index.js";import{InputError as m}from"../../../core/io.js";function f(e){const t=b(e);if(t===null)throw R(`unknown node: ${e}`,{received:e});return t}s(f,"requireMeta");function C(e){return{subscribesTo:E(e),subscribers:ce(e),children:le(e)}}s(C,"edgesFor");function y(e){const t=f(e);return x(t,C(e))}s(y,"detailOf");function J(e){let t=0;for(const n of[P(e),we(e)])try{t+=q(n).length}catch{}return t}s(J,"countFiles");function rn(e){if(typeof e!="object"||e===null)throw u("a node create requires a JSON body");const t=e;if(t.kind!==void 0&&(typeof t.kind!="string"||t.kind.trim()===""))throw u("kind must be a non-empty string when provided");if(t.description!==void 0&&(typeof t.description!="string"||t.description.trim()===""))throw u("description must be a non-empty string when provided");if(t.creator!==void 0&&(typeof t.creator!="string"||t.creator.trim()===""))throw u("creator must be a non-empty node id when provided");t.scopes!==void 0&&W(t.scopes);const n=t.root_lifecycle;if(n!==void 0&&n!=="resident"&&n!=="terminal")throw u("root_lifecycle must be 'resident' or 'terminal'");return t}s(rn,"parseCreateBody");function dn(e){if(e===void 0)return;const t=Ve(e),n=t===null?null:new Date(Date.now()+t);if(t===null||!Number.isFinite(t)||t<=0||n===null||!Number.isFinite(n.getTime()))throw new h(422,"invalid_deadline","`deadline` must be a positive representable duration");return n.toISOString()}s(dn,"parseDeadline");function sn(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new h(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!Be.test(e.action))throw new h(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let t;try{t=JSON.stringify(e.payload)}catch{throw new h(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(t===void 0)throw new h(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(t,"utf8")>G)throw new h(413,"payload_too_large",`serialized payload exceeds ${G} bytes`)}return e}}s(sn,"parseOutcomeDelivery");function an(e,t){const n=Je(e.action,t);if(!("kind"in n))return{actionName:e.action,argv:n.argv,cwd:n.cwd,configOrigin:n.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw n.kind==="unknown_action"?new h(422,"unknown_action",`no action named ${e.action} is declared from ${t}`):new h(422,"invalid_action",`${e.action} is declared in ${n.configOrigin} but unusable: ${n.reason}`,{reason:n.reason,configOrigin:n.configOrigin})}s(an,"resolveOutcomeDelivery");function ln(e,t,n){const o={kind:e.kind,cwd:n,prompt:e.prompt??""};return e.mode!==void 0&&(o.mode=e.mode),e.name!==void 0&&(o.name=e.name),e.description!==void 0&&(o.description=e.description),t!==void 0&&(o.parent=t),e.creator!==void 0&&(o.creator=e.creator),e.scopes!==void 0&&(o.scopes=e.scopes),e.root===!0&&(o.root=!0),e.root_lifecycle!==void 0&&(o.rootLifecycle=e.root_lifecycle),(e.worktree===!0||typeof e.worktree=="string")&&(o.worktree=!0),typeof e.worktree=="string"&&(o.worktreeBase=e.worktree),e.worktree!==void 0&&(o.worktreeCwd=I(e.pin_cwd??e.cwd??n)),e.fork_from!==void 0&&(o.forkFrom=e.fork_from),e.model!==void 0&&(o.model=e.model),e.profile!==void 0&&(o.profile=e.profile),e.situational_context!==void 0&&(o.situationalContext=e.situational_context),e.node_id!==void 0&&(o.nodeId=e.node_id),o}s(ln,"buildRecipe");function cn(e,t,n){return!Ye()||e.prefer_warm!==!0||e.root!==!0||e.parent!=null||e.root_lifecycle==="terminal"||(e.prompt??"")!==""||e.model!==void 0||e.fork_from!==void 0||e.worktree!==void 0||e.node_id!==void 0||e.scopes!==void 0?null:{kind:e.kind,mode:e.mode??"base",cwd:t,profileId:n,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}s(cn,"warmRequestFor");import{resolveCreateKind as Dt}from"../../../core/runtime/launch-target.js";function V(e){const t=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Le(e.model,t,e.modelExact===!0)}s(V,"requestFromLaunch");function un(e,t){if(t===null)return e;if(e.scopes===void 0)return{...e,scopes:[...t]};const n=e.scopes.filter(o=>!B(t,o));if(n.length===0)return e;throw new h(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${n.join(", ")}`,{scopes:n,ceiling:t})}s(un,"withinCeiling");async function K(e,t,n){const o=(await Ie(t.kind,t.mode,{lifecycle:t.lifecycle,hasManager:e.parent!==null,model:t.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null})).launch;await $(V(o),{cwd:e.cwd,profileId:e.profile_id??null},n)}s(K,"assertNodeModelChangeRegistered");async function fn(e,t={}){const n=un(rn(e.body),e.ceiling);n.creator!==void 0&&en(f(n.creator),"act");const o=dn(n.deadline),r=sn(n.outcome_delivery),i=n.parent??void 0;if(i==null&&n.root!==!0)throw u("a node create requires a parent (or root: true for an independent root)");let d=null;if(n.output_schema!==void 0)try{d=JSON.parse(n.output_schema)}catch{throw u("output_schema must be a JSON schema string")}const{profileId:a,kind:c,cwd:l,launch:p}=await He(n,{validateKind:H}),v={...n,kind:c},g=r===void 0?void 0:an(r,l);await $(V(p),{cwd:l,profileId:a},t.modelRegistry);let _=null;{const k=cn(v,l,a);if(k!==null){const O=await Ke(k,{...o===void 0?{}:{deadlineAt:o},...g===void 0?{}:{outcomeDelivery:g}},d===null?void 0:U=>F(U,"terminal",d));if(O!==null)return z(k),{status:201,body:y(O)};_=k}const S=ln(v,i,l);o!==void 0&&(S.deadlineAt=o),g!==void 0&&(S.outcomeDelivery=g),S.readiness=n.root===!0?"await":"launch";const Q=await ae(S,d===null?void 0:O=>F(O,"terminal",d),()=>{_!==null&&z(_)});return{status:201,body:y(Q.node.node_id)}}}s(fn,"handleCreate");function w(e,t){const n=e.query.getAll(t);if(n.length>1)throw u(`${t} must appear at most once`);return n[0]}s(w,"singleQueryValue");function Y(e,t){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw u(`${t} must be true or false`)}}s(Y,"optionalBoolean");function N(e,t,n){if(e!==void 0){if(n.includes(e))return e;throw u(`${t} must be one of: ${n.join(", ")}`)}}s(N,"oneOf");function mn(e){const t=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","hanging","include"]);for(const[_]of e.query)if(!t.has(_))throw u(`unknown nodes query parameter: ${_}`);const n=N(w(e,"status"),"status",["active","idle","done","dead","canceled"]),o=N(w(e,"lifecycle"),"lifecycle",["terminal","resident"]),r=w(e,"kind"),i=N(w(e,"mode"),"mode",["base","orchestrator"]),d=w(e,"profile_id"),a=w(e,"profile_prefix"),c=w(e,"parent"),l=Y(w(e,"top_level"),"top_level"),p=w(e,"under"),v=Y(w(e,"hanging"),"hanging"),g=N(w(e,"include"),"include",["activity"]);if(c!==void 0&&l===!0)throw u("parent and top_level=true cannot be combined");return{...n!==void 0?{status:n}:{},...o!==void 0?{lifecycle:o}:{},...r!==void 0?{kind:r}:{},...i!==void 0?{mode:i}:{},...d!==void 0?{profile_id:d}:{},...a!==void 0?{profile_prefix:a}:{},...c!==void 0?{parent:c}:{},...l!==void 0?{top_level:l}:{},...p!==void 0?{under:p}:{},...v!==void 0?{hanging:v}:{},...g!==void 0?{include:g}:{}}}s(mn,"parseListQuery");function pn(e){const t=mn(e);let n=t.status!==void 0?M({status:t.status}):M();if(t.lifecycle!==void 0&&(n=n.filter(i=>i.lifecycle===t.lifecycle)),t.kind!==void 0&&(n=n.filter(i=>i.kind===t.kind)),t.mode!==void 0&&(n=n.filter(i=>i.mode===t.mode)),t.profile_id!==void 0&&(n=n.filter(i=>i.profile_id===t.profile_id)),t.profile_prefix!==void 0&&(n=n.filter(i=>i.profile_id?.startsWith(t.profile_prefix))),t.parent!==void 0&&(n=n.filter(i=>i.parent===t.parent)),t.top_level===!0&&(n=n.filter(i=>i.parent===null)),t.under!==void 0){const i=new Set(fe(t.under));n=n.filter(d=>i.has(d.node_id))}t.hanging===!0&&(n=n.filter(i=>i.parent!==null&&b(i.parent)===null));const o=t.include==="activity"?he(n.map(i=>i.node_id)):null;return{status:200,body:n.map(i=>{const d=tn(i);if(o!==null){const a=Ue(i.node_id);d.activity={latest_report:a[0]??null,final_report:i.final_report===null?null:a.find(c=>ne(c.path)===i.final_report)??null,pending_human_count:o[i.node_id]??0}}return d})}}s(pn,"handleList");function hn(e){const t=e.params.id;return f(t),{status:200,body:y(t)}}s(hn,"handleDetail");async function wn(e){const t=e.params.id;f(t);const n=await be(t);return{status:200,body:{node_id:t,snapshot:{messages:n.snapshot.messages,...n.snapshot.messageIds===void 0?{}:{messageIds:n.snapshot.messageIds},messageVisibility:n.snapshot.messageVisibility,turnVisibility:n.snapshot.turnVisibility,stats:n.snapshot.stats,state:n.snapshot.state,display:n.snapshot.display,...n.snapshot.queued===void 0?{}:{queued:n.snapshot.queued},...n.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:n.snapshot.toolGroupSummaries},...n.snapshot.workingActivity===void 0?{}:{workingActivity:n.snapshot.workingActivity}},commands:n.commands.map(r=>({name:r.name,description:r.description,source:r.source})),captured_at:T()}}}s(wn,"handleSnapshot");async function yn(e){const t=e.params.id,n=ke(t);if(n===null)throw R(`unknown node: ${t}`,{received:t});return{status:200,body:n}}s(yn,"handleSubject");function gn(e){for(const[i]of e.query)if(i!=="cursor"&&i!=="limit")throw u(`unknown messages query parameter: ${i}`);const t=e.query.getAll("cursor"),n=e.query.getAll("limit");if(t.length>1)throw u("cursor must appear at most once");if(n.length>1)throw u("limit must appear at most once");if(n.length===0)return t.length===0?{}:{cursor:t[0]};const o=n[0],r=Number(o);if(!Number.isSafeInteger(r)||o==="")throw u("limit must be an integer from 1 through 500");return t.length===0?{limit:r}:{cursor:t[0],limit:r}}s(gn,"parseMessagesQuery");async function _n(e){const t=e.params.id,n=await ge(t,gn(e));return{status:200,body:{node_id:t,messages:n.messages,...n.messageIds===void 0?{}:{message_ids:n.messageIds},message_visibility:n.messageVisibility,next_cursor:n.nextCursor,captured_at:T()}}}s(_n,"handleMessages");function bn(e){const t=e.params.id;f(t);const n=_e(t);return{status:200,body:{node_id:t,session_file:n.sessionFile,session_jsonl:n.sessionJsonl,system_prompt:n.systemPrompt,captured_at:T()}}}s(bn,"handleSession");async function vn(e){const t=e.params.id;return f(t),{status:200,body:{node_id:t,markdown:await ve(t)}}}s(vn,"handleTranscript");function kn(e){const t=e.params.id;f(t);const n=[{node_id:t,label:b(t)?.name??t,dir:P(t),self:!0,files:J(t)}];for(const o of E(t))n.push({node_id:o.node_id,label:b(o.node_id)?.name??o.node_id,dir:P(o.node_id),self:!1,files:J(o.node_id)});return{status:200,body:{node_id:t,roots:n}}}s(kn,"handleContext");function Sn(e){const t=e.params.id;f(t);const n=e.query.get("type"),o=ye(t,n!==null?[n]:void 0).map(i=>({ref:i.ref,source:i.source==="report"&&i.reportKind!==void 0?`report:${i.reportKind}`:i.source,ts:i.ts,title:i.title}));return{status:200,body:{node_id:t,artifacts:o}}}s(Sn,"handleArtifacts");async function On(e){const t=await se(e.params.id,e.ceiling===null?void 0:[...e.ceiling]);return{status:201,body:y(t.node.node_id)}}s(On,"handleFork");async function Nn(e){const t=e.params.id;f(t);const n=e.body,o=n?.resume??!0,r=n?.reopen??!1;Ae(t,r);const i=!o&&n?.cron_id!==void 0?Xe(n.cron_id):null,d=await de(t,{resume:o,capacity:"refuse",...i!==null?{wakeReason:Ze(i,"schedule_revive")}:{}}),a=b(t)?.status??"active";return{status:200,body:on(t,d,a)}}s(Nn,"handleRevive");async function Tn(e){const t=e.params.id;return{status:200,body:{newNodeId:(await $e(t))?.newNodeId??null}}}s(Tn,"handleRelaunchRoot");function $n(e){const t=e.params.id;f(t);const n=e.body;if(n?.caller_pid!==void 0&&(!Number.isInteger(n.caller_pid)||n.caller_pid<=0))throw u("caller_pid must be a positive integer when provided");const o=qe(),r=re(t,{rootEvent:n?.finish===!0?"finish":"cancel",callerPid:n?.caller_pid,...o===null?{}:{registerDetached:o.registerDetached}});return{status:200,body:nn(r)}}s($n,"handleClose");async function An(e){const t=e.params.id;f(t);const n=await Te(t);return{status:200,body:{recycled:n.recycled,finalized:n.finalized,new_root:n.newRoot,delivered:n.delivered}}}s(An,"handleRecycle");async function Pn(e){const t=e.params.id;return f(t),await L(t,{lifecycle:"terminal"}),{status:200,body:y(t)}}s(Pn,"handleDemote");async function Rn(e,t={}){const n=e.params.id,o=f(n),r=e.body??{};r.model!==void 0&&await K(o,{kind:r.kind??o.kind,mode:"orchestrator",lifecycle:r.resident===!0?"resident":o.lifecycle,model:r.model},t.modelRegistry);const i=await Oe(n,{...r.kind!==void 0?{kind:r.kind}:{},...r.resident===!0?{resident:!0}:{},...r.model!==void 0?{model:r.model}:{}}),d=x(i.meta,C(n));return d.roadmap_written=i.roadmapWritten,d.roadmap_path=i.roadmapPath,d.goal_path=i.goalPath,{status:200,body:d}}s(Rn,"handlePromote");async function xn(e,t={}){const n=e.params.id,o=f(n),r=e.body??{};r.model!==void 0&&await K(o,{kind:r.kind??o.kind,mode:r.promote===!0?"orchestrator":o.mode,lifecycle:o.lifecycle,model:r.model},t.modelRegistry);const i=r.note??"Refresh: continue against your roadmap or goal.";Pe(n,i);const d=await Ne(n,{...r.promote===!0?{promote:!0}:{},...r.kind!==void 0?{kind:r.kind}:{},...r.model!==void 0?{model:r.model}:{}});return{status:200,body:x(d.meta,C(n))}}s(xn,"handleYield");function Cn(e){const t=e.params.id;f(t);const n=e.body;if(n===void 0||typeof n.controller!="string"||n.controller.trim()==="")throw u("a wait requires a controller node id");const o=b(n.controller);if(o===null)throw R(`unknown controller: ${n.controller}`,{received:n.controller});if(o.status!=="active"&&o.status!=="idle")throw new h(422,"unprocessable",`controller ${n.controller} is ${o.status}`);return ue(t,n.controller),{status:200,body:y(t)}}s(Cn,"handleWait");async function Dn(){const e=await Se();return{status:200,body:{revived:[...e.revived],failed:[...e.failed],frozen:[...e.frozen]}}}s(Dn,"handleReviveAll");async function In(e,t={}){const n=e.params.id,o=e.body;let r;if(o===void 0)r={};else if(typeof o=="object"&&o!==null&&!Array.isArray(o))r=o;else throw new m({error:"cwd_invalid",message:"cwd repair requires a non-null object with a non-empty cwd string",received:o,field:"cwd",next:"Send a config patch with a non-empty absolute cwd string."});if(Object.prototype.hasOwnProperty.call(r,"cwd")){const d=r.cwd;if(typeof d!="string"||d==="")throw new m({error:"cwd_invalid",message:"cwd must be a non-empty string",received:d,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(r).some(l=>l!=="cwd"&&r[l]!==void 0))throw new m({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:r,field:"cwd",next:"Send cwd as the only config field."});const a=f(n);if(We().has(n)){const l=`${n} cannot repair its cwd while its broker is live`;throw new h(409,"cwd_node_live",l,{error:"cwd_node_live",message:l,received:d,field:"cwd",next:"Let the node become dormant, then retry the cwd repair."})}if(a.fork_from!=null)throw new m({error:"cwd_node_forked",message:`${n} is a fork and cannot repair its cwd; recorded cwd: ${a.cwd}`,received:d,field:"cwd",next:`Restore ${a.cwd}, then revive the fork normally.`});if(a.managed_worktree?.state==="open")throw new m({error:"cwd_node_managed_worktree_open",message:`${n} owns an open managed worktree and cannot repair its cwd`,received:d,field:"cwd",next:"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon flow."});if(D(a.cwd))throw new m({error:"cwd_still_present",message:`${n} recorded cwd still exists: ${a.cwd}; cwd repair is not a relocation command`,received:d,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!te(d))throw new m({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${d}`,received:d,field:"cwd",next:"Send an absolute path."});const c=I(d);if(!D(c))throw new m({error:"cwd_missing",message:`cwd does not exist: ${c}`,received:d,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!ee(c).isDirectory())throw new m({error:"cwd_not_a_directory",message:`cwd is not a directory: ${c}`,received:d,field:"cwd",next:"Send an existing absolute directory."})}catch(l){throw l instanceof m?l:new m({error:"cwd_missing",message:`cwd does not exist: ${c}`,received:d,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return me(()=>{A(n,{cwd:c}),pe(n)}),{status:200,body:y(n)}}let i=f(n);if(r.scopes!==void 0){const d=W(r.scopes);if(!d.every(a=>B(i.scopes,a)))throw new m({error:"unknown_scope",message:"scopes may only narrow the node's current list",received:d,field:"scopes",next:"Send only scopes the node already holds."});i=A(n,{scopes:d})}if(r.situational_context!==void 0&&oe(n,ie(r.situational_context)),r.model!==void 0){const d=Me(r.model),a=(await j(i.cwd,i.profile_id??null)).modelLadders,c=Ee(r.model,a);await $({kind:"concrete",spec:c},{cwd:i.cwd,profileId:i.profile_id??null},t.modelRegistry);const l=s(()=>{if(!c.includes("/"))throw u(`model must resolve to a provider/id spec: ${r.model}`);Ge(n,c,d)},"persistDormant");if(Fe(i))try{await ze(n,c,d)}catch(p){if(!(p instanceof je))throw p;l()}else l();i=f(n)}if(r.kind!==void 0||r.mode!==void 0||r.lifecycle!==void 0){r.kind!==void 0&&await H(r.kind);const d=r.kind??i.kind,a=r.mode??i.mode,c=r.lifecycle??i.lifecycle;let l;a==="orchestrator"&&!xe(n)&&(l=s(()=>{const p=Re(n);Ce(n,p!==null&&p.trim()!==""?{goal:p.trim()}:{})},"beforePersist")),i=await L(n,{...r.kind!==void 0?{kind:d}:{},...r.mode!==void 0?{mode:a}:{},...r.lifecycle!==void 0?{lifecycle:c}:{}},l)}return r.name!==void 0&&(i=A(n,{name:r.name}),i.window&&De(i.window,Qe(i))),{status:200,body:y(n)}}s(In,"handleConfig");async function H(e){const t=Object.keys((await j(process.cwd(),Z()||null)).kinds);if(!t.includes(e))throw u(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}s(H,"assertKindServer");const Rt=[{method:"POST",pattern:"/v1/nodes",scope:"act",handler:fn},{method:"GET",pattern:"/v1/nodes",handler:pn},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"act",handler:s(()=>Dn(),"handler")},{method:"GET",pattern:"/v1/nodes/:id",handler:hn},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:wn},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:yn},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:_n},{method:"GET",pattern:"/v1/nodes/:id/session",handler:bn},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:vn},{method:"GET",pattern:"/v1/nodes/:id/context",handler:kn},{method:"GET",pattern:"/v1/nodes/:id/artifacts",handler:Sn},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"act",handler:On},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"act",handler:Nn},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"act",handler:Tn},{method:"POST",pattern:"/v1/nodes/:id/close",handler:$n},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"act",handler:An},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"act",handler:Pn},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"act",handler:Rn},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"act",handler:xn},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:Cn},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:In}];export{In as handleConfig,fn as handleCreate,On as handleFork,pn as handleList,Rn as handlePromote,xn as handleYield,Rt as nodeRoutes,Dt as resolveCreateKind};
|
|
1
|
+
var oe=Object.defineProperty;var d=(e,t)=>oe(e,"name",{value:t,configurable:!0});import{envProfileId as re}from"../../../shared/env.js";import{existsSync as E,statSync as ie}from"node:fs";import{basename as de,isAbsolute as se,resolve as M}from"node:path";import{appendSituationalContext as ae,formatSituationalProse as le}from"../../../core/runtime/situational-context.js";import{closeNode as ce}from"../../../core/runtime/close.js";import{reviveNode as ue}from"../../../core/runtime/revive.js";import{nowIso as A}from"../../../core/fs-utils.js";import{assertLaunchModelRegistered as R,forkNode as fe,resolveForkSource as me,spawnChildPrepared as pe}from"../../../core/runtime/spawn.js";import{forkSourceNode as he}from"../../../core/runtime/nodes.js";import{childrenOf as we,getNode as O,listNodes as I,subscribersOf as ye,subscriptionsOf as L,setMessageWait as _e,updateNode as $}from"../../../core/canvas/canvas.js";import{subtreeIds as ge}from"../../../core/canvas/nav-model.js";import{withCanvasWrite as ve}from"../../../core/canvas/db.js";import{unbindSession as be}from"../../../core/canvas/sessions.js";import{ticketCountsForNodes as ke}from"../../../core/canvas/attention.js";import{contextDir as G,nodeAgentDir as C,reportsDir as j}from"../../../core/canvas/node-agent-paths.js";import{existsBeneath as Se,isAbsentOrRefused as Oe,isBeneathRefusal as Ne,readdirBeneath as Te,statBeneath as Ae}from"../../../core/spaces/open-beneath.js";import{nodeArtifacts as Re}from"../../../core/canvas/history.js";import{readNodeMessagesPage as $e,readNodeSession as Ce,readNodeSnapshot as Pe,transcriptMarkdown as De}from"../../../core/runtime/node-read.js";import{assembleNodeSubject as xe}from"../../../core/substrate/subject.js";import{reviveAll as Ee}from"../../../core/runtime/revive-all.js";import{promoteAsync as Me,requestYieldAsync as Ie,reshapeNodeAsync as F}from"../../../core/runtime/promote.js";import{recycleNode as Le}from"../../../core/runtime/recycle.js";import{relaunchRoot as Ge}from"../../../core/runtime/reset.js";import{assertReopenGate as je}from"../../../core/runtime/reopen.js";import{writeYieldMessage as Fe,readGoal as ze}from"../../../core/runtime/kickoff.js";import{hasRoadmap as Be,seedRoadmap as Ke}from"../../../core/runtime/roadmap.js";import{renameWindow as Ve}from"../../../core/runtime/placement.js";import{buildLaunchSpecAsync as We,explicitModelIntent as Je,normalizeModel as Ye,readMergedLaunchConfigAsync as z}from"../../../core/runtime/launch.js";import{modelRequestFromConfig as Ue}from"../../../core/model-routes.js";import{persistDormantModel as He,setModelLive as Qe}from"../../../core/runtime/model-swap.js";import{waitForBrokerViewSocket as Xe}from"../../../core/runtime/view-socket.js";import{BrokerUnreachableError as Ze}from"../../../core/runtime/broker-request.js";import{boundFleet as B}from"../../../core/runtime/fleet.js";import{writeOutputSchema as K}from"../../../core/runtime/structured-output.js";import{OUTCOME_PAYLOAD_MAX_BYTES as V}from"../../../core/canvas/types.js";import{HUMAN_ACTION_NAME_PATTERN as qe}from"../../../core/human/action-binding.js";import{resolveHumanAction as en}from"../../../core/human-actions.js";import{parseDurationMs as nn}from"../../../core/wake.js";import{claimWarmNode as tn,refillWarmPool as W,warmPoolEnabled as on}from"../../../core/runtime/warm-pool.js";import{assertLaunchKind as J,resolveLaunchTarget as rn}from"../../../core/runtime/launch-target.js";import{fullName as dn}from"../../../core/canvas/labels.js";import{reportsForNode as sn}from"./reports.js";import{getCron as an}from"../../../core/canvas/crons.js";import{cronWakeOrigin as ln}from"../../../core/runtime/bearings.js";import{boundDaemonControl as cn}from"../../control.js";import{notFound as P,usage as u}from"../../../core/errors.js";import{assertScope as un,validateScopes as Y}from"../../../core/scopes.js";import{scopeAllowed as S}from"../../../shared/env.js";import{toCloseResultDTO as fn,toNodeDetailDTO as D,toNodeSummaryDTO as mn,toReviveResultDTO as pn}from"../map.js";import{ApiError as m}from"../../../api/index.js";import{InputError as p}from"../../../core/io.js";import{canReadNode as hn}from"../router.js";import{activeGrant as wn,terminalGrant as yn}from"../../../core/grants/mirror.js";import{readConfig as _n}from"../../../core/config.js";import{hasConfiguredProviderCredential as gn,NO_PROVIDER_CREDENTIAL_MESSAGE as U}from"../../../core/runtime/provider-credential-gate.js";function f(e){const t=O(e);if(t===null)throw P(`unknown node: ${e}`,{received:e});return t}d(f,"requireMeta");function x(e){return{subscribesTo:L(e),subscribers:ye(e),children:we(e)}}d(x,"edgesFor");function v(e){const t=f(e);return D(t,x(e))}d(v,"detailOf");function vn(e){let t=0;for(const n of[G(e),j(e)])try{t+=Te(C(e),n).length}catch(i){if(!Oe(i))throw i}return t}d(vn,"countFiles");function bn(e){if(typeof e!="object"||e===null)throw u("a node create requires a JSON body");const t=e;if(t.kind!==void 0&&(typeof t.kind!="string"||t.kind.trim()===""))throw u("kind must be a non-empty string when provided");if(t.description!==void 0&&(typeof t.description!="string"||t.description.trim()===""))throw u("description must be a non-empty string when provided");if(t.creator!==void 0&&(typeof t.creator!="string"||t.creator.trim()===""))throw u("creator must be a non-empty node id when provided");t.scopes!==void 0&&Y(t.scopes);const n=t.root_lifecycle;if(n!==void 0&&n!=="resident"&&n!=="terminal")throw u("root_lifecycle must be 'resident' or 'terminal'");return t}d(bn,"parseCreateBody");function kn(e){if(e===void 0)return;const t=nn(e),n=t===null?null:new Date(Date.now()+t);if(t===null||!Number.isFinite(t)||t<=0||n===null||!Number.isFinite(n.getTime()))throw new m(422,"invalid_deadline","`deadline` must be a positive representable duration");return n.toISOString()}d(kn,"parseDeadline");function Sn(e){if(e!==void 0){if(typeof e!="object"||e===null||Array.isArray(e))throw new m(400,"invalid_request","`outcome_delivery` must be an object");if(typeof e.action!="string"||!qe.test(e.action))throw new m(400,"invalid_request","`outcome_delivery.action` must be a declared action name");if(e.payload!==void 0){let t;try{t=JSON.stringify(e.payload)}catch{throw new m(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable")}if(t===void 0)throw new m(400,"invalid_request","`outcome_delivery.payload` must be JSON-serializable");if(Buffer.byteLength(t,"utf8")>V)throw new m(413,"payload_too_large",`serialized payload exceeds ${V} bytes`)}return e}}d(Sn,"parseOutcomeDelivery");function On(e,t){const n=en(e.action,t);if(!("kind"in n))return{actionName:e.action,argv:n.argv,cwd:n.cwd,configOrigin:n.configOrigin,...e.payload===void 0?{}:{payload:e.payload}};throw n.kind==="unknown_action"?new m(422,"unknown_action",`no action named ${e.action} is declared from ${t}`):new m(422,"invalid_action",`${e.action} is declared in ${n.configOrigin} but unusable: ${n.reason}`,{reason:n.reason,configOrigin:n.configOrigin})}d(On,"resolveOutcomeDelivery");function Nn(e,t,n){const i={kind:e.kind,cwd:n,prompt:e.prompt??""};return e.mode!==void 0&&(i.mode=e.mode),e.name!==void 0&&(i.name=e.name),e.description!==void 0&&(i.description=e.description),t!==void 0&&(i.parent=t),e.creator!==void 0&&(i.creator=e.creator),e.scopes!==void 0&&(i.scopes=e.scopes),e.root===!0&&(i.root=!0),e.root_lifecycle!==void 0&&(i.rootLifecycle=e.root_lifecycle),(e.worktree===!0||typeof e.worktree=="string")&&(i.worktree=!0),typeof e.worktree=="string"&&(i.worktreeBase=e.worktree),e.worktree!==void 0&&(i.worktreeCwd=M(e.pin_cwd??e.cwd??n)),e.fork_from!==void 0&&(i.forkFrom=e.fork_from),e.model!==void 0&&(i.model=e.model),e.profile!==void 0&&(i.profile=e.profile),e.situational_context!==void 0&&(i.situationalContext=e.situational_context),e.node_id!==void 0&&(i.nodeId=e.node_id),i}d(Nn,"buildRecipe");function Tn(e,t,n){return!on()||e.prefer_warm!==!0||e.root!==!0||e.parent!=null||e.root_lifecycle==="terminal"||(e.prompt??"")!==""||e.model!==void 0||e.fork_from!==void 0||e.worktree!==void 0||e.node_id!==void 0||e.scopes!==void 0?null:{kind:e.kind,mode:e.mode??"base",cwd:t,profileId:n,model:e.model??null,situationalContext:e.situational_context??null,name:e.name??null,creator:e.creator??null}}d(Tn,"warmRequestFor");import{resolveCreateKind as ro}from"../../../core/runtime/launch-target.js";function H(e){const t=e.modelIntent===void 0?void 0:`${e.modelIntent.family}/${e.modelIntent.strength}`;return Ue(e.model,t,e.modelExact===!0)}d(H,"requestFromLaunch");function An(e,t){if(t===null)return e;if(e.scopes===void 0)return{...e,scopes:[...t]};const n=e.scopes.filter(i=>!S(t,i));if(n.length===0)return e;throw new m(403,"scope_denied",`scopes exceed the bearer token's ceiling: ${n.join(", ")}`,{scopes:n,ceiling:t})}d(An,"withinCeiling");async function Q(e,t,n){const i=(await We(t.kind,t.mode,{lifecycle:t.lifecycle,hasManager:e.parent!==null,model:t.model,modelOverride:!0,cwd:e.cwd,profileId:e.profile_id??null})).launch;await R(H(i),{cwd:e.cwd,profileId:e.profile_id??null},n)}d(Q,"assertNodeModelChangeRegistered");async function Rn(e,t={}){const n=An(bn(e.body),e.ceiling);if(e.principal.class==="broker"){const _=e.principal;if(n.root===!0||n.parent==null||n.prefer_warm===!0)throw new m(403,"other_app_run","a broker may create only a child of its run, without a warm claim");if(n.parent!=null){const g=f(n.parent);if(g.grantee!==_.app||g.run_id!==_.run)throw new m(403,"other_app_run","cannot create outside the calling app run")}if(n.creator!==void 0&&n.creator!==_.node)throw new m(403,"other_app_run","cannot create for another node");if(n.fork_from!==void 0){let g=null;try{g=he(me(n.fork_from))}catch{}if(g?.grantee!==_.app)throw new m(403,"other_app_run","cannot fork another app's conversation")}n.creator=_.node}n.creator!==void 0&&un(f(n.creator),"crtr:act");const i=kn(n.deadline),o=Sn(n.outcome_delivery),r=n.parent??void 0;if(r==null&&n.root!==!0)throw u("a node create requires a parent (or root: true for an independent root)");let s=null;if(n.output_schema!==void 0)try{s=JSON.parse(n.output_schema)}catch{throw u("output_schema must be a JSON schema string")}const{profileId:a,kind:c,cwd:l,launch:h}=await rn(n,{validateKind:ee}),w={...n,kind:c},b=o===void 0?void 0:On(o,l);if(await R(H(h),{cwd:l,profileId:a},t.modelRegistry),!await gn(a))throw new m(412,"no_provider_credential",U,{error:"no_provider_credential",message:U,next:"The person running this runtime logs a provider in with `crtr sys setup`, or stores a provider key on the profile."});let k=null;{const _=Tn(w,l,a);if(_!==null){const N=await tn(_,{...i===void 0?{}:{deadlineAt:i},...b===void 0?{}:{outcomeDelivery:b}},s===null?void 0:te=>K(te,"terminal",s));if(N!==null)return W(_),{status:201,body:v(N)};k=_}const g=Nn(w,r,l);i!==void 0&&(g.deadlineAt=i),b!==void 0&&(g.outcomeDelivery=b),g.readiness=n.root===!0?"await":"launch";const ne=await pe(g,s===null?void 0:N=>K(N,"terminal",s),()=>{k!==null&&W(k)});return{status:201,body:v(ne.node.node_id)}}}d(Rn,"handleCreate");function y(e,t){const n=e.query.getAll(t);if(n.length>1)throw u(`${t} must appear at most once`);return n[0]}d(y,"singleQueryValue");function X(e,t){if(e!==void 0){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw u(`${t} must be true or false`)}}d(X,"optionalBoolean");function T(e,t,n){if(e!==void 0){if(n.includes(e))return e;throw u(`${t} must be one of: ${n.join(", ")}`)}}d(T,"oneOf");function $n(e){const t=new Set(["status","lifecycle","kind","mode","profile_id","profile_prefix","parent","top_level","under","hanging","include"]);for(const[k]of e.query)if(!t.has(k))throw u(`unknown nodes query parameter: ${k}`);const n=T(y(e,"status"),"status",["active","idle","done","dead","canceled"]),i=T(y(e,"lifecycle"),"lifecycle",["terminal","resident"]),o=y(e,"kind"),r=T(y(e,"mode"),"mode",["base","orchestrator"]),s=y(e,"profile_id"),a=y(e,"profile_prefix"),c=y(e,"parent"),l=X(y(e,"top_level"),"top_level"),h=y(e,"under"),w=X(y(e,"hanging"),"hanging"),b=T(y(e,"include"),"include",["activity"]);if(c!==void 0&&l===!0)throw u("parent and top_level=true cannot be combined");return{...n!==void 0?{status:n}:{},...i!==void 0?{lifecycle:i}:{},...o!==void 0?{kind:o}:{},...r!==void 0?{mode:r}:{},...s!==void 0?{profile_id:s}:{},...a!==void 0?{profile_prefix:a}:{},...c!==void 0?{parent:c}:{},...l!==void 0?{top_level:l}:{},...h!==void 0?{under:h}:{},...w!==void 0?{hanging:w}:{},...b!==void 0?{include:b}:{}}}d($n,"parseListQuery");function Cn(e){const t=$n(e);let n=t.status!==void 0?I({status:t.status}):I();if(e.principal.class!=="person"&&(n=n.filter(r=>hn(e.principal,r.grantee??"app:terminal"))),t.lifecycle!==void 0&&(n=n.filter(r=>r.lifecycle===t.lifecycle)),t.kind!==void 0&&(n=n.filter(r=>r.kind===t.kind)),t.mode!==void 0&&(n=n.filter(r=>r.mode===t.mode)),t.profile_id!==void 0&&(n=n.filter(r=>r.profile_id===t.profile_id)),t.profile_prefix!==void 0&&(n=n.filter(r=>r.profile_id?.startsWith(t.profile_prefix))),t.parent!==void 0&&(n=n.filter(r=>r.parent===t.parent)),t.top_level===!0&&(n=n.filter(r=>r.parent===null)),t.under!==void 0){const r=new Set(ge(t.under));n=n.filter(s=>r.has(s.node_id))}t.hanging===!0&&(n=n.filter(r=>r.parent!==null&&O(r.parent)===null));const i=t.include==="activity"?ke(n.map(r=>r.node_id)):null;return{status:200,body:n.map(r=>{const s=mn(r);if(i!==null){const a=sn(r.node_id);s.activity={latest_report:a[0]??null,final_report:r.final_report===null?null:a.find(c=>de(c.path)===r.final_report)??null,pending_human_count:i[r.node_id]??0}}return s})}}d(Cn,"handleList");function Pn(e){const t=e.params.id;return f(t),{status:200,body:v(t)}}d(Pn,"handleDetail");async function Dn(e){const t=e.params.id;f(t);const n=await Pe(t);return{status:200,body:{node_id:t,snapshot:{messages:n.snapshot.messages,...n.snapshot.messageIds===void 0?{}:{messageIds:n.snapshot.messageIds},messageVisibility:n.snapshot.messageVisibility,turnVisibility:n.snapshot.turnVisibility,stats:n.snapshot.stats,state:n.snapshot.state,display:n.snapshot.display,...n.snapshot.queued===void 0?{}:{queued:n.snapshot.queued},...n.snapshot.toolGroupSummaries===void 0?{}:{toolGroupSummaries:n.snapshot.toolGroupSummaries},...n.snapshot.workingActivity===void 0?{}:{workingActivity:n.snapshot.workingActivity}},commands:n.commands.map(o=>({name:o.name,description:o.description,source:o.source})),captured_at:A()}}}d(Dn,"handleSnapshot");async function xn(e){const t=e.params.id,n=xe(t);if(n===null)throw P(`unknown node: ${t}`,{received:t});return{status:200,body:n}}d(xn,"handleSubject");function En(e){for(const[r]of e.query)if(r!=="cursor"&&r!=="limit")throw u(`unknown messages query parameter: ${r}`);const t=e.query.getAll("cursor"),n=e.query.getAll("limit");if(t.length>1)throw u("cursor must appear at most once");if(n.length>1)throw u("limit must appear at most once");if(n.length===0)return t.length===0?{}:{cursor:t[0]};const i=n[0],o=Number(i);if(!Number.isSafeInteger(o)||i==="")throw u("limit must be an integer from 1 through 500");return t.length===0?{limit:o}:{cursor:t[0],limit:o}}d(En,"parseMessagesQuery");async function Mn(e){const t=e.params.id,n=await $e(t,En(e));return{status:200,body:{node_id:t,messages:n.messages,...n.messageIds===void 0?{}:{message_ids:n.messageIds},message_visibility:n.messageVisibility,next_cursor:n.nextCursor,captured_at:A()}}}d(Mn,"handleMessages");function In(e){const t=e.params.id;f(t);const n=Ce(t);return{status:200,body:{node_id:t,session_file:n.sessionFile,session_jsonl:n.sessionJsonl,system_prompt:n.systemPrompt,captured_at:A()}}}d(In,"handleSession");async function Ln(e){const t=e.params.id;return f(t),{status:200,body:{node_id:t,markdown:await De(t)}}}d(Ln,"handleTranscript");function Gn(e){const t=e.params.id;f(t);const n=d((o,r)=>({node_id:o,label:O(o)?.name??o,dir:G(o),reports_dir:j(o),self:r,files:vn(o)}),"root"),i=[n(t,!0),...L(t).map(o=>n(o.node_id,!1))].filter(o=>Z(o.node_id,o.dir)||Z(o.node_id,o.reports_dir));return{status:200,body:{node_id:t,roots:i}}}d(Gn,"handleContext");function Z(e,t){try{return Se(C(e),t)}catch(n){if(Ne(n))return!1;throw n}}d(Z,"hasDir");function jn(e,t){if(t===null)return 0;try{return Ae(C(e),t).size}catch{return 0}}d(jn,"artifactSize");function Fn(e){const t=e.params.id;f(t);const n=e.query.get("type"),i=Re(t,n!==null?[n]:void 0).map(r=>({ref:r.ref,source:r.source==="report"&&r.reportKind!==void 0?`report:${r.reportKind}`:r.source,ts:r.ts,title:r.title,size:jn(t,r.path)}));return{status:200,body:{node_id:t,artifacts:i}}}d(Fn,"handleArtifacts");async function zn(e){const t=f(e.params.id),n=e.principal.class==="broker"?e.principal.scopes:e.ceiling,i=n===null?void 0:t.scopes==null?[...n]:[...new Set([...t.scopes.filter(r=>S(n,r)),...n.filter(r=>S(t.scopes,r))])],o=await fe(t.node_id,i);return{status:201,body:v(o.node.node_id)}}d(zn,"handleFork");async function Bn(e){const t=e.params.id;f(t);const n=e.body,i=n?.resume??!0,o=n?.reopen??!1;je(t,o);const r=!i&&n?.cron_id!==void 0?an(n.cron_id):null,s=await ue(t,{resume:i,capacity:"refuse",...r!==null?{wakeReason:ln(r,"schedule_revive")}:{}}),a=O(t)?.status??"active";return{status:200,body:pn(t,s,a)}}d(Bn,"handleRevive");async function Kn(e){const t=e.params.id;return{status:200,body:{newNodeId:(await Ge(t))?.newNodeId??null}}}d(Kn,"handleRelaunchRoot");function Vn(e){const t=e.params.id;f(t);const n=e.body;if(n?.caller_pid!==void 0&&(!Number.isInteger(n.caller_pid)||n.caller_pid<=0))throw u("caller_pid must be a positive integer when provided");const i=cn(),o=ce(t,{rootEvent:n?.finish===!0?"finish":"cancel",callerPid:n?.caller_pid,...i===null?{}:{registerDetached:i.registerDetached}});return{status:200,body:fn(o)}}d(Vn,"handleClose");async function Wn(e){const t=e.params.id;f(t);const n=await Le(t);return{status:200,body:{recycled:n.recycled,finalized:n.finalized,new_root:n.newRoot,delivered:n.delivered}}}d(Wn,"handleRecycle");async function Jn(e){const t=e.params.id;return f(t),await F(t,{lifecycle:"terminal"}),{status:200,body:v(t)}}d(Jn,"handleDemote");async function Yn(e,t={}){const n=e.params.id,i=f(n),o=e.body??{};o.kind!==void 0&&await J(o.kind,i.cwd,i.profile_id??null),o.model!==void 0&&await Q(i,{kind:o.kind??i.kind,mode:"orchestrator",lifecycle:o.resident===!0?"resident":i.lifecycle,model:o.model},t.modelRegistry);const r=await Me(n,{...o.kind!==void 0?{kind:o.kind}:{},...o.resident===!0?{resident:!0}:{},...o.model!==void 0?{model:o.model}:{}}),s=D(r.meta,x(n));return s.roadmap_written=r.roadmapWritten,s.roadmap_path=r.roadmapPath,s.goal_path=r.goalPath,{status:200,body:s}}d(Yn,"handlePromote");async function Un(e,t={}){const n=e.params.id,i=f(n),o=e.body??{};o.kind!==void 0&&await J(o.kind,i.cwd,i.profile_id??null),o.model!==void 0&&await Q(i,{kind:o.kind??i.kind,mode:o.promote===!0?"orchestrator":i.mode,lifecycle:i.lifecycle,model:o.model},t.modelRegistry);const r=o.note??"Refresh: continue against your roadmap or goal.";Fe(n,r);const s=await Ie(n,{...o.promote===!0?{promote:!0}:{},...o.kind!==void 0?{kind:o.kind}:{},...o.model!==void 0?{model:o.model}:{}});return{status:200,body:D(s.meta,x(n))}}d(Un,"handleYield");function Hn(e){const t=e.params.id;f(t);const n=e.body;if(n===void 0||typeof n.controller!="string"||n.controller.trim()==="")throw u("a wait requires a controller node id");const i=O(n.controller);if(i===null)throw P(`unknown controller: ${n.controller}`,{received:n.controller});if(i.status!=="active"&&i.status!=="idle")throw new m(422,"unprocessable",`controller ${n.controller} is ${i.status}`);return _e(t,n.controller),{status:200,body:v(t)}}d(Hn,"handleWait");async function Qn(){const e=await Ee();return{status:200,body:{revived:[...e.revived],failed:[...e.failed],frozen:[...e.frozen]}}}d(Qn,"handleReviveAll");async function Xn(e,t={}){const n=e.params.id,i=e.body;let o;if(i===void 0)o={};else if(typeof i=="object"&&i!==null&&!Array.isArray(i))o=i;else throw new p({error:"cwd_invalid",message:"cwd repair requires a non-null object with a non-empty cwd string",received:i,field:"cwd",next:"Send a config patch with a non-empty absolute cwd string."});if(Object.prototype.hasOwnProperty.call(o,"cwd")){const s=o.cwd;if(typeof s!="string"||s==="")throw new p({error:"cwd_invalid",message:"cwd must be a non-empty string",received:s,field:"cwd",next:"Send a non-empty absolute cwd string."});if(Object.keys(o).some(l=>l!=="cwd"&&o[l]!==void 0))throw new p({error:"cwd_not_exclusive",message:"cwd repair cannot be combined with another config field",received:o,field:"cwd",next:"Send cwd as the only config field."});const a=f(n);if(B().has(n)){const l=`${n} cannot repair its cwd while its broker is live`;throw new m(409,"cwd_node_live",l,{error:"cwd_node_live",message:l,received:s,field:"cwd",next:"Let the node become dormant, then retry the cwd repair."})}if(a.fork_from!=null)throw new p({error:"cwd_node_forked",message:`${n} is a fork and cannot repair its cwd; recorded cwd: ${a.cwd}`,received:s,field:"cwd",next:`Restore ${a.cwd}, then revive the fork normally.`});if(a.managed_worktree?.state==="open")throw new p({error:"cwd_node_managed_worktree_open",message:`${n} owns an open managed worktree and cannot repair its cwd`,received:s,field:"cwd",next:"Restore or reconcile the recorded checkout, then use the managed-worktree close or abandon flow."});if(E(a.cwd))throw new p({error:"cwd_still_present",message:`${n} recorded cwd still exists: ${a.cwd}; cwd repair is not a relocation command`,received:s,field:"cwd",next:"This command only repairs a node whose recorded cwd is gone."});if(!se(s))throw new p({error:"cwd_not_absolute",message:`cwd must be an absolute path: ${s}`,received:s,field:"cwd",next:"Send an absolute path."});const c=M(s);if(!E(c))throw new p({error:"cwd_missing",message:`cwd does not exist: ${c}`,received:s,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."});try{if(!ie(c).isDirectory())throw new p({error:"cwd_not_a_directory",message:`cwd is not a directory: ${c}`,received:s,field:"cwd",next:"Send an existing absolute directory."})}catch(l){throw l instanceof p?l:new p({error:"cwd_missing",message:`cwd does not exist: ${c}`,received:s,field:"cwd",next:"Create the replacement directory or send an existing absolute directory."})}return ve(()=>{$(n,{cwd:c}),be(n)}),{status:200,body:v(n)}}let r=f(n);if(o.scopes!==void 0){const s=Y(o.scopes),a=r.grantee==="app:terminal"?yn():r.grant_id?wn(r.grant_id):null,c=r.grantee==="app:terminal"&&!_n("user").runtime?.issuer;if(!s.every(l=>S(r.scopes,l)&&(a?S(a.resolved,l):c)))throw new p({error:"unknown_scope",message:"scopes may only narrow the node's current effective set",received:s,field:"scopes",next:"Send only scopes the node currently holds."});if(s.includes("crtr:act")&&!S(s,"crtr:llm"))throw new m(400,"invalid_scope","crtr:act requires crtr:llm");r=$(n,{scopes:s})}if(o.situational_context!==void 0&&ae(n,le(o.situational_context)),o.model!==void 0){const s=(await z(r.cwd,r.profile_id??null)).modelLadders,a=Je(o.model,s),c=Ye(o.model,s);await R({kind:"concrete",spec:c},{cwd:r.cwd,profileId:r.profile_id??null},t.modelRegistry);const l=B();let h=!1;if(l.isClaimed(n)&&await Xe(n,l.get(n)?.handle.exited)&&(h=await Qe(n,c,a).then(()=>!0,w=>{if(w instanceof Ze)return!1;throw w})),!h){if(l.isClaimed(n)){const w=`${n}'s broker did not accept the model switch; the model was not changed`;throw new m(409,"broker_not_ready",w,{error:"broker_not_ready",message:w,received:o.model,field:"model",next:"Check the node with `crtr node show`, then retry the model change."})}if(!c.includes("/"))throw u(`model must resolve to a provider/id spec: ${o.model}`);He(n,c,a)}r=f(n)}if(o.kind!==void 0||o.mode!==void 0||o.lifecycle!==void 0){o.kind!==void 0&&await ee(o.kind);const s=o.kind??r.kind,a=o.mode??r.mode,c=o.lifecycle??r.lifecycle;let l;a==="orchestrator"&&!Be(n)&&(l=d(()=>{const h=ze(n);Ke(n,h!==null&&h.trim()!==""?{goal:h.trim()}:{})},"beforePersist")),r=await F(n,{...o.kind!==void 0?{kind:s}:{},...o.mode!==void 0?{mode:a}:{},...o.lifecycle!==void 0?{lifecycle:c}:{}},l)}return o.name!==void 0&&(r=$(n,{name:o.name}),r.window&&Ve(r.window,dn(r))),{status:200,body:v(n)}}d(Xn,"handleConfig");async function q(){return(await z(process.cwd(),re()||null)).kinds}d(q,"daemonKinds");async function ee(e){const t=Object.keys(await q());if(!t.includes(e))throw u(`unknown kind: ${e}`,{received:e,next:`Valid kinds: ${t.sort().join(", ")}.`})}d(ee,"assertKindServer");async function Zn(){const e=await q();return{status:200,body:{kinds:Object.keys(e).sort().map(n=>({kind:n,when_to_use:e[n]?.whenToUse??null,available_to:e[n]?.availableTo??null}))}}}d(Zn,"handleListKinds");const no=[{method:"POST",pattern:"/v1/nodes",scope:"crtr:act",handler:Rn},{method:"GET",pattern:"/v1/nodes",handler:Cn},{method:"GET",pattern:"/v1/kinds",handler:d(()=>Zn(),"handler")},{method:"POST",pattern:"/v1/nodes/revive-all",scope:"crtr:act",handler:d(()=>Qn(),"handler")},{method:"GET",pattern:"/v1/nodes/:id",handler:Pn},{method:"GET",pattern:"/v1/nodes/:id/snapshot",handler:Dn},{method:"GET",pattern:"/v1/nodes/:id/subject",handler:xn},{method:"GET",pattern:"/v1/nodes/:id/messages",handler:Mn},{method:"GET",pattern:"/v1/nodes/:id/session",handler:In},{method:"GET",pattern:"/v1/nodes/:id/transcript",handler:Ln},{method:"GET",pattern:"/v1/nodes/:id/context",handler:Gn},{method:"GET",pattern:"/v1/nodes/:id/artifacts",handler:Fn},{method:"POST",pattern:"/v1/nodes/:id/fork",scope:"crtr:act",handler:zn},{method:"POST",pattern:"/v1/nodes/:id/revive",scope:"crtr:act",handler:Bn},{method:"POST",pattern:"/v1/nodes/:id/relaunch-root",scope:"crtr:act",handler:Kn},{method:"POST",pattern:"/v1/nodes/:id/close",handler:Vn},{method:"POST",pattern:"/v1/nodes/:id/recycle",scope:"crtr:act",handler:Wn},{method:"POST",pattern:"/v1/nodes/:id/demote",scope:"crtr:act",handler:Jn},{method:"POST",pattern:"/v1/nodes/:id/promote",scope:"crtr:act",handler:Yn},{method:"POST",pattern:"/v1/nodes/:id/yield",scope:"crtr:act",handler:Un},{method:"POST",pattern:"/v1/nodes/:id/wait",handler:Hn},{method:"PATCH",pattern:"/v1/nodes/:id/config",handler:Xn}];export{Xn as handleConfig,Rn as handleCreate,zn as handleFork,Cn as handleList,Yn as handlePromote,Un as handleYield,no as nodeRoutes,ro as resolveCreateKind};
|
|
@@ -1,2 +1,5 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { listProfiles } from '../../../core/profiles/manifest.js';
|
|
2
|
+
import { type RequestContext, type RouteTable } from '../router.js';
|
|
3
|
+
/** One visible profile by exact id or unique name; a miss or an invisible profile is 404. */
|
|
4
|
+
export declare function requireUsableProfile(ctx: RequestContext, name: string): ReturnType<typeof listProfiles>[number];
|
|
2
5
|
export declare const profileRoutes: RouteTable;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var
|
|
1
|
+
var A=Object.defineProperty;var i=(r,e)=>A(r,"name",{value:e,configurable:!0});import{assertLaunchKind as m}from"../../../core/runtime/launch-target.js";import{listNodesByProfile as v,shiftProfileNodeDeadlines as T}from"../../../core/canvas/canvas.js";import{shiftAutoBackgroundBashDeadlines as k}from"../../../core/bash-jobs.js";import{contextDir as q}from"../../../core/canvas/node-agent-paths.js";import{boundFleet as D}from"../../../core/runtime/fleet.js";import{recordedPidLiveness as N}from"../../../core/canvas/pid.js";import{usage as l}from"../../../core/errors.js";import{ApiError as p}from"../../../api/errors.js";import{scopeAllowed as y}from"../../../core/scopes.js";import{validateEnvVarName as O}from"../../../core/env-name.js";import{listProfileEnvNames as L,removeProfileEnvVar as $,setProfileEnvVar as M}from"../../../core/profiles/env-store.js";import{addProfileProject as R,assertProfileProjects as c,createProfile as _,ensureRootProfile as S,listProfiles as u,loadProfileManifest as h,pauseProfile as F,removeProfileProject as V,renameProfile as G,resumeProfile as K,setProfileDefaultKind as U,updateProfileMetadata as B}from"../../../core/profiles/manifest.js";import{requestProfileDeletion as C}from"../../profile-delete.js";import{toProfileDTO as d}from"../map.js";import{resolvedScopes as H}from"../router.js";const b="root";function P(r){return r.principal.class==="person"?"app:terminal":r.principal.app}i(P,"callerApp");function w(r,e,t=null){if(u().some(n=>n.manifest.name===e&&n.profileId!==t&&(n.manifest.grantee??"app:terminal")===r))throw new p(400,"invalid_request",`${r} already has a profile named ${e}`)}i(w,"assertNameFree");function f(r,e){const t=j(r,e),n=t.manifest.grantee??"app:terminal";if(r.principal.class!=="person"&&n!==r.principal.app)throw new p(403,"permission_error",`profile ${t.profileId} belongs to ${n}; only that app changes it`);return t}i(f,"requireOwnProfile");async function z(r){const e=r.body??{};if(typeof e.name!="string"||e.name.trim()==="")throw l("a profile name is required",{field:"name"});e.projects!==void 0&&c(e.projects);const t=P(r),n=e.name.trim();w(t,n),e.default_kind!==void 0&&await m(e.default_kind,process.cwd(),null);const o=_(n,e.projects??[],{defaultKind:e.default_kind,metadata:e.metadata,grantee:t});return{status:201,body:d(o)}}i(z,"handleCreate");async function J(r){const{profileId:e,manifest:t}=f(r,r.params.name),n=r.body??{};return n.name!==void 0&&w(t.grantee??"app:terminal",n.name.trim(),e),n.default_kind!==void 0&&await m(n.default_kind,process.cwd(),e),n.add_project!==void 0&&c([n.add_project]),n.name!==void 0&&G(e,n.name),n.default_kind!==void 0&&U(e,n.default_kind),n.add_project!==void 0&&R(e,n.add_project.path,{memory:n.add_project.memory}),n.remove_project!==void 0&&V(e,n.remove_project),{status:200,body:d(h(e))}}i(J,"handleUpdate");function Q(r){const{profileId:e}=f(r,r.params.name);return{status:200,body:{profile_id:e,names:L(e)}}}i(Q,"handleEnvList");function g(r){const e=r.params.var,t=O(e);if(!t.isValid)throw l(`invalid env var name: ${t.errors.join("; ")}`,{field:"name",received:e});return e}i(g,"requireEnvVarName");function W(r){const{profileId:e}=f(r,r.params.name),t=g(r),{value:n}=r.body??{};if(typeof n!="string"||n==="")throw l("a non-empty env value is required",{field:"value"});return{status:200,body:{profile_id:e,changed:M(e,t,n)}}}i(W,"handleEnvSet");function X(r){const{profileId:e}=f(r,r.params.name),t=g(r);return{status:200,body:{profile_id:e,changed:$(e,t)}}}i(X,"handleEnvRemove");async function Y(r){const e=r.params.name,t=r.body??{};t.projects!==void 0&&c(t.projects);const n=P(r);if(e===b&&n==="app:terminal")return{status:200,body:d(S())};if(e===b)throw new p(403,"permission_error","root belongs to the terminal app");const o=u().find(s=>s.manifest.name===e&&(s.manifest.grantee??"app:terminal")===n);if(o!==void 0)return{status:200,body:d(o)};t.default_kind!==void 0&&await m(t.default_kind,process.cwd(),null);const a=_(e,t.projects??[],{defaultKind:t.default_kind,metadata:t.metadata,grantee:n});return{status:200,body:d(a)}}i(Y,"handleEnsure");function Z(r){const e=f(r,r.params.name),t=r.body??{};if(typeof t!="object"||t===null||Array.isArray(t))throw l("profile metadata body must be an object",{field:"body"});const n=t,o=n.unset===void 0?[]:n.unset;if(!Array.isArray(o)||o.some(I=>typeof I!="string"))throw l("profile metadata `unset` must be an array of strings",{field:"unset"});const a=n.set===void 0?{}:n.set,s=B(e.profileId,a,o);return{status:200,body:d(s)}}i(Z,"handleSetMetadata");function x(r){const e=h(r.params.name),t=F(e.profileId),n=v(e.profileId).filter(a=>a.status==="active"||a.status==="idle");if(n.length===0)return{status:200,body:{profile_id:e.profileId,paused_at:t.manifest.paused_at}};const o=D();for(const a of n){const s=o.get(a.node_id);if(s!==void 0){o.interruptForProfilePause(a.node_id,s.pid);continue}a.pi_pid!=null&&N(a.pi_pid,a.pi_pid_identity)==="alive"&&o.interruptForProfilePause(a.node_id,a.pi_pid)}return{status:200,body:{profile_id:e.profileId,paused_at:t.manifest.paused_at}}}i(x,"handlePause");function ee(r){const e=h(r.params.name),t=K(e.profileId);if(t.pausedAt!==null){const n=Date.parse(t.pausedAt);if(!Number.isNaN(n)){const o=Math.max(0,Date.now()-n);T(e.profileId,o);for(const a of v(e.profileId))a.status!=="dead"&&k(q(a.node_id),o)}}return{status:200,body:{profile_id:e.profileId,paused_at:t.manifest.paused_at}}}i(ee,"handleResume");function E(r){const e=r.principal;if(e.class==="person")return u();const t=H(e);return u().filter(({profileId:n,manifest:o})=>{const a=o.grantee??"app:terminal";if(a===e.app)return!0;const s=`crtr:memory:rw:${a}:profile:${n}`;return y(t,s)&&(e.class!=="broker"||y(e.scopes,s))})}i(E,"visibleProfiles");function j(r,e){const t=E(r),n=t.find(({profileId:a})=>a===e),o=n?[n]:t.filter(({manifest:a})=>a.name===e);if(o.length===0)throw new p(404,"not_found","profile not found");if(o.length>1)throw new p(400,"ambiguous","profile name matches multiple visible profiles; use an exact id");return o[0]}i(j,"requireUsableProfile");function re(r){return{status:200,body:E(r).map(d)}}i(re,"handleList");function ne(r){return{status:200,body:d(j(r,r.params.name))}}i(ne,"handleGet");async function te(r){return C(f(r,r.params.name).profileId,r.body)}i(te,"handleDelete");const Pe=[{method:"PUT",pattern:"/v1/profiles/:name",handler:Y},{method:"POST",pattern:"/v1/profiles/:name/pause",ownerOnly:!0,handler:x},{method:"POST",pattern:"/v1/profiles/:name/resume",ownerOnly:!0,handler:ee},{method:"PATCH",pattern:"/v1/profiles/:name/metadata",handler:Z},{method:"POST",pattern:"/v1/profiles",handler:z},{method:"PATCH",pattern:"/v1/profiles/:name",handler:J},{method:"GET",pattern:"/v1/profiles/:name/env",handler:Q},{method:"PUT",pattern:"/v1/profiles/:name/env/:var",handler:W},{method:"DELETE",pattern:"/v1/profiles/:name/env/:var",handler:X},{method:"DELETE",pattern:"/v1/profiles/:name",handler:te},{method:"GET",pattern:"/v1/profiles",handler:re},{method:"GET",pattern:"/v1/profiles/:name",handler:ne}];export{Pe as profileRoutes,j as requireUsableProfile};
|