nova-personal-agent-server 0.4.0 → 1.0.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/LICENSE +674 -201
- package/README.md +12 -2
- package/bin/nova-space-host.mjs +4 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/cli.js +71 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/client.js +340 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/crypto.js +167 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/live.js +169 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/mailbox.js +217 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/media.js +320 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/pairing.js +13 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/protocol.js +50 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/security.js +305 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/server.js +477 -0
- package/node_modules/@nova-personal-agent/relay/dist/src/source-address.js +58 -0
- package/node_modules/@nova-personal-agent/relay/package.json +1 -0
- package/package.json +13 -6
- package/runtime/dist/src/cascaded-text-provider.js +8 -3
- package/runtime/dist/src/composition/assembly.js +133 -35
- package/runtime/dist/src/composition/cascaded-realtime-assembly.js +114 -59
- package/runtime/dist/src/composition/production-composition.js +57 -21
- package/runtime/dist/src/composition/realtime-assembly.js +160 -52
- package/runtime/dist/src/composition/soul-context.js +22 -0
- package/runtime/dist/src/config/capability-registry.js +48 -3
- package/runtime/dist/src/config/cascaded-realtime-config.js +23 -10
- package/runtime/dist/src/config/config.js +541 -128
- package/runtime/dist/src/config/credential-rotation.js +26 -0
- package/runtime/dist/src/config/data-root.js +764 -0
- package/runtime/dist/src/config/diagnostics.js +3 -1
- package/runtime/dist/src/config/environment-contract.js +190 -188
- package/runtime/dist/src/config/model-routes.js +140 -0
- package/runtime/dist/src/config/voice-credentials.js +55 -0
- package/runtime/dist/src/connectors/composio/index.js +9 -0
- package/runtime/dist/src/connectors/feishu/index.js +258 -44
- package/runtime/dist/src/connectors/macos/mail.js +7 -3
- package/runtime/dist/src/connectors/macos/reader.js +3 -1
- package/runtime/dist/src/conversation-voice-provider.js +5 -2
- package/runtime/dist/src/core/causal-runtime.js +38 -3
- package/runtime/dist/src/core/context-view.js +7 -0
- package/runtime/dist/src/core/guards.js +32 -0
- package/runtime/dist/src/core/runtime.js +3 -0
- package/runtime/dist/src/core/schedule-tools.js +2 -2
- package/runtime/dist/src/core/source-processing-instructions.js +2 -2
- package/runtime/dist/src/core/source-processing-tools.js +3 -1
- package/runtime/dist/src/core/tool-schema.js +42 -7
- package/runtime/dist/src/desktop/desktop-camera.js +3 -5
- package/runtime/dist/src/desktop/desktop-control.js +41 -8
- package/runtime/dist/src/desktop/desktop-session.js +90 -19
- package/runtime/dist/src/desktop/desktop-wire.js +5 -7
- package/runtime/dist/src/desktop/startup-error.js +18 -16
- package/runtime/dist/src/desktop/workbench-acceptance.js +52 -14
- package/runtime/dist/src/desktop-entry.js +6 -2
- package/runtime/dist/src/desktop.js +5 -1
- package/runtime/dist/src/device/attempt.js +65 -0
- package/runtime/dist/src/device/authority.js +159 -0
- package/runtime/dist/src/device/gateway.js +87 -0
- package/runtime/dist/src/device/ledger.js +91 -0
- package/runtime/dist/src/device/ownership.js +92 -0
- package/runtime/dist/src/device/port.js +2 -0
- package/runtime/dist/src/device/schedule-ownership.js +103 -0
- package/runtime/dist/src/executors/acp/transport.js +2 -0
- package/runtime/dist/src/executors/browser.js +4 -3
- package/runtime/dist/src/executors/codex/adapter-project.js +58 -12
- package/runtime/dist/src/executors/codex/app-server-schema.js +12 -21
- package/runtime/dist/src/executors/codex/app-server-transport.js +32 -18
- package/runtime/dist/src/executors/codex/common.js +1 -1
- package/runtime/dist/src/executors/codex/contract.js +12 -16
- package/runtime/dist/src/executors/codex/credential-snapshot.js +1 -9
- package/runtime/dist/src/executors/codex/factory.js +54 -32
- package/runtime/dist/src/executors/codex/host-config.js +69 -20
- package/runtime/dist/src/executors/codex/launch-profile.js +3 -2
- package/runtime/dist/src/executors/codex/local-provider-credential.js +39 -0
- package/runtime/dist/src/executors/codex/process-owner.js +4 -6
- package/runtime/dist/src/executors/codex/production-host.js +33 -34
- package/runtime/dist/src/executors/codex/protocol.js +9 -14
- package/runtime/dist/src/executors/codex/session-title.js +6 -8
- package/runtime/dist/src/executors/codex/spawn-env.js +27 -6
- package/runtime/dist/src/executors/codex/turn-projection.js +12 -17
- package/runtime/dist/src/executors/codex/windows-guardian.js +4 -6
- package/runtime/dist/src/executors/coding/intake.js +12 -7
- package/runtime/dist/src/executors/computer-backend.js +18 -10
- package/runtime/dist/src/executors/computer-config.js +32 -0
- package/runtime/dist/src/executors/computer-device.js +68 -16
- package/runtime/dist/src/executors/computer-worker.js +18 -6
- package/runtime/dist/src/executors/computer.js +29 -56
- package/runtime/dist/src/executors/device-lock.js +14 -5
- package/runtime/dist/src/executors/gui-execution.js +2 -0
- package/runtime/dist/src/executors/index.js +0 -1
- package/runtime/dist/src/executors/mobile.js +9 -8
- package/runtime/dist/src/executors/native-process.js +4 -0
- package/runtime/dist/src/executors/search.js +3 -5
- package/runtime/dist/src/executors/task-resources.js +21 -0
- package/runtime/dist/src/executors/watcher.js +2 -4
- package/runtime/dist/src/experience/host.js +179 -0
- package/runtime/dist/src/index.js +2 -0
- package/runtime/dist/src/knowledge/assembly.js +3 -4
- package/runtime/dist/src/knowledge/embeddings.js +50 -34
- package/runtime/dist/src/knowledge/service.js +1 -0
- package/runtime/dist/src/knowledge/store-client.js +1 -6
- package/runtime/dist/src/knowledge/store-worker.js +1 -3
- package/runtime/dist/src/mem0/resource.js +25 -0
- package/runtime/dist/src/mem0/store-worker.js +234 -21
- package/runtime/dist/src/memory/consumer.js +31 -0
- package/runtime/dist/src/memory/engine-worker.js +210 -0
- package/runtime/dist/src/memory/entry.js +8 -1
- package/runtime/dist/src/memory/explicit-memory.js +20 -0
- package/runtime/dist/src/memory/factory.js +30 -15
- package/runtime/dist/src/memory/grounded-voicemem.js +10 -0
- package/runtime/dist/src/memory/ledger-recall-engine.js +86 -0
- package/runtime/dist/src/memory/prerecall-port.js +27 -0
- package/runtime/dist/src/memory/prerecall.js +1 -1
- package/runtime/dist/src/memory/production-engine.js +151 -0
- package/runtime/dist/src/memory/provenance.js +1 -0
- package/runtime/dist/src/memory/remote-personal-memory.js +3 -1
- package/runtime/dist/src/memory/retrieval.js +107 -22
- package/runtime/dist/src/memory/sensitivity.js +6 -2
- package/runtime/dist/src/memory/source-retrieval.js +11 -0
- package/runtime/dist/src/memory/tool-capabilities.js +46 -0
- package/runtime/dist/src/memory/voicemem-sdk/LICENSE +202 -0
- package/runtime/dist/src/memory/voicemem-sdk/NOTICE.md +97 -0
- package/runtime/dist/src/memory/voicemem-sdk/PATCH-NOTICE.md +23 -0
- package/runtime/dist/src/memory/voicemem-sdk/archive.js +12 -0
- package/runtime/dist/src/memory/voicemem-sdk/audio.js +111 -0
- package/runtime/dist/src/memory/voicemem-sdk/barge-in.js +59 -0
- package/runtime/dist/src/memory/voicemem-sdk/checkpoint.js +56 -0
- package/runtime/dist/src/memory/voicemem-sdk/cleanup.js +139 -0
- package/runtime/dist/src/memory/voicemem-sdk/dashscope-asr.js +254 -0
- package/runtime/dist/src/memory/voicemem-sdk/dashscope-tts.js +247 -0
- package/runtime/dist/src/memory/voicemem-sdk/evaluation.js +330 -0
- package/runtime/dist/src/memory/voicemem-sdk/extraction.js +220 -0
- package/runtime/dist/src/memory/voicemem-sdk/finetune-data.js +115 -0
- package/runtime/dist/src/memory/voicemem-sdk/finetune.js +170 -0
- package/runtime/dist/src/memory/voicemem-sdk/grounded-reply-preferences.js +81 -0
- package/runtime/dist/src/memory/voicemem-sdk/index.js +22 -0
- package/runtime/dist/src/memory/voicemem-sdk/local-embedding.js +164 -0
- package/runtime/dist/src/memory/voicemem-sdk/local-runtime.js +53 -0
- package/runtime/dist/src/memory/voicemem-sdk/local-speaker.js +240 -0
- package/runtime/dist/src/memory/voicemem-sdk/memory.js +767 -0
- package/runtime/dist/src/memory/voicemem-sdk/model-json.js +14 -0
- package/runtime/dist/src/memory/voicemem-sdk/personamem.js +209 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/addenda.js +215 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/additive-extraction.js +478 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/index.js +32 -0
- package/runtime/dist/src/memory/voicemem-sdk/prompts/update-memory.js +152 -0
- package/runtime/dist/src/memory/voicemem-sdk/providers.js +325 -0
- package/runtime/dist/src/memory/voicemem-sdk/ranking.js +65 -0
- package/runtime/dist/src/memory/voicemem-sdk/reaction.js +33 -0
- package/runtime/dist/src/memory/voicemem-sdk/realtime.js +215 -0
- package/runtime/dist/src/memory/voicemem-sdk/reply.js +68 -0
- package/runtime/dist/src/memory/voicemem-sdk/routing.js +209 -0
- package/runtime/dist/src/memory/voicemem-sdk/slots.js +61 -0
- package/runtime/dist/src/memory/voicemem-sdk/speaker-bindings.js +120 -0
- package/runtime/dist/src/memory/voicemem-sdk/speaker-profiles.js +327 -0
- package/runtime/dist/src/memory/voicemem-sdk/store.js +577 -0
- package/runtime/dist/src/memory/voicemem-sdk/stream.js +317 -0
- package/runtime/dist/src/memory/voicemem-sdk/subgraph.js +113 -0
- package/runtime/dist/src/memory/voicemem-sdk/summaries.js +56 -0
- package/runtime/dist/src/memory/voicemem-sdk/time.js +157 -0
- package/runtime/dist/src/memory/voicemem-sdk/types.js +2 -0
- package/runtime/dist/src/memory-ledger/store-client.js +235 -37
- package/runtime/dist/src/memory-ledger/store-worker.js +8 -5
- package/runtime/dist/src/memory-ledger/store.js +91 -1
- package/runtime/dist/src/memory-substrate/consolidation.js +23 -7
- package/runtime/dist/src/memory-substrate/diary.js +27 -0
- package/runtime/dist/src/memory-substrate/engine-outbox.js +107 -0
- package/runtime/dist/src/memory-substrate/explicit-memory.js +112 -0
- package/runtime/dist/src/memory-substrate/fact-fidelity.js +68 -0
- package/runtime/dist/src/memory-substrate/feishu-consent.js +41 -0
- package/runtime/dist/src/memory-substrate/file-authority.js +29 -6
- package/runtime/dist/src/memory-substrate/life-operations.js +35 -9
- package/runtime/dist/src/memory-substrate/markdown-repository.js +271 -65
- package/runtime/dist/src/memory-substrate/memory-documents.js +96 -0
- package/runtime/dist/src/memory-substrate/migration.js +2 -0
- package/runtime/dist/src/memory-substrate/purge.js +12 -2
- package/runtime/dist/src/memory-substrate/resource.js +514 -129
- package/runtime/dist/src/memory-substrate/retrieval.js +8 -5
- package/runtime/dist/src/memory-substrate/source-operations.js +9 -1
- package/runtime/dist/src/memory-substrate/source-processing.js +436 -40
- package/runtime/dist/src/memory-substrate/source-retrieval.js +28 -0
- package/runtime/dist/src/memory-substrate/source-state.js +8 -0
- package/runtime/dist/src/memory-substrate/space-source-input.js +90 -0
- package/runtime/dist/src/memory-substrate/store.js +125 -23
- package/runtime/dist/src/model/goal-checkin-writer.js +72 -0
- package/runtime/dist/src/model/goal-writer.js +80 -0
- package/runtime/dist/src/model/jev-client.js +24 -13
- package/runtime/dist/src/model/model-adapters.js +2 -3
- package/runtime/dist/src/model/model-catalog.js +80 -0
- package/runtime/dist/src/model/model-gateway.js +47 -18
- package/runtime/dist/src/model/model-purpose.js +3 -4
- package/runtime/dist/src/model/personal-writer.js +536 -44
- package/runtime/dist/src/model/proactivity.js +50 -6
- package/runtime/dist/src/model/responses-model-gateway.js +59 -0
- package/runtime/dist/src/model/task-verifier.js +3 -3
- package/runtime/dist/src/model/timeline-anchors.js +77 -0
- package/runtime/dist/src/model/timeline-perspective.js +13 -0
- package/runtime/dist/src/model/timeline-selection.js +182 -0
- package/runtime/dist/src/model/understanding-writer.js +27 -0
- package/runtime/dist/src/model/vision-capability.js +3 -1
- package/runtime/dist/src/model/workbench-writer.js +96 -0
- package/runtime/dist/src/news/feeds.js +6 -10
- package/runtime/dist/src/news/interests.js +23 -0
- package/runtime/dist/src/news/service.js +87 -31
- package/runtime/dist/src/news/sources.json +116 -0
- package/runtime/dist/src/notifications/adapters/space-relay.js +4 -0
- package/runtime/dist/src/notifications/content.js +41 -0
- package/runtime/dist/src/notifications/contracts.js +4 -2
- package/runtime/dist/src/notifications/feed.js +6 -2
- package/runtime/dist/src/notifications/service.js +27 -14
- package/runtime/dist/src/notifications/store.js +3 -1
- package/runtime/dist/src/personal-agent/app-context.js +39 -4
- package/runtime/dist/src/personal-agent/chat-failure.js +37 -0
- package/runtime/dist/src/personal-agent/computer-use/contract.js +42 -0
- package/runtime/dist/src/personal-agent/computer-use/session.js +280 -0
- package/runtime/dist/src/personal-agent/computer-use/skill.js +18 -0
- package/runtime/dist/src/personal-agent/computer-use/tools.js +15 -0
- package/runtime/dist/src/personal-agent/context-candidates.js +9 -13
- package/runtime/dist/src/personal-agent/context-dependencies.js +28 -0
- package/runtime/dist/src/personal-agent/contracts.js +24 -4
- package/runtime/dist/src/personal-agent/conversation-runtime.js +440 -42
- package/runtime/dist/src/personal-agent/conversation-tool-bridge.js +97 -0
- package/runtime/dist/src/personal-agent/conversation-tool-policy.js +22 -0
- package/runtime/dist/src/personal-agent/conversations.js +71 -15
- package/runtime/dist/src/personal-agent/daily-brief.js +5 -0
- package/runtime/dist/src/personal-agent/daily-workbench.js +558 -0
- package/runtime/dist/src/personal-agent/discovery-window.js +36 -0
- package/runtime/dist/src/personal-agent/goal-checkin.js +53 -0
- package/runtime/dist/src/personal-agent/host.js +2379 -223
- package/runtime/dist/src/personal-agent/identity-context.js +33 -0
- package/runtime/dist/src/personal-agent/life.js +129 -11
- package/runtime/dist/src/personal-agent/local-shell.js +181 -0
- package/runtime/dist/src/personal-agent/local-tools.js +234 -0
- package/runtime/dist/src/personal-agent/preferred-name-sync.js +35 -0
- package/runtime/dist/src/personal-agent/profile-warmup.js +100 -39
- package/runtime/dist/src/personal-agent/project-digests.js +7 -3
- package/runtime/dist/src/personal-agent/project-history.js +36 -0
- package/runtime/dist/src/personal-agent/reading-copies.js +183 -0
- package/runtime/dist/src/personal-agent/scheduled-tasks.js +50 -13
- package/runtime/dist/src/personal-agent/scheduled-tool-runtime.js +26 -10
- package/runtime/dist/src/personal-agent/source-processing-agent.js +239 -17
- package/runtime/dist/src/personal-agent/sources.js +9 -1
- package/runtime/dist/src/personal-agent/store.js +124 -14
- package/runtime/dist/src/personal-agent/task-loop.js +3 -0
- package/runtime/dist/src/personal-agent/tasks.js +16 -4
- package/runtime/dist/src/personal-agent/timeline-brief.js +462 -0
- package/runtime/dist/src/personal-agent/timeline-cache.js +191 -0
- package/runtime/dist/src/personal-agent/timeline-cluster.js +30 -0
- package/runtime/dist/src/personal-agent/timeline-inputs.js +47 -0
- package/runtime/dist/src/personal-agent/timeline-time.js +60 -0
- package/runtime/dist/src/personal-agent/understanding-products.js +49 -0
- package/runtime/dist/src/personal-agent/understanding.js +7 -22
- package/runtime/dist/src/personal-agent/workbench-context.js +17 -21
- package/runtime/dist/src/personal-agent/workbench-copy.js +124 -0
- package/runtime/dist/src/personal-agent/workbench-evidence.js +77 -0
- package/runtime/dist/src/personal-agent/workbench-instructions.js +21 -0
- package/runtime/dist/src/personal-agent/workbench-runtime.js +1006 -0
- package/runtime/dist/src/personal-agent/workbench-shell-class.js +304 -0
- package/runtime/dist/src/personal-agent/workbench-store.js +292 -0
- package/runtime/dist/src/personal-agent/workbench-temporal.js +66 -0
- package/runtime/dist/src/projects/project-native-resource.js +10 -8
- package/runtime/dist/src/projects/project-store.js +36 -4
- package/runtime/dist/src/realtime/bridge.js +77 -8
- package/runtime/dist/src/realtime/capabilities.js +19 -0
- package/runtime/dist/src/realtime/cascaded/adapter.js +180 -40
- package/runtime/dist/src/realtime/cascaded/ark-llm.js +150 -24
- package/runtime/dist/src/realtime/cascaded/chat-completions-llm.js +243 -83
- package/runtime/dist/src/realtime/cascaded/llm-stream-limits.js +18 -0
- package/runtime/dist/src/realtime/cascaded/llm.js +96 -0
- package/runtime/dist/src/realtime/cascaded/openai-compatible-speech.js +251 -0
- package/runtime/dist/src/realtime/cascaded/provider.js +8 -0
- package/runtime/dist/src/realtime/evidence.js +1 -1
- package/runtime/dist/src/realtime/frontend-instructions.js +76 -55
- package/runtime/dist/src/realtime/gemini.js +14 -3
- package/runtime/dist/src/realtime/host-delivery.js +37 -4
- package/runtime/dist/src/realtime/protocol.js +18 -3
- package/runtime/dist/src/realtime/provider-projection.js +4 -1
- package/runtime/dist/src/realtime/provider-session.js +73 -16
- package/runtime/dist/src/realtime/qwen-transport.js +35 -4
- package/runtime/dist/src/realtime/qwen.js +144 -9
- package/runtime/dist/src/realtime/service-state.js +0 -1
- package/runtime/dist/src/realtime/service.js +93 -7
- package/runtime/dist/src/realtime/session.js +39 -32
- package/runtime/dist/src/realtime/sglang-native.js +214 -0
- package/runtime/dist/src/realtime/system-prompts.en.js +14 -2
- package/runtime/dist/src/realtime/telemetry.js +6 -3
- package/runtime/dist/src/realtime/tool-continuations.js +84 -7
- package/runtime/dist/src/realtime/transport.js +17 -0
- package/runtime/dist/src/realtime/usage.js +33 -17
- package/runtime/dist/src/realtime/volcengine/ark.js +40 -15
- package/runtime/dist/src/realtime/volcengine/asr.js +2 -1
- package/runtime/dist/src/realtime/volcengine/silence-endpointing.js +1 -7
- package/runtime/dist/src/realtime/volcengine/tts.js +2 -1
- package/runtime/dist/src/server/aoq-chat-server.js +1 -1
- package/runtime/dist/src/server/client-server.js +21 -0
- package/runtime/dist/src/server-entry.js +3 -0
- package/runtime/dist/src/space-host/admin-socket.js +115 -0
- package/runtime/dist/src/space-host/audio-owner.js +44 -0
- package/runtime/dist/src/space-host/cli.js +195 -0
- package/runtime/dist/src/space-host/config.js +247 -0
- package/runtime/dist/src/space-host/context-input.js +12 -0
- package/runtime/dist/src/space-host/contracts.js +10 -0
- package/runtime/dist/src/space-host/host-admin.js +114 -0
- package/runtime/dist/src/space-host/key-delivery.js +28 -0
- package/runtime/dist/src/space-host/mobile-tools.js +9 -0
- package/runtime/dist/src/space-host/model-settings.js +213 -0
- package/runtime/dist/src/space-host/projection.js +37 -0
- package/runtime/dist/src/space-host/push.js +137 -0
- package/runtime/dist/src/space-host/relay-transport.js +55 -0
- package/runtime/dist/src/space-host/service.js +841 -0
- package/runtime/dist/src/space-host/voice-crypto.js +240 -0
- package/runtime/dist/src/space-host/voice.js +600 -0
- package/runtime/dist/src/space-host/windows-secret-key.js +82 -0
- package/runtime/dist/src/storage/private-database.js +7 -10
- package/runtime/dist/src/text/unicode-normalize.js +5 -1
- package/runtime/dist/src/understanding/candidates.js +8 -10
- package/runtime/dist/src/understanding/fixture.js +1 -1
- package/runtime/dist/src/understanding/pipeline.js +4 -4
- package/runtime/dist/src/usage/context.js +23 -0
- package/runtime/dist/src/usage/index.js +4 -0
- package/runtime/dist/src/usage/ledger-worker.js +90 -0
- package/runtime/dist/src/usage/ledger.js +74 -0
- package/runtime/dist/src/usage/model-call.js +63 -0
- package/runtime/dist/src/usage/pricing.js +68 -0
- package/runtime/dist/src/usage/summary.js +69 -0
- package/runtime/dist/src/voicemem/store-client.js +104 -21
- package/runtime/dist/src/voicemem/store-worker.js +5 -8
- package/runtime/dist/src/voicemem/versioned-memory.js +1 -1
- package/src/command.mjs +8 -1
- package/runtime/dist/src/executors/autoglm.js +0 -376
|
@@ -0,0 +1,1006 @@
|
|
|
1
|
+
import { emptyContextDependencies, mergeContextDependencies } from './context-dependencies.js';
|
|
2
|
+
import { memoryHostToolNames } from './conversation-tool-bridge.js';
|
|
3
|
+
import { abortable } from '../core/camera-session.js';
|
|
4
|
+
import { computerApplicationSchema } from './computer-use/contract.js';
|
|
5
|
+
import { randomUUID } from 'node:crypto';
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
import { mergeTurnText } from '../realtime/cascaded/llm.js';
|
|
8
|
+
import { LOCAL_TOOLS, executeLocalTool, isLocalTool, localPathEscapesProject, localToolArguments, projectResourceKey } from './local-tools.js';
|
|
9
|
+
import { acquireTaskResources, taskResourcesBusy, taskResourcesUncertain, quarantineTaskResources, releaseQuarantinedTaskResources } from '../executors/task-resources.js';
|
|
10
|
+
import { localShellTreeState } from './local-shell.js';
|
|
11
|
+
import { approvalClasses, classDenied, commandLine, stepPhrase, workbenchCopy, DENIED_MESSAGE, DENIED_BEFORE_MESSAGE, SKIPPED_MESSAGE, DENIED_RESUME_INSTRUCTION } from './workbench-copy.js';
|
|
12
|
+
import { MAX_WORKBENCH_THOUGHTS, MAX_WORKBENCH_THOUGHT_CODEPOINTS } from './workbench-store.js';
|
|
13
|
+
import { computerTools } from './computer-use/tools.js';
|
|
14
|
+
import { computerUseSkill } from './computer-use/skill.js';
|
|
15
|
+
import { isComputerTool, computerToolArguments, COMPUTER_VISION_REQUIRED_MESSAGE, COMPUTER_WRITE_TOOLS } from './computer-use/contract.js';
|
|
16
|
+
const publishArguments = z.object({ title: z.string().min(1).max(120), content: z.string().min(1).max(131072) }).strict();
|
|
17
|
+
const publishTool = { name: 'publish_plan', description: 'Publish the complete detailed plan for the user to review and choose local Build or executor Build. This does not authorize or start execution. Call again to publish an amended version.', parameters: { type: 'object', properties: { title: { type: 'string', minLength: 1, maxLength: 120 }, content: { type: 'string', minLength: 1, maxLength: 131072 } }, required: ['title', 'content'], additionalProperties: false } };
|
|
18
|
+
const finishArguments = z.object({ summary: z.string().min(1).max(12000) }).strict();
|
|
19
|
+
const finishTool = { name: 'finish_build', description: 'End this Build conversation after the confirmed work and verification are complete. Provide the final user-facing summary. This permanently locks the conversation; use only when no further Build interaction is needed.', parameters: { type: 'object', properties: { summary: { type: 'string', minLength: 1, maxLength: 12000 } }, required: ['summary'], additionalProperties: false } };
|
|
20
|
+
function withoutPendingMemory(inputs) {
|
|
21
|
+
return inputs.filter(input => {
|
|
22
|
+
if (input.kind !== 'host_context')
|
|
23
|
+
return true;
|
|
24
|
+
try {
|
|
25
|
+
return JSON.parse(input.content)?.purpose !== 'possible_memory';
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return true;
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
const RESUME_CHECK = 'Resume the Build goal. Inspect actual state before continuing any cancelled, timed-out or unknown operation. Never replay a completed call.';
|
|
33
|
+
export async function createWorkbenchRuntime(options) {
|
|
34
|
+
const { conversation, host } = options, build = conversation.kind === 'build', store = host.workbench;
|
|
35
|
+
const reasoningMode = options.reasoning === true ? 'enabled' : 'disabled';
|
|
36
|
+
const approvalMode = () => typeof options.approval === 'function' ? options.approval() : options.approval;
|
|
37
|
+
const turnToolLimit = build ? 128 : 24;
|
|
38
|
+
const copy = workbenchCopy(options.language);
|
|
39
|
+
const roundLimitReply = () => copy.roundLimit(build, state.calls.filter(call => call.state === 'completed').length, turnToolLimit);
|
|
40
|
+
if (build && (!conversation.build || !['darwin', 'win32'].includes(process.platform)))
|
|
41
|
+
throw Error('local_build_unavailable');
|
|
42
|
+
const state = await store.checkpoint(conversation.id, conversation.generation);
|
|
43
|
+
const confirmedPlan = build && !state.confirmed_plan_omitted && conversation.build?.plan_id && conversation.build.plan_version ? await store.plan(conversation.build.plan_id, conversation.build.plan_version) : undefined;
|
|
44
|
+
const suppliedDependencies = mergeContextDependencies(host.conversationContextDependencies(conversation), confirmedPlan ? await host.planContextDependencies(confirmedPlan) : undefined);
|
|
45
|
+
let previousDependencies = state.context_dependencies;
|
|
46
|
+
if (previousDependencies === undefined && (state.model !== null || state.inputs.length)) {
|
|
47
|
+
previousDependencies = host.retainedConversationDependencies(conversation.id, conversation.generation);
|
|
48
|
+
const matchedUser = conversation.messages.some(message => message.role === 'user' && message.text === state.last_user);
|
|
49
|
+
const containsText = (value) => typeof value === 'string' || Array.isArray(value) && value.some(containsText) || value !== null && typeof value === 'object' && Object.values(value).some(containsText);
|
|
50
|
+
const model = state.model;
|
|
51
|
+
const knownModel = model === null || !containsText(model) || !Array.isArray(model) && typeof model === 'object' && model.protocol === 'chat-completions' && Array.isArray(model.history) && model.history.every(unit => Array.isArray(unit) && unit.every(message => message !== null && typeof message === 'object' && !Array.isArray(message) && typeof message.content === 'string' && conversation.messages.some(prior => prior.role === message.role && prior.text === message.content)));
|
|
52
|
+
if (state.model !== null && (!matchedUser || !knownModel))
|
|
53
|
+
previousDependencies = { state: 'unavailable' };
|
|
54
|
+
}
|
|
55
|
+
state.context_dependencies = mergeContextDependencies(previousDependencies ?? emptyContextDependencies(), suppliedDependencies);
|
|
56
|
+
const emit = (frame) => options.emit({ ...frame, ...(frame.role === 'assistant' ? { context_dependencies: state.context_dependencies } : {}) });
|
|
57
|
+
const authorizeContext = async (parent) => {
|
|
58
|
+
parent.throwIfAborted();
|
|
59
|
+
if (state.context_dependencies?.state === 'tracked' && !state.context_dependencies.items.length)
|
|
60
|
+
return;
|
|
61
|
+
const signal = AbortSignal.any([parent, AbortSignal.timeout(5000)]);
|
|
62
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
63
|
+
signal.throwIfAborted();
|
|
64
|
+
const before = await abortable(host.contextAuthorizationRevision(signal), signal);
|
|
65
|
+
if (!await abortable(host.contextDependenciesAuthorized(state.context_dependencies, options.contextConsumer ?? null), signal))
|
|
66
|
+
throw Error('context_authorization_changed');
|
|
67
|
+
const after = await abortable(host.contextAuthorizationRevision(signal), signal);
|
|
68
|
+
signal.throwIfAborted();
|
|
69
|
+
if (before === after)
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
throw Error('context_authorization_changed');
|
|
73
|
+
};
|
|
74
|
+
state.inputs = withoutPendingMemory(state.inputs);
|
|
75
|
+
const workspaceContext = () => build ? JSON.stringify({ ...(confirmedPlan && !state.confirmed_plan_omitted ? { confirmed_plan: { id: confirmedPlan.id, version: confirmedPlan.version, title: confirmedPlan.title, content: confirmedPlan.content } } : {}), project: conversation.build.project }) : null;
|
|
76
|
+
let session, bridgeRuntime;
|
|
77
|
+
let closed = false, controller, active, version = state.run_version;
|
|
78
|
+
let computer;
|
|
79
|
+
let currentComputerCall, connectedApp;
|
|
80
|
+
const deniedByUser = new Map();
|
|
81
|
+
let computerInputStarted = false;
|
|
82
|
+
let observeRequired = true;
|
|
83
|
+
let coordinateObservationRequired = true;
|
|
84
|
+
let verificationRequired = false;
|
|
85
|
+
for (const call of state.calls) {
|
|
86
|
+
if (call.name.startsWith('computer_') && call.started_at && call.name !== 'computer_screenshot')
|
|
87
|
+
verificationRequired = true;
|
|
88
|
+
if (call.name === 'computer_screenshot' && call.result?.image_ref)
|
|
89
|
+
verificationRequired = false;
|
|
90
|
+
}
|
|
91
|
+
if (state.reason === 'cleanup_unknown')
|
|
92
|
+
verificationRequired = true;
|
|
93
|
+
const computerState = () => build ? host.computerUseState(conversation.id) : { enabled: false, direct: false };
|
|
94
|
+
let computerVisible = false;
|
|
95
|
+
const computerFrame = (state, action, point) => {
|
|
96
|
+
if (state === 'idle' && !computerVisible)
|
|
97
|
+
return;
|
|
98
|
+
computerVisible = state !== 'idle';
|
|
99
|
+
emit({ type: 'computer_use', conversation_id: conversation.id, state, ...(action ? { action } : {}), ...(point ? { point } : {}) });
|
|
100
|
+
};
|
|
101
|
+
const closeComputer = async () => { const previous = computer; computer = undefined; observeRequired = true; try {
|
|
102
|
+
await previous?.close();
|
|
103
|
+
}
|
|
104
|
+
finally {
|
|
105
|
+
computerFrame('idle');
|
|
106
|
+
} };
|
|
107
|
+
let approval;
|
|
108
|
+
const model = () => { if (!session) {
|
|
109
|
+
session = options.factory.open();
|
|
110
|
+
session.setHistoryLimits?.({ items: 2048, codepoints: 16 * 1024 * 1024 });
|
|
111
|
+
if (state.model !== null) {
|
|
112
|
+
if (!session.restoreCheckpoint)
|
|
113
|
+
throw Error('model_checkpoint_unsupported');
|
|
114
|
+
session.restoreCheckpoint(state.model);
|
|
115
|
+
}
|
|
116
|
+
else
|
|
117
|
+
session.checkpoint?.();
|
|
118
|
+
} return session; };
|
|
119
|
+
const bridge = async () => { bridgeRuntime ??= await options.createBridge(); if (!bridgeRuntime.toolBridge)
|
|
120
|
+
throw Error('conversation_tools_unavailable'); return bridgeRuntime.toolBridge; };
|
|
121
|
+
let saving = Promise.resolve(), reasonDetail = null;
|
|
122
|
+
const save = () => {
|
|
123
|
+
state.updated_at = new Date().toISOString();
|
|
124
|
+
const checkpoint = structuredClone(state), pendingApproval = approval ? { id: approval.id, call_id: approval.call.id, name: approval.call.name, preview: JSON.stringify(approval.call.arguments, null, 2).slice(0, 1800) } : null;
|
|
125
|
+
// Retrieved context is one-shot: never persist it for retries or process recovery.
|
|
126
|
+
checkpoint.inputs = withoutPendingMemory(checkpoint.inputs);
|
|
127
|
+
const operation = saving.then(async () => { await store.saveCheckpoint(checkpoint); if (build)
|
|
128
|
+
await host.updateLocalBuild(conversation.id, conversation.generation, { status: checkpoint.status, reason: checkpoint.reason, reason_detail: checkpoint.reason ? reasonDetail : null, approval: pendingApproval }); });
|
|
129
|
+
saving = operation.catch(() => { });
|
|
130
|
+
return operation;
|
|
131
|
+
};
|
|
132
|
+
const treeState = (owner) => options.shell?.processState?.(owner) ?? localShellTreeState(owner);
|
|
133
|
+
// In-flight receipts from an earlier process are facts, never permission to retry.
|
|
134
|
+
if (['running', 'awaiting_approval'].includes(state.status)) {
|
|
135
|
+
for (const call of state.pending_calls)
|
|
136
|
+
if (call.state !== 'completed') {
|
|
137
|
+
call.result = call.state === 'running' ? { status: 'outcome_unknown', ...(call.name === 'shell_execute' ? { cleanup_confirmed: !call.process || treeState(call.process) === 'gone' } : {}), message: 'The previous process stopped during this operation. Inspect actual state before continuing.' } : { status: 'cancelled_before_execution' };
|
|
138
|
+
call.state = 'completed';
|
|
139
|
+
delete call.approval_id;
|
|
140
|
+
}
|
|
141
|
+
state.status = state.pending_calls.some(call => call.result?.status === 'outcome_unknown') ? 'outcome_unknown' : 'paused';
|
|
142
|
+
state.reason = 'restart_requires_resume';
|
|
143
|
+
await save();
|
|
144
|
+
}
|
|
145
|
+
async function ask(call, signal, preview) {
|
|
146
|
+
const id = randomUUID();
|
|
147
|
+
call.approval_id = id;
|
|
148
|
+
call.state = 'awaiting_approval';
|
|
149
|
+
state.status = 'awaiting_approval';
|
|
150
|
+
let resolve;
|
|
151
|
+
const promise = new Promise(done => { resolve = done; });
|
|
152
|
+
approval = { id, call: preview ? { ...call, ...preview } : call, resolve };
|
|
153
|
+
await save();
|
|
154
|
+
const cancel = () => resolve(false);
|
|
155
|
+
signal.addEventListener('abort', cancel, { once: true });
|
|
156
|
+
try {
|
|
157
|
+
if (signal.aborted)
|
|
158
|
+
return false;
|
|
159
|
+
return await promise;
|
|
160
|
+
}
|
|
161
|
+
finally {
|
|
162
|
+
signal.removeEventListener('abort', cancel);
|
|
163
|
+
approval = undefined;
|
|
164
|
+
delete call.approval_id;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
async function run(text, parent, context) {
|
|
168
|
+
if (closed || active)
|
|
169
|
+
throw Error('conversation_busy');
|
|
170
|
+
if (build && state.status === 'finished')
|
|
171
|
+
throw Error('build_finished');
|
|
172
|
+
if (build && !host.localBuildAuthorized(conversation.id))
|
|
173
|
+
throw Error('local_build_not_authorized');
|
|
174
|
+
const own = new AbortController();
|
|
175
|
+
controller = own;
|
|
176
|
+
const signal = AbortSignal.any([parent, own.signal, options.lifetime]), runVersion = ++version;
|
|
177
|
+
state.run_version = runVersion;
|
|
178
|
+
const execute = async () => {
|
|
179
|
+
let release;
|
|
180
|
+
// A shell command can exit while a child it started lives on; that holds the project, not the whole Build.
|
|
181
|
+
const leftovers = () => state.calls.filter(call => call.name === 'shell_execute' && call.result?.cleanup_confirmed === false);
|
|
182
|
+
// No process identity or no tree evidence (Windows) is 'unknown': never proof of cleanup, only the user's acknowledgement releases it.
|
|
183
|
+
const leftoverState = (call) => call.process ? treeState(call.process) : 'unknown';
|
|
184
|
+
const blockingLeftover = () => leftovers().find(call => leftoverState(call) !== 'gone');
|
|
185
|
+
const releaseProject = () => { const key = projectResourceKey(conversation.build.project); if (taskResourcesUncertain([key]))
|
|
186
|
+
releaseQuarantinedTaskResources([key]); };
|
|
187
|
+
const settleLeftovers = () => {
|
|
188
|
+
const all = leftovers();
|
|
189
|
+
if (!all.length || blockingLeftover())
|
|
190
|
+
return;
|
|
191
|
+
for (const call of all)
|
|
192
|
+
call.result = { ...call.result, cleanup_confirmed: true };
|
|
193
|
+
releaseProject();
|
|
194
|
+
};
|
|
195
|
+
// Resume on a "cannot verify" pause is the user's acknowledgement. Leftovers that are provably alive stay blocking.
|
|
196
|
+
const acknowledgeLeftovers = () => {
|
|
197
|
+
const unknown = leftovers().filter(call => leftoverState(call) === 'unknown');
|
|
198
|
+
if (!unknown.length)
|
|
199
|
+
return;
|
|
200
|
+
for (const call of unknown)
|
|
201
|
+
call.result = { ...call.result, cleanup_confirmed: true, cleanup_acknowledged: true, cleanup_acknowledged_at: new Date().toISOString() };
|
|
202
|
+
if (!blockingLeftover())
|
|
203
|
+
releaseProject();
|
|
204
|
+
};
|
|
205
|
+
let holding;
|
|
206
|
+
const holdProject = async () => {
|
|
207
|
+
if (release)
|
|
208
|
+
return;
|
|
209
|
+
holding ??= (async () => { const key = projectResourceKey(conversation.build.project); if (taskResourcesBusy([key]))
|
|
210
|
+
throw Error('project_busy'); release = await acquireTaskResources([key], signal); })().finally(() => { holding = undefined; });
|
|
211
|
+
await holding;
|
|
212
|
+
};
|
|
213
|
+
const leftoverCopy = (call) => {
|
|
214
|
+
const command = commandLine(call), exit = call.result?.exit_code ?? 0;
|
|
215
|
+
if (leftoverState(call) === 'unknown')
|
|
216
|
+
return { text: copy.unverifiable(command), detail: copy.unverifiableShort(command) };
|
|
217
|
+
return { text: copy.leftover(command, exit), detail: copy.leftoverShort(command) };
|
|
218
|
+
};
|
|
219
|
+
try {
|
|
220
|
+
reasonDetail = null;
|
|
221
|
+
state.context_dependencies = mergeContextDependencies(state.context_dependencies, host.referenceContextDependencies(context?.references ?? []));
|
|
222
|
+
await authorizeContext(signal);
|
|
223
|
+
if (build) {
|
|
224
|
+
if (context?.resume && state.reason === 'cleanup_unconfirmed')
|
|
225
|
+
acknowledgeLeftovers();
|
|
226
|
+
settleLeftovers();
|
|
227
|
+
if (!blockingLeftover())
|
|
228
|
+
await holdProject();
|
|
229
|
+
}
|
|
230
|
+
state.inputs = withoutPendingMemory(state.inputs);
|
|
231
|
+
const toolBridge = await bridge();
|
|
232
|
+
if (!state.model && !state.inputs.length) {
|
|
233
|
+
if (build)
|
|
234
|
+
state.inputs.push({ kind: 'host_context', content: workspaceContext() });
|
|
235
|
+
else
|
|
236
|
+
for (const message of conversation.messages.filter(message => message.generation_status !== 'pending' && message.input_mode !== 'voice').slice(-32))
|
|
237
|
+
state.inputs.push({ kind: 'host_context', content: JSON.stringify({ previous_message: { role: message.role, text: message.text } }) });
|
|
238
|
+
}
|
|
239
|
+
const voiceMessages = conversation.messages.filter(message => message.input_mode === 'voice');
|
|
240
|
+
for (const message of voiceMessages)
|
|
241
|
+
if (!state.voice_message_ids?.includes(message.id))
|
|
242
|
+
state.inputs.push({ kind: 'host_context', content: JSON.stringify({ previous_message: { role: message.role, text: message.text }, source: 'voice', trust: 'untrusted_external' }) });
|
|
243
|
+
state.voice_message_ids = voiceMessages.map(message => message.id);
|
|
244
|
+
if (!context?.resume) {
|
|
245
|
+
// Only typed user input can authorize explicit writes, never any host/tool/voice context.
|
|
246
|
+
state.last_user = text;
|
|
247
|
+
state.denied_classes = [];
|
|
248
|
+
let injected = false;
|
|
249
|
+
if (toolBridge.prerecall) {
|
|
250
|
+
const budget = AbortSignal.any([signal, AbortSignal.timeout(400)]);
|
|
251
|
+
try {
|
|
252
|
+
const prepared = await abortable(toolBridge.prerecall(text, budget), budget);
|
|
253
|
+
const memory = prepared ? await abortable(prepared(budget), budget) : null;
|
|
254
|
+
budget.throwIfAborted();
|
|
255
|
+
if (memory) {
|
|
256
|
+
state.inputs.push({ kind: 'host_context', content: JSON.stringify({ purpose: 'possible_memory', trust: 'untrusted_external', text: memory }) });
|
|
257
|
+
injected = true;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
catch { /* Retrieval is optional; failure or timeout must not block the turn. */ }
|
|
261
|
+
}
|
|
262
|
+
options.telemetry?.record('workbench.memory.injected', { injected });
|
|
263
|
+
signal.throwIfAborted();
|
|
264
|
+
state.inputs.push({ kind: 'user_text', text });
|
|
265
|
+
}
|
|
266
|
+
// Resume is a control action: it never invents a user turn in the provider conversation.
|
|
267
|
+
else if (!state.inputs.length && !state.pending_calls.length)
|
|
268
|
+
state.inputs.push({ kind: 'host_context', content: JSON.stringify({ purpose: 'resume_control', instruction: RESUME_CHECK }) });
|
|
269
|
+
if (context?.resume && state.reason === 'approval_denied') {
|
|
270
|
+
const declined = state.pending_calls.filter(call => ['denied', 'denied_previously'].includes(call.result?.status ?? '')).map(call => stepPhrase(call, 'en'));
|
|
271
|
+
state.inputs.push({ kind: 'host_context', content: JSON.stringify({ purpose: 'denial_resume', declined, instruction: DENIED_RESUME_INSTRUCTION }) });
|
|
272
|
+
}
|
|
273
|
+
state.status = 'running';
|
|
274
|
+
state.reason = null;
|
|
275
|
+
state.assistant = '';
|
|
276
|
+
delete state.model_failure;
|
|
277
|
+
await save();
|
|
278
|
+
const baseTools = build ? [...toolBridge.tools.filter(tool => tool.name !== 'dispatch'), ...LOCAL_TOOLS, finishTool] : [...toolBridge.tools.filter(tool => toolBridge.readonlyNames.includes(tool.name) || memoryHostToolNames.has(tool.name)), publishTool];
|
|
279
|
+
const authorizedTools = [...baseTools, ...(build ? computerTools(true) : [])];
|
|
280
|
+
const allowed = new Set(authorizedTools.map(tool => tool.name));
|
|
281
|
+
if (allowed.size !== authorizedTools.length || authorizedTools.length > 128)
|
|
282
|
+
throw Error('workbench_tool_configuration');
|
|
283
|
+
let toolRounds = 0, finishedReply, denials = 0, batchDenied = false, unknownCall, leftoverCall;
|
|
284
|
+
const deniedSteps = [];
|
|
285
|
+
// A denial covers its whole class for this turn and its resumes; a new typed message may ask again.
|
|
286
|
+
const deniedClasses = new Set(context?.resume ? state.denied_classes ?? [] : []);
|
|
287
|
+
const recordDenial = (call, classes, previously, preview) => {
|
|
288
|
+
// `shell:*` only marks "could not analyse"; it is remembered when nothing more specific is known.
|
|
289
|
+
for (const klass of classes.length > 1 ? classes.filter(item => item !== 'shell:*') : classes)
|
|
290
|
+
deniedClasses.add(klass);
|
|
291
|
+
state.denied_classes = [...deniedClasses].slice(-256).map(item => item.slice(0, 1000));
|
|
292
|
+
denials++;
|
|
293
|
+
batchDenied = true;
|
|
294
|
+
deniedSteps.push(stepPhrase(preview ? { ...call, ...preview } : call, options.language));
|
|
295
|
+
return { status: previously ? 'denied_previously' : 'denied', message: previously ? DENIED_BEFORE_MESSAGE : DENIED_MESSAGE, approval_classes: classes.slice(0, 16) };
|
|
296
|
+
};
|
|
297
|
+
// Keep one turn identity across model rounds. Build commits tool-bound text before
|
|
298
|
+
// the tool batch, while Plan keeps the accumulated answer.
|
|
299
|
+
const turn = randomUUID();
|
|
300
|
+
let turnText = '', outputLimitContinues = 0, toolTruncationRetried = false;
|
|
301
|
+
const compactCaption = (text, limit = 4000) => { const points = [...text]; return points.length > limit ? points.slice(0, limit).join('') + '…' : text; };
|
|
302
|
+
const emitTurnCaption = (roundText) => {
|
|
303
|
+
const visible = compactCaption(mergeTurnText(turnText, roundText));
|
|
304
|
+
emit({ type: 'caption', role: 'assistant', text: visible, full_text: visible, turn_id: turn, final: false });
|
|
305
|
+
};
|
|
306
|
+
while (true) {
|
|
307
|
+
signal.throwIfAborted();
|
|
308
|
+
if (version !== runVersion)
|
|
309
|
+
throw Error('build_stale');
|
|
310
|
+
const executeCall = async (call) => {
|
|
311
|
+
signal.throwIfAborted();
|
|
312
|
+
const wasCompleted = call.state === 'completed';
|
|
313
|
+
if (!wasCompleted && toolRounds >= turnToolLimit)
|
|
314
|
+
return;
|
|
315
|
+
if (call.state !== 'completed') {
|
|
316
|
+
toolRounds++;
|
|
317
|
+
if (isComputerTool(call.name) && !computerState().enabled) {
|
|
318
|
+
call.result = { code: 'computer_use_disabled', message: '在 Build 会话里打开 Computer Use 后才能操作电脑' };
|
|
319
|
+
call.state = 'completed';
|
|
320
|
+
}
|
|
321
|
+
else if (isComputerTool(call.name) && !computerState().direct) {
|
|
322
|
+
call.result = { code: 'vision_model_required', message: COMPUTER_VISION_REQUIRED_MESSAGE };
|
|
323
|
+
call.state = 'completed';
|
|
324
|
+
}
|
|
325
|
+
else if (!allowed.has(call.name)) {
|
|
326
|
+
call.result = { code: 'tool_not_authorized', state: 'refused' };
|
|
327
|
+
call.state = 'completed';
|
|
328
|
+
}
|
|
329
|
+
else if (isComputerTool(call.name)) {
|
|
330
|
+
const name = call.name, validation = computerToolArguments[name].safeParse(call.arguments);
|
|
331
|
+
if (!validation.success) {
|
|
332
|
+
call.result = { code: 'invalid_params' };
|
|
333
|
+
call.state = 'completed';
|
|
334
|
+
}
|
|
335
|
+
else if ((observeRequired && COMPUTER_WRITE_TOOLS.includes(name)) || (coordinateObservationRequired && (name === 'computer_click' || name === 'computer_scroll'))) {
|
|
336
|
+
call.result = { code: 'observe_required' };
|
|
337
|
+
call.state = 'completed';
|
|
338
|
+
}
|
|
339
|
+
else {
|
|
340
|
+
if (!host.localBuildAuthorized(conversation.id))
|
|
341
|
+
throw Error('local_build_not_authorized');
|
|
342
|
+
call.state = 'running';
|
|
343
|
+
call.started_at = new Date().toISOString();
|
|
344
|
+
state.status = 'running';
|
|
345
|
+
await save();
|
|
346
|
+
currentComputerCall = call;
|
|
347
|
+
computerInputStarted = false;
|
|
348
|
+
const getComputer = async () => {
|
|
349
|
+
if (computer)
|
|
350
|
+
return computer;
|
|
351
|
+
const Session = options.computerSession ? undefined : (await import('./computer-use/session.js')).ComputerSession;
|
|
352
|
+
const create = options.computerSession ?? ((settings) => new Session(settings));
|
|
353
|
+
let applicationAuthorized = false;
|
|
354
|
+
computer = create({
|
|
355
|
+
signal, approve: async (action, params) => {
|
|
356
|
+
// 自动批准 (never) covers the connection consent too; ask mode keeps per-application consent.
|
|
357
|
+
if (approvalMode() === 'never' || (action !== 'Connect' && applicationAuthorized))
|
|
358
|
+
return !signal.aborted && computerState().enabled && host.localBuildAuthorized(conversation.id);
|
|
359
|
+
const app = action === 'Connect' ? computerApplicationSchema.safeParse(params?.application) : undefined;
|
|
360
|
+
if (app?.success && await store.computerApplicationAllowed(app.data)) {
|
|
361
|
+
applicationAuthorized = true;
|
|
362
|
+
connectedApp = app.data.bundleId;
|
|
363
|
+
return !signal.aborted && computerState().enabled && host.localBuildAuthorized(conversation.id);
|
|
364
|
+
}
|
|
365
|
+
const current = currentComputerCall;
|
|
366
|
+
const preview = { name: action === 'Connect' ? 'computer_connect' : current.name, arguments: { action, params: JSON.parse(JSON.stringify(params)) } }, klass = app?.success ? 'computer:' + app.data.bundleId : 'computer-input:' + (connectedApp ?? '');
|
|
367
|
+
if (classDenied([klass], deniedClasses) && !signal.aborted) {
|
|
368
|
+
deniedByUser.set(current, recordDenial(current, [klass], true, preview));
|
|
369
|
+
return false;
|
|
370
|
+
}
|
|
371
|
+
const approved = await ask(current, signal, preview);
|
|
372
|
+
if (approved && app?.success) {
|
|
373
|
+
applicationAuthorized = true;
|
|
374
|
+
connectedApp = app.data.bundleId;
|
|
375
|
+
}
|
|
376
|
+
if (!approved && !signal.aborted)
|
|
377
|
+
deniedByUser.set(current, recordDenial(current, [klass], false, preview));
|
|
378
|
+
state.status = 'running';
|
|
379
|
+
current.state = 'running';
|
|
380
|
+
await save();
|
|
381
|
+
return approved && computerState().enabled && host.localBuildAuthorized(conversation.id);
|
|
382
|
+
}, acting: (action, point) => { signal.throwIfAborted(); if (!computerState().enabled || !host.localBuildAuthorized(conversation.id))
|
|
383
|
+
throw Error('computer_use_disabled'); computerInputStarted = true; computerFrame('acting', action, point); },
|
|
384
|
+
});
|
|
385
|
+
return computer;
|
|
386
|
+
};
|
|
387
|
+
const capture = async (application) => {
|
|
388
|
+
computerFrame('active', name);
|
|
389
|
+
const { image, ...observation } = await (await getComputer()).observe(application);
|
|
390
|
+
const ref = await store.saveImage(conversation.id, conversation.generation, image);
|
|
391
|
+
observeRequired = false;
|
|
392
|
+
coordinateObservationRequired = false;
|
|
393
|
+
return { image_ref: ref, ...observation, untrusted_application_data: ['ax.summary', 'ax.editor'] };
|
|
394
|
+
};
|
|
395
|
+
try {
|
|
396
|
+
signal.throwIfAborted();
|
|
397
|
+
if (!computerState().enabled)
|
|
398
|
+
throw Error('computer_use_disabled');
|
|
399
|
+
if (name === 'computer_screenshot') {
|
|
400
|
+
call.result = await capture('application' in validation.data ? validation.data.application : undefined);
|
|
401
|
+
verificationRequired = false;
|
|
402
|
+
}
|
|
403
|
+
else {
|
|
404
|
+
verificationRequired = true;
|
|
405
|
+
const receipt = await (await getComputer()).action(name, call.arguments);
|
|
406
|
+
observeRequired = true;
|
|
407
|
+
coordinateObservationRequired = true;
|
|
408
|
+
call.result = { status: 'completed', verified: false, ...receipt };
|
|
409
|
+
computerFrame('active', name);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
catch (error) {
|
|
413
|
+
let code = error instanceof Error ? error.message : 'action_failed', cleanupConfirmed = true;
|
|
414
|
+
try {
|
|
415
|
+
await closeComputer();
|
|
416
|
+
}
|
|
417
|
+
catch {
|
|
418
|
+
code = 'cleanup_unknown';
|
|
419
|
+
cleanupConfirmed = false;
|
|
420
|
+
}
|
|
421
|
+
let cause = error, detail;
|
|
422
|
+
for (let depth = 0; depth < 4 && cause instanceof Error; depth++) {
|
|
423
|
+
if (/^native_gui:[a-z_]{1,80}$/u.test(cause.message))
|
|
424
|
+
detail = cause.message;
|
|
425
|
+
else if (!detail && cause.message.startsWith('worker:'))
|
|
426
|
+
detail = cause.message.slice(0, 300);
|
|
427
|
+
cause = cause.cause;
|
|
428
|
+
}
|
|
429
|
+
// The worker tree is confirmed gone, so nothing can still act: report the unverified input and let the model re-observe.
|
|
430
|
+
if (code === 'cleanup_unknown' && cleanupConfirmed && !signal.aborted)
|
|
431
|
+
code = 'outcome_unverified';
|
|
432
|
+
call.result = deniedByUser.get(call) ?? { code, ...(detail ? { detail } : {}), ...(code === 'outcome_unverified' ? { verified: false, message: 'This input may or may not have taken effect. Take a fresh computer_screenshot and check before acting again; do not repeat it blindly.' } : {}), status: code === 'cleanup_unknown' || (signal.aborted && computerInputStarted) ? 'outcome_unknown' : signal.aborted ? 'cancelled_before_execution' : 'failed' };
|
|
433
|
+
observeRequired = true;
|
|
434
|
+
}
|
|
435
|
+
call.state = 'completed';
|
|
436
|
+
call.finished_at = new Date().toISOString();
|
|
437
|
+
await save();
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
else if (isLocalTool(call.name)) {
|
|
441
|
+
if (!build)
|
|
442
|
+
throw Error('local_tools_not_authorized');
|
|
443
|
+
const validation = localToolArguments[call.name].safeParse(call.arguments);
|
|
444
|
+
if (!validation.success) {
|
|
445
|
+
call.result = { code: 'invalid_params', issues: validation.error.issues.map(issue => ({ path: issue.path.map(String).join('.'), message: issue.message })) };
|
|
446
|
+
call.state = 'completed';
|
|
447
|
+
}
|
|
448
|
+
else {
|
|
449
|
+
if (!host.localBuildAuthorized(conversation.id))
|
|
450
|
+
throw Error('local_build_not_authorized');
|
|
451
|
+
if (build) {
|
|
452
|
+
settleLeftovers();
|
|
453
|
+
const stuck = blockingLeftover();
|
|
454
|
+
if (stuck) {
|
|
455
|
+
leftoverCall = stuck;
|
|
456
|
+
state.reason = 'cleanup_unconfirmed';
|
|
457
|
+
toolRounds--;
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
await holdProject();
|
|
461
|
+
}
|
|
462
|
+
// Reads inside the project stay free; a read that leaves it needs the same consent as a write.
|
|
463
|
+
const needsApproval = approvalMode() === 'ask' && (call.name !== 'file_read' || await localPathEscapesProject(conversation.build.project, validation.data.path).catch(() => true));
|
|
464
|
+
const klasses = needsApproval ? approvalClasses(call, conversation.build.project) : [];
|
|
465
|
+
if (needsApproval && classDenied(klasses, deniedClasses)) {
|
|
466
|
+
call.result = recordDenial(call, klasses, true);
|
|
467
|
+
call.state = 'completed';
|
|
468
|
+
await save();
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
if (needsApproval && !await ask(call, signal)) {
|
|
472
|
+
if (signal.aborted) {
|
|
473
|
+
call.result = { status: 'denied', message: 'This call was not executed. Wait for new user instructions.' };
|
|
474
|
+
call.state = 'completed';
|
|
475
|
+
state.reason = 'stopped';
|
|
476
|
+
await save();
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
call.result = recordDenial(call, klasses, false);
|
|
480
|
+
call.state = 'completed';
|
|
481
|
+
await save();
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
signal.throwIfAborted();
|
|
485
|
+
if (!host.localBuildAuthorized(conversation.id))
|
|
486
|
+
throw Error('local_build_not_authorized');
|
|
487
|
+
state.status = 'running';
|
|
488
|
+
call.state = 'running';
|
|
489
|
+
call.started_at = new Date().toISOString();
|
|
490
|
+
await save(); // intent must reach disk first
|
|
491
|
+
if (signal.aborted || !host.localBuildAuthorized(conversation.id)) {
|
|
492
|
+
call.result = { status: 'cancelled_before_execution' };
|
|
493
|
+
call.state = 'completed';
|
|
494
|
+
call.finished_at = new Date().toISOString();
|
|
495
|
+
signal.throwIfAborted();
|
|
496
|
+
throw Error('local_build_not_authorized');
|
|
497
|
+
}
|
|
498
|
+
try {
|
|
499
|
+
call.result = await executeLocalTool(call.name, call.arguments, conversation.build.project, signal, { ...options.shell, onStarted: async (owner) => { call.process = owner; await save(); await options.shell?.onStarted?.(owner); } });
|
|
500
|
+
}
|
|
501
|
+
catch (error) {
|
|
502
|
+
call.result = { status: signal.aborted ? 'outcome_unknown' : 'failed', code: error instanceof Error ? error.message : 'tool_failed' };
|
|
503
|
+
}
|
|
504
|
+
call.state = 'completed';
|
|
505
|
+
call.finished_at = new Date().toISOString();
|
|
506
|
+
await save();
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
else if (call.name === 'finish_build') {
|
|
510
|
+
const q = finishArguments.safeParse(call.arguments);
|
|
511
|
+
if (!build || !q.success) {
|
|
512
|
+
call.result = { code: 'invalid_params', state: 'refused' };
|
|
513
|
+
call.state = 'completed';
|
|
514
|
+
}
|
|
515
|
+
else if (verificationRequired) {
|
|
516
|
+
call.result = { code: 'verification_required' };
|
|
517
|
+
call.state = 'completed';
|
|
518
|
+
}
|
|
519
|
+
else {
|
|
520
|
+
call.state = 'running';
|
|
521
|
+
call.started_at = new Date().toISOString();
|
|
522
|
+
await save();
|
|
523
|
+
signal.throwIfAborted();
|
|
524
|
+
await closeComputer();
|
|
525
|
+
signal.throwIfAborted();
|
|
526
|
+
if (!host.localBuildAuthorized(conversation.id))
|
|
527
|
+
throw Error('local_build_not_authorized');
|
|
528
|
+
const finished = await host.finishLocalBuild(conversation.id, conversation.generation, context?.user_message_id);
|
|
529
|
+
call.result = { finished, ...(!finished ? { reason: 'new_user_input_received' } : {}) };
|
|
530
|
+
call.state = 'completed';
|
|
531
|
+
call.finished_at = new Date().toISOString();
|
|
532
|
+
if (finished) {
|
|
533
|
+
state.status = 'finished';
|
|
534
|
+
state.reason = null;
|
|
535
|
+
finishedReply = q.data.summary;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
await save();
|
|
539
|
+
}
|
|
540
|
+
else if (call.name === 'publish_plan') {
|
|
541
|
+
const q = publishArguments.safeParse(call.arguments);
|
|
542
|
+
if (!q.success) {
|
|
543
|
+
call.result = { code: 'invalid_params', issues: q.error.issues.map(issue => ({ path: issue.path.map(String).join('.'), message: issue.message })) };
|
|
544
|
+
call.state = 'completed';
|
|
545
|
+
}
|
|
546
|
+
else {
|
|
547
|
+
call.state = 'running';
|
|
548
|
+
call.started_at = new Date().toISOString();
|
|
549
|
+
await save();
|
|
550
|
+
signal.throwIfAborted();
|
|
551
|
+
const plan = await host.publishPlan(conversation.id, conversation.generation, q.data.title, q.data.content, call.id, state.context_dependencies);
|
|
552
|
+
call.result = { published: true, id: plan.id, version: plan.version, title: plan.title };
|
|
553
|
+
call.state = 'completed';
|
|
554
|
+
call.finished_at = new Date().toISOString();
|
|
555
|
+
}
|
|
556
|
+
await save();
|
|
557
|
+
}
|
|
558
|
+
else {
|
|
559
|
+
call.state = 'running';
|
|
560
|
+
call.started_at = new Date().toISOString();
|
|
561
|
+
await save();
|
|
562
|
+
try {
|
|
563
|
+
call.result = await toolBridge.invoke(state.last_user, call, signal);
|
|
564
|
+
}
|
|
565
|
+
catch (error) {
|
|
566
|
+
call.result = { status: signal.aborted ? 'outcome_unknown' : 'failed', code: error instanceof Error ? error.message : 'tool_failed' };
|
|
567
|
+
}
|
|
568
|
+
call.state = 'completed';
|
|
569
|
+
call.finished_at = new Date().toISOString();
|
|
570
|
+
await save();
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
if (!wasCompleted) {
|
|
574
|
+
const result = call.result;
|
|
575
|
+
if (build && call.name === 'shell_execute' && result?.cleanup_confirmed === false) {
|
|
576
|
+
quarantineTaskResources([projectResourceKey(conversation.build.project)]);
|
|
577
|
+
release = undefined;
|
|
578
|
+
// The command itself finished: report its real result and hold the project instead of stopping the Build.
|
|
579
|
+
if (typeof result.exit_code === 'number')
|
|
580
|
+
call.result = { ...call.result, message: 'The command exited, but some child processes could not be confirmed stopped. The host holds this project and verifies before the next local operation; continue with work that does not touch the project.' };
|
|
581
|
+
}
|
|
582
|
+
if (result?.status === 'outcome_unknown') {
|
|
583
|
+
state.reason = 'outcome_unknown';
|
|
584
|
+
unknownCall = call;
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
};
|
|
588
|
+
// The approval slot is single; a read that must ask therefore runs alone like a write.
|
|
589
|
+
const askingReads = new Set();
|
|
590
|
+
if (build && approvalMode() === 'ask')
|
|
591
|
+
for (const call of state.pending_calls)
|
|
592
|
+
if (call.name === 'file_read' && call.state !== 'completed') {
|
|
593
|
+
const q = localToolArguments.file_read.safeParse(call.arguments);
|
|
594
|
+
if (!q.success || await localPathEscapesProject(conversation.build.project, q.data.path).catch(() => true))
|
|
595
|
+
askingReads.add(call.id);
|
|
596
|
+
}
|
|
597
|
+
const concurrent = (call) => allowed.has(call.name) && (call.name === 'file_read' && !askingReads.has(call.id) || toolBridge.readonlyNames.includes(call.name));
|
|
598
|
+
for (let index = 0; index < state.pending_calls.length;) {
|
|
599
|
+
const call = state.pending_calls[index];
|
|
600
|
+
if (call.state === 'completed') {
|
|
601
|
+
index++;
|
|
602
|
+
continue;
|
|
603
|
+
}
|
|
604
|
+
if (toolRounds >= turnToolLimit)
|
|
605
|
+
break;
|
|
606
|
+
if (concurrent(call)) {
|
|
607
|
+
const group = [], capacity = Math.min(4, turnToolLimit - toolRounds);
|
|
608
|
+
while (index < state.pending_calls.length && group.length < capacity) {
|
|
609
|
+
const next = state.pending_calls[index];
|
|
610
|
+
if (next.state === 'completed') {
|
|
611
|
+
index++;
|
|
612
|
+
continue;
|
|
613
|
+
}
|
|
614
|
+
if (!concurrent(next))
|
|
615
|
+
break;
|
|
616
|
+
group.push(next);
|
|
617
|
+
index++;
|
|
618
|
+
}
|
|
619
|
+
// Settle every read before cancellation/recovery can change their durable state.
|
|
620
|
+
const results = await Promise.allSettled(group.map(executeCall)), failure = results.find(result => result.status === 'rejected');
|
|
621
|
+
if (failure?.status === 'rejected')
|
|
622
|
+
throw failure.reason;
|
|
623
|
+
}
|
|
624
|
+
else {
|
|
625
|
+
await executeCall(call);
|
|
626
|
+
index++;
|
|
627
|
+
}
|
|
628
|
+
if (batchDenied) {
|
|
629
|
+
batchDenied = false;
|
|
630
|
+
for (const rest of state.pending_calls)
|
|
631
|
+
if (rest.state !== 'completed') {
|
|
632
|
+
rest.result = { status: 'cancelled_before_execution', message: SKIPPED_MESSAGE };
|
|
633
|
+
rest.state = 'completed';
|
|
634
|
+
}
|
|
635
|
+
if (denials >= 2 && !state.reason)
|
|
636
|
+
state.reason = 'approval_denied';
|
|
637
|
+
await save();
|
|
638
|
+
break;
|
|
639
|
+
}
|
|
640
|
+
if (state.reason)
|
|
641
|
+
break;
|
|
642
|
+
if (finishedReply !== undefined)
|
|
643
|
+
break;
|
|
644
|
+
}
|
|
645
|
+
if (state.reason) {
|
|
646
|
+
// A leftover-process pause keeps its call prepared: Resume verifies first, then runs it once.
|
|
647
|
+
if (state.reason !== 'cleanup_unconfirmed')
|
|
648
|
+
for (const call of state.pending_calls)
|
|
649
|
+
if (call.state === 'prepared') {
|
|
650
|
+
call.result = { status: 'cancelled_before_execution' };
|
|
651
|
+
call.state = 'completed';
|
|
652
|
+
}
|
|
653
|
+
let assistant = copy.generic;
|
|
654
|
+
if (state.reason === 'approval_denied') {
|
|
655
|
+
assistant = copy.denied(deniedSteps);
|
|
656
|
+
reasonDetail = copy.deniedShort(deniedSteps);
|
|
657
|
+
}
|
|
658
|
+
else if (state.reason === 'stopped') {
|
|
659
|
+
const user = signal.reason === 'user_stop';
|
|
660
|
+
assistant = user ? copy.stopped(build) : copy.pausedNeutral(build);
|
|
661
|
+
reasonDetail = user ? copy.stoppedShort : copy.pausedShort;
|
|
662
|
+
}
|
|
663
|
+
else if (state.reason === 'cleanup_unconfirmed' && leftoverCall) {
|
|
664
|
+
const note = leftoverCopy(leftoverCall);
|
|
665
|
+
assistant = note.text;
|
|
666
|
+
reasonDetail = note.detail;
|
|
667
|
+
}
|
|
668
|
+
else if (state.reason === 'outcome_unknown') {
|
|
669
|
+
const step = unknownCall ? stepPhrase(unknownCall, options.language) : options.language === 'en' ? 'the last operation' : '上一步操作';
|
|
670
|
+
assistant = copy.unknown(step);
|
|
671
|
+
reasonDetail = copy.unknownShort(step);
|
|
672
|
+
}
|
|
673
|
+
state.status = state.reason === 'outcome_unknown' ? 'outcome_unknown' : 'paused';
|
|
674
|
+
await save();
|
|
675
|
+
return { assistant };
|
|
676
|
+
}
|
|
677
|
+
if (finishedReply !== undefined) {
|
|
678
|
+
for (const call of state.pending_calls)
|
|
679
|
+
if (call.state !== 'completed') {
|
|
680
|
+
call.result = { status: 'cancelled_after_finish' };
|
|
681
|
+
call.state = 'completed';
|
|
682
|
+
}
|
|
683
|
+
state.status = 'finished';
|
|
684
|
+
await save();
|
|
685
|
+
return { assistant: finishedReply, turn_id: randomUUID() };
|
|
686
|
+
}
|
|
687
|
+
if (state.pending_calls.some(call => call.state !== 'completed')) {
|
|
688
|
+
state.status = 'paused';
|
|
689
|
+
state.reason = 'round_limit';
|
|
690
|
+
reasonDetail = build ? copy.roundLimitShort(state.calls.filter(call => call.state === 'completed').length) : null;
|
|
691
|
+
await save();
|
|
692
|
+
return { assistant: roundLimitReply() };
|
|
693
|
+
}
|
|
694
|
+
if (state.pending_calls.length) {
|
|
695
|
+
const uncertain = state.pending_calls.some(call => ['outcome_unknown', 'timed_out', 'cancelled'].includes(call.result?.status ?? ''));
|
|
696
|
+
state.inputs.unshift(...await Promise.all(state.pending_calls.map(async (call) => {
|
|
697
|
+
const ref = isComputerTool(call.name) ? call.result?.image_ref : undefined;
|
|
698
|
+
const images = ref && computerState().direct ? [await store.loadImage(conversation.id, conversation.generation, ref)] : undefined;
|
|
699
|
+
return { kind: 'tool_result', call_id: call.id, output: call.result ?? { status: 'outcome_unknown' }, ...(images ? { images } : {}) };
|
|
700
|
+
})));
|
|
701
|
+
if (uncertain)
|
|
702
|
+
state.inputs.push({ kind: 'host_context', content: RESUME_CHECK });
|
|
703
|
+
state.pending_calls = [];
|
|
704
|
+
await save();
|
|
705
|
+
}
|
|
706
|
+
if (toolRounds >= turnToolLimit) {
|
|
707
|
+
state.status = 'paused';
|
|
708
|
+
state.reason = 'round_limit';
|
|
709
|
+
reasonDetail = build ? copy.roundLimitShort(state.calls.filter(call => call.state === 'completed').length) : null;
|
|
710
|
+
await save();
|
|
711
|
+
return { assistant: roundLimitReply() };
|
|
712
|
+
}
|
|
713
|
+
const enabled = computerState(), tools = [...baseTools, ...(enabled.enabled ? computerTools(enabled.direct) : [])];
|
|
714
|
+
try {
|
|
715
|
+
await authorizeContext(signal);
|
|
716
|
+
}
|
|
717
|
+
catch (error) {
|
|
718
|
+
signal.throwIfAborted();
|
|
719
|
+
if (!build || !(error instanceof Error) || (error.message !== 'context_authorization_changed' && error.name !== 'TimeoutError'))
|
|
720
|
+
throw error;
|
|
721
|
+
// Keep local receipts, but start a fresh model session without withdrawn inputs or tool output.
|
|
722
|
+
await session?.close();
|
|
723
|
+
session = undefined;
|
|
724
|
+
state.model = null;
|
|
725
|
+
state.context_dependencies = emptyContextDependencies();
|
|
726
|
+
if (confirmedPlan)
|
|
727
|
+
state.confirmed_plan_omitted = true;
|
|
728
|
+
const completed = state.calls.filter(call => call.state === 'completed' && allowed.has(call.name)).slice(-32).map(call => call.name);
|
|
729
|
+
state.inputs = [
|
|
730
|
+
{ kind: 'user_text', text: state.last_user },
|
|
731
|
+
{ kind: 'host_context', content: JSON.stringify({ purpose: 'resume_without_previous_context', completed_tools: completed, instruction: 'Some prior reference material is unavailable. Continue the authorized work with current inputs. Inspect actual project state before acting and do not repeat completed operations. If the goal depended on unavailable material, complete independent work and explain what is missing.' }) },
|
|
732
|
+
];
|
|
733
|
+
turnText = options.language === 'en' ? 'Some reference material is unavailable. Continuing with the available context.' : '部分引用资料已不可用,继续使用现有资料执行。';
|
|
734
|
+
state.assistant = turnText;
|
|
735
|
+
await save();
|
|
736
|
+
emitTurnCaption('');
|
|
737
|
+
}
|
|
738
|
+
const workspace = workspaceContext();
|
|
739
|
+
const llm = model(), before = state.model, inputs = structuredClone(state.inputs), calls = [];
|
|
740
|
+
let assistant = '', preview = '', captionSent = false, completed = false;
|
|
741
|
+
// Only this attempt may consume the freshly authorized context, including on output-limit retries.
|
|
742
|
+
state.inputs = withoutPendingMemory(state.inputs);
|
|
743
|
+
// One bounded thought per model round; display-only, never model input or history.
|
|
744
|
+
let thinkingChunks = [], thinkingCodepoints = 0, thinkingStartedAt = null;
|
|
745
|
+
const addThinking = (text) => {
|
|
746
|
+
const left = MAX_WORKBENCH_THOUGHT_CODEPOINTS - thinkingCodepoints;
|
|
747
|
+
if (left <= 0 || text === '')
|
|
748
|
+
return;
|
|
749
|
+
// The thought belongs before the tool calls it produces, so keep the
|
|
750
|
+
// timestamp of its first delta instead of the round's completion time.
|
|
751
|
+
thinkingStartedAt ??= new Date().toISOString();
|
|
752
|
+
const points = [...text];
|
|
753
|
+
thinkingChunks.push(points.length <= left ? text : points.slice(0, left).join(''));
|
|
754
|
+
thinkingCodepoints += Math.min(points.length, left);
|
|
755
|
+
};
|
|
756
|
+
const recordThinking = () => {
|
|
757
|
+
if (!thinkingChunks.length)
|
|
758
|
+
return;
|
|
759
|
+
const text = thinkingChunks.join(''), created_at = thinkingStartedAt ?? new Date().toISOString();
|
|
760
|
+
thinkingChunks = [];
|
|
761
|
+
thinkingCodepoints = 0;
|
|
762
|
+
thinkingStartedAt = null;
|
|
763
|
+
const thoughts = state.thoughts ?? [];
|
|
764
|
+
thoughts.push({ id: randomUUID(), text, created_at, ...(context?.user_message_id ? { message_id: context.user_message_id } : {}) });
|
|
765
|
+
state.thoughts = thoughts.slice(-MAX_WORKBENCH_THOUGHTS);
|
|
766
|
+
};
|
|
767
|
+
try {
|
|
768
|
+
for await (const event of llm.stream({ language: options.language, previewText: true, reasoning: reasoningMode, inputs, tools, workspaceContext: enabled.enabled ? [workspace, computerUseSkill(enabled.direct)].filter(Boolean).join('\n') : workspace, signal })) {
|
|
769
|
+
if (event.kind === 'reasoning_delta') {
|
|
770
|
+
addThinking(event.text);
|
|
771
|
+
signal.throwIfAborted();
|
|
772
|
+
if (version !== runVersion)
|
|
773
|
+
throw Error('build_stale');
|
|
774
|
+
continue;
|
|
775
|
+
}
|
|
776
|
+
signal.throwIfAborted();
|
|
777
|
+
if (version !== runVersion)
|
|
778
|
+
throw Error('build_stale');
|
|
779
|
+
if (event.kind === 'text_preview' || event.kind === 'text_delta') {
|
|
780
|
+
if (event.kind === 'text_preview') {
|
|
781
|
+
const points = [...preview + event.text];
|
|
782
|
+
preview = points.length > 16000 ? points.slice(0, 16000).join('') : points.join('');
|
|
783
|
+
}
|
|
784
|
+
else {
|
|
785
|
+
assistant += event.text;
|
|
786
|
+
preview = '';
|
|
787
|
+
}
|
|
788
|
+
// Keep progress frames compact from the head: the opening paragraph must not scroll out
|
|
789
|
+
// of the live caption before the durable reply replaces it.
|
|
790
|
+
captionSent = true;
|
|
791
|
+
emitTurnCaption(assistant + preview);
|
|
792
|
+
}
|
|
793
|
+
else if (event.kind === 'tool_call') {
|
|
794
|
+
// Narration before a tool call is the opening of this turn's answer, not display-only
|
|
795
|
+
// speculation: commit it as authoritative and keep it across the tool round.
|
|
796
|
+
if (preview) {
|
|
797
|
+
assistant = mergeTurnText(assistant, preview);
|
|
798
|
+
preview = '';
|
|
799
|
+
}
|
|
800
|
+
if (calls.some(call => call.id === event.call_id))
|
|
801
|
+
throw Error('duplicate_tool_call');
|
|
802
|
+
calls.push({ id: event.call_id, name: event.name, arguments: structuredClone(event.arguments), state: 'prepared', created_at: new Date().toISOString(), ...(context?.user_message_id ? { message_id: context.user_message_id } : {}) });
|
|
803
|
+
}
|
|
804
|
+
else if (event.kind === 'response_completed')
|
|
805
|
+
completed = true;
|
|
806
|
+
else if (event.kind === 'response_failed') {
|
|
807
|
+
const code = /^[a-z_]{1,64}$/u.test(event.code) ? event.code : 'unknown', detail = event.detail && /^[a-z_]{1,64}$/u.test(event.detail) ? event.detail : undefined, count = event.tool_call_count;
|
|
808
|
+
state.model_failure = { code, ...(detail ? { detail } : {}), ...(typeof count === 'number' && Number.isSafeInteger(count) && count >= 0 && count <= 128 ? { tool_call_count: count } : {}) };
|
|
809
|
+
throw Error('model_' + code + (detail ? '_' + detail : ''));
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
if (!completed)
|
|
813
|
+
throw Error('model_response_incomplete');
|
|
814
|
+
if (preview) {
|
|
815
|
+
assistant = mergeTurnText(assistant, preview);
|
|
816
|
+
preview = '';
|
|
817
|
+
}
|
|
818
|
+
recordThinking();
|
|
819
|
+
if (!llm.checkpoint)
|
|
820
|
+
throw Error('model_checkpoint_unsupported');
|
|
821
|
+
state.model = llm.checkpoint();
|
|
822
|
+
state.inputs = [];
|
|
823
|
+
delete state.model_failure;
|
|
824
|
+
const roundText = mergeTurnText(turnText, assistant);
|
|
825
|
+
const narratedCall = build && roundText.trim() ? calls.find(call => !state.calls.some(previous => previous.id === call.id)) : undefined;
|
|
826
|
+
if (narratedCall)
|
|
827
|
+
narratedCall.narration = compactCaption(roundText, 16000);
|
|
828
|
+
turnText = narratedCall ? '' : roundText;
|
|
829
|
+
if (turnText.length > 16000)
|
|
830
|
+
await store.saveReply(conversation.id, conversation.generation, turn, turnText);
|
|
831
|
+
state.assistant = turnText.slice(0, 16000);
|
|
832
|
+
for (const call of calls) {
|
|
833
|
+
const prior = state.calls.find(item => item.id === call.id);
|
|
834
|
+
if (prior) {
|
|
835
|
+
if (prior.name !== call.name || JSON.stringify(prior.arguments) !== JSON.stringify(call.arguments))
|
|
836
|
+
throw Error('tool_call_id_conflict');
|
|
837
|
+
state.pending_calls.push(prior);
|
|
838
|
+
}
|
|
839
|
+
else {
|
|
840
|
+
state.calls.push(call);
|
|
841
|
+
state.pending_calls.push(call);
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
await save();
|
|
845
|
+
if (narratedCall)
|
|
846
|
+
emit({ type: 'caption', role: 'assistant', text: '', full_text: '', turn_id: turn, final: true });
|
|
847
|
+
}
|
|
848
|
+
catch (error) {
|
|
849
|
+
recordThinking();
|
|
850
|
+
const reason = error instanceof Error ? error.message : '';
|
|
851
|
+
// An output-limit failure is respendable: the provider stopped at its ceiling without a
|
|
852
|
+
// protocol error. Continue text turns at most twice; retry a truncated tool call once with
|
|
853
|
+
// an instruction to split the payload, and never execute the truncated call itself.
|
|
854
|
+
const outputLimit = reason === 'model_output_limit' || reason.startsWith('model_output_limit_');
|
|
855
|
+
if (outputLimit && version === runVersion && !signal.aborted) {
|
|
856
|
+
state.model = before;
|
|
857
|
+
await session?.close();
|
|
858
|
+
session = undefined;
|
|
859
|
+
// Keep the text that did arrive before the ceiling: the continuation extends it.
|
|
860
|
+
turnText = mergeTurnText(turnText, assistant);
|
|
861
|
+
state.assistant = turnText.slice(0, 16000);
|
|
862
|
+
const truncatedTool = reason.endsWith('_tool_arguments'), partial = assistant.slice(-4000), en = options.language === 'en';
|
|
863
|
+
if (!truncatedTool && outputLimitContinues < 2) {
|
|
864
|
+
outputLimitContinues += 1;
|
|
865
|
+
state.inputs.push({ kind: 'host_context', content: JSON.stringify({ purpose: 'output_limit_continuation', attempt: outputLimitContinues, previous_partial: partial, instruction: en ? 'The previous reply was cut off by the model output limit before it finished. Continue the same answer from where it stopped without repeating text the user already saw, and finish the requested work in this turn.' : '上一轮回复因模型输出长度上限在完成前被截断。请从截断处继续同一段回答,不要重复用户已经看到的内容,并在本轮完成用户要求的全部工作。' }) });
|
|
866
|
+
delete state.model_failure;
|
|
867
|
+
await save();
|
|
868
|
+
continue;
|
|
869
|
+
}
|
|
870
|
+
if (truncatedTool && !toolTruncationRetried) {
|
|
871
|
+
toolTruncationRetried = true;
|
|
872
|
+
state.inputs.push({ kind: 'host_context', content: JSON.stringify({ purpose: 'output_limit_tool_split', attempt: 1, previous_partial: partial, instruction: en ? 'The previous tool call was cut off by the model output limit and was NOT executed. Do not send one oversized call: split the payload into several smaller sequential calls (for example one file or one section per call) and never repeat a call that already completed.' : '上一轮工具调用因输出长度上限被截断,且没有被执行。不要再次发送一个超大的调用:请把内容拆成多个较小的串行调用(例如每次只写一个文件或一个段落),不要重复已经完成的调用。' }) });
|
|
873
|
+
delete state.model_failure;
|
|
874
|
+
await save();
|
|
875
|
+
continue;
|
|
876
|
+
}
|
|
877
|
+
state.status = 'paused';
|
|
878
|
+
state.reason = 'model_output_limit';
|
|
879
|
+
const modeLabel = build ? 'Build' : 'Plan', limitLabel = truncatedTool
|
|
880
|
+
? (en ? 'the tool call exceeded the model output limit and was not executed' : `工具调用超出模型输出长度上限,未执行`)
|
|
881
|
+
: (en ? 'the model reply exceeded its output limit' : '模型回复超出输出长度上限');
|
|
882
|
+
const continuation = copy.outputLimitContinue(build);
|
|
883
|
+
const notice = en ? `${modeLabel} paused: ${limitLabel}. ${continuation}` : `${modeLabel} 已暂停:${limitLabel}。${continuation}`;
|
|
884
|
+
const fullReply = mergeTurnText(turnText, notice);
|
|
885
|
+
if (fullReply.length > 16000)
|
|
886
|
+
await store.saveReply(conversation.id, conversation.generation, turn, fullReply);
|
|
887
|
+
const visible = fullReply.length > 16000 ? turnText.slice(0, 16000 - notice.length - 2) + '\n\n' + notice : fullReply;
|
|
888
|
+
state.assistant = visible;
|
|
889
|
+
reasonDetail = build ? limitLabel.charAt(0).toUpperCase() + limitLabel.slice(1) : null;
|
|
890
|
+
await save();
|
|
891
|
+
return { assistant: visible, ...(fullReply.length > 16000 ? { full_text_ref: true } : {}), turn_id: turn };
|
|
892
|
+
}
|
|
893
|
+
if (captionSent && version === runVersion)
|
|
894
|
+
emit({ type: 'caption', role: 'assistant', text: '', full_text: '', turn_id: turn, final: true });
|
|
895
|
+
state.model = before;
|
|
896
|
+
await session?.close();
|
|
897
|
+
session = undefined;
|
|
898
|
+
if (error instanceof Error && 'code' in error && typeof error.code === 'string') {
|
|
899
|
+
const detail = 'detail' in error && typeof error.detail === 'string' && /^[a-z_]{1,64}$/u.test(error.detail) ? '_' + error.detail : '';
|
|
900
|
+
throw Error('model_' + error.code + detail, { cause: error });
|
|
901
|
+
}
|
|
902
|
+
throw error;
|
|
903
|
+
}
|
|
904
|
+
if (!calls.length) {
|
|
905
|
+
state.status = 'completed';
|
|
906
|
+
state.reason = null;
|
|
907
|
+
await save();
|
|
908
|
+
return { assistant: turnText, turn_id: turn };
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
catch (error) {
|
|
913
|
+
if (error instanceof Error && error.message === 'context_authorization_changed') {
|
|
914
|
+
if (state.status !== 'outcome_unknown')
|
|
915
|
+
state.status = 'paused';
|
|
916
|
+
state.reason = 'context_authorization_changed';
|
|
917
|
+
await save();
|
|
918
|
+
throw error;
|
|
919
|
+
}
|
|
920
|
+
for (const call of state.pending_calls)
|
|
921
|
+
if (call.state !== 'completed') {
|
|
922
|
+
call.result = { status: call.state === 'running' ? 'outcome_unknown' : 'cancelled_before_execution' };
|
|
923
|
+
call.state = 'completed';
|
|
924
|
+
delete call.approval_id;
|
|
925
|
+
}
|
|
926
|
+
approval = undefined;
|
|
927
|
+
const reason = error instanceof Error ? error.message : 'build_failed', modelInterrupted = build && reason.startsWith('model_');
|
|
928
|
+
if (/^model_[a-z_]{1,96}$/u.test(reason))
|
|
929
|
+
options.onDiagnostic?.('[workbench-diagnostic] ' + JSON.stringify({ mode: build ? 'build' : 'plan', conversation_id: conversation.id, generation: conversation.generation, reason, ...(state.model_failure ? { model_failure: state.model_failure } : {}) }));
|
|
930
|
+
if (reason === 'cleanup_unknown')
|
|
931
|
+
verificationRequired = true;
|
|
932
|
+
state.status = reason === 'cleanup_unknown' ? 'outcome_unknown' : signal.aborted || modelInterrupted ? 'paused' : 'failed';
|
|
933
|
+
state.reason = signal.aborted ? 'stopped' : reason;
|
|
934
|
+
const user = signal.reason === 'user_stop';
|
|
935
|
+
if (signal.aborted)
|
|
936
|
+
reasonDetail = user ? copy.stoppedShort : copy.pausedShort;
|
|
937
|
+
await save();
|
|
938
|
+
if (signal.aborted)
|
|
939
|
+
return { assistant: user ? copy.stopped(build) : copy.pausedNeutral(build) };
|
|
940
|
+
if (modelInterrupted) {
|
|
941
|
+
const label = options.language === 'en' ? { model_timeout: 'The model stopped returning data', model_overflow: 'The model response exceeded the stream capacity', model_http: 'The model service returned an error', model_network: 'The model connection was interrupted', model_output_limit: 'The model reply exceeded its output limit', model_output_limit_tool_arguments: 'The tool call exceeded the model output limit and was not executed', model_protocol_output_limit: 'The model reply exceeded its output limit' }[reason] ?? 'The model response was interrupted' : { model_timeout: '模型等待数据超时', model_overflow: '模型回复超出流容量限制', model_http: '模型服务返回错误', model_network: '模型连接中断', model_output_limit: '模型回复超出输出长度上限', model_output_limit_tool_arguments: '工具调用超出模型输出长度上限,未执行', model_protocol_output_limit: '模型回复超出输出长度上限' }[reason] ?? '模型回复中断';
|
|
942
|
+
reasonDetail = label;
|
|
943
|
+
await save();
|
|
944
|
+
return { assistant: copy.modelPaused(label) };
|
|
945
|
+
}
|
|
946
|
+
throw error;
|
|
947
|
+
}
|
|
948
|
+
finally {
|
|
949
|
+
try {
|
|
950
|
+
await closeComputer();
|
|
951
|
+
}
|
|
952
|
+
catch (error) {
|
|
953
|
+
verificationRequired = true;
|
|
954
|
+
state.status = 'outcome_unknown';
|
|
955
|
+
state.reason = 'cleanup_unknown';
|
|
956
|
+
const last = state.calls.findLast(call => isComputerTool(call.name) && call.started_at);
|
|
957
|
+
if (last)
|
|
958
|
+
last.result = { ...(last.result && typeof last.result === 'object' && !Array.isArray(last.result) ? last.result : {}), status: 'outcome_unknown', code: 'cleanup_unknown' };
|
|
959
|
+
await save();
|
|
960
|
+
throw error;
|
|
961
|
+
}
|
|
962
|
+
finally {
|
|
963
|
+
release?.();
|
|
964
|
+
controller = undefined;
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
};
|
|
968
|
+
const operation = execute();
|
|
969
|
+
active = operation;
|
|
970
|
+
try {
|
|
971
|
+
return { ...await operation, context_dependencies: state.context_dependencies };
|
|
972
|
+
}
|
|
973
|
+
finally {
|
|
974
|
+
if (active === operation)
|
|
975
|
+
active = undefined;
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
return {
|
|
979
|
+
runTurn: run, canSwitch: () => !active,
|
|
980
|
+
stopBuild: async () => { controller?.abort('user_stop'); approval?.resolve(false); await active; },
|
|
981
|
+
localApproval: async (id, approved, always) => {
|
|
982
|
+
if (approval?.id !== id || !active || controller?.signal.aborted)
|
|
983
|
+
throw Error('local_approval_stale');
|
|
984
|
+
const current = approval;
|
|
985
|
+
if (always) {
|
|
986
|
+
if (!approved || current.call.name !== 'computer_connect')
|
|
987
|
+
throw Error('invalid_application_consent');
|
|
988
|
+
const params = current.call.arguments.params;
|
|
989
|
+
await store.allowComputerApplication(computerApplicationSchema.parse(params?.application));
|
|
990
|
+
}
|
|
991
|
+
if (approval !== current || controller?.signal.aborted)
|
|
992
|
+
throw Error('local_approval_stale');
|
|
993
|
+
approval = undefined;
|
|
994
|
+
current.resolve(approved);
|
|
995
|
+
},
|
|
996
|
+
close: async () => { if (closed)
|
|
997
|
+
return; closed = true; controller?.abort(); approval?.resolve(false); await active; await session?.close(); await bridgeRuntime?.close(); },
|
|
998
|
+
approvalDecision: async (id, approved) => { if (!bridgeRuntime?.approvalDecision)
|
|
999
|
+
throw Error('approval_unavailable'); await bridgeRuntime.approvalDecision(id, approved); },
|
|
1000
|
+
retainTasks: () => bridgeRuntime?.retainTasks?.() ?? false,
|
|
1001
|
+
ownsWork: id => bridgeRuntime?.ownsWork?.(id) ?? false,
|
|
1002
|
+
confirmationDecision: async (id, confirmed) => { if (!bridgeRuntime?.confirmationDecision)
|
|
1003
|
+
throw Error('confirmation_unavailable'); await bridgeRuntime.confirmationDecision(id, confirmed); },
|
|
1004
|
+
};
|
|
1005
|
+
}
|
|
1006
|
+
//# sourceMappingURL=workbench-runtime.js.map
|