@oyasmi/pipiclaw 0.9.4-beta.2 → 0.9.5-beta.2
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/README.en.md +28 -22
- package/README.md +27 -21
- package/dist/agent/builtin-commands.d.ts +7 -2
- package/dist/agent/builtin-commands.js +19 -23
- package/dist/agent/channel-runner.d.ts +13 -13
- package/dist/agent/channel-runner.js +93 -76
- package/dist/agent/maintenance-context.d.ts +6 -5
- package/dist/agent/maintenance-context.js +15 -15
- package/dist/agent/prompt/manifest.js +1 -1
- package/dist/agent/prompt/resources.d.ts +1 -1
- package/dist/agent/prompt/resources.js +1 -1
- package/dist/agent/prompt/sections.js +4 -4
- package/dist/agent/runner-factory.d.ts +6 -6
- package/dist/agent/runner-factory.js +6 -7
- package/dist/agent/session/compaction-input.d.ts +6 -0
- package/dist/agent/session/compaction-input.js +75 -0
- package/dist/agent/session/compaction-snapshot.d.ts +30 -0
- package/dist/agent/session/compaction-snapshot.js +154 -0
- package/dist/agent/session/compaction-summary.d.ts +39 -0
- package/dist/agent/session/compaction-summary.js +158 -0
- package/dist/agent/session/compaction.d.ts +35 -0
- package/dist/agent/session/compaction.js +294 -0
- package/dist/agent/session/context-input.d.ts +15 -0
- package/dist/agent/session/context-input.js +82 -0
- package/dist/agent/session/context-snapshot.d.ts +11 -0
- package/dist/agent/session/context-snapshot.js +72 -0
- package/dist/agent/session/event-guards.d.ts +2 -0
- package/dist/agent/session/event-guards.js +4 -0
- package/dist/agent/session/request-tools.d.ts +3 -0
- package/dist/agent/session/request-tools.js +20 -0
- package/dist/agent/session/session-adapter.d.ts +2 -1
- package/dist/agent/session/session-adapter.js +6 -3
- package/dist/agent/session/session-events.d.ts +5 -4
- package/dist/agent/session/session-events.js +46 -59
- package/dist/agent/session/session-host.d.ts +29 -41
- package/dist/agent/session/session-host.js +86 -69
- package/dist/agent/session/settings-diagnostics.d.ts +5 -0
- package/dist/agent/session/settings-diagnostics.js +21 -0
- package/dist/agent/status-render.js +5 -2
- package/dist/{runtime → agent}/stop-watchdog.d.ts +3 -1
- package/dist/{runtime → agent}/stop-watchdog.js +7 -3
- package/dist/agent/turn/progress-formatter.d.ts +1 -3
- package/dist/agent/turn/progress-formatter.js +3 -22
- package/dist/agent/turn/task-digest.d.ts +4 -2
- package/dist/agent/turn/task-digest.js +7 -4
- package/dist/agent/turn/turn-context.d.ts +11 -7
- package/dist/agent/turn/turn-context.js +26 -18
- package/dist/agent/turn/turn-finish.d.ts +17 -5
- package/dist/agent/turn/turn-finish.js +51 -77
- package/dist/agent/turn/turn-input.d.ts +2 -2
- package/dist/agent/turn/turn-input.js +4 -3
- package/dist/agent/turn/turn-output.d.ts +19 -0
- package/dist/agent/turn/turn-output.js +41 -0
- package/dist/agent/turn/turn-pipeline.d.ts +11 -8
- package/dist/agent/turn/turn-pipeline.js +54 -55
- package/dist/agent/turn/turn-prompt.d.ts +1 -1
- package/dist/agent/turn/turn-recovery.d.ts +11 -10
- package/dist/agent/turn/turn-recovery.js +14 -29
- package/dist/agent/types.d.ts +31 -12
- package/dist/agent/types.js +2 -1
- package/dist/app/auth-command.js +1 -1
- package/dist/app/home.js +31 -15
- package/dist/channel/active-session-store.d.ts +14 -12
- package/dist/channel/active-session-store.js +29 -25
- package/dist/channel/attachments.d.ts +25 -0
- package/dist/channel/attachments.js +56 -0
- package/dist/channel/channel-context.d.ts +87 -96
- package/dist/channel/channel-context.js +1 -66
- package/dist/channel/channel-event.d.ts +51 -41
- package/dist/channel/channel-event.js +6 -11
- package/dist/channel/channel-id.d.ts +22 -0
- package/dist/channel/channel-id.js +13 -0
- package/dist/channel/channel-index.d.ts +17 -34
- package/dist/channel/channel-index.js +41 -80
- package/dist/channel/config.d.ts +10 -0
- package/dist/channel/config.js +55 -0
- package/dist/channel/ingress.d.ts +101 -0
- package/dist/channel/ingress.js +5 -0
- package/dist/channel/store.d.ts +13 -15
- package/dist/channel/store.js +21 -25
- package/dist/channel/transport.d.ts +99 -0
- package/dist/channel/turn-context.d.ts +23 -0
- package/dist/channel/turn-context.js +1 -0
- package/dist/commands/catalog.d.ts +4 -7
- package/dist/commands/catalog.js +24 -31
- package/dist/commands/router.d.ts +23 -12
- package/dist/commands/router.js +22 -24
- package/dist/config/settings.d.ts +5 -4
- package/dist/desk/bindings.d.ts +6 -0
- package/dist/desk/bindings.js +105 -0
- package/dist/desk/commands.d.ts +81 -0
- package/dist/desk/commands.js +145 -0
- package/dist/desk/default.d.ts +4 -0
- package/dist/desk/default.js +11 -0
- package/dist/desk/paths.d.ts +41 -0
- package/dist/desk/paths.js +81 -0
- package/dist/desk/registry.d.ts +17 -0
- package/dist/desk/registry.js +191 -0
- package/dist/desk/startup-error.d.ts +4 -0
- package/dist/desk/startup-error.js +7 -0
- package/dist/desk/types.d.ts +72 -0
- package/dist/desk/types.js +7 -0
- package/dist/dingtalk/bot.d.ts +18 -35
- package/dist/dingtalk/bot.js +21 -204
- package/dist/dingtalk/channel-ids.d.ts +15 -0
- package/dist/dingtalk/channel-ids.js +39 -0
- package/dist/dingtalk/config.d.ts +6 -3
- package/dist/dingtalk/config.js +13 -25
- package/dist/dingtalk/connection.d.ts +1 -0
- package/dist/dingtalk/connection.js +5 -4
- package/dist/dingtalk/conversation-meta.d.ts +10 -5
- package/dist/dingtalk/conversation-meta.js +72 -50
- package/dist/dingtalk/delivery.d.ts +30 -14
- package/dist/dingtalk/delivery.js +189 -62
- package/dist/dingtalk/inbound-media.d.ts +2 -18
- package/dist/dingtalk/inbound-media.js +0 -53
- package/dist/dingtalk/inbound.d.ts +10 -11
- package/dist/dingtalk/inbound.js +12 -19
- package/dist/dingtalk/media.d.ts +9 -11
- package/dist/dingtalk/media.js +18 -31
- package/dist/dingtalk/progress.d.ts +8 -0
- package/dist/dingtalk/progress.js +20 -0
- package/dist/dingtalk/response-mode.d.ts +13 -0
- package/dist/dingtalk/response-mode.js +31 -0
- package/dist/dingtalk/transport.d.ts +47 -0
- package/dist/dingtalk/transport.js +71 -0
- package/dist/events/commands.d.ts +7 -2
- package/dist/events/commands.js +40 -22
- package/dist/events/pre-action-error.d.ts +10 -0
- package/dist/events/pre-action-error.js +10 -0
- package/dist/events/types.d.ts +20 -2
- package/dist/events/watcher.d.ts +14 -7
- package/dist/events/watcher.js +49 -26
- package/dist/index.d.ts +4 -2
- package/dist/jobs/completion-wake.d.ts +14 -0
- package/dist/jobs/completion-wake.js +36 -0
- package/dist/jobs/manager.d.ts +27 -22
- package/dist/jobs/manager.js +58 -91
- package/dist/jobs/record.d.ts +2 -0
- package/dist/jobs/record.js +2 -0
- package/dist/log.d.ts +0 -1
- package/dist/log.js +1 -1
- package/dist/main.js +10 -3
- package/dist/memory/boundary-work.d.ts +17 -0
- package/dist/memory/boundary-work.js +162 -0
- package/dist/memory/commands.d.ts +4 -3
- package/dist/memory/commands.js +16 -16
- package/dist/memory/desk-memory-queue.d.ts +18 -0
- package/dist/memory/desk-memory-queue.js +33 -0
- package/dist/memory/index-budget.d.ts +3 -3
- package/dist/memory/index-budget.js +3 -3
- package/dist/memory/journal.d.ts +6 -6
- package/dist/memory/journal.js +14 -14
- package/dist/memory/lifecycle.d.ts +14 -21
- package/dist/memory/lifecycle.js +73 -103
- package/dist/memory/maintenance-state.d.ts +14 -15
- package/dist/memory/maintenance-state.js +43 -42
- package/dist/memory/reflect-job.d.ts +5 -4
- package/dist/memory/reflect-job.js +21 -15
- package/dist/memory/reflect.d.ts +2 -1
- package/dist/memory/reflect.js +13 -12
- package/dist/memory/render.d.ts +1 -1
- package/dist/memory/render.js +2 -2
- package/dist/memory/review-log.d.ts +4 -4
- package/dist/memory/review-log.js +5 -5
- package/dist/memory/scheduler.d.ts +12 -19
- package/dist/memory/scheduler.js +28 -64
- package/dist/memory/session-corpus.d.ts +4 -1
- package/dist/memory/session-corpus.js +70 -29
- package/dist/memory/session-search.d.ts +11 -3
- package/dist/memory/session-search.js +14 -11
- package/dist/memory/sidecar-worker.d.ts +1 -0
- package/dist/memory/sidecar-worker.js +57 -76
- package/dist/memory/source-window.d.ts +0 -6
- package/dist/memory/source-window.js +0 -20
- package/dist/memory/store.d.ts +12 -12
- package/dist/memory/store.js +44 -44
- package/dist/paths.d.ts +2 -0
- package/dist/paths.js +2 -0
- package/dist/playbooks/agent-delegation.md +16 -16
- package/dist/playbooks/background-jobs.md +5 -3
- package/dist/playbooks/event-scheduling.md +7 -5
- package/dist/playbooks/memory-and-learning.md +16 -12
- package/dist/playbooks/outbound-media.md +1 -1
- package/dist/playbooks/runtime-orientation.md +35 -23
- package/dist/playbooks/task-lead.md +13 -11
- package/dist/runtime/bootstrap.d.ts +36 -13
- package/dist/runtime/bootstrap.js +310 -138
- package/dist/runtime/channel-queue.d.ts +23 -0
- package/dist/{dingtalk → runtime}/channel-queue.js +20 -9
- package/dist/runtime/daemon-lock.d.ts +12 -0
- package/dist/runtime/daemon-lock.js +28 -0
- package/dist/runtime/desk-runtime.d.ts +131 -0
- package/dist/runtime/desk-runtime.js +402 -0
- package/dist/runtime/durable-dispatch.d.ts +11 -5
- package/dist/runtime/durable-dispatch.js +20 -8
- package/dist/runtime/inbound-images.d.ts +32 -10
- package/dist/runtime/inbound-images.js +95 -21
- package/dist/runtime/ingress-busy.d.ts +26 -0
- package/dist/runtime/ingress-busy.js +211 -0
- package/dist/runtime/ingress-commands.d.ts +7 -0
- package/dist/runtime/ingress-commands.js +162 -0
- package/dist/runtime/ingress-deps.d.ts +62 -0
- package/dist/runtime/ingress-deps.js +1 -0
- package/dist/runtime/ingress.d.ts +22 -0
- package/dist/runtime/ingress.js +376 -0
- package/dist/runtime/request-execution.d.ts +19 -0
- package/dist/runtime/request-execution.js +88 -0
- package/dist/runtime/shutdown.d.ts +13 -5
- package/dist/runtime/shutdown.js +10 -4
- package/dist/runtime/task-driver.d.ts +38 -22
- package/dist/runtime/task-driver.js +142 -116
- package/dist/runtime/task-spawn.d.ts +4 -4
- package/dist/runtime/task-spawn.js +6 -5
- package/dist/runtime/task-wake.d.ts +6 -4
- package/dist/runtime/task-wake.js +7 -7
- package/dist/runtime/transports.d.ts +32 -0
- package/dist/runtime/transports.js +101 -0
- package/dist/runtime/turn-run.d.ts +18 -9
- package/dist/runtime/turn-run.js +302 -71
- package/dist/runtime/wake-coalescing.d.ts +11 -3
- package/dist/runtime/wake-coalescing.js +10 -0
- package/dist/security/config.js +5 -10
- package/dist/security/logger.js +1 -1
- package/dist/security/path-guard.js +7 -63
- package/dist/security/types.d.ts +27 -30
- package/dist/security/types.js +0 -1
- package/dist/shared/atomic-file.d.ts +2 -0
- package/dist/shared/atomic-file.js +14 -1
- package/dist/shared/file-lock.d.ts +35 -0
- package/dist/shared/file-lock.js +195 -0
- package/dist/shared/with-timeout.d.ts +2 -0
- package/dist/shared/with-timeout.js +21 -0
- package/dist/skills/loader.d.ts +1 -1
- package/dist/skills/loader.js +2 -2
- package/dist/skills/workspace.js +2 -2
- package/dist/subagents/completion-wake.d.ts +11 -2
- package/dist/subagents/completion-wake.js +22 -9
- package/dist/subagents/discovery.js +1 -1
- package/dist/subagents/dispatch.d.ts +0 -10
- package/dist/subagents/dispatch.js +10 -28
- package/dist/subagents/external/dispatch.js +1 -1
- package/dist/subagents/external/run.d.ts +1 -1
- package/dist/subagents/external/run.js +3 -3
- package/dist/subagents/internal/run.js +1 -1
- package/dist/subagents/internal/worker.js +6 -14
- package/dist/subagents/run-archive.d.ts +11 -0
- package/dist/subagents/run-archive.js +49 -0
- package/dist/subagents/run-record.d.ts +9 -8
- package/dist/subagents/run-record.js +3 -3
- package/dist/subagents/run-registry.d.ts +5 -3
- package/dist/subagents/run-registry.js +22 -45
- package/dist/subagents/runs.d.ts +23 -13
- package/dist/subagents/runs.js +75 -82
- package/dist/subagents/task-envelope.js +9 -11
- package/dist/subagents/types.d.ts +6 -5
- package/dist/tasks/board.d.ts +1 -1
- package/dist/tasks/board.js +2 -2
- package/dist/tasks/bound-work.d.ts +2 -2
- package/dist/tasks/bound-work.js +7 -7
- package/dist/tasks/brief.d.ts +1 -1
- package/dist/tasks/brief.js +9 -9
- package/dist/tasks/commands.d.ts +11 -2
- package/dist/tasks/commands.js +66 -41
- package/dist/tasks/contract.d.ts +0 -2
- package/dist/tasks/contract.js +1 -3
- package/dist/tasks/create.d.ts +3 -1
- package/dist/tasks/create.js +10 -4
- package/dist/tasks/frontmatter.d.ts +6 -2
- package/dist/tasks/frontmatter.js +10 -10
- package/dist/tasks/loop-log.d.ts +7 -13
- package/dist/tasks/loop-log.js +14 -17
- package/dist/tasks/mutation-lock.d.ts +7 -5
- package/dist/tasks/mutation-lock.js +32 -9
- package/dist/tasks/session-path.d.ts +3 -3
- package/dist/tasks/session-path.js +5 -5
- package/dist/tasks/steer.d.ts +5 -5
- package/dist/tasks/steer.js +42 -40
- package/dist/tasks/store.d.ts +11 -11
- package/dist/tasks/store.js +32 -29
- package/dist/tools/bash.d.ts +5 -5
- package/dist/tools/bash.js +19 -18
- package/dist/tools/contract/names.d.ts +7 -0
- package/dist/tools/contract/names.js +22 -0
- package/dist/tools/edit.js +1 -1
- package/dist/tools/event-manage.d.ts +3 -1
- package/dist/tools/event-manage.js +34 -33
- package/dist/tools/glob.js +5 -5
- package/dist/tools/grep.js +2 -2
- package/dist/tools/index.d.ts +9 -8
- package/dist/tools/index.js +12 -16
- package/dist/tools/job.d.ts +4 -2
- package/dist/tools/job.js +11 -8
- package/dist/tools/memory-manage.d.ts +5 -3
- package/dist/tools/memory-manage.js +24 -24
- package/dist/tools/read.js +1 -1
- package/dist/tools/registry.d.ts +12 -8
- package/dist/tools/registry.js +13 -9
- package/dist/tools/send-media.d.ts +2 -2
- package/dist/tools/send-media.js +3 -3
- package/dist/tools/session-search.d.ts +3 -1
- package/dist/tools/session-search.js +8 -6
- package/dist/tools/subagent-manage.d.ts +2 -8
- package/dist/tools/subagent-manage.js +19 -15
- package/dist/tools/subagent.js +1 -1
- package/dist/tools/task-manage/create.js +1 -1
- package/dist/tools/task-manage/factory.js +2 -2
- package/dist/tools/task-manage/lifecycle.js +3 -1
- package/dist/tools/task-manage/log-view.js +2 -2
- package/dist/tools/task-manage/shared.js +3 -3
- package/dist/tools/task-manage/step-end.js +3 -3
- package/dist/tools/task-manage/types.d.ts +8 -3
- package/dist/tools/web-cache.d.ts +3 -3
- package/dist/tools/web-cache.js +12 -12
- package/dist/tools/web-fetch.d.ts +2 -2
- package/dist/tools/web-fetch.js +7 -7
- package/dist/tools/write-content.js +1 -1
- package/dist/tui/cli.d.ts +17 -5
- package/dist/tui/cli.js +90 -27
- package/dist/tui/client.d.ts +26 -0
- package/dist/tui/client.js +157 -0
- package/dist/tui/colors.d.ts +0 -1
- package/dist/tui/colors.js +0 -1
- package/dist/tui/commands.d.ts +10 -51
- package/dist/tui/commands.js +16 -39
- package/dist/tui/frontend.d.ts +2 -2
- package/dist/tui/frontend.js +2 -2
- package/dist/tui/pitui-frontend.d.ts +0 -2
- package/dist/tui/pitui-frontend.js +1 -6
- package/dist/tui/render.d.ts +62 -0
- package/dist/tui/render.js +123 -0
- package/dist/tui/session.d.ts +92 -0
- package/dist/tui/session.js +317 -0
- package/dist/usage/ledger.d.ts +5 -0
- package/dist/usage/ledger.js +2 -0
- package/dist/usage/render.d.ts +6 -1
- package/dist/usage/render.js +18 -13
- package/dist/webapi/auth.d.ts +13 -0
- package/dist/webapi/auth.js +29 -0
- package/dist/webapi/config.d.ts +29 -0
- package/dist/webapi/config.js +100 -0
- package/dist/webapi/errors.d.ts +39 -0
- package/dist/webapi/errors.js +32 -0
- package/dist/webapi/http.d.ts +25 -0
- package/dist/webapi/http.js +4 -0
- package/dist/webapi/ids.d.ts +9 -0
- package/dist/webapi/ids.js +20 -0
- package/dist/webapi/input.d.ts +17 -0
- package/dist/webapi/input.js +229 -0
- package/dist/webapi/items.d.ts +37 -0
- package/dist/webapi/items.js +48 -0
- package/dist/webapi/key-command.d.ts +2 -0
- package/dist/webapi/key-command.js +110 -0
- package/dist/webapi/limits.d.ts +47 -0
- package/dist/webapi/limits.js +48 -0
- package/dist/webapi/request-policy.d.ts +17 -0
- package/dist/webapi/request-policy.js +160 -0
- package/dist/webapi/response-record.d.ts +68 -0
- package/dist/webapi/response-record.js +58 -0
- package/dist/webapi/response-state.d.ts +90 -0
- package/dist/webapi/response-state.js +347 -0
- package/dist/webapi/routes/conversations.d.ts +8 -0
- package/dist/webapi/routes/conversations.js +80 -0
- package/dist/webapi/routes/models.d.ts +3 -0
- package/dist/webapi/routes/models.js +12 -0
- package/dist/webapi/routes/responses.d.ts +8 -0
- package/dist/webapi/routes/responses.js +118 -0
- package/dist/webapi/routes/websocket.d.ts +9 -0
- package/dist/webapi/routes/websocket.js +328 -0
- package/dist/webapi/server.d.ts +24 -0
- package/dist/webapi/server.js +229 -0
- package/dist/webapi/service.d.ts +130 -0
- package/dist/webapi/service.js +588 -0
- package/dist/webapi/store.d.ts +46 -0
- package/dist/webapi/store.js +245 -0
- package/dist/webapi/stream.d.ts +13 -0
- package/dist/webapi/stream.js +76 -0
- package/dist/webapi/transport.d.ts +43 -0
- package/dist/webapi/transport.js +100 -0
- package/package.json +9 -2
- package/dist/channel/channel-paths.d.ts +0 -16
- package/dist/channel/channel-paths.js +0 -53
- package/dist/channel/commands.d.ts +0 -32
- package/dist/channel/commands.js +0 -109
- package/dist/channel/project-scope-store.d.ts +0 -51
- package/dist/channel/project-scope-store.js +0 -112
- package/dist/dingtalk/channel-queue.d.ts +0 -19
- package/dist/dingtalk/handler.d.ts +0 -90
- package/dist/memory/channel-maintenance-queue.d.ts +0 -5
- package/dist/memory/channel-maintenance-queue.js +0 -8
- package/dist/runtime/task-migration.d.ts +0 -30
- package/dist/runtime/task-migration.js +0 -465
- package/dist/runtime/turn-handler.d.ts +0 -47
- package/dist/runtime/turn-handler.js +0 -318
- package/dist/security/project-scope.d.ts +0 -45
- package/dist/security/project-scope.js +0 -105
- package/dist/tui/app.d.ts +0 -16
- package/dist/tui/app.js +0 -166
- package/dist/tui/terminal-context.d.ts +0 -27
- package/dist/tui/terminal-context.js +0 -84
- package/dist/tui/terminal-media-sender.d.ts +0 -9
- package/dist/tui/terminal-media-sender.js +0 -15
- package/dist/tui/turn-controller.d.ts +0 -64
- package/dist/tui/turn-controller.js +0 -311
- /package/dist/{dingtalk/handler.js → channel/transport.js} +0 -0
|
@@ -0,0 +1,588 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Web API's core (spec 061, D12–D21): turns a validated request into a message for the
|
|
3
|
+
* runtime's `Ingress`, follows it to a Response, and routes everything the runtime says back —
|
|
4
|
+
* turn events, command replies, dropped messages — to the Response it belongs to. Every route and
|
|
5
|
+
* the WebSocket handler go through here; nothing outside this file creates a Response.
|
|
6
|
+
*/
|
|
7
|
+
import { loadContextAt } from "../agent/session/context-snapshot.js";
|
|
8
|
+
import { slashCommandName } from "../commands/catalog.js";
|
|
9
|
+
import * as log from "../log.js";
|
|
10
|
+
import { errorMessage } from "../shared/text-utils.js";
|
|
11
|
+
import { createEmptyUsageTotals } from "../usage/totals.js";
|
|
12
|
+
import { badRequest, conflict, forbidden, notFound, serverError, tooManyRequests, unavailable, } from "./errors.js";
|
|
13
|
+
import { channelIdOf, isConversationId, newId } from "./ids.js";
|
|
14
|
+
import { parseInput } from "./input.js";
|
|
15
|
+
import { STREAM_REPLAY_TTL_MS } from "./limits.js";
|
|
16
|
+
import { isTerminal, nowSeconds, toApiUsage } from "./response-record.js";
|
|
17
|
+
import { LiveResponse } from "./response-state.js";
|
|
18
|
+
const NO_OUTPUT = { emit: () => undefined, finish: async () => undefined };
|
|
19
|
+
/** The reason a caller sees for a refusal the ingress decided. */
|
|
20
|
+
export function rejectionError(result) {
|
|
21
|
+
const { reason } = result;
|
|
22
|
+
switch (reason.code) {
|
|
23
|
+
case "control_command":
|
|
24
|
+
return badRequest("unsupported_value", `\`/${reason.command}\` as text is not supported here: use POST /v1/responses/{id}/cancel to stop a response, \`response.steer\` over WebSocket to steer one, or send a new message.`, "input");
|
|
25
|
+
case "desk_not_allowed":
|
|
26
|
+
return forbidden("desk_not_allowed", `This key may not use desk "${reason.desk}".`);
|
|
27
|
+
case "request_capacity":
|
|
28
|
+
return tooManyRequests("Too many request-scoped generations are running; retry after one completes.", 5);
|
|
29
|
+
case "queue_full":
|
|
30
|
+
return tooManyRequests("This conversation already has too many requests waiting; retry shortly.", 5);
|
|
31
|
+
case "shutting_down":
|
|
32
|
+
return unavailable("The server is shutting down; retry shortly.");
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export class WebApiService {
|
|
36
|
+
constructor(options) {
|
|
37
|
+
/** Responses that are running, waiting, or ended within the replay window. */
|
|
38
|
+
this.live = new Map();
|
|
39
|
+
this.pendingSteers = new Map();
|
|
40
|
+
this.accepting = true;
|
|
41
|
+
/** Conversations whose delete is under way: no new message may bind them again meanwhile. */
|
|
42
|
+
this.closing = new Set();
|
|
43
|
+
/** Each request-scoped generation's full input, until it ends and its tail is cut against it. */
|
|
44
|
+
this.generationInputs = new Map();
|
|
45
|
+
// ---- steering --------------------------------------------------------------------------
|
|
46
|
+
/**
|
|
47
|
+
* A turn can be steered several times and each steer ends the response it split, so one turn is a
|
|
48
|
+
* chain of responses. Pending steers belong to the turn, keyed by the response that began it.
|
|
49
|
+
*/
|
|
50
|
+
this.turnRoots = new Map();
|
|
51
|
+
this.store = options.store;
|
|
52
|
+
this.replayTtlMs = options.replayTtlMs ?? STREAM_REPLAY_TTL_MS;
|
|
53
|
+
}
|
|
54
|
+
setIngress(ingress) {
|
|
55
|
+
this.ingressRef = ingress;
|
|
56
|
+
}
|
|
57
|
+
get ingress() {
|
|
58
|
+
if (!this.ingressRef)
|
|
59
|
+
throw serverError("The Web API is not started.");
|
|
60
|
+
return this.ingressRef;
|
|
61
|
+
}
|
|
62
|
+
// ---- lookup ----------------------------------------------------------------------------
|
|
63
|
+
getLive(id) {
|
|
64
|
+
return this.live.get(id);
|
|
65
|
+
}
|
|
66
|
+
/** The record of a response: the live one while it runs, the stored one afterwards. */
|
|
67
|
+
findRecord(id) {
|
|
68
|
+
return this.live.get(id)?.record ?? this.store.getResponse(id);
|
|
69
|
+
}
|
|
70
|
+
/** A conversation the caller may use; a stranger's is as good as absent, and so is one being deleted. */
|
|
71
|
+
conversationFor(principal, id) {
|
|
72
|
+
const conversation = isConversationId(id) ? this.store.getConversation(id) : undefined;
|
|
73
|
+
if (!conversation || this.closing.has(id) || !canAccess(principal, conversation.owner))
|
|
74
|
+
throw notFound(`Conversation ${id}`);
|
|
75
|
+
return conversation;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* `DELETE /v1/conversations/{id}`: the conversation's channel is released by the runtime (its
|
|
79
|
+
* binding, runner and background scans) and its history removed. Refused while something runs.
|
|
80
|
+
*/
|
|
81
|
+
async deleteConversation(principal, id) {
|
|
82
|
+
const conversation = this.conversationFor(principal, id);
|
|
83
|
+
this.closing.add(conversation.id);
|
|
84
|
+
try {
|
|
85
|
+
if ((await this.ingress.closeChannel(channelIdOf(conversation.id))) === "busy") {
|
|
86
|
+
throw conflict("conversation_busy", "The conversation has a response running or queued; cancel it or wait for it to end, then delete again.");
|
|
87
|
+
}
|
|
88
|
+
for (const record of this.store.listResponses(conversation.id))
|
|
89
|
+
this.live.delete(record.id);
|
|
90
|
+
await this.store.deleteConversation(conversation.id);
|
|
91
|
+
}
|
|
92
|
+
finally {
|
|
93
|
+
this.closing.delete(conversation.id);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
recordFor(principal, id) {
|
|
97
|
+
const record = this.findRecord(id);
|
|
98
|
+
if (record?.store === false)
|
|
99
|
+
throw notFound(`Response ${id}`);
|
|
100
|
+
if (!record || !canAccess(principal, record.owner))
|
|
101
|
+
throw notFound(`Response ${id}`);
|
|
102
|
+
return record;
|
|
103
|
+
}
|
|
104
|
+
/** The responses of a conversation, with a running one shown as it stands. */
|
|
105
|
+
responsesOf(conversationId) {
|
|
106
|
+
return this.store.listResponses(conversationId).map((stored) => this.live.get(stored.id)?.record ?? stored);
|
|
107
|
+
}
|
|
108
|
+
// ---- creating --------------------------------------------------------------------------
|
|
109
|
+
/**
|
|
110
|
+
* Admit one message. The response exists in memory first and is invisible until the ingress has
|
|
111
|
+
* decided what to do with the message, so a refused request leaves nothing behind (INV-5), and
|
|
112
|
+
* whatever the runtime says in the meantime (a command's reply, an early turn event) waits for
|
|
113
|
+
* the response to be announced.
|
|
114
|
+
*/
|
|
115
|
+
async create(principal, request, input) {
|
|
116
|
+
if (!this.accepting)
|
|
117
|
+
throw unavailable("The server is shutting down; retry shortly.");
|
|
118
|
+
const target = await this.resolveTarget(principal, request);
|
|
119
|
+
const context = [...target.context, ...input.context];
|
|
120
|
+
// A conversation's user messages are an ordinary channel turn (memory bootstrap, desk context,
|
|
121
|
+
// commands, attachments saved to the desk), as a string input is. Only history with other roles,
|
|
122
|
+
// and every request-scoped generation, is imported as context.
|
|
123
|
+
const imported = target.requestScoped || input.context.some((message) => message.role !== "user");
|
|
124
|
+
if (imported && input.binaryFile)
|
|
125
|
+
throw badRequest("unsupported_value", "Binary files (PDF, Office documents…) cannot be read inline. Send them in a `conversation` whose input is user messages only, where they are saved to the desk for the agent's tools; send text files here.", input.binaryFile);
|
|
126
|
+
const id = newId("resp");
|
|
127
|
+
const record = {
|
|
128
|
+
store: request.store,
|
|
129
|
+
request_scoped: target.requestScoped,
|
|
130
|
+
// Only a request-scoped generation is continued from its own input; what came before it is
|
|
131
|
+
// its parent's, kept there. A conversation's context is its session (`context_ref`).
|
|
132
|
+
...(target.requestScoped ? { context: input.context } : {}),
|
|
133
|
+
...(target.previousResponseId && target.requestScoped ? { context_parent: target.previousResponseId } : {}),
|
|
134
|
+
instructions: request.instructions,
|
|
135
|
+
id,
|
|
136
|
+
conversation_id: target.conversationId,
|
|
137
|
+
owner: target.owner,
|
|
138
|
+
status: "queued",
|
|
139
|
+
created_at: nowSeconds(),
|
|
140
|
+
completed_at: null,
|
|
141
|
+
previous_response_id: target.previousResponseId,
|
|
142
|
+
background: request.background,
|
|
143
|
+
metadata: request.metadata,
|
|
144
|
+
input_items: input.items,
|
|
145
|
+
output: [],
|
|
146
|
+
usage: null,
|
|
147
|
+
error: null,
|
|
148
|
+
incomplete_details: null,
|
|
149
|
+
};
|
|
150
|
+
const live = this.register(record, request.background && request.stream);
|
|
151
|
+
if (target.requestScoped)
|
|
152
|
+
this.generationInputs.set(id, context);
|
|
153
|
+
const message = {
|
|
154
|
+
channelId: channelIdOf(target.conversationId),
|
|
155
|
+
user: principal.name,
|
|
156
|
+
userName: principal.name,
|
|
157
|
+
text: input.text,
|
|
158
|
+
desk: target.desk,
|
|
159
|
+
...(imported
|
|
160
|
+
? { context: { messages: context, instructions: request.instructions } }
|
|
161
|
+
: request.instructions !== undefined
|
|
162
|
+
? { context: { messages: [], instructions: request.instructions } }
|
|
163
|
+
: {}),
|
|
164
|
+
...(!target.requestScoped && input.attachments.length > 0 ? { attachments: input.attachments } : {}),
|
|
165
|
+
ref: id,
|
|
166
|
+
ts: String(Date.now()),
|
|
167
|
+
...(principal.desks ? { allowedDesks: principal.desks } : {}),
|
|
168
|
+
};
|
|
169
|
+
let result;
|
|
170
|
+
try {
|
|
171
|
+
if (target.requestScoped) {
|
|
172
|
+
if (!this.ingress.execute)
|
|
173
|
+
throw new Error("Request execution is unavailable.");
|
|
174
|
+
result = await this.ingress.execute(message);
|
|
175
|
+
}
|
|
176
|
+
else
|
|
177
|
+
result = await this.ingress.receive(message);
|
|
178
|
+
}
|
|
179
|
+
catch (error) {
|
|
180
|
+
this.live.delete(id);
|
|
181
|
+
this.generationInputs.delete(id);
|
|
182
|
+
log.logWarn("webapi.ingress.failed", "Ingress refused a message with an error", {
|
|
183
|
+
reason: errorMessage(error),
|
|
184
|
+
});
|
|
185
|
+
throw serverError();
|
|
186
|
+
}
|
|
187
|
+
if (result.kind === "rejected") {
|
|
188
|
+
this.live.delete(id);
|
|
189
|
+
this.generationInputs.delete(id);
|
|
190
|
+
throw rejectionError(result);
|
|
191
|
+
}
|
|
192
|
+
live.announce(result.kind === "queued" ? "queued" : "in_progress");
|
|
193
|
+
if (result.kind === "replied")
|
|
194
|
+
live.complete(toApiUsage(createEmptyUsageTotals()));
|
|
195
|
+
return live;
|
|
196
|
+
}
|
|
197
|
+
async resolveTarget(principal, request) {
|
|
198
|
+
if (request.conversation !== undefined) {
|
|
199
|
+
const conversation = this.conversationFor(principal, request.conversation);
|
|
200
|
+
return {
|
|
201
|
+
conversationId: conversation.id,
|
|
202
|
+
owner: conversation.owner,
|
|
203
|
+
previousResponseId: this.store.latestResponseId(conversation.id) ?? null,
|
|
204
|
+
requestScoped: false,
|
|
205
|
+
context: [],
|
|
206
|
+
};
|
|
207
|
+
}
|
|
208
|
+
if (request.previousResponseId !== undefined) {
|
|
209
|
+
const previous = this.findRecord(request.previousResponseId);
|
|
210
|
+
if (!previous || previous.store === false || !canAccess(principal, previous.owner)) {
|
|
211
|
+
throw notFound(`Response ${request.previousResponseId}`, "previous_response_not_found");
|
|
212
|
+
}
|
|
213
|
+
if (!isTerminal(previous.status))
|
|
214
|
+
throw badRequest("invalid_value", "Wait for the previous response to finish before continuing it.", "previous_response_id");
|
|
215
|
+
const context = await this.contextAfter(previous);
|
|
216
|
+
if (!context)
|
|
217
|
+
throw badRequest("invalid_value", "The context of that response is no longer on the server. Continue with its `conversation`, or send the history in `input`.", "previous_response_id");
|
|
218
|
+
return {
|
|
219
|
+
conversationId: newId("conv"),
|
|
220
|
+
owner: principal.name,
|
|
221
|
+
previousResponseId: previous.id,
|
|
222
|
+
desk: previous.desk,
|
|
223
|
+
requestScoped: true,
|
|
224
|
+
context,
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
return {
|
|
228
|
+
conversationId: newId("conv"),
|
|
229
|
+
owner: principal.name,
|
|
230
|
+
previousResponseId: null,
|
|
231
|
+
requestScoped: true,
|
|
232
|
+
context: [],
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* The context a request continuing from `target` starts with: everything `target`'s generation
|
|
237
|
+
* saw and said. Request-scoped responses are followed back through their parents to one whose
|
|
238
|
+
* context stands on its own, then rebuilt forward; `undefined` when a piece is gone.
|
|
239
|
+
*/
|
|
240
|
+
async contextAfter(target) {
|
|
241
|
+
const links = [];
|
|
242
|
+
let record = target;
|
|
243
|
+
let context;
|
|
244
|
+
while (record) {
|
|
245
|
+
if (!record.request_scoped) {
|
|
246
|
+
context = await this.conversationContextAt(record);
|
|
247
|
+
break;
|
|
248
|
+
}
|
|
249
|
+
if (record.continuation) {
|
|
250
|
+
context = record.continuation;
|
|
251
|
+
break;
|
|
252
|
+
}
|
|
253
|
+
links.push(record);
|
|
254
|
+
if (!record.context_parent) {
|
|
255
|
+
context = [];
|
|
256
|
+
break;
|
|
257
|
+
}
|
|
258
|
+
record = this.store.getResponse(record.context_parent);
|
|
259
|
+
}
|
|
260
|
+
if (!context)
|
|
261
|
+
return undefined;
|
|
262
|
+
for (const link of links.reverse()) {
|
|
263
|
+
const input = [...context, ...(link.context ?? [])];
|
|
264
|
+
// No tail: the generation never finished (a restart failed it), so what it said is its output.
|
|
265
|
+
context = link.continuation_tail ? [...input, ...link.continuation_tail] : [...input, ...outputContext(link)];
|
|
266
|
+
}
|
|
267
|
+
return context;
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* A conversation's model context as of `target`: the session where the last turn up to it left
|
|
271
|
+
* off. A command's reply never entered the session, so it shares the turn before it; `/new`
|
|
272
|
+
* started an empty one.
|
|
273
|
+
*/
|
|
274
|
+
async conversationContextAt(target) {
|
|
275
|
+
const records = this.responsesOf(target.conversation_id);
|
|
276
|
+
const end = records.findIndex((record) => record.id === target.id);
|
|
277
|
+
for (let index = end; index >= 0; index--) {
|
|
278
|
+
const record = records[index];
|
|
279
|
+
if (record.context_ref)
|
|
280
|
+
return loadContextAt(record.context_ref);
|
|
281
|
+
if (record.continuation)
|
|
282
|
+
return record.continuation;
|
|
283
|
+
if (slashCommandName(inputTextOf(record)) === "new")
|
|
284
|
+
return [];
|
|
285
|
+
}
|
|
286
|
+
return [];
|
|
287
|
+
}
|
|
288
|
+
/** Record how a later request continues from `live` (see `ResponseRecord`). */
|
|
289
|
+
recordContinuation(live, outcome) {
|
|
290
|
+
const input = this.generationInputs.get(live.id);
|
|
291
|
+
this.generationInputs.delete(live.id);
|
|
292
|
+
if (outcome.contextRef)
|
|
293
|
+
live.record.context_ref = outcome.contextRef;
|
|
294
|
+
const full = outcome.continuation;
|
|
295
|
+
if (!full)
|
|
296
|
+
return;
|
|
297
|
+
if (input && startsWith(full, input))
|
|
298
|
+
live.record.continuation_tail = full.slice(input.length);
|
|
299
|
+
else
|
|
300
|
+
live.record.continuation = full;
|
|
301
|
+
}
|
|
302
|
+
register(record, replayable = false) {
|
|
303
|
+
const live = new LiveResponse(record, {
|
|
304
|
+
persist: (snapshot) => this.store.saveResponse(snapshot),
|
|
305
|
+
onTerminal: (ended) => {
|
|
306
|
+
const timer = setTimeout(() => this.live.delete(ended.id), this.replayTtlMs);
|
|
307
|
+
timer.unref?.();
|
|
308
|
+
},
|
|
309
|
+
}, replayable);
|
|
310
|
+
this.live.set(record.id, live);
|
|
311
|
+
return live;
|
|
312
|
+
}
|
|
313
|
+
// ---- ending ----------------------------------------------------------------------------
|
|
314
|
+
/**
|
|
315
|
+
* Cancel a response the caller no longer wants (`cancel`, a dropped connection): what has not
|
|
316
|
+
* started is taken out of the queue, and only the turn that answers it is stopped — not `/stop`,
|
|
317
|
+
* which would also drop what every other caller has queued on the conversation.
|
|
318
|
+
*/
|
|
319
|
+
async cancel(live) {
|
|
320
|
+
if (live.terminal)
|
|
321
|
+
return;
|
|
322
|
+
const channelId = channelIdOf(live.record.conversation_id);
|
|
323
|
+
const wasWaiting = live.status === "queued";
|
|
324
|
+
const root = this.rootOf(live.id);
|
|
325
|
+
live.cancel();
|
|
326
|
+
this.pendingSteers.forEach((steer, ref) => {
|
|
327
|
+
if (steer.targetId === root)
|
|
328
|
+
this.pendingSteers.delete(ref);
|
|
329
|
+
});
|
|
330
|
+
if (wasWaiting && this.ingress.dropQueued(channelId, live.id))
|
|
331
|
+
return;
|
|
332
|
+
// A steered successor answers its turn under the response that began it; a steer that missed
|
|
333
|
+
// its turn runs as a turn of its own, under its own id.
|
|
334
|
+
if (await this.ingress.cancelTurn(channelId, live.id))
|
|
335
|
+
return;
|
|
336
|
+
if (root !== live.id)
|
|
337
|
+
await this.ingress.cancelTurn(channelId, root);
|
|
338
|
+
}
|
|
339
|
+
/** Shutdown has begun: refuse new messages, keep delivering what runs (see `Transport.stopAccepting`). */
|
|
340
|
+
stopAccepting() {
|
|
341
|
+
this.accepting = false;
|
|
342
|
+
}
|
|
343
|
+
/** Fail whatever is still running: the process is going away. */
|
|
344
|
+
async shutdown() {
|
|
345
|
+
for (const live of this.live.values()) {
|
|
346
|
+
if (!live.terminal)
|
|
347
|
+
live.fail("服务关闭,回合被中断。");
|
|
348
|
+
}
|
|
349
|
+
await Promise.all([...this.live.values()].map((live) => live.whenPersisted()));
|
|
350
|
+
}
|
|
351
|
+
// ---- the runtime talks back ------------------------------------------------------------
|
|
352
|
+
openTurn(turn, opts) {
|
|
353
|
+
const live = this.liveFor(turn);
|
|
354
|
+
if (live) {
|
|
355
|
+
live.start();
|
|
356
|
+
return new ResponseTurn(this, live, opts.quiet);
|
|
357
|
+
}
|
|
358
|
+
if (turn.ref !== undefined)
|
|
359
|
+
return NO_OUTPUT;
|
|
360
|
+
return new SyntheticTurn(this, turn);
|
|
361
|
+
}
|
|
362
|
+
/** The response a turn answers: the one that was asked, or the successor a steering input made. */
|
|
363
|
+
liveFor(turn) {
|
|
364
|
+
if (turn.ref === undefined)
|
|
365
|
+
return undefined;
|
|
366
|
+
const existing = this.live.get(turn.ref);
|
|
367
|
+
if (existing)
|
|
368
|
+
return existing;
|
|
369
|
+
const steer = this.pendingSteers.get(turn.ref);
|
|
370
|
+
return steer ? this.createSuccessor(steer, "in_progress") : undefined;
|
|
371
|
+
}
|
|
372
|
+
push(channelId, message) {
|
|
373
|
+
if (message.ref !== undefined) {
|
|
374
|
+
const live = this.live.get(message.ref);
|
|
375
|
+
if (!live || live.terminal)
|
|
376
|
+
return false;
|
|
377
|
+
live.addMessage("final_answer", message.text);
|
|
378
|
+
return true;
|
|
379
|
+
}
|
|
380
|
+
const conversation = this.store.getConversation(channelId.slice("webapi:".length));
|
|
381
|
+
if (!conversation)
|
|
382
|
+
return false;
|
|
383
|
+
// A notice nobody asked for is a response of its own: one `final_answer`, already complete.
|
|
384
|
+
const response = this.synthesize(conversation);
|
|
385
|
+
response.add(message.text);
|
|
386
|
+
response.complete({ kind: "completed", usage: createEmptyUsageTotals() });
|
|
387
|
+
return true;
|
|
388
|
+
}
|
|
389
|
+
/** Messages that were queued behind a stopped turn will never run. */
|
|
390
|
+
dropped(refs) {
|
|
391
|
+
for (const ref of refs) {
|
|
392
|
+
this.live.get(ref)?.cancel();
|
|
393
|
+
this.pendingSteers.delete(ref);
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
// ---- responses nobody asked for (task reports, wake results) ---------------------------
|
|
397
|
+
/** A response with no request behind it, in `conversation`: its `input_items` are empty (INV-4). */
|
|
398
|
+
synthesize(conversation) {
|
|
399
|
+
let live;
|
|
400
|
+
const open = () => {
|
|
401
|
+
if (live)
|
|
402
|
+
return live;
|
|
403
|
+
live = this.register({
|
|
404
|
+
id: newId("resp"),
|
|
405
|
+
conversation_id: conversation.id,
|
|
406
|
+
owner: conversation.owner,
|
|
407
|
+
status: "in_progress",
|
|
408
|
+
created_at: nowSeconds(),
|
|
409
|
+
completed_at: null,
|
|
410
|
+
previous_response_id: this.store.latestResponseId(conversation.id) ?? null,
|
|
411
|
+
background: false,
|
|
412
|
+
metadata: null,
|
|
413
|
+
input_items: [],
|
|
414
|
+
output: [],
|
|
415
|
+
usage: null,
|
|
416
|
+
error: null,
|
|
417
|
+
incomplete_details: null,
|
|
418
|
+
});
|
|
419
|
+
live.announce("in_progress");
|
|
420
|
+
return live;
|
|
421
|
+
};
|
|
422
|
+
return {
|
|
423
|
+
add: (text) => {
|
|
424
|
+
const response = open();
|
|
425
|
+
response.addMessage("final_answer", text);
|
|
426
|
+
},
|
|
427
|
+
complete: (outcome) => {
|
|
428
|
+
// A turn that had nothing to say makes no response; one that said something ends it.
|
|
429
|
+
if (!live)
|
|
430
|
+
return;
|
|
431
|
+
this.recordContinuation(live, outcome);
|
|
432
|
+
if (outcome.executionDesk)
|
|
433
|
+
live.record.desk = outcome.executionDesk;
|
|
434
|
+
if (outcome.kind === "failed")
|
|
435
|
+
live.fail(outcome.message ?? "回合异常结束。", toApiUsage(outcome.usage));
|
|
436
|
+
else if (outcome.kind === "cancelled")
|
|
437
|
+
live.cancel();
|
|
438
|
+
else
|
|
439
|
+
live.complete(toApiUsage(outcome.usage));
|
|
440
|
+
},
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
rootOf(responseId) {
|
|
444
|
+
return this.turnRoots.get(responseId) ?? responseId;
|
|
445
|
+
}
|
|
446
|
+
registerSteer(steer) {
|
|
447
|
+
this.pendingSteers.set(steer.successorId, { ...steer, targetId: this.rootOf(steer.targetId) });
|
|
448
|
+
}
|
|
449
|
+
/** The steers still waiting to be applied to the turn `responseId` belongs to, oldest first. */
|
|
450
|
+
pendingSteersOf(responseId) {
|
|
451
|
+
const root = this.rootOf(responseId);
|
|
452
|
+
return [...this.pendingSteers.values()].filter((steer) => steer.targetId === root);
|
|
453
|
+
}
|
|
454
|
+
forgetSteer(successorId) {
|
|
455
|
+
this.pendingSteers.delete(successorId);
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* The running response was steered: it ends `incomplete` and its successor takes over. Returns
|
|
459
|
+
* the successor; `undefined` when no steering input was waiting (a message the SDK injected on
|
|
460
|
+
* its own), in which case the response simply carries on.
|
|
461
|
+
*/
|
|
462
|
+
splitForSteer(current) {
|
|
463
|
+
const steer = this.pendingSteersOf(current.id)[0];
|
|
464
|
+
if (!steer)
|
|
465
|
+
return undefined;
|
|
466
|
+
current.incomplete("steered");
|
|
467
|
+
return this.createSuccessor(steer, "in_progress", current.id);
|
|
468
|
+
}
|
|
469
|
+
createSuccessor(steer, initial, followsId) {
|
|
470
|
+
this.pendingSteers.delete(steer.successorId);
|
|
471
|
+
this.turnRoots.set(steer.successorId, steer.targetId);
|
|
472
|
+
const target = this.findRecord(steer.targetId);
|
|
473
|
+
const conversation = this.store.getConversation(steer.conversationId);
|
|
474
|
+
const live = this.register({
|
|
475
|
+
id: steer.successorId,
|
|
476
|
+
conversation_id: steer.conversationId,
|
|
477
|
+
owner: conversation?.owner ?? steer.principal.name,
|
|
478
|
+
status: "in_progress",
|
|
479
|
+
created_at: nowSeconds(),
|
|
480
|
+
completed_at: null,
|
|
481
|
+
previous_response_id: followsId ?? steer.targetId,
|
|
482
|
+
background: false,
|
|
483
|
+
metadata: target?.metadata ?? null,
|
|
484
|
+
input_items: steer.input.items,
|
|
485
|
+
output: [],
|
|
486
|
+
usage: null,
|
|
487
|
+
error: null,
|
|
488
|
+
incomplete_details: null,
|
|
489
|
+
});
|
|
490
|
+
live.announce(initial);
|
|
491
|
+
steer.onSuccessor?.(live);
|
|
492
|
+
return live;
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
export function canAccess(principal, owner) {
|
|
496
|
+
return principal.local || principal.name === owner;
|
|
497
|
+
}
|
|
498
|
+
/** A turn that answers a request: its events become the response's items. */
|
|
499
|
+
class ResponseTurn {
|
|
500
|
+
constructor(service, current, quiet) {
|
|
501
|
+
this.service = service;
|
|
502
|
+
this.current = current;
|
|
503
|
+
this.quiet = quiet;
|
|
504
|
+
}
|
|
505
|
+
emit(event) {
|
|
506
|
+
const live = this.current;
|
|
507
|
+
switch (event.type) {
|
|
508
|
+
case "tool.start":
|
|
509
|
+
if (!this.quiet)
|
|
510
|
+
live.beginToolCall(event.callId, event.tool, event.args);
|
|
511
|
+
return;
|
|
512
|
+
case "tool.end":
|
|
513
|
+
if (!this.quiet)
|
|
514
|
+
live.endToolCall(event.callId, event.ok, event.output, event.failure);
|
|
515
|
+
return;
|
|
516
|
+
case "reasoning":
|
|
517
|
+
if (!this.quiet)
|
|
518
|
+
live.addReasoning(event.text);
|
|
519
|
+
return;
|
|
520
|
+
case "commentary":
|
|
521
|
+
if (!this.quiet)
|
|
522
|
+
live.addMessage("commentary", event.text, event.level);
|
|
523
|
+
return;
|
|
524
|
+
case "answer":
|
|
525
|
+
live.addMessage("final_answer", event.text);
|
|
526
|
+
return;
|
|
527
|
+
case "steer.applied": {
|
|
528
|
+
const successor = this.service.splitForSteer(live);
|
|
529
|
+
if (successor)
|
|
530
|
+
this.current = successor;
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
case "tool.update":
|
|
534
|
+
case "compaction":
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
async finish(outcome) {
|
|
539
|
+
const live = this.current;
|
|
540
|
+
this.service.recordContinuation(live, outcome);
|
|
541
|
+
if (outcome.executionDesk)
|
|
542
|
+
live.record.desk = outcome.executionDesk;
|
|
543
|
+
const usage = toApiUsage(outcome.usage);
|
|
544
|
+
switch (outcome.kind) {
|
|
545
|
+
case "completed":
|
|
546
|
+
case "silent":
|
|
547
|
+
live.complete(usage);
|
|
548
|
+
return;
|
|
549
|
+
case "failed":
|
|
550
|
+
live.fail(outcome.message ?? "回合异常结束。", usage);
|
|
551
|
+
return;
|
|
552
|
+
case "cancelled":
|
|
553
|
+
live.cancel();
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
/** A wake's turn: no request behind it, so a response exists only if the turn says something. */
|
|
559
|
+
class SyntheticTurn {
|
|
560
|
+
constructor(service, turn) {
|
|
561
|
+
const conversation = service.store.getConversation(turn.channelId.slice("webapi:".length));
|
|
562
|
+
this.response = conversation ? service.synthesize(conversation) : undefined;
|
|
563
|
+
}
|
|
564
|
+
emit(event) {
|
|
565
|
+
// A wake delivers its result, never its process.
|
|
566
|
+
if (event.type === "answer")
|
|
567
|
+
this.response?.add(event.text);
|
|
568
|
+
}
|
|
569
|
+
async finish(outcome) {
|
|
570
|
+
this.response?.complete(outcome);
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
function outputContext(record) {
|
|
574
|
+
return record.output.flatMap((item) => parseInput([item]).context);
|
|
575
|
+
}
|
|
576
|
+
/** What the caller typed, as one string (for recognising a command). */
|
|
577
|
+
function inputTextOf(record) {
|
|
578
|
+
return record.input_items
|
|
579
|
+
.flatMap((item) => item.type === "message" && Array.isArray(item.content)
|
|
580
|
+
? item.content.flatMap((part) => (part.type === "input_text" ? [part.text] : []))
|
|
581
|
+
: [])
|
|
582
|
+
.join("\n");
|
|
583
|
+
}
|
|
584
|
+
/** Whether `full` begins with exactly the messages of `prefix` (field by field: key order differs). */
|
|
585
|
+
function startsWith(full, prefix) {
|
|
586
|
+
const same = (a, b) => a.role === b.role && a.phase === b.phase && JSON.stringify(a.content) === JSON.stringify(b.content);
|
|
587
|
+
return prefix.length <= full.length && prefix.every((message, index) => same(message, full[index]));
|
|
588
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { type ResponseRecord } from "./response-record.js";
|
|
2
|
+
export interface ConversationRecord {
|
|
3
|
+
id: string;
|
|
4
|
+
created_at: number;
|
|
5
|
+
metadata: Record<string, string> | null;
|
|
6
|
+
owner: string;
|
|
7
|
+
}
|
|
8
|
+
export declare class WebApiStore {
|
|
9
|
+
private readonly dir;
|
|
10
|
+
private readonly conversations;
|
|
11
|
+
private readonly responses;
|
|
12
|
+
/** Response ids per conversation, in the order they were created. */
|
|
13
|
+
private readonly order;
|
|
14
|
+
private readonly appender;
|
|
15
|
+
/** The tail of the disk writes `saveResponse` has queued. */
|
|
16
|
+
private writes;
|
|
17
|
+
private constructor();
|
|
18
|
+
/** Open the store, reading everything and failing the responses a previous run left unfinished. */
|
|
19
|
+
static open(stateDir: string): Promise<WebApiStore>;
|
|
20
|
+
private conversationDir;
|
|
21
|
+
private load;
|
|
22
|
+
private readConversation;
|
|
23
|
+
private readResponses;
|
|
24
|
+
createConversation(owner: string, metadata: Record<string, string> | null, id?: string): Promise<ConversationRecord>;
|
|
25
|
+
getConversation(id: string): ConversationRecord | undefined;
|
|
26
|
+
updateConversationMetadata(id: string, metadata: Record<string, string> | null): Promise<ConversationRecord>;
|
|
27
|
+
/**
|
|
28
|
+
* Forget a conversation and its responses, and remove its directory. The index line in
|
|
29
|
+
* `responses.jsonl` stays: it is the operator's record, and it names an id that no longer resolves.
|
|
30
|
+
*/
|
|
31
|
+
deleteConversation(id: string): Promise<void>;
|
|
32
|
+
private writeConversation;
|
|
33
|
+
getResponse(id: string): ResponseRecord | undefined;
|
|
34
|
+
/** A conversation's responses, oldest first. */
|
|
35
|
+
listResponses(conversationId: string): ResponseRecord[];
|
|
36
|
+
latestResponseId(conversationId: string): string | undefined;
|
|
37
|
+
/**
|
|
38
|
+
* Record a response's current state: the first call for an id also registers it in the conversation.
|
|
39
|
+
* Registration is immediate; the disk writes happen in call order, so the last snapshot on disk is
|
|
40
|
+
* always the last one saved (the first save also writes the index line, which would otherwise let a
|
|
41
|
+
* later snapshot overtake it).
|
|
42
|
+
*/
|
|
43
|
+
saveResponse(record: ResponseRecord): Promise<void>;
|
|
44
|
+
private appendSnapshot;
|
|
45
|
+
close(): Promise<void>;
|
|
46
|
+
}
|