@minionry/minion 0.7.36
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 +14 -0
- package/PRIVACY.md +357 -0
- package/README.md +57 -0
- package/THIRD_PARTY_NOTICES.md +245 -0
- package/bin/branding.js +4 -0
- package/bin/commands/browser-install.js +483 -0
- package/bin/commands/create-sandbox.js +542 -0
- package/bin/commands/fingerprint.js +101 -0
- package/bin/commands/login.js +400 -0
- package/bin/commands/logout.js +93 -0
- package/bin/commands/minions.js +211 -0
- package/bin/commands/sandboxes.js +309 -0
- package/bin/commands/status.js +298 -0
- package/bin/commands/whoami.js +153 -0
- package/bin/launch-env.js +35 -0
- package/bin/machine-identity.js +221 -0
- package/bin/machine-layout.js +200 -0
- package/bin/minion.js +839 -0
- package/bin/platform-endpoints.js +8 -0
- package/bin/postinstall.js +52 -0
- package/bin/pty-doctor.js +326 -0
- package/bin/pty-locator.js +110 -0
- package/bin/pty-provision.js +186 -0
- package/bin/sandbox/Dockerfile +78 -0
- package/bin/sandbox/entrypoint.sh +14 -0
- package/bin/sandbox/install-repo.sh +53 -0
- package/bin/sandbox/seccomp-userns.json +883 -0
- package/bin/sandbox-config.js +306 -0
- package/dist/bin/machine-identity.js +221 -0
- package/dist/bin/machine-layout.js +200 -0
- package/dist/electron-host/agent-lease.js +141 -0
- package/dist/electron-host/dom-driver.js +642 -0
- package/dist/electron-host/ipc-protocol.js +89 -0
- package/dist/electron-host/js-driver.js +216 -0
- package/dist/electron-host/view-manager.js +254 -0
- package/dist/server/cli/engine-resume.js +49 -0
- package/dist/server/cli/eta-estimator.js +278 -0
- package/dist/server/cli/headless/background-activity.js +109 -0
- package/dist/server/cli/headless/claude-invoker-process.js +614 -0
- package/dist/server/cli/headless/claude-invoker-stall.js +150 -0
- package/dist/server/cli/headless/claude-invoker-stream.js +555 -0
- package/dist/server/cli/headless/claude-invoker-tools.js +148 -0
- package/dist/server/cli/headless/claude-invoker.js +151 -0
- package/dist/server/cli/headless/engine-availability.js +92 -0
- package/dist/server/cli/headless/engine-notice.js +185 -0
- package/dist/server/cli/headless/haiku-assessments.js +293 -0
- package/dist/server/cli/headless/headless-logger.js +75 -0
- package/dist/server/cli/headless/index.js +9 -0
- package/dist/server/cli/headless/mcp-config.js +314 -0
- package/dist/server/cli/headless/native-timeout-detector.js +72 -0
- package/dist/server/cli/headless/output-utils.js +71 -0
- package/dist/server/cli/headless/prompt-utils.js +82 -0
- package/dist/server/cli/headless/resilient-runner.js +326 -0
- package/dist/server/cli/headless/retry-strategies.js +292 -0
- package/dist/server/cli/headless/runner.js +245 -0
- package/dist/server/cli/headless/stall-assessor.js +295 -0
- package/dist/server/cli/headless/tool-watchdog.js +447 -0
- package/dist/server/cli/headless/types.js +18 -0
- package/dist/server/cli/history-portability.js +85 -0
- package/dist/server/cli/improvisation-attachments.js +99 -0
- package/dist/server/cli/improvisation-history-store.js +121 -0
- package/dist/server/cli/improvisation-movements.js +137 -0
- package/dist/server/cli/improvisation-output-queue.js +34 -0
- package/dist/server/cli/improvisation-retry.js +8 -0
- package/dist/server/cli/improvisation-session-manager.js +1016 -0
- package/dist/server/cli/improvisation-types.js +31 -0
- package/dist/server/cli/plan-lifecycle.js +72 -0
- package/dist/server/cli/prompt-builders.js +371 -0
- package/dist/server/cli/retry/retry-best-result.js +28 -0
- package/dist/server/cli/retry/retry-context-loss.js +75 -0
- package/dist/server/cli/retry/retry-recovery-strategies.js +213 -0
- package/dist/server/cli/retry/retry-resume-strategy.js +20 -0
- package/dist/server/cli/retry/retry-runner-factory.js +92 -0
- package/dist/server/cli/retry/retry-tool-results.js +22 -0
- package/dist/server/cli/retry/retry-types.js +3 -0
- package/dist/server/engines/EngineEvent.js +57 -0
- package/dist/server/engines/claude/ClaudeCodeEngine.js +316 -0
- package/dist/server/engines/claude/claude-command.js +32 -0
- package/dist/server/engines/codex/CodexEngine.js +469 -0
- package/dist/server/engines/codex/codex-auth.js +203 -0
- package/dist/server/engines/codex/codex-invoker.js +205 -0
- package/dist/server/engines/codex/codex-provision.js +215 -0
- package/dist/server/engines/credentials/credential-probe.js +88 -0
- package/dist/server/engines/credentials/model-profiles.js +249 -0
- package/dist/server/engines/credentials/provider-credentials.js +146 -0
- package/dist/server/engines/engine-event-stream.js +52 -0
- package/dist/server/engines/execution/engine-session.js +380 -0
- package/dist/server/engines/factory.js +42 -0
- package/dist/server/engines/hermes/HermesEngine.js +628 -0
- package/dist/server/engines/hermes/hermes-auth.js +159 -0
- package/dist/server/engines/hermes/hermes-gateway-home.js +271 -0
- package/dist/server/engines/hermes/hermes-invoker.js +350 -0
- package/dist/server/engines/hermes/hermes-provision.js +318 -0
- package/dist/server/engines/read-only.js +20 -0
- package/dist/server/engines/types.js +27 -0
- package/dist/server/handlers/company-execution-registry.js +67 -0
- package/dist/server/handlers/company-handlers.js +514 -0
- package/dist/server/handlers/company-triggers.js +189 -0
- package/dist/server/handlers/company-types.js +3 -0
- package/dist/server/index.js +244 -0
- package/dist/server/mcp/app-tools-bridge.js +110 -0
- package/dist/server/mcp/app-tools-mcp-server.js +99 -0
- package/dist/server/mcp/bouncer-integration.js +744 -0
- package/dist/server/mcp/browser-mcp-server.js +915 -0
- package/dist/server/mcp/browser-redaction.js +103 -0
- package/dist/server/mcp/classifier/BouncerClassifier.js +3 -0
- package/dist/server/mcp/classifier/ClaudeBouncerClassifier.js +212 -0
- package/dist/server/mcp/classifier/factory.js +124 -0
- package/dist/server/mcp/classifier/health.js +54 -0
- package/dist/server/mcp/classifier/telemetry.js +0 -0
- package/dist/server/mcp/company-patterns.js +104 -0
- package/dist/server/mcp/department-profiles.js +133 -0
- package/dist/server/mcp/quality-bridge.js +153 -0
- package/dist/server/mcp/quality-mcp-server.js +105 -0
- package/dist/server/mcp/security-analysis.js +384 -0
- package/dist/server/mcp/security-audit.js +152 -0
- package/dist/server/mcp/security-patterns.js +314 -0
- package/dist/server/mcp/server.js +194 -0
- package/dist/server/mcp/test-utils/agent-simulator.js +301 -0
- package/dist/server/mcp/test-utils/e2e-agent.js +103 -0
- package/dist/server/mcp/test-utils/e2e-capture.js +92 -0
- package/dist/server/mcp/test-utils/e2e-client.js +116 -0
- package/dist/server/mcp/test-utils/e2e-fixtures.js +87 -0
- package/dist/server/mcp/test-utils/e2e-gating.js +8 -0
- package/dist/server/mcp/test-utils/e2e-harness.js +8 -0
- package/dist/server/mcp/test-utils/e2e-scenarios.js +105 -0
- package/dist/server/routes/files.js +18 -0
- package/dist/server/routes/improvise.js +64 -0
- package/dist/server/routes/index.js +7 -0
- package/dist/server/routes/instances.js +41 -0
- package/dist/server/routes/internal.js +900 -0
- package/dist/server/routes/notifications.js +110 -0
- package/dist/server/server-setup.js +282 -0
- package/dist/server/services/agent-push.js +148 -0
- package/dist/server/services/analytics.js +197 -0
- package/dist/server/services/apps/build.js +249 -0
- package/dist/server/services/apps/greenlight.js +199 -0
- package/dist/server/services/apps/install.js +101 -0
- package/dist/server/services/apps/layout.js +35 -0
- package/dist/server/services/apps/serve.js +665 -0
- package/dist/server/services/apps/space-apps.js +248 -0
- package/dist/server/services/auth.js +48 -0
- package/dist/server/services/browser/chrome-sandbox.js +245 -0
- package/dist/server/services/browser/chromium-launch-spec.js +51 -0
- package/dist/server/services/browser/claude-reasoner.js +669 -0
- package/dist/server/services/browser/debug-log.js +3 -0
- package/dist/server/services/browser/driver-state.js +546 -0
- package/dist/server/services/browser/electron-provision.js +256 -0
- package/dist/server/services/browser/host-internal.js +245 -0
- package/dist/server/services/browser/host-mock.js +334 -0
- package/dist/server/services/browser/host-types.js +3 -0
- package/dist/server/services/browser/host.js +1067 -0
- package/dist/server/services/browser/index.js +4 -0
- package/dist/server/services/browser/ipc-client.js +354 -0
- package/dist/server/services/browser/pipewire-sink.js +199 -0
- package/dist/server/services/browser/preflight.js +590 -0
- package/dist/server/services/browser/reasoning-agent.js +659 -0
- package/dist/server/services/browser/sandbox-policy.js +169 -0
- package/dist/server/services/browser/stderr-noise-filter.js +26 -0
- package/dist/server/services/browser/telemetry.js +107 -0
- package/dist/server/services/browser/xvfb-supervisor.js +139 -0
- package/dist/server/services/browser-frame-policy.js +56 -0
- package/dist/server/services/client-id.js +32 -0
- package/dist/server/services/collab/registry.js +408 -0
- package/dist/server/services/collab/session.js +489 -0
- package/dist/server/services/collab/text-diff.js +28 -0
- package/dist/server/services/collab/types.js +19 -0
- package/dist/server/services/e2ee-group-key.js +197 -0
- package/dist/server/services/e2ee-identity.js +203 -0
- package/dist/server/services/file-explorer-ops.js +328 -0
- package/dist/server/services/file-transfer-zip.js +188 -0
- package/dist/server/services/files.js +111 -0
- package/dist/server/services/git/branch-ops.js +62 -0
- package/dist/server/services/git/command.js +68 -0
- package/dist/server/services/git/commit-message.js +74 -0
- package/dist/server/services/git/diff-ops.js +56 -0
- package/dist/server/services/git/haiku.js +76 -0
- package/dist/server/services/git/head-watcher.js +226 -0
- package/dist/server/services/git/index.js +17 -0
- package/dist/server/services/git/log-ops.js +98 -0
- package/dist/server/services/git/merge-ops.js +314 -0
- package/dist/server/services/git/parsers.js +401 -0
- package/dist/server/services/git/remote-ops.js +192 -0
- package/dist/server/services/git/status-ops.js +105 -0
- package/dist/server/services/git/suggestion-ops.js +80 -0
- package/dist/server/services/git/tag-ops.js +36 -0
- package/dist/server/services/git/types.js +4 -0
- package/dist/server/services/git/worktree-ops.js +114 -0
- package/dist/server/services/instances.js +337 -0
- package/dist/server/services/model-catalog.js +247 -0
- package/dist/server/services/observability/posthog.js +153 -0
- package/dist/server/services/pathUtils.js +114 -0
- package/dist/server/services/plan/agent-loader.js +97 -0
- package/dist/server/services/plan/agent-manager.js +363 -0
- package/dist/server/services/plan/agent-resolver.js +74 -0
- package/dist/server/services/plan/agents/assess-stall.md +33 -0
- package/dist/server/services/plan/agents/browser-planner.md +53 -0
- package/dist/server/services/plan/agents/browser-reasoner.md +114 -0
- package/dist/server/services/plan/agents/check-injection.md +95 -0
- package/dist/server/services/plan/agents/classify-error.md +30 -0
- package/dist/server/services/plan/agents/code-review.md +142 -0
- package/dist/server/services/plan/agents/commit-message.md +28 -0
- package/dist/server/services/plan/agents/detect-context-loss.md +30 -0
- package/dist/server/services/plan/agents/execute-issue.md +58 -0
- package/dist/server/services/plan/agents/fix-quality.md +25 -0
- package/dist/server/services/plan/agents/plan-coordinator.md +72 -0
- package/dist/server/services/plan/agents/pr-description.md +29 -0
- package/dist/server/services/plan/agents/retry-task.md +27 -0
- package/dist/server/services/plan/agents/review-code.md +38 -0
- package/dist/server/services/plan/agents/review-quality.md +45 -0
- package/dist/server/services/plan/agents/triage-findings.md +78 -0
- package/dist/server/services/plan/agents/verify-review.md +57 -0
- package/dist/server/services/plan/approval-evaluator.js +143 -0
- package/dist/server/services/plan/board-archive.js +102 -0
- package/dist/server/services/plan/board-config.js +108 -0
- package/dist/server/services/plan/board-export.js +214 -0
- package/dist/server/services/plan/composer-prompt.js +115 -0
- package/dist/server/services/plan/composer.js +664 -0
- package/dist/server/services/plan/config-installer.js +103 -0
- package/dist/server/services/plan/dependency-resolver.js +137 -0
- package/dist/server/services/plan/executor.js +696 -0
- package/dist/server/services/plan/front-matter.js +43 -0
- package/dist/server/services/plan/issue-classification.js +10 -0
- package/dist/server/services/plan/issue-effort.js +182 -0
- package/dist/server/services/plan/issue-loader.js +35 -0
- package/dist/server/services/plan/issue-prompt-builder.js +152 -0
- package/dist/server/services/plan/issue-retry.js +42 -0
- package/dist/server/services/plan/issue-writer.js +102 -0
- package/dist/server/services/plan/metrics-collector.js +272 -0
- package/dist/server/services/plan/output-manager.js +77 -0
- package/dist/server/services/plan/parser-core.js +435 -0
- package/dist/server/services/plan/parser-migration.js +108 -0
- package/dist/server/services/plan/parser.js +258 -0
- package/dist/server/services/plan/plan-runner-factory.js +68 -0
- package/dist/server/services/plan/pm-timeline.js +320 -0
- package/dist/server/services/plan/progress-log.js +101 -0
- package/dist/server/services/plan/prompt-builder.js +142 -0
- package/dist/server/services/plan/quality-delta.js +274 -0
- package/dist/server/services/plan/readiness-planner.js +34 -0
- package/dist/server/services/plan/review-gate.js +409 -0
- package/dist/server/services/plan/review-report.js +134 -0
- package/dist/server/services/plan/review-verdict-stream.js +161 -0
- package/dist/server/services/plan/state-reconciler.js +238 -0
- package/dist/server/services/plan/template-diff.js +175 -0
- package/dist/server/services/plan/template-instantiator.js +516 -0
- package/dist/server/services/plan/template-manifest.js +56 -0
- package/dist/server/services/plan/template-types.js +3 -0
- package/dist/server/services/plan/trigger-evaluator.js +211 -0
- package/dist/server/services/plan/types.js +3 -0
- package/dist/server/services/plan/watcher.js +73 -0
- package/dist/server/services/platform-credentials.js +56 -0
- package/dist/server/services/platform-e2ee.js +421 -0
- package/dist/server/services/platform-envelope.js +102 -0
- package/dist/server/services/platform-heartbeat.js +88 -0
- package/dist/server/services/platform-reconnect.js +60 -0
- package/dist/server/services/platform-token-lifecycle.js +95 -0
- package/dist/server/services/platform-url.js +17 -0
- package/dist/server/services/platform.js +656 -0
- package/dist/server/services/runtime-info.js +9 -0
- package/dist/server/services/schedule/agent-schedule-store.js +232 -0
- package/dist/server/services/schedule/agent-scheduler.js +323 -0
- package/dist/server/services/schedule/daily-timing.js +105 -0
- package/dist/server/services/schedule/quality-schedule-launch.js +11 -0
- package/dist/server/services/schedule/quality-schedule-store.js +211 -0
- package/dist/server/services/schedule/quality-scheduler.js +215 -0
- package/dist/server/services/schedule/run-bootstrap.js +329 -0
- package/dist/server/services/schedule/schedule-store.js +238 -0
- package/dist/server/services/schedule/schedule-wire.js +77 -0
- package/dist/server/services/schedule/scheduler.js +310 -0
- package/dist/server/services/schedule/template-source.js +97 -0
- package/dist/server/services/sdk/agent-sessions.js +264 -0
- package/dist/server/services/sdk/agents.js +557 -0
- package/dist/server/services/sdk/app-endpoints.js +48 -0
- package/dist/server/services/sdk/app-tools.js +303 -0
- package/dist/server/services/sdk/audit.js +48 -0
- package/dist/server/services/sdk/browser-transport.js +188 -0
- package/dist/server/services/sdk/browser.js +605 -0
- package/dist/server/services/sdk/composer.js +129 -0
- package/dist/server/services/sdk/connect.js +273 -0
- package/dist/server/services/sdk/consent-cooldown.js +31 -0
- package/dist/server/services/sdk/endpoint-url.js +141 -0
- package/dist/server/services/sdk/endpoints.js +314 -0
- package/dist/server/services/sdk/file-change-notify.js +36 -0
- package/dist/server/services/sdk/files-app.js +163 -0
- package/dist/server/services/sdk/files-search.js +131 -0
- package/dist/server/services/sdk/files-transfer.js +279 -0
- package/dist/server/services/sdk/files-workspace.js +233 -0
- package/dist/server/services/sdk/git.js +520 -0
- package/dist/server/services/sdk/grant-store.js +318 -0
- package/dist/server/services/sdk/host-ops.js +84 -0
- package/dist/server/services/sdk/inference-claude.js +214 -0
- package/dist/server/services/sdk/inference.js +247 -0
- package/dist/server/services/sdk/live-registry.js +42 -0
- package/dist/server/services/sdk/local-app-bindings.js +71 -0
- package/dist/server/services/sdk/pipeline.js +190 -0
- package/dist/server/services/sdk/pm-execute.js +228 -0
- package/dist/server/services/sdk/pm-planning-tap.js +29 -0
- package/dist/server/services/sdk/pm-schedule.js +165 -0
- package/dist/server/services/sdk/pm.js +634 -0
- package/dist/server/services/sdk/quality-change-notify.js +20 -0
- package/dist/server/services/sdk/quality-schedule.js +165 -0
- package/dist/server/services/sdk/quality.js +602 -0
- package/dist/server/services/sdk/rate-limits.js +198 -0
- package/dist/server/services/sdk/registry.js +597 -0
- package/dist/server/services/sdk/revoke.js +86 -0
- package/dist/server/services/sdk/run-profile.js +41 -0
- package/dist/server/services/sdk/sandbox.js +89 -0
- package/dist/server/services/sdk/storage.js +110 -0
- package/dist/server/services/sdk/streams.js +147 -0
- package/dist/server/services/sdk/terminal.js +201 -0
- package/dist/server/services/sdk/test-utils/workshop-browser-app.js +466 -0
- package/dist/server/services/sentry.js +99 -0
- package/dist/server/services/settings.js +374 -0
- package/dist/server/services/snippets/expander.js +87 -0
- package/dist/server/services/snippets/index.js +6 -0
- package/dist/server/services/snippets/loader.js +119 -0
- package/dist/server/services/snippets/parser.js +52 -0
- package/dist/server/services/snippets/types.js +3 -0
- package/dist/server/services/snippets/watcher.js +60 -0
- package/dist/server/services/space-layout.js +80 -0
- package/dist/server/services/system-prompts.js +219 -0
- package/dist/server/services/terminal/pty-manager.js +206 -0
- package/dist/server/services/terminal/pty-utils.js +150 -0
- package/dist/server/services/timeline/assembler.js +890 -0
- package/dist/server/services/timeline/contract.js +196 -0
- package/dist/server/services/timeline/index.js +4 -0
- package/dist/server/services/websocket/agent-schedule-handlers.js +217 -0
- package/dist/server/services/websocket/apps-handlers.js +399 -0
- package/dist/server/services/websocket/ask-user-question-bridge.js +112 -0
- package/dist/server/services/websocket/autocomplete-index.js +415 -0
- package/dist/server/services/websocket/autocomplete-match.js +243 -0
- package/dist/server/services/websocket/autocomplete.js +407 -0
- package/dist/server/services/websocket/browser-agent-runtime.js +208 -0
- package/dist/server/services/websocket/browser-device-profile.js +46 -0
- package/dist/server/services/websocket/browser-handlers.js +377 -0
- package/dist/server/services/websocket/browser-host-broadcast.js +179 -0
- package/dist/server/services/websocket/browser-ice-config.js +121 -0
- package/dist/server/services/websocket/browser-payloads.js +222 -0
- package/dist/server/services/websocket/browser-viewer-lifecycle.js +84 -0
- package/dist/server/services/websocket/browser-viewer-registry.js +118 -0
- package/dist/server/services/websocket/collab-broadcast.js +11 -0
- package/dist/server/services/websocket/collab-handlers.js +116 -0
- package/dist/server/services/websocket/commit-suggestion-service.js +132 -0
- package/dist/server/services/websocket/debug-log.js +38 -0
- package/dist/server/services/websocket/dispatch-util.js +10 -0
- package/dist/server/services/websocket/engine-auth-handlers.js +323 -0
- package/dist/server/services/websocket/engine-credential-watcher.js +83 -0
- package/dist/server/services/websocket/engine-profile-handlers.js +92 -0
- package/dist/server/services/websocket/file-definition-handlers.js +180 -0
- package/dist/server/services/websocket/file-download-handler.js +291 -0
- package/dist/server/services/websocket/file-explorer-handlers.js +291 -0
- package/dist/server/services/websocket/file-search-handlers.js +267 -0
- package/dist/server/services/websocket/file-share-handlers.js +328 -0
- package/dist/server/services/websocket/file-transfer-http.js +361 -0
- package/dist/server/services/websocket/file-upload-handler.js +267 -0
- package/dist/server/services/websocket/file-utils.js +346 -0
- package/dist/server/services/websocket/git-branch-handlers.js +90 -0
- package/dist/server/services/websocket/git-diff-handlers.js +59 -0
- package/dist/server/services/websocket/git-handlers.js +212 -0
- package/dist/server/services/websocket/git-head-watcher.js +85 -0
- package/dist/server/services/websocket/git-log-handlers.js +104 -0
- package/dist/server/services/websocket/git-pr-handlers.js +56 -0
- package/dist/server/services/websocket/git-tag-handlers.js +53 -0
- package/dist/server/services/websocket/git-utils.js +11 -0
- package/dist/server/services/websocket/git-worktree-handlers.js +521 -0
- package/dist/server/services/websocket/handler-context.js +113 -0
- package/dist/server/services/websocket/handler.js +1197 -0
- package/dist/server/services/websocket/index.js +5 -0
- package/dist/server/services/websocket/movement-written-files.js +26 -0
- package/dist/server/services/websocket/msg-id-tracker.js +48 -0
- package/dist/server/services/websocket/plan-board-handlers.js +410 -0
- package/dist/server/services/websocket/plan-execution-handlers.js +244 -0
- package/dist/server/services/websocket/plan-handlers.js +67 -0
- package/dist/server/services/websocket/plan-helpers.js +161 -0
- package/dist/server/services/websocket/plan-issue-handlers.js +168 -0
- package/dist/server/services/websocket/plan-sprint-handlers.js +190 -0
- package/dist/server/services/websocket/plan-transfer-handlers.js +310 -0
- package/dist/server/services/websocket/pm-timeline-broadcast.js +28 -0
- package/dist/server/services/websocket/post-session-scan.js +132 -0
- package/dist/server/services/websocket/prompt-queue-handlers.js +96 -0
- package/dist/server/services/websocket/quality-agent-cost.js +229 -0
- package/dist/server/services/websocket/quality-agent-notes.js +113 -0
- package/dist/server/services/websocket/quality-change-activity.js +187 -0
- package/dist/server/services/websocket/quality-complexity.js +345 -0
- package/dist/server/services/websocket/quality-dependencies.js +445 -0
- package/dist/server/services/websocket/quality-duplication.js +162 -0
- package/dist/server/services/websocket/quality-eta.js +65 -0
- package/dist/server/services/websocket/quality-fingerprint.js +104 -0
- package/dist/server/services/websocket/quality-grading.js +575 -0
- package/dist/server/services/websocket/quality-handlers.js +48 -0
- package/dist/server/services/websocket/quality-linting.js +270 -0
- package/dist/server/services/websocket/quality-operations.js +54 -0
- package/dist/server/services/websocket/quality-persistence.js +410 -0
- package/dist/server/services/websocket/quality-review-agent.js +526 -0
- package/dist/server/services/websocket/quality-run.js +220 -0
- package/dist/server/services/websocket/quality-secrets.js +0 -0
- package/dist/server/services/websocket/quality-service.js +775 -0
- package/dist/server/services/websocket/quality-tools.js +383 -0
- package/dist/server/services/websocket/quality-triage-agent.js +101 -0
- package/dist/server/services/websocket/quality-types.js +149 -0
- package/dist/server/services/websocket/recommended-answers.js +28 -0
- package/dist/server/services/websocket/schedule-handlers.js +197 -0
- package/dist/server/services/websocket/sdk-agent-host.js +569 -0
- package/dist/server/services/websocket/sdk-browser-host.js +459 -0
- package/dist/server/services/websocket/sdk-composer-host.js +10 -0
- package/dist/server/services/websocket/sdk-git-host.js +115 -0
- package/dist/server/services/websocket/sdk-handlers.js +242 -0
- package/dist/server/services/websocket/sdk-pm-execution-host.js +63 -0
- package/dist/server/services/websocket/sdk-pm-schedule-host.js +21 -0
- package/dist/server/services/websocket/sdk-quality-schedule-host.js +34 -0
- package/dist/server/services/websocket/sdk-terminal-host.js +140 -0
- package/dist/server/services/websocket/session-handlers.js +565 -0
- package/dist/server/services/websocket/session-history.js +335 -0
- package/dist/server/services/websocket/session-initialization.js +315 -0
- package/dist/server/services/websocket/session-registry.js +340 -0
- package/dist/server/services/websocket/session-role-directory.js +39 -0
- package/dist/server/services/websocket/settings-handlers.js +276 -0
- package/dist/server/services/websocket/skill-handlers.js +324 -0
- package/dist/server/services/websocket/skill-watcher.js +83 -0
- package/dist/server/services/websocket/snippet-handlers.js +261 -0
- package/dist/server/services/websocket/tab-broadcast.js +35 -0
- package/dist/server/services/websocket/tab-event-buffer.js +110 -0
- package/dist/server/services/websocket/tab-event-replay.js +47 -0
- package/dist/server/services/websocket/tab-handlers.js +211 -0
- package/dist/server/services/websocket/terminal-handlers.js +268 -0
- package/dist/server/services/websocket/types.js +96 -0
- package/dist/server/types/company-messages.js +102 -0
- package/dist/server/utils/agent-manager.js +202 -0
- package/dist/server/utils/console-timestamps.js +24 -0
- package/dist/server/utils/file-store.js +112 -0
- package/dist/server/utils/paths.js +28 -0
- package/dist/server/utils/port-manager.js +43 -0
- package/dist/server/utils/port.js +204 -0
- package/electron-host/dist/agent-lease.js +141 -0
- package/electron-host/dist/capture-recovery.js +77 -0
- package/electron-host/dist/codec-policy.js +37 -0
- package/electron-host/dist/controller-channel.js +60 -0
- package/electron-host/dist/controller-handlers.js +153 -0
- package/electron-host/dist/device-emulator.js +106 -0
- package/electron-host/dist/dom-driver.js +642 -0
- package/electron-host/dist/domain-registry.js +159 -0
- package/electron-host/dist/domain-validators.js +308 -0
- package/electron-host/dist/editable-focus-reporter.js +143 -0
- package/electron-host/dist/fake-peer.test-util.js +105 -0
- package/electron-host/dist/host-log.js +31 -0
- package/electron-host/dist/host-wire.js +11 -0
- package/electron-host/dist/input-router.js +421 -0
- package/electron-host/dist/ipc-protocol.js +89 -0
- package/electron-host/dist/ipc-server.js +193 -0
- package/electron-host/dist/js-driver.js +216 -0
- package/electron-host/dist/main-guards.js +70 -0
- package/electron-host/dist/main.js +716 -0
- package/electron-host/dist/roster-sync.js +87 -0
- package/electron-host/dist/rpc-context.js +1 -0
- package/electron-host/dist/rpc-tab-methods.js +138 -0
- package/electron-host/dist/rpc-webrtc-methods.js +121 -0
- package/electron-host/dist/screen-capture-cache.js +147 -0
- package/electron-host/dist/sdk-injector.js +166 -0
- package/electron-host/dist/sdp.js +102 -0
- package/electron-host/dist/session-surface.js +78 -0
- package/electron-host/dist/surface-sizing.js +59 -0
- package/electron-host/dist/view-manager.js +254 -0
- package/electron-host/dist/viewer-registry.js +46 -0
- package/electron-host/dist/viewer-session.js +288 -0
- package/electron-host/dist/webrtc-channels.js +14 -0
- package/electron-host/dist/webrtc-controller.js +57 -0
- package/electron-host/dist/webrtc-ice-filter.js +13 -0
- package/electron-host/dist/webrtc-peer.js +45 -0
- package/electron-host/package.json +12 -0
- package/electron-host/tsconfig.json +23 -0
- package/electron-host/webrtc-controller-preload.cjs +3 -0
- package/electron-host/webrtc-controller.html +14 -0
- package/package.json +85 -0
- package/vendor/e2ee/LICENSE +14 -0
- package/vendor/e2ee/package.json +14 -0
- package/vendor/e2ee/src/index.js +310 -0
|
@@ -0,0 +1,1016 @@
|
|
|
1
|
+
// Copyright (c) 2025-present Minionry, Inc. All rights reserved.
|
|
2
|
+
import { EventEmitter } from 'node:events';
|
|
3
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
4
|
+
import { homedir } from 'node:os';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { EngineSession, shouldRouteToEngine, toPromptAttachments } from '../engines/execution/engine-session.js';
|
|
7
|
+
import { createEngine } from '../engines/factory.js';
|
|
8
|
+
import { EngineStartError, isEngineId } from '../engines/types.js';
|
|
9
|
+
import { AnalyticsEvents, trackEvent } from '../services/analytics.js';
|
|
10
|
+
import { getClientId } from '../services/client-id.js';
|
|
11
|
+
import { resolveEnabledEngineId } from '../services/settings.js';
|
|
12
|
+
import { resolveSystemPromptContent, resolveSystemPromptLabel } from '../services/system-prompts.js';
|
|
13
|
+
import { formatErrorMarker, parseErrorMarker } from '../services/timeline/assembler.js';
|
|
14
|
+
import { forgetNativeResumeHandles, hasSettledMovements, nativeResumeHandle, recordNativeResumeHandle, shouldPrimeFromHistory, } from './engine-resume.js';
|
|
15
|
+
import { getEtaProfileCached } from './eta-estimator.js';
|
|
16
|
+
import { resolveClaudeEffort } from './headless/claude-invoker-process.js';
|
|
17
|
+
import { describeDispatchBlocker, engineAvailability } from './headless/engine-availability.js';
|
|
18
|
+
import { describeParkUntil } from './headless/engine-notice.js';
|
|
19
|
+
import { getAssessorHealth } from './headless/haiku-assessments.js';
|
|
20
|
+
import { herror, runWithFileLogger } from './headless/headless-logger.js';
|
|
21
|
+
import { isTerminalEngineNotice, pickPreferredResult } from './headless/retry-strategies.js';
|
|
22
|
+
import { addTokenUsage, emptyTokenUsage } from './headless/types.js';
|
|
23
|
+
import { currentSessionOrigin } from './history-portability.js';
|
|
24
|
+
import { cleanupAttachments, preparePromptAndAttachments } from './improvisation-attachments.js';
|
|
25
|
+
import { ensureHistoryDir, loadHistory, normalizeSessionHistory, reconcileOrphanedMovements, resolveHistoryPaths, saveHistory, } from './improvisation-history-store.js';
|
|
26
|
+
import { buildCancelledMovement, buildErrorMovement, buildSuccessMovement, CANCELLED_FALLBACK_RESULT, shouldAutoContinue, } from './improvisation-movements.js';
|
|
27
|
+
import { OutputQueue } from './improvisation-output-queue.js';
|
|
28
|
+
import { applyToolTimeoutRetry, buildStreamingCallbacks, createExecutionRunner, detectNativeTimeoutContextLoss, detectResumeContextLoss, determineResumeStrategy, selectBestResult, shouldRetryContextLoss, shouldRetryServerError, shouldRetrySessionNotFound, shouldRetrySignalCrash } from './improvisation-retry.js';
|
|
29
|
+
import { createRetryLoopState } from './improvisation-types.js';
|
|
30
|
+
const AGENT_LOG_DIR = join(homedir(), '.minionry', 'logs', 'agent');
|
|
31
|
+
function stallContinuationPrompt(result) {
|
|
32
|
+
const pendingTasks = result.pendingBackgroundTasks ?? [];
|
|
33
|
+
if (pendingTasks.length > 0) {
|
|
34
|
+
return `${buildPendingBackgroundContinuePrompt(pendingTasks)}\nThose tasks were terminated with the process; their notifications will never arrive. Do not wait for them and do not schedule wakeups to check on them.`;
|
|
35
|
+
}
|
|
36
|
+
if (result.backgroundTasksPendingAtExit) {
|
|
37
|
+
return 'Your process was terminated while background agents/workflows were still running; that background work was lost and its notifications will never arrive. Do not wait for them — re-launch what is still needed and finish the original task.';
|
|
38
|
+
}
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
import { abortPlan as abortPlanCascade, completePlan as completePlanCascade, pausePlan as pausePlanCascade, resumePlan as resumePlanCascade, } from './plan-lifecycle.js';
|
|
42
|
+
import { buildHistoricalContext, buildPendingBackgroundContinuePrompt } from './prompt-builders.js';
|
|
43
|
+
function attachmentRecords(attachments) {
|
|
44
|
+
if (!attachments || attachments.length === 0)
|
|
45
|
+
return [];
|
|
46
|
+
return attachments.map((attachment) => ({
|
|
47
|
+
fileName: attachment.fileName,
|
|
48
|
+
...(attachment.mimeType ? { mimeType: attachment.mimeType } : {}),
|
|
49
|
+
isImage: attachment.isImage,
|
|
50
|
+
...(attachment.content ? { sizeBytes: Math.floor((attachment.content.length * 3) / 4) } : {}),
|
|
51
|
+
}));
|
|
52
|
+
}
|
|
53
|
+
export class ImprovisationSessionManager extends EventEmitter {
|
|
54
|
+
sessionId;
|
|
55
|
+
improviseDir;
|
|
56
|
+
historyPath;
|
|
57
|
+
history;
|
|
58
|
+
currentRunner = null;
|
|
59
|
+
options;
|
|
60
|
+
engineId = 'claude-code';
|
|
61
|
+
engineSession = null;
|
|
62
|
+
engineSessionModel;
|
|
63
|
+
engineSessionPromptKey;
|
|
64
|
+
engineSessionWorkingDir;
|
|
65
|
+
pendingApproval;
|
|
66
|
+
outputBuffer;
|
|
67
|
+
thinkingBuffer;
|
|
68
|
+
isFirstPrompt = true;
|
|
69
|
+
claudeSessionId;
|
|
70
|
+
isResumedSession = false;
|
|
71
|
+
_currentAttachments = [];
|
|
72
|
+
_primeFromHistory = false;
|
|
73
|
+
_resolvedModel;
|
|
74
|
+
accumulatedKnowledge = '';
|
|
75
|
+
_isExecuting = false;
|
|
76
|
+
_executionStartTimestamp;
|
|
77
|
+
executionEventLog = [];
|
|
78
|
+
_cancelled = false;
|
|
79
|
+
_cancelCompleteEmitted = false;
|
|
80
|
+
_currentUserPrompt = '';
|
|
81
|
+
_currentSequenceNumber = 0;
|
|
82
|
+
_hasPersistedToDisk = false;
|
|
83
|
+
_etaProfile = null;
|
|
84
|
+
_frozenPromptTokenUsage = emptyTokenUsage();
|
|
85
|
+
_currentInvocationTokenUsage = emptyTokenUsage();
|
|
86
|
+
static resumeFromHistory(workingDir, historicalSessionId, overrides) {
|
|
87
|
+
const historyDir = join(workingDir, '.minionry', 'history');
|
|
88
|
+
const timestamp = historicalSessionId.replace('improv-', '');
|
|
89
|
+
const historyPath = join(historyDir, `${timestamp}.json`);
|
|
90
|
+
if (!existsSync(historyPath)) {
|
|
91
|
+
throw new Error(`Historical session not found: ${historicalSessionId}`);
|
|
92
|
+
}
|
|
93
|
+
const historyData = normalizeSessionHistory(JSON.parse(readFileSync(historyPath, 'utf-8')), historicalSessionId);
|
|
94
|
+
const manager = new ImprovisationSessionManager({
|
|
95
|
+
workingDir,
|
|
96
|
+
sessionId: historyData.sessionId,
|
|
97
|
+
...overrides,
|
|
98
|
+
});
|
|
99
|
+
manager.history = historyData;
|
|
100
|
+
manager.keepToolRestrictions();
|
|
101
|
+
manager.settleOrphanedStubs();
|
|
102
|
+
manager.accumulatedKnowledge = historyData.movements
|
|
103
|
+
.filter(m => m.summary)
|
|
104
|
+
.map(m => m.summary)
|
|
105
|
+
.join('\n\n');
|
|
106
|
+
manager.isResumedSession = true;
|
|
107
|
+
manager.isFirstPrompt = true;
|
|
108
|
+
manager._hasPersistedToDisk = true;
|
|
109
|
+
manager.claudeSessionId = nativeResumeHandle(historyData, manager.resolveEngineId(), manager.localOrigin());
|
|
110
|
+
return manager;
|
|
111
|
+
}
|
|
112
|
+
constructor(options = {}) {
|
|
113
|
+
super();
|
|
114
|
+
const resolvedSessionId = options.sessionId || `improv-${Date.now()}`;
|
|
115
|
+
this.options = {
|
|
116
|
+
workingDir: options.workingDir || process.cwd(),
|
|
117
|
+
sessionId: resolvedSessionId,
|
|
118
|
+
tokenBudgetThreshold: options.tokenBudgetThreshold || 170000,
|
|
119
|
+
maxSessions: options.maxSessions || 10,
|
|
120
|
+
verbose: options.verbose || false,
|
|
121
|
+
noColor: options.noColor || false,
|
|
122
|
+
model: options.model,
|
|
123
|
+
effortLevel: options.effortLevel,
|
|
124
|
+
fastMode: options.fastMode,
|
|
125
|
+
ultracode: options.ultracode,
|
|
126
|
+
agentLabel: options.agentLabel || resolvedSessionId,
|
|
127
|
+
...(options.tabId ? { tabId: options.tabId } : {}),
|
|
128
|
+
...(options.planId ? { planId: options.planId } : {}),
|
|
129
|
+
...(options.disallowedTools?.length ? { disallowedTools: [...options.disallowedTools] } : {}),
|
|
130
|
+
...(options.appOrigin ? { appOrigin: options.appOrigin } : {}),
|
|
131
|
+
...(options.appRun ? { appRun: options.appRun } : {}),
|
|
132
|
+
...(options.appSystemPrompt ? { appSystemPrompt: options.appSystemPrompt } : {}),
|
|
133
|
+
};
|
|
134
|
+
this.sessionId = this.options.sessionId;
|
|
135
|
+
const paths = resolveHistoryPaths(this.options.workingDir, this.sessionId);
|
|
136
|
+
this.improviseDir = paths.improviseDir;
|
|
137
|
+
this.historyPath = paths.historyPath;
|
|
138
|
+
ensureHistoryDir(this.improviseDir);
|
|
139
|
+
createEngine(this.engineId);
|
|
140
|
+
this.history = loadHistory(this.historyPath, this.sessionId);
|
|
141
|
+
this.keepToolRestrictions();
|
|
142
|
+
this.settleOrphanedStubs();
|
|
143
|
+
this.outputBuffer = new OutputQueue(text => this.emit('onOutput', text));
|
|
144
|
+
this.outputBuffer.start();
|
|
145
|
+
this.thinkingBuffer = new OutputQueue(text => this.emit('onThinking', text));
|
|
146
|
+
this.thinkingBuffer.start();
|
|
147
|
+
}
|
|
148
|
+
applyOverrides(overrides) {
|
|
149
|
+
if (typeof overrides.model === 'string' && overrides.model.length > 0) {
|
|
150
|
+
this.options.model = overrides.model;
|
|
151
|
+
this._resolvedModel = undefined;
|
|
152
|
+
}
|
|
153
|
+
if (typeof overrides.effortLevel === 'string' && overrides.effortLevel.length > 0) {
|
|
154
|
+
if (overrides.effortLevel === 'ultracode') {
|
|
155
|
+
this.options.effortLevel = 'auto';
|
|
156
|
+
this.options.ultracode = true;
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
this.options.effortLevel = overrides.effortLevel;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
if (typeof overrides.fastMode === 'boolean') {
|
|
163
|
+
this.options.fastMode = overrides.fastMode;
|
|
164
|
+
}
|
|
165
|
+
if (typeof overrides.ultracode === 'boolean') {
|
|
166
|
+
this.options.ultracode = overrides.ultracode;
|
|
167
|
+
}
|
|
168
|
+
this.options.systemPromptProfile =
|
|
169
|
+
typeof overrides.systemPromptProfile === 'string' && overrides.systemPromptProfile.length > 0
|
|
170
|
+
? overrides.systemPromptProfile
|
|
171
|
+
: undefined;
|
|
172
|
+
this.options.systemPromptLang =
|
|
173
|
+
typeof overrides.systemPromptLang === 'string' && overrides.systemPromptLang.length > 0
|
|
174
|
+
? overrides.systemPromptLang
|
|
175
|
+
: undefined;
|
|
176
|
+
this.applyEngineOverride(overrides.engine);
|
|
177
|
+
}
|
|
178
|
+
applyEngineOverride(engine) {
|
|
179
|
+
if (!isEngineId(engine))
|
|
180
|
+
return;
|
|
181
|
+
if (engine !== this.history.engine) {
|
|
182
|
+
this._resolvedModel = undefined;
|
|
183
|
+
this.history.engine = engine;
|
|
184
|
+
this.claudeSessionId = nativeResumeHandle(this.history, engine, this.localOrigin());
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
this.history.engine = engine;
|
|
188
|
+
}
|
|
189
|
+
localOrigin() {
|
|
190
|
+
return { clientId: getClientId(), workingDir: this.options.workingDir };
|
|
191
|
+
}
|
|
192
|
+
keepToolRestrictions() {
|
|
193
|
+
const tools = [...new Set([...(this.options.disallowedTools ?? []), ...(this.history.disallowedTools ?? [])])];
|
|
194
|
+
if (tools.length === 0)
|
|
195
|
+
return;
|
|
196
|
+
this.options.disallowedTools = tools;
|
|
197
|
+
this.history.disallowedTools = tools;
|
|
198
|
+
}
|
|
199
|
+
settleOrphanedStubs() {
|
|
200
|
+
const settled = reconcileOrphanedMovements(this.history);
|
|
201
|
+
if (settled === 0)
|
|
202
|
+
return;
|
|
203
|
+
herror(`[session] ${this.sessionId}: settled ${settled} orphaned in-flight movement(s) left by a previous process`);
|
|
204
|
+
if (existsSync(this.historyPath))
|
|
205
|
+
this.persistHistory();
|
|
206
|
+
}
|
|
207
|
+
queueOutput(text) {
|
|
208
|
+
this.outputBuffer.queue_(text);
|
|
209
|
+
}
|
|
210
|
+
queueThinking(text) {
|
|
211
|
+
this.thinkingBuffer.queue_(text);
|
|
212
|
+
}
|
|
213
|
+
flushOutputQueue() {
|
|
214
|
+
this.thinkingBuffer.flush();
|
|
215
|
+
this.outputBuffer.flush();
|
|
216
|
+
}
|
|
217
|
+
allocateSequenceNumber(msgId) {
|
|
218
|
+
if (msgId) {
|
|
219
|
+
const orphan = this.history.movements.find((m) => m.msgId === msgId && m.outcome?.cancelOrigin === 'process-exit');
|
|
220
|
+
if (orphan)
|
|
221
|
+
return orphan.sequenceNumber;
|
|
222
|
+
}
|
|
223
|
+
return this.history.movements.length + 1;
|
|
224
|
+
}
|
|
225
|
+
async executePrompt(userPrompt, attachments, options) {
|
|
226
|
+
const _execStart = Date.now();
|
|
227
|
+
const isAutoContinue = options?.isAutoContinue ?? false;
|
|
228
|
+
const displayPrompt = options?.displayPrompt ?? userPrompt;
|
|
229
|
+
this._isExecuting = true;
|
|
230
|
+
this._cancelled = false;
|
|
231
|
+
this._cancelOrigin = 'user';
|
|
232
|
+
this._cancelCompleteEmitted = false;
|
|
233
|
+
this._currentRetryState = null;
|
|
234
|
+
this.clearWakeupTimer();
|
|
235
|
+
if (!isAutoContinue) {
|
|
236
|
+
this._autoContinueCount = 0;
|
|
237
|
+
this._autoContinuePending = false;
|
|
238
|
+
this._wakeupContinueCount = 0;
|
|
239
|
+
this._limitContinueCount = 0;
|
|
240
|
+
}
|
|
241
|
+
this._executionStartTimestamp = _execStart;
|
|
242
|
+
this.executionEventLog = [];
|
|
243
|
+
this._frozenPromptTokenUsage = emptyTokenUsage();
|
|
244
|
+
this._currentInvocationTokenUsage = emptyTokenUsage();
|
|
245
|
+
const sequenceNumber = this.allocateSequenceNumber(options?.msgId);
|
|
246
|
+
this._currentUserPrompt = displayPrompt;
|
|
247
|
+
this._currentSequenceNumber = sequenceNumber;
|
|
248
|
+
this._currentMsgId = options?.msgId;
|
|
249
|
+
this._currentAttachments = attachmentRecords(attachments);
|
|
250
|
+
const pendingMovement = {
|
|
251
|
+
id: `prompt-${sequenceNumber}`,
|
|
252
|
+
sequenceNumber,
|
|
253
|
+
userPrompt: displayPrompt,
|
|
254
|
+
timestamp: new Date().toISOString(),
|
|
255
|
+
tokensUsed: 0,
|
|
256
|
+
summary: '',
|
|
257
|
+
filesModified: [],
|
|
258
|
+
durationMs: 0,
|
|
259
|
+
...(isAutoContinue && { isAutoContinue: true }),
|
|
260
|
+
...(options?.msgId && { msgId: options.msgId }),
|
|
261
|
+
...(this._currentAttachments.length > 0 && { attachments: this._currentAttachments }),
|
|
262
|
+
};
|
|
263
|
+
this.persistMovement(pendingMovement);
|
|
264
|
+
const engineId = this.resolveEngineId();
|
|
265
|
+
this._primeFromHistory = shouldPrimeFromHistory({
|
|
266
|
+
history: this.history,
|
|
267
|
+
engineId,
|
|
268
|
+
isFirstPrompt: this.isFirstPrompt,
|
|
269
|
+
isResumedSession: this.isResumedSession,
|
|
270
|
+
hasNativeHandle: this.claudeSessionId !== undefined,
|
|
271
|
+
hasLiveProcess: shouldRouteToEngine(engineId),
|
|
272
|
+
});
|
|
273
|
+
await this.refreshEtaProfile();
|
|
274
|
+
this.emit('onMovementStart', sequenceNumber, displayPrompt, isAutoContinue, this._etaProfile);
|
|
275
|
+
trackEvent(AnalyticsEvents.IMPROVISE_PROMPT_RECEIVED, {
|
|
276
|
+
prompt_length: userPrompt.length,
|
|
277
|
+
has_attachments: !!(attachments && attachments.length > 0),
|
|
278
|
+
attachment_count: attachments?.length || 0,
|
|
279
|
+
image_attachment_count: attachments?.filter(a => a.isImage).length || 0,
|
|
280
|
+
sequence_number: sequenceNumber,
|
|
281
|
+
is_resumed_session: this.isResumedSession,
|
|
282
|
+
model: this.options.model || 'default',
|
|
283
|
+
effort_level: this.options.effortLevel || 'auto',
|
|
284
|
+
});
|
|
285
|
+
let retryLoopState;
|
|
286
|
+
try {
|
|
287
|
+
this.executionEventLog.push({
|
|
288
|
+
type: 'movementStart',
|
|
289
|
+
data: { sequenceNumber, prompt: displayPrompt, timestamp: Date.now(), executionStartTimestamp: this._executionStartTimestamp },
|
|
290
|
+
timestamp: Date.now(),
|
|
291
|
+
});
|
|
292
|
+
const { prompt: promptWithAttachments, imageAttachments } = preparePromptAndAttachments(userPrompt, attachments, this.options.workingDir, this.sessionId, (msg) => { this.queueOutput(msg); this.flushOutputQueue(); });
|
|
293
|
+
const state = createRetryLoopState(promptWithAttachments, 3);
|
|
294
|
+
retryLoopState = state;
|
|
295
|
+
this._currentRetryState = state;
|
|
296
|
+
let result = await runWithFileLogger(`${this.sessionId}-${sequenceNumber}`, () => this.runRetryLoop(state, sequenceNumber, imageAttachments, options?.workingDir), AGENT_LOG_DIR);
|
|
297
|
+
if (this._cancelled || this._cancelCompleteEmitted) {
|
|
298
|
+
return this.handleCancelledExecution(result, displayPrompt, sequenceNumber, _execStart, state);
|
|
299
|
+
}
|
|
300
|
+
if (state.contextLost)
|
|
301
|
+
this.claudeSessionId = undefined;
|
|
302
|
+
result = await selectBestResult(state, result, userPrompt, this.options.verbose);
|
|
303
|
+
this.captureSessionAndSurfaceErrors(result);
|
|
304
|
+
this.surfaceAssessorHealth(state);
|
|
305
|
+
this.isFirstPrompt = false;
|
|
306
|
+
this.flushOutputQueue();
|
|
307
|
+
const movement = buildSuccessMovement(result, { sequenceNumber, userPrompt: displayPrompt, execStart: _execStart, isAutoContinue, ...this.movementMetaArgs(), outcome: this.outcomeExtras(state) }, state.retryLog);
|
|
308
|
+
this.handleConflicts(result);
|
|
309
|
+
this.persistMovement(movement);
|
|
310
|
+
this._isExecuting = false;
|
|
311
|
+
this._executionStartTimestamp = undefined;
|
|
312
|
+
this.executionEventLog = [];
|
|
313
|
+
this._currentRetryState = null;
|
|
314
|
+
if (!this._cancelCompleteEmitted) {
|
|
315
|
+
this.emitMovementComplete(movement, result, _execStart, sequenceNumber);
|
|
316
|
+
}
|
|
317
|
+
this.maybeAutoContinue(result, userPrompt);
|
|
318
|
+
return movement;
|
|
319
|
+
}
|
|
320
|
+
catch (error) {
|
|
321
|
+
this.handleExecutionError(error, displayPrompt, sequenceNumber, _execStart, retryLoopState?.bestResult ?? undefined, retryLoopState);
|
|
322
|
+
}
|
|
323
|
+
finally {
|
|
324
|
+
this.flushOutputQueue();
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
outcomeExtras(state) {
|
|
328
|
+
if (!state)
|
|
329
|
+
return {};
|
|
330
|
+
return {
|
|
331
|
+
attempts: state.retryNumber + 1,
|
|
332
|
+
...(state.assessments.length > 0 ? { assessments: state.assessments } : {}),
|
|
333
|
+
...(state.assessorFailed ? { assessorFailed: true } : {}),
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
surfaceAssessorHealth(state) {
|
|
337
|
+
if (!state.assessorFailed || this._assessorDegradedNoticeEmitted)
|
|
338
|
+
return;
|
|
339
|
+
const health = getAssessorHealth();
|
|
340
|
+
if (health.consecutiveFailures < 3)
|
|
341
|
+
return;
|
|
342
|
+
this._assessorDegradedNoticeEmitted = true;
|
|
343
|
+
this.queueOutput(`\n[[MINIONRY_ASSESSOR_DEGRADED]] The Haiku assessor has failed ${health.consecutiveFailures} times in a row (${health.lastError ?? 'unknown error'}) — retry decisions are using deterministic fallbacks until it recovers.\n`);
|
|
344
|
+
this.flushOutputQueue();
|
|
345
|
+
}
|
|
346
|
+
buildRetryCallbacks() {
|
|
347
|
+
return {
|
|
348
|
+
isCancelled: () => this._cancelled,
|
|
349
|
+
queueOutput: (text) => this.queueOutput(text),
|
|
350
|
+
queueThinking: (text) => this.queueThinking(text),
|
|
351
|
+
flushOutputQueue: () => this.flushOutputQueue(),
|
|
352
|
+
emit: (event, ...args) => {
|
|
353
|
+
if (event === 'onTokenUsage' && args[0] && typeof args[0] === 'object') {
|
|
354
|
+
this._currentInvocationTokenUsage = args[0];
|
|
355
|
+
const total = addTokenUsage(this._frozenPromptTokenUsage, this._currentInvocationTokenUsage);
|
|
356
|
+
this.emit(event, total);
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
if (event === 'onExecutionTargetUpdate' && args[0] && typeof args[0] === 'object') {
|
|
360
|
+
const resolved = args[0];
|
|
361
|
+
if (typeof resolved.model === 'string' && resolved.model)
|
|
362
|
+
this._resolvedModel = resolved.model;
|
|
363
|
+
this.emit(event, this.getExecutionTarget());
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
this.emit(event, ...args);
|
|
367
|
+
},
|
|
368
|
+
addEventLog: (entry) => this.executionEventLog.push(entry),
|
|
369
|
+
setRunner: (runner) => { this.currentRunner = runner; },
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
freezeInvocationTokens() {
|
|
373
|
+
this._frozenPromptTokenUsage = addTokenUsage(this._frozenPromptTokenUsage, this._currentInvocationTokenUsage);
|
|
374
|
+
this._currentInvocationTokenUsage = emptyTokenUsage();
|
|
375
|
+
}
|
|
376
|
+
buildRetrySessionState() {
|
|
377
|
+
return {
|
|
378
|
+
options: { ...this.options, verbose: true },
|
|
379
|
+
claudeSessionId: this.claudeSessionId,
|
|
380
|
+
isFirstPrompt: this.isFirstPrompt,
|
|
381
|
+
isResumedSession: this.isResumedSession,
|
|
382
|
+
history: this.history,
|
|
383
|
+
executionStartTimestamp: this._executionStartTimestamp,
|
|
384
|
+
primeFromHistory: this._primeFromHistory,
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
syncSessionStateBack(session) {
|
|
388
|
+
if (session.claudeSessionId !== this.claudeSessionId) {
|
|
389
|
+
this.claudeSessionId = session.claudeSessionId;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
async runRetryLoop(state, sequenceNumber, imageAttachments, workingDirOverride) {
|
|
393
|
+
let result;
|
|
394
|
+
const callbacks = this.buildRetryCallbacks();
|
|
395
|
+
const RETRY_BACKOFF_MS = [1000, 5000, 30000];
|
|
396
|
+
while (true) {
|
|
397
|
+
if (this._cancelled)
|
|
398
|
+
break;
|
|
399
|
+
if (state.retryNumber > 0) {
|
|
400
|
+
const delay = RETRY_BACKOFF_MS[Math.min(state.retryNumber - 1, RETRY_BACKOFF_MS.length - 1)];
|
|
401
|
+
await new Promise(r => setTimeout(r, delay));
|
|
402
|
+
if (this._cancelled)
|
|
403
|
+
break;
|
|
404
|
+
}
|
|
405
|
+
result = await this.executeRetryIteration(state, callbacks, sequenceNumber, imageAttachments, workingDirOverride);
|
|
406
|
+
if (this._cancelled)
|
|
407
|
+
break;
|
|
408
|
+
if (await this.evaluateRetryStrategies(result, state, callbacks))
|
|
409
|
+
continue;
|
|
410
|
+
break;
|
|
411
|
+
}
|
|
412
|
+
return result;
|
|
413
|
+
}
|
|
414
|
+
async executeRetryIteration(state, callbacks, sequenceNumber, imageAttachments, workingDirOverride) {
|
|
415
|
+
if (state.checkpointRef.value)
|
|
416
|
+
state.lastWatchdogCheckpoint = state.checkpointRef.value;
|
|
417
|
+
state.checkpointRef.value = null;
|
|
418
|
+
state.contextLost = false;
|
|
419
|
+
const engineId = this.resolveEngineId();
|
|
420
|
+
if (shouldRouteToEngine(engineId)) {
|
|
421
|
+
state.lastUseResume = false;
|
|
422
|
+
state.lastNativeTimeouts = 0;
|
|
423
|
+
return this.runEngineIteration(engineId, state, callbacks, imageAttachments, workingDirOverride);
|
|
424
|
+
}
|
|
425
|
+
const session = this.buildRetrySessionState();
|
|
426
|
+
const resume = determineResumeStrategy(state, session);
|
|
427
|
+
const runner = createExecutionRunner(state, session, callbacks, sequenceNumber, resume, imageAttachments, workingDirOverride);
|
|
428
|
+
this.currentRunner = runner;
|
|
429
|
+
const result = await runner.run();
|
|
430
|
+
this.currentRunner = null;
|
|
431
|
+
this.freezeInvocationTokens();
|
|
432
|
+
state.bestResult = state.bestResult ? pickPreferredResult(state.bestResult, result) : result;
|
|
433
|
+
state.lastUseResume = resume.useResume;
|
|
434
|
+
state.lastNativeTimeouts = result.nativeTimeoutCount ?? 0;
|
|
435
|
+
detectResumeContextLoss(result, state, this.options.verbose);
|
|
436
|
+
await detectNativeTimeoutContextLoss(result, state, this.options.verbose);
|
|
437
|
+
if (!state.contextLost && result.postTimeoutOutput) {
|
|
438
|
+
this.queueOutput(result.postTimeoutOutput);
|
|
439
|
+
this.flushOutputQueue();
|
|
440
|
+
}
|
|
441
|
+
return result;
|
|
442
|
+
}
|
|
443
|
+
resolveEngineId() {
|
|
444
|
+
return resolveEnabledEngineId(this.history.engine);
|
|
445
|
+
}
|
|
446
|
+
async runEngineIteration(engineId, state, callbacks, imageAttachments, workingDirOverride) {
|
|
447
|
+
const { session: engineSession, lostResume } = await this.ensureEngineSession(engineId, workingDirOverride);
|
|
448
|
+
this.currentRunner = null;
|
|
449
|
+
const prime = this._primeFromHistory || (lostResume && hasSettledMovements(this.history));
|
|
450
|
+
const prompt = state.retryNumber === 0 && prime
|
|
451
|
+
? `${buildHistoricalContext(this.history.movements.filter((m) => m.sequenceNumber !== this._currentSequenceNumber))}\n${state.currentPrompt}`
|
|
452
|
+
: state.currentPrompt;
|
|
453
|
+
const result = await engineSession.runTurn(prompt, toPromptAttachments(imageAttachments), { ...buildStreamingCallbacks(callbacks), questionCallback: (req) => this.askUser(req) });
|
|
454
|
+
this.freezeInvocationTokens();
|
|
455
|
+
state.bestResult = state.bestResult ? pickPreferredResult(state.bestResult, result) : result;
|
|
456
|
+
this.adoptNativeResumeHandle(engineId, result.claudeSessionId);
|
|
457
|
+
return result;
|
|
458
|
+
}
|
|
459
|
+
adoptNativeResumeHandle(engineId, handle) {
|
|
460
|
+
recordNativeResumeHandle(this.history, engineId, handle);
|
|
461
|
+
const vetted = this.history.engineSessions?.[engineId];
|
|
462
|
+
if (vetted)
|
|
463
|
+
this.claudeSessionId = vetted;
|
|
464
|
+
}
|
|
465
|
+
askUser(req) {
|
|
466
|
+
return new Promise((resolve) => {
|
|
467
|
+
const delivered = this.emit('onAskUserQuestion', {
|
|
468
|
+
toolUseId: req.requestId,
|
|
469
|
+
questions: req.questions,
|
|
470
|
+
respond: (answers) => resolve(answers),
|
|
471
|
+
});
|
|
472
|
+
if (!delivered)
|
|
473
|
+
resolve(null);
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
async ensureEngineSession(engineId, workingDirOverride) {
|
|
477
|
+
const model = this.options.model;
|
|
478
|
+
const workingDir = workingDirOverride || this.options.workingDir;
|
|
479
|
+
const promptKey = this.options.systemPromptProfile
|
|
480
|
+
? `${this.options.systemPromptProfile}${this.options.systemPromptLang ?? ''}`
|
|
481
|
+
: undefined;
|
|
482
|
+
if (this.engineSession?.isAlive &&
|
|
483
|
+
this.engineSession.engineId === engineId &&
|
|
484
|
+
this.engineSessionModel === model &&
|
|
485
|
+
this.engineSessionWorkingDir === workingDir &&
|
|
486
|
+
this.engineSessionPromptKey === promptKey) {
|
|
487
|
+
return { session: this.engineSession, lostResume: false };
|
|
488
|
+
}
|
|
489
|
+
if (this.engineSession) {
|
|
490
|
+
const stale = this.engineSession;
|
|
491
|
+
this.engineSession = null;
|
|
492
|
+
await stale.dispose();
|
|
493
|
+
}
|
|
494
|
+
const appRun = this.options.appRun;
|
|
495
|
+
const systemPrompt = this.startSystemPrompt();
|
|
496
|
+
const startOptions = {
|
|
497
|
+
workingDir,
|
|
498
|
+
...(model ? { model } : {}),
|
|
499
|
+
...(this.options.effortLevel ? { effortLevel: this.options.effortLevel } : {}),
|
|
500
|
+
...(this.options.fastMode ? { fastMode: this.options.fastMode } : {}),
|
|
501
|
+
...(this.options.ultracode ? { ultracode: this.options.ultracode } : {}),
|
|
502
|
+
...(systemPrompt ? { systemPrompt } : {}),
|
|
503
|
+
...(this.options.disallowedTools ? { disallowedTools: this.options.disallowedTools } : {}),
|
|
504
|
+
...(this.claudeSessionId ? { resumeSessionId: this.claudeSessionId } : {}),
|
|
505
|
+
...(appRun ? { appRun } : {}),
|
|
506
|
+
};
|
|
507
|
+
const session = await EngineSession.start(engineId, startOptions);
|
|
508
|
+
this.engineSession = session;
|
|
509
|
+
this.engineSessionModel = model;
|
|
510
|
+
this.engineSessionWorkingDir = workingDir;
|
|
511
|
+
this.engineSessionPromptKey = promptKey;
|
|
512
|
+
return { session, lostResume: this.lostNativeResume(engineId, session, startOptions.resumeSessionId) };
|
|
513
|
+
}
|
|
514
|
+
lostNativeResume(engineId, session, resumeSessionId) {
|
|
515
|
+
if (resumeSessionId === undefined || session.resumedNatively !== false)
|
|
516
|
+
return false;
|
|
517
|
+
herror(`[session] ${this.sessionId}: ${engineId} could not continue ${resumeSessionId}; this turn carries the transcript`);
|
|
518
|
+
return true;
|
|
519
|
+
}
|
|
520
|
+
startSystemPrompt() {
|
|
521
|
+
if (this.options.appRun)
|
|
522
|
+
return this.options.appSystemPrompt;
|
|
523
|
+
if (!this.options.systemPromptProfile)
|
|
524
|
+
return undefined;
|
|
525
|
+
return resolveSystemPromptContent(this.options.systemPromptProfile, this.options.systemPromptLang);
|
|
526
|
+
}
|
|
527
|
+
disposeEngineSession() {
|
|
528
|
+
if (!this.engineSession)
|
|
529
|
+
return;
|
|
530
|
+
const session = this.engineSession;
|
|
531
|
+
this.engineSession = null;
|
|
532
|
+
this.engineSessionModel = undefined;
|
|
533
|
+
this.engineSessionWorkingDir = undefined;
|
|
534
|
+
this.engineSessionPromptKey = undefined;
|
|
535
|
+
session.dispose().catch((err) => herror('Engine session dispose failed:', err));
|
|
536
|
+
}
|
|
537
|
+
async evaluateRetryStrategies(result, state, callbacks) {
|
|
538
|
+
const session = this.buildRetrySessionState();
|
|
539
|
+
if (isTerminalEngineNotice(result)) {
|
|
540
|
+
herror(`[session] ${this.sessionId}: no retry — engine notice (${result.engineNotice?.kind}): ${result.engineNotice?.text.slice(0, 120)}`);
|
|
541
|
+
this.syncSessionStateBack(session);
|
|
542
|
+
return false;
|
|
543
|
+
}
|
|
544
|
+
if (shouldRetrySessionNotFound(result, state, session, callbacks)) {
|
|
545
|
+
this.syncSessionStateBack(session);
|
|
546
|
+
return true;
|
|
547
|
+
}
|
|
548
|
+
if (shouldRetryServerError(result, state, session, callbacks)) {
|
|
549
|
+
this.syncSessionStateBack(session);
|
|
550
|
+
return true;
|
|
551
|
+
}
|
|
552
|
+
if (shouldRetrySignalCrash(result, state, session, callbacks)) {
|
|
553
|
+
this.syncSessionStateBack(session);
|
|
554
|
+
return true;
|
|
555
|
+
}
|
|
556
|
+
if (shouldRetryContextLoss(result, state, session, callbacks)) {
|
|
557
|
+
this.syncSessionStateBack(session);
|
|
558
|
+
return true;
|
|
559
|
+
}
|
|
560
|
+
if (applyToolTimeoutRetry(state, callbacks, this.options.model, this.options.effortLevel))
|
|
561
|
+
return true;
|
|
562
|
+
this.syncSessionStateBack(session);
|
|
563
|
+
return false;
|
|
564
|
+
}
|
|
565
|
+
resetExecutionState() {
|
|
566
|
+
this._isExecuting = false;
|
|
567
|
+
this._executionStartTimestamp = undefined;
|
|
568
|
+
this.executionEventLog = [];
|
|
569
|
+
this.currentRunner = null;
|
|
570
|
+
}
|
|
571
|
+
handleCancelledExecution(result, userPrompt, sequenceNumber, execStart, state) {
|
|
572
|
+
this.resetExecutionState();
|
|
573
|
+
if (result)
|
|
574
|
+
this.adoptNativeResumeHandle(this.resolveEngineId(), result.claudeSessionId);
|
|
575
|
+
this.isFirstPrompt = false;
|
|
576
|
+
const origin = this._cancelOrigin;
|
|
577
|
+
const buildArgs = { sequenceNumber, userPrompt, execStart, msgId: this._currentMsgId, ...this.movementMetaArgs(), outcome: this.outcomeExtras(state) };
|
|
578
|
+
if (this._cancelCompleteEmitted) {
|
|
579
|
+
const existingIdx = this.history.movements.findIndex(m => m.sequenceNumber === sequenceNumber);
|
|
580
|
+
if (existingIdx >= 0) {
|
|
581
|
+
const existing = this.history.movements[existingIdx];
|
|
582
|
+
const resultHasContent = !!result && (!!result.assistantResponse || (result.toolUseHistory?.length ?? 0) > 0);
|
|
583
|
+
if (!result || (!resultHasContent && (existing.assistantResponse || existing.toolUseHistory?.length))) {
|
|
584
|
+
this.persistHistory();
|
|
585
|
+
return existing;
|
|
586
|
+
}
|
|
587
|
+
const upgraded = buildCancelledMovement(result, buildArgs, { origin, retryLog: state?.retryLog });
|
|
588
|
+
upgraded.durationMs = existing.durationMs;
|
|
589
|
+
this.persistMovement(upgraded);
|
|
590
|
+
return upgraded;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
const cancelledMovement = buildCancelledMovement(result, buildArgs, { origin, retryLog: state?.retryLog });
|
|
594
|
+
this.persistMovement(cancelledMovement);
|
|
595
|
+
this.emitMovementComplete(cancelledMovement, result ?? CANCELLED_FALLBACK_RESULT, execStart, sequenceNumber);
|
|
596
|
+
return cancelledMovement;
|
|
597
|
+
}
|
|
598
|
+
handleExecutionError(error, displayPrompt, sequenceNumber, execStart, failedResult, state) {
|
|
599
|
+
this.resetExecutionState();
|
|
600
|
+
if (failedResult)
|
|
601
|
+
this.adoptNativeResumeHandle(this.resolveEngineId(), failedResult.claudeSessionId);
|
|
602
|
+
this.isFirstPrompt = false;
|
|
603
|
+
const errorMessage = error instanceof EngineStartError
|
|
604
|
+
? formatErrorMarker(error.code, error.message)
|
|
605
|
+
: error instanceof Error ? error.message : String(error);
|
|
606
|
+
const reported = error instanceof EngineStartError ? new Error(errorMessage, { cause: error }) : error;
|
|
607
|
+
const errorMovement = buildErrorMovement(errorMessage, { sequenceNumber, userPrompt: displayPrompt, execStart, msgId: this._currentMsgId, ...this.movementMetaArgs(), outcome: this.outcomeExtras(state) }, failedResult, state?.retryLog);
|
|
608
|
+
this.persistMovement(errorMovement);
|
|
609
|
+
this.flushOutputQueue();
|
|
610
|
+
this.emit('onMovementError', reported, sequenceNumber);
|
|
611
|
+
trackEvent(AnalyticsEvents.IMPROVISE_MOVEMENT_ERROR, {
|
|
612
|
+
error_message: errorMessage.slice(0, 200),
|
|
613
|
+
sequence_number: sequenceNumber,
|
|
614
|
+
duration_ms: Date.now() - execStart,
|
|
615
|
+
model: this.options.model || 'default',
|
|
616
|
+
effort_level: this.options.effortLevel || 'auto',
|
|
617
|
+
});
|
|
618
|
+
if (!parseErrorMarker(errorMessage)) {
|
|
619
|
+
this.queueOutput(`\n❌ Error: ${errorMessage}\n`);
|
|
620
|
+
}
|
|
621
|
+
this.flushOutputQueue();
|
|
622
|
+
throw reported;
|
|
623
|
+
}
|
|
624
|
+
captureSessionAndSurfaceErrors(result) {
|
|
625
|
+
this.adoptNativeResumeHandle(this.resolveEngineId(), result.claudeSessionId);
|
|
626
|
+
if (!result.completed && result.error && !result.engineNotice) {
|
|
627
|
+
const line = parseErrorMarker(result.error)
|
|
628
|
+
? result.error
|
|
629
|
+
: formatErrorMarker(result.errorCode ?? 'EXECUTION_FAILED', result.error);
|
|
630
|
+
this.queueOutput(`\n${line}\n`);
|
|
631
|
+
this.flushOutputQueue();
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
handleConflicts(result) {
|
|
635
|
+
if (!result.conflicts || result.conflicts.length === 0)
|
|
636
|
+
return;
|
|
637
|
+
this.queueOutput(`\n⚠ File conflicts detected: ${result.conflicts.length}`);
|
|
638
|
+
result.conflicts.forEach(c => {
|
|
639
|
+
this.queueOutput(` - ${c.filePath} (modified by: ${c.modifiedBy.join(', ')})`);
|
|
640
|
+
if (c.backupPath)
|
|
641
|
+
this.queueOutput(` Backup created: ${c.backupPath}`);
|
|
642
|
+
});
|
|
643
|
+
this.flushOutputQueue();
|
|
644
|
+
}
|
|
645
|
+
persistMovement(movement) {
|
|
646
|
+
const existingIdx = this.history.movements.findIndex(m => m.sequenceNumber === movement.sequenceNumber);
|
|
647
|
+
if (existingIdx >= 0) {
|
|
648
|
+
const previousTokens = this.history.movements[existingIdx].tokensUsed;
|
|
649
|
+
this.history.movements[existingIdx] = movement;
|
|
650
|
+
this.history.totalTokens += movement.tokensUsed - previousTokens;
|
|
651
|
+
}
|
|
652
|
+
else {
|
|
653
|
+
this.history.movements.push(movement);
|
|
654
|
+
this.history.totalTokens += movement.tokensUsed;
|
|
655
|
+
}
|
|
656
|
+
this.history.execution = this.executionRecord();
|
|
657
|
+
this.persistHistory();
|
|
658
|
+
}
|
|
659
|
+
executionRecord() {
|
|
660
|
+
const model = this._resolvedModel ?? this.options.model;
|
|
661
|
+
return {
|
|
662
|
+
engine: this.resolveEngineId(),
|
|
663
|
+
...(model ? { model } : {}),
|
|
664
|
+
...(this.options.effortLevel ? { effortLevel: this.options.effortLevel } : {}),
|
|
665
|
+
...(this.options.fastMode ? { fastMode: true } : {}),
|
|
666
|
+
...(this.options.ultracode ? { ultracode: true } : {}),
|
|
667
|
+
...(this.options.systemPromptProfile ? { systemPromptProfile: this.options.systemPromptProfile } : {}),
|
|
668
|
+
...(this.options.systemPromptLang ? { systemPromptLang: this.options.systemPromptLang } : {}),
|
|
669
|
+
};
|
|
670
|
+
}
|
|
671
|
+
movementMetaArgs() {
|
|
672
|
+
return {
|
|
673
|
+
...this.executionMeta(),
|
|
674
|
+
...(this._currentAttachments.length > 0 ? { attachments: this._currentAttachments } : {}),
|
|
675
|
+
};
|
|
676
|
+
}
|
|
677
|
+
emitMovementComplete(movement, result, execStart, sequenceNumber) {
|
|
678
|
+
this.emit('onMovementComplete', movement);
|
|
679
|
+
trackEvent(AnalyticsEvents.IMPROVISE_MOVEMENT_COMPLETED, {
|
|
680
|
+
tokens_used: movement.tokensUsed,
|
|
681
|
+
duration_ms: Date.now() - execStart,
|
|
682
|
+
sequence_number: sequenceNumber,
|
|
683
|
+
tool_count: result.toolUseHistory?.length || 0,
|
|
684
|
+
model: this.options.model || 'default',
|
|
685
|
+
effort_level: this.options.effortLevel || 'auto',
|
|
686
|
+
});
|
|
687
|
+
this.emit('onSessionUpdate', this.getHistory());
|
|
688
|
+
}
|
|
689
|
+
_autoContinueCount = 0;
|
|
690
|
+
_autoContinuePending = false;
|
|
691
|
+
static MAX_AUTO_CONTINUES = 1;
|
|
692
|
+
maybeAutoContinue(result, userPrompt) {
|
|
693
|
+
if (this._cancelled)
|
|
694
|
+
return;
|
|
695
|
+
if (result.engineNotice?.kind === 'limit') {
|
|
696
|
+
this.scheduleLimitContinue(result.engineNotice);
|
|
697
|
+
return;
|
|
698
|
+
}
|
|
699
|
+
if (result.engineNotice || result.startupTimedOut)
|
|
700
|
+
return;
|
|
701
|
+
if (result.completed && result.pendingWakeup) {
|
|
702
|
+
this.scheduleWakeupContinue(result.pendingWakeup);
|
|
703
|
+
return;
|
|
704
|
+
}
|
|
705
|
+
const isStallKill = !!result.signalName || !!result.interrupted;
|
|
706
|
+
if (isStallKill && this._autoContinueCount < ImprovisationSessionManager.MAX_AUTO_CONTINUES) {
|
|
707
|
+
this.scheduleAutoContinue('Process stalled', stallContinuationPrompt(result));
|
|
708
|
+
}
|
|
709
|
+
else if (shouldAutoContinue(result, this._autoContinueCount, ImprovisationSessionManager.MAX_AUTO_CONTINUES, this._cancelled)) {
|
|
710
|
+
this.scheduleAutoContinue();
|
|
711
|
+
}
|
|
712
|
+
void userPrompt;
|
|
713
|
+
}
|
|
714
|
+
scheduleAutoContinue(reason, continuationPrompt) {
|
|
715
|
+
this._autoContinueCount++;
|
|
716
|
+
this._autoContinuePending = true;
|
|
717
|
+
const msg = reason || 'Response appears incomplete';
|
|
718
|
+
this.queueOutput(`\n[[MINIONRY_AUTO_CONTINUE]] ${msg} — resuming session (retry ${this._autoContinueCount}/${ImprovisationSessionManager.MAX_AUTO_CONTINUES}).\n`);
|
|
719
|
+
this.flushOutputQueue();
|
|
720
|
+
setImmediate(() => {
|
|
721
|
+
if (this._cancelled || this._isExecuting || !this._autoContinuePending)
|
|
722
|
+
return;
|
|
723
|
+
this._autoContinuePending = false;
|
|
724
|
+
this.runAutomaticContinuation(continuationPrompt ?? 'continue', 'continue');
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
runAutomaticContinuation(prompt, displayPrompt) {
|
|
728
|
+
const blocker = engineAvailability.automaticDispatchBlocker();
|
|
729
|
+
if (blocker?.kind === 'limit' && blocker.until !== undefined) {
|
|
730
|
+
this.queueOutput(`\n[[MINIONRY_LIMIT_PARK]] Automatic continuation deferred — ${describeDispatchBlocker(blocker)}.\n`);
|
|
731
|
+
this.flushOutputQueue();
|
|
732
|
+
this.armTimerAt(blocker.until, () => this.runAutomaticContinuation(prompt, displayPrompt));
|
|
733
|
+
return;
|
|
734
|
+
}
|
|
735
|
+
if (blocker?.kind === 'auth') {
|
|
736
|
+
this.queueOutput(`\n[[MINIONRY_ERROR:AUTH_REQUIRED]] Automatic continuation skipped — ${describeDispatchBlocker(blocker)}. Send a new prompt once you are logged in.\n`);
|
|
737
|
+
this.flushOutputQueue();
|
|
738
|
+
return;
|
|
739
|
+
}
|
|
740
|
+
this.executePrompt(prompt, undefined, { isAutoContinue: true, displayPrompt }).catch((err) => {
|
|
741
|
+
herror('Automatic continuation failed:', err);
|
|
742
|
+
});
|
|
743
|
+
}
|
|
744
|
+
armTimerAt(at, fn) {
|
|
745
|
+
const MAX_TIMER_MS = 24 * 60 * 60_000;
|
|
746
|
+
const delay = Math.min(Math.max(at - Date.now(), 0), MAX_TIMER_MS);
|
|
747
|
+
this.clearWakeupTimer();
|
|
748
|
+
this._wakeupTimer = setTimeout(() => {
|
|
749
|
+
this._wakeupTimer = null;
|
|
750
|
+
if (this._isExecuting || this._cancelled)
|
|
751
|
+
return;
|
|
752
|
+
if (Date.now() < at) {
|
|
753
|
+
this.armTimerAt(at, fn);
|
|
754
|
+
return;
|
|
755
|
+
}
|
|
756
|
+
fn();
|
|
757
|
+
}, delay);
|
|
758
|
+
}
|
|
759
|
+
_limitContinueCount = 0;
|
|
760
|
+
static MAX_LIMIT_CONTINUES = 3;
|
|
761
|
+
scheduleLimitContinue(notice) {
|
|
762
|
+
const resetAt = notice.resetAt ?? Date.now() + 15 * 60_000;
|
|
763
|
+
if (this._limitContinueCount >= ImprovisationSessionManager.MAX_LIMIT_CONTINUES) {
|
|
764
|
+
this.queueOutput(`\n[[MINIONRY_LIMIT_PARK]] Usage limit reached again — ${ImprovisationSessionManager.MAX_LIMIT_CONTINUES} automatic resumes already used for this prompt. Send a new prompt after ${describeParkUntil(resetAt)}.\n`);
|
|
765
|
+
this.flushOutputQueue();
|
|
766
|
+
return;
|
|
767
|
+
}
|
|
768
|
+
this._limitContinueCount++;
|
|
769
|
+
this.queueOutput(`\n[[MINIONRY_LIMIT_PARK]] Usage limit reached — this conversation resumes automatically at ${describeParkUntil(resetAt)} (resume ${this._limitContinueCount}/${ImprovisationSessionManager.MAX_LIMIT_CONTINUES}).${notice.resetParsed ? '' : ' The notice named no reset time, so this is a short wait; a new prompt from you overrides it.'}\n`);
|
|
770
|
+
this.flushOutputQueue();
|
|
771
|
+
this.armTimerAt(resetAt, () => this.runAutomaticContinuation('Your previous turn stopped because the usage limit was reached. The limit has reset — continue the task from where you left off.', 'continue (after usage limit reset)'));
|
|
772
|
+
}
|
|
773
|
+
_wakeupTimer = null;
|
|
774
|
+
_wakeupContinueCount = 0;
|
|
775
|
+
static MAX_WAKEUP_CONTINUES = 24;
|
|
776
|
+
clearWakeupTimer() {
|
|
777
|
+
if (this._wakeupTimer) {
|
|
778
|
+
clearTimeout(this._wakeupTimer);
|
|
779
|
+
this._wakeupTimer = null;
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
scheduleWakeupContinue(wakeup) {
|
|
783
|
+
if (this._wakeupContinueCount >= ImprovisationSessionManager.MAX_WAKEUP_CONTINUES) {
|
|
784
|
+
this.queueOutput(`\n[[MINIONRY_BACKGROUND_WAIT]] Scheduled wakeup NOT honored — ${ImprovisationSessionManager.MAX_WAKEUP_CONTINUES} automatic continuations reached for this prompt. Send a new prompt to keep going.\n`);
|
|
785
|
+
this.flushOutputQueue();
|
|
786
|
+
return;
|
|
787
|
+
}
|
|
788
|
+
this._wakeupContinueCount++;
|
|
789
|
+
const delayMs = Math.min(Math.max(wakeup.fireAtMs - Date.now(), 0), 3_600_000);
|
|
790
|
+
const fireAt = new Date(Date.now() + delayMs);
|
|
791
|
+
this.queueOutput(`\n[[MINIONRY_BACKGROUND_WAIT]] Scheduled wakeup honored — session resumes at ${fireAt.toLocaleTimeString()} (continuation ${this._wakeupContinueCount}/${ImprovisationSessionManager.MAX_WAKEUP_CONTINUES})${wakeup.reason ? `: ${wakeup.reason}` : ''}.\n`);
|
|
792
|
+
this.flushOutputQueue();
|
|
793
|
+
const prompt = wakeup.prompt && !wakeup.prompt.startsWith('<<')
|
|
794
|
+
? wakeup.prompt
|
|
795
|
+
: 'Your scheduled wakeup fired. Check progress on your background work and continue the task.';
|
|
796
|
+
this.clearWakeupTimer();
|
|
797
|
+
this._wakeupTimer = setTimeout(() => {
|
|
798
|
+
this._wakeupTimer = null;
|
|
799
|
+
if (this._isExecuting || this._cancelled)
|
|
800
|
+
return;
|
|
801
|
+
this.runAutomaticContinuation(prompt, 'continue (scheduled wakeup)');
|
|
802
|
+
}, delayMs);
|
|
803
|
+
}
|
|
804
|
+
executionMeta() {
|
|
805
|
+
return {
|
|
806
|
+
engine: this.resolveEngineId(),
|
|
807
|
+
model: this._resolvedModel ?? this.options.model,
|
|
808
|
+
fastMode: this.options.fastMode,
|
|
809
|
+
};
|
|
810
|
+
}
|
|
811
|
+
async refreshEtaProfile() {
|
|
812
|
+
try {
|
|
813
|
+
this._etaProfile = await getEtaProfileCached(this.improviseDir, this.executionMeta());
|
|
814
|
+
}
|
|
815
|
+
catch {
|
|
816
|
+
this._etaProfile = null;
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
persistHistory() {
|
|
820
|
+
if (!this.history.origin)
|
|
821
|
+
this.history.origin = currentSessionOrigin(this.options.workingDir);
|
|
822
|
+
saveHistory(this.historyPath, this.history);
|
|
823
|
+
if (!this._hasPersistedToDisk) {
|
|
824
|
+
this._hasPersistedToDisk = true;
|
|
825
|
+
this.emit('onHistoryPersisted');
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
getHistory() {
|
|
829
|
+
return this.history;
|
|
830
|
+
}
|
|
831
|
+
_cancelOrigin = 'user';
|
|
832
|
+
_currentRetryState = null;
|
|
833
|
+
_currentMsgId;
|
|
834
|
+
_assessorDegradedNoticeEmitted = false;
|
|
835
|
+
snapshotInFlightResult() {
|
|
836
|
+
const runner = this.currentRunner;
|
|
837
|
+
const snapshot = runner && typeof runner.snapshot === 'function' ? runner.snapshot() : null;
|
|
838
|
+
if (!snapshot)
|
|
839
|
+
return CANCELLED_FALLBACK_RESULT;
|
|
840
|
+
return {
|
|
841
|
+
...CANCELLED_FALLBACK_RESULT,
|
|
842
|
+
...(snapshot.assistantResponse !== undefined ? { assistantResponse: snapshot.assistantResponse } : {}),
|
|
843
|
+
...(snapshot.thinkingOutput !== undefined ? { thinkingOutput: snapshot.thinkingOutput } : {}),
|
|
844
|
+
...(snapshot.toolUseHistory ? { toolUseHistory: snapshot.toolUseHistory } : {}),
|
|
845
|
+
...(snapshot.claudeSessionId ? { claudeSessionId: snapshot.claudeSessionId } : {}),
|
|
846
|
+
...(snapshot.apiTokenUsage ? { apiTokenUsage: snapshot.apiTokenUsage, outputTokens: snapshot.apiTokenUsage.outputTokens } : {}),
|
|
847
|
+
...(snapshot.engineNotice ? { engineNotice: snapshot.engineNotice } : {}),
|
|
848
|
+
};
|
|
849
|
+
}
|
|
850
|
+
settleInFlight(origin) {
|
|
851
|
+
this._cancelled = true;
|
|
852
|
+
this._cancelOrigin = origin;
|
|
853
|
+
this.clearWakeupTimer();
|
|
854
|
+
this._autoContinuePending = false;
|
|
855
|
+
const snapshot = this._isExecuting ? this.snapshotInFlightResult() : undefined;
|
|
856
|
+
if (this.currentRunner) {
|
|
857
|
+
this.currentRunner.cleanup();
|
|
858
|
+
this.currentRunner = null;
|
|
859
|
+
}
|
|
860
|
+
this.engineSession?.cancel().catch((err) => herror('Engine session cancel failed:', err));
|
|
861
|
+
if (this._isExecuting && !this._cancelCompleteEmitted) {
|
|
862
|
+
this._cancelCompleteEmitted = true;
|
|
863
|
+
const execStart = this._executionStartTimestamp || Date.now();
|
|
864
|
+
this._isExecuting = false;
|
|
865
|
+
this._executionStartTimestamp = undefined;
|
|
866
|
+
if (snapshot?.claudeSessionId)
|
|
867
|
+
this.adoptNativeResumeHandle(this.resolveEngineId(), snapshot.claudeSessionId);
|
|
868
|
+
const cancelledMovement = buildCancelledMovement(snapshot, {
|
|
869
|
+
sequenceNumber: this._currentSequenceNumber,
|
|
870
|
+
userPrompt: this._currentUserPrompt,
|
|
871
|
+
execStart,
|
|
872
|
+
msgId: this._currentMsgId,
|
|
873
|
+
...this.movementMetaArgs(),
|
|
874
|
+
outcome: this.outcomeExtras(this._currentRetryState),
|
|
875
|
+
}, { origin, retryLog: this._currentRetryState?.retryLog });
|
|
876
|
+
this.persistMovement(cancelledMovement);
|
|
877
|
+
this.emitMovementComplete(cancelledMovement, snapshot ?? CANCELLED_FALLBACK_RESULT, execStart, this._currentSequenceNumber);
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
cancel() {
|
|
881
|
+
this.settleInFlight('user');
|
|
882
|
+
this.outputBuffer.destroy();
|
|
883
|
+
this.thinkingBuffer.destroy();
|
|
884
|
+
this.flushOutputQueue();
|
|
885
|
+
}
|
|
886
|
+
settleForLifecycle(origin) {
|
|
887
|
+
if (!this._isExecuting)
|
|
888
|
+
return false;
|
|
889
|
+
this.settleInFlight(origin);
|
|
890
|
+
this.flushOutputQueue();
|
|
891
|
+
return true;
|
|
892
|
+
}
|
|
893
|
+
destroy() {
|
|
894
|
+
if (this._isExecuting)
|
|
895
|
+
this.settleInFlight('destroy');
|
|
896
|
+
this.clearWakeupTimer();
|
|
897
|
+
if (this.currentRunner) {
|
|
898
|
+
this.currentRunner.cleanup();
|
|
899
|
+
this.currentRunner = null;
|
|
900
|
+
}
|
|
901
|
+
this.disposeEngineSession();
|
|
902
|
+
this.outputBuffer.destroy();
|
|
903
|
+
this.thinkingBuffer.destroy();
|
|
904
|
+
this.flushOutputQueue();
|
|
905
|
+
}
|
|
906
|
+
clearHistory() {
|
|
907
|
+
this.history.movements = [];
|
|
908
|
+
this.history.totalTokens = 0;
|
|
909
|
+
this.accumulatedKnowledge = '';
|
|
910
|
+
this.isFirstPrompt = true;
|
|
911
|
+
this.claudeSessionId = undefined;
|
|
912
|
+
forgetNativeResumeHandles(this.history);
|
|
913
|
+
this.disposeEngineSession();
|
|
914
|
+
cleanupAttachments(this.options.workingDir, this.sessionId);
|
|
915
|
+
this.persistHistory();
|
|
916
|
+
this.emit('onSessionUpdate', this.getHistory());
|
|
917
|
+
}
|
|
918
|
+
async requestApproval(plan) {
|
|
919
|
+
return new Promise((resolve) => {
|
|
920
|
+
this.pendingApproval = { plan, resolve };
|
|
921
|
+
this.emit('onApprovalRequired', plan);
|
|
922
|
+
});
|
|
923
|
+
}
|
|
924
|
+
respondToApproval(approved) {
|
|
925
|
+
if (this.pendingApproval) {
|
|
926
|
+
this.pendingApproval.resolve(approved);
|
|
927
|
+
this.pendingApproval = undefined;
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
getSessionInfo() {
|
|
931
|
+
return {
|
|
932
|
+
sessionId: this.sessionId,
|
|
933
|
+
startTime: this.history.startedAt,
|
|
934
|
+
workingDir: this.options.workingDir,
|
|
935
|
+
totalTokens: this.history.totalTokens,
|
|
936
|
+
tokenBudgetThreshold: this.options.tokenBudgetThreshold,
|
|
937
|
+
movementCount: this.history.movements.length,
|
|
938
|
+
};
|
|
939
|
+
}
|
|
940
|
+
get isExecuting() {
|
|
941
|
+
return this._isExecuting;
|
|
942
|
+
}
|
|
943
|
+
setTabId(tabId) {
|
|
944
|
+
this.options.tabId = tabId;
|
|
945
|
+
}
|
|
946
|
+
setPlanId(planId) {
|
|
947
|
+
this.options.planId = planId;
|
|
948
|
+
}
|
|
949
|
+
get agentId() {
|
|
950
|
+
return `agent-${this.sessionId}`;
|
|
951
|
+
}
|
|
952
|
+
get agentLabel() {
|
|
953
|
+
return this.options.agentLabel ?? this.sessionId;
|
|
954
|
+
}
|
|
955
|
+
get planId() {
|
|
956
|
+
return this.options.planId;
|
|
957
|
+
}
|
|
958
|
+
get appOrigin() {
|
|
959
|
+
return this.options.appOrigin;
|
|
960
|
+
}
|
|
961
|
+
get engine() {
|
|
962
|
+
return this.history.engine || 'claude-code';
|
|
963
|
+
}
|
|
964
|
+
get executionStartTimestamp() {
|
|
965
|
+
return this._executionStartTimestamp;
|
|
966
|
+
}
|
|
967
|
+
resolveClaudeCodeEffort() {
|
|
968
|
+
const modelForTier = this._resolvedModel ?? this.options.model;
|
|
969
|
+
return resolveClaudeEffort(modelForTier, this.options.effortLevel) ?? this.options.effortLevel;
|
|
970
|
+
}
|
|
971
|
+
getExecutionTarget() {
|
|
972
|
+
const profile = this.options.systemPromptProfile;
|
|
973
|
+
const engine = this.resolveEngineId();
|
|
974
|
+
const isClaudeDefaultModel = engine === 'claude-code' && this.options.model === 'default';
|
|
975
|
+
return {
|
|
976
|
+
engine,
|
|
977
|
+
model: this._resolvedModel ?? (isClaudeDefaultModel ? undefined : this.options.model),
|
|
978
|
+
effortLevel: engine === 'claude-code' ? this.resolveClaudeCodeEffort() : this.options.effortLevel,
|
|
979
|
+
fastMode: this.options.fastMode,
|
|
980
|
+
ultracode: this.options.ultracode,
|
|
981
|
+
...(profile
|
|
982
|
+
? {
|
|
983
|
+
systemPromptProfile: profile,
|
|
984
|
+
systemPromptLang: this.options.systemPromptLang,
|
|
985
|
+
systemPromptLabel: resolveSystemPromptLabel(profile),
|
|
986
|
+
}
|
|
987
|
+
: {}),
|
|
988
|
+
};
|
|
989
|
+
}
|
|
990
|
+
get etaProfile() {
|
|
991
|
+
return this._etaProfile;
|
|
992
|
+
}
|
|
993
|
+
getExecutionEventLog() {
|
|
994
|
+
return this.executionEventLog;
|
|
995
|
+
}
|
|
996
|
+
startNewSession(overrides) {
|
|
997
|
+
this.persistHistory();
|
|
998
|
+
return new ImprovisationSessionManager({
|
|
999
|
+
...this.options,
|
|
1000
|
+
sessionId: `improv-${Date.now()}`,
|
|
1001
|
+
...overrides,
|
|
1002
|
+
});
|
|
1003
|
+
}
|
|
1004
|
+
static abortPlan(planId, deps, opts = {}) {
|
|
1005
|
+
return abortPlanCascade(planId, deps, opts);
|
|
1006
|
+
}
|
|
1007
|
+
static pausePlan(planId, deps) {
|
|
1008
|
+
return pausePlanCascade(planId, deps);
|
|
1009
|
+
}
|
|
1010
|
+
static resumePlan(planId, deps) {
|
|
1011
|
+
return resumePlanCascade(planId, deps);
|
|
1012
|
+
}
|
|
1013
|
+
static completePlan(planId, deps) {
|
|
1014
|
+
return completePlanCascade(planId, deps);
|
|
1015
|
+
}
|
|
1016
|
+
}
|