@staix/agent-hub 0.51.0 → 0.52.0
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/CHANGELOG.md +35 -0
- package/README.md +1 -1
- package/docs/adding-an-ai-tool.md +24 -2
- package/docs/agent-notes/adapters.md +1 -0
- package/docs/agent-notes/budget.md +8 -2
- package/docs/agent-notes/daemon.md +13 -8
- package/docs/agent-notes/security-review.md +6 -5
- package/docs/agent-notes/tasks.md +5 -2
- package/docs/agent-notes/tests.md +4 -3
- package/docs/cooperbench.md +1 -1
- package/docs/design/adapters.md +4 -0
- package/docs/design/cli-output-inventory.md +162 -152
- package/docs/design/cli-output.md +4 -3
- package/docs/design/guidance-probes.md +1 -0
- package/docs/design/roadmap.md +2 -0
- package/docs/design/task-board.md +1 -0
- package/docs/dogfood.md +14 -0
- package/docs/events.md +4 -2
- package/docs/memory.md +5 -3
- package/docs/operations.md +210 -16
- package/docs/quickstart.md +12 -2
- package/docs/roles.md +1 -1
- package/docs/sdlc.md +26 -3
- package/docs/security.md +11 -5
- package/docs/specs/2026-09-19-agent-hub-design.md +43 -0
- package/docs/specs/2026-09-19-multi-project-design.md +4 -0
- package/docs/specs/2026-09-20-upgrade-recovery-design.md +17 -0
- package/docs/specs/mcp-endpoint.md +63 -0
- package/docs/verification/2026-11-30-capability-listing-shape-1808.md +45 -0
- package/docs/verification/2026-11-30-upgrade-keep-1807.md +174 -0
- package/docs/verification/2026-12-01-1811-confirmation-receipt.md +19 -0
- package/docs/verification/2026-12-01-1811-orca-agent-list.md +20 -0
- package/docs/verification/2026-12-01-1811-orca-pane-key.md +21 -0
- package/docs/verification/2026-12-02-1819-claude-process-after-renewal.md +54 -0
- package/docs/verification/2026-12-02-agy-1.5.21.md +74 -0
- package/docs/verification/2026-12-02-claude-implementer-2.1.334.md +44 -0
- package/docs/verification/2026-12-02-cli-import-graph.md +33 -0
- package/docs/verification/2026-12-03-0.52.0.md +150 -0
- package/docs/verification/2026-12-03-codex-0173-reviewer-isolation.md +53 -0
- package/docs/verification/2026-12-03-codex-0173-reviewer-tool-call.md +34 -0
- package/docs/verification/2026-12-03-jcode-1.3.0.md +25 -0
- package/docs/verification/agy/README.md +17 -0
- package/docs/verification/agy/cli-surface.ts +68 -0
- package/docs/verification/agy/interactive-bridge.ts +92 -0
- package/docs/verification/agy/interactive-session.ts +131 -0
- package/docs/verification/agy/launcher-nonce.ts +215 -0
- package/docs/verification/agy/native-hooks.ts +210 -0
- package/docs/verification/agy/originals/agent-hub-681/cli-surface.ts +87 -0
- package/docs/verification/agy/originals/agent-hub-681/native-hooks-adapted.ts +91 -0
- package/docs/verification/agy/originals/agent-hub-681/tui-actual.ts +200 -0
- package/docs/verification/agy/originals/agent-hub-684/probe.ts +107 -0
- package/docs/verification/agy/originals.json +25 -0
- package/docs/verification/agy/permission-new-functions.ts +128 -0
- package/docs/verification/agy/run-probe.py +108 -0
- package/docs/verification/agy/runtime.ts +171 -0
- package/docs/verification/agy/tmux-helper-control.ts +6 -0
- package/docs/verification/agy/tmux-session.ts +235 -0
- package/docs/verified.json +82 -41
- package/package.json +3 -3
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/compat.json +157 -0
- package/plugins/agent-hub/kimi-hook.js +621 -865
- package/plugins/agent-hub/server.js +17423 -32962
- package/src/adapters/agy/definition.ts +7 -24
- package/src/adapters/channel-peer.ts +3 -1
- package/src/adapters/claude-channel.ts +38 -257
- package/src/adapters/claude-implementer.ts +3 -1
- package/src/adapters/codex-appserver.ts +77 -15
- package/src/adapters/compat.ts +74 -11
- package/src/adapters/configured-acp.ts +23 -163
- package/src/adapters/configured-adapter-policy.ts +160 -0
- package/src/adapters/configured-pull-entry.ts +53 -0
- package/src/adapters/configured-pull.ts +38 -0
- package/src/adapters/conformance/fakes/app-server.ts +9 -2
- package/src/adapters/declaration-catalog.ts +25 -0
- package/src/adapters/declaration-data.ts +342 -0
- package/src/adapters/declaration-resolution.ts +53 -0
- package/src/adapters/definitions/builtin-metadata.ts +61 -83
- package/src/adapters/definitions/jcode-launch.ts +13 -0
- package/src/adapters/definitions/native-adapter-policy.ts +390 -0
- package/src/adapters/definitions/native-cli-claude-launch.ts +3 -2
- package/src/adapters/definitions/native-cli-codex-launch.ts +2 -1
- package/src/adapters/definitions/native-cli-entry-jcode.ts +4 -2
- package/src/adapters/definitions/native-cli-entry-types.ts +9 -2
- package/src/adapters/definitions/native-cli-launch-common.ts +2 -2
- package/src/adapters/definitions/native-cli-retained.ts +1 -1
- package/src/adapters/definitions/native-configuration.ts +18 -0
- package/src/adapters/definitions/native-help.ts +24 -0
- package/src/adapters/definitions/native-launch-declarations.ts +34 -0
- package/src/adapters/definitions/native-launch-policy.ts +4 -0
- package/src/adapters/definitions/native-launch-settings.ts +72 -0
- package/src/adapters/definitions/native-light-cli.ts +18 -0
- package/src/adapters/definitions/native-light-preview.ts +10 -0
- package/src/adapters/definitions/native-wrapper-launch.ts +10 -0
- package/src/adapters/definitions/qwen.ts +6 -29
- package/src/adapters/definitions/reviewer-variants.ts +7 -8
- package/src/adapters/external-declarations.ts +31 -0
- package/src/adapters/external-modules.ts +4 -29
- package/src/adapters/jcode.ts +3 -12
- package/src/adapters/native-capabilities.ts +18 -8
- package/src/adapters/native-proof-ports.ts +1 -1
- package/src/adapters/presets.ts +136 -0
- package/src/adapters/qwen-dual.ts +2 -2
- package/src/adapters/registry-types.ts +3 -0
- package/src/adapters/registry.ts +20 -81
- package/src/adapters/reviewer-print.ts +26 -9
- package/src/adapters/role-eligibility.ts +2 -1
- package/src/cli/accounts-import.ts +72 -0
- package/src/cli/agents-latest-table.ts +88 -0
- package/src/cli/agents-latest.ts +22 -0
- package/src/cli/agents-output.ts +10 -0
- package/src/cli/agents-presets.ts +100 -0
- package/src/cli/agents.ts +1 -1
- package/src/cli/attention.ts +3 -2
- package/src/cli/autonomy-homes.ts +7 -2
- package/src/cli/budget-renew-guidance.ts +129 -0
- package/src/cli/claude-homes.ts +9 -5
- package/src/cli/command-context.ts +3 -0
- package/src/cli/command-table.ts +123 -0
- package/src/cli/commands/accounts.ts +8 -0
- package/src/cli/commands/agents.ts +18 -0
- package/src/cli/commands/answer.ts +28 -0
- package/src/cli/commands/ask.ts +17 -0
- package/src/cli/commands/autonomy.ts +83 -0
- package/src/cli/commands/backlog.ts +46 -0
- package/src/cli/commands/bench.ts +60 -0
- package/src/cli/commands/board.ts +48 -0
- package/src/cli/commands/broker.ts +9 -0
- package/src/cli/commands/budget.ts +96 -0
- package/src/cli/commands/capabilities.ts +12 -0
- package/src/cli/commands/check-path.ts +55 -0
- package/src/cli/commands/completion.ts +8 -0
- package/src/cli/commands/console.ts +12 -0
- package/src/cli/commands/daemon.ts +8 -0
- package/src/cli/commands/deliverables.ts +25 -0
- package/src/cli/commands/doctor.ts +249 -0
- package/src/cli/commands/down.ts +3 -0
- package/src/cli/commands/export.ts +15 -0
- package/src/cli/commands/facts.ts +15 -0
- package/src/cli/commands/goal.ts +22 -0
- package/src/cli/commands/guidance.ts +102 -0
- package/src/cli/commands/help.ts +17 -0
- package/src/cli/commands/host.ts +45 -0
- package/src/cli/commands/init.ts +121 -0
- package/src/cli/commands/instructed.ts +19 -0
- package/src/cli/commands/instruction-hook.ts +15 -0
- package/src/cli/commands/intake.ts +24 -0
- package/src/cli/commands/kill.ts +15 -0
- package/src/cli/commands/learn.ts +23 -0
- package/src/cli/commands/lineage.ts +30 -0
- package/src/cli/commands/logs.ts +21 -0
- package/src/cli/commands/manager.ts +15 -0
- package/src/cli/commands/memory.ts +21 -0
- package/src/cli/commands/model.ts +25 -0
- package/src/cli/commands/models.ts +40 -0
- package/src/cli/commands/native.ts +39 -0
- package/src/cli/commands/pause.ts +5 -0
- package/src/cli/commands/peer.ts +32 -0
- package/src/cli/commands/permission.ts +26 -0
- package/src/cli/commands/permit.ts +12 -0
- package/src/cli/commands/pet.ts +24 -0
- package/src/cli/commands/projects.ts +49 -0
- package/src/cli/commands/queue.ts +70 -0
- package/src/cli/commands/recovery-run.ts +13 -0
- package/src/cli/commands/recovery.ts +130 -0
- package/src/cli/commands/release.ts +23 -0
- package/src/cli/commands/releases.ts +9 -0
- package/src/cli/commands/remember.ts +6 -0
- package/src/cli/commands/report.ts +27 -0
- package/src/cli/commands/research.ts +53 -0
- package/src/cli/commands/reset.ts +89 -0
- package/src/cli/commands/restart.ts +5 -0
- package/src/cli/commands/results.ts +31 -0
- package/src/cli/commands/resume.ts +5 -0
- package/src/cli/commands/review.ts +24 -0
- package/src/cli/commands/roadmap.ts +21 -0
- package/src/cli/commands/role.ts +34 -0
- package/src/cli/commands/roles.ts +30 -0
- package/src/cli/commands/room.ts +14 -0
- package/src/cli/commands/roster.ts +48 -0
- package/src/cli/commands/route.ts +9 -0
- package/src/cli/commands/say.ts +21 -0
- package/src/cli/commands/schedule.ts +17 -0
- package/src/cli/commands/sdlc.ts +321 -0
- package/src/cli/commands/settings.ts +148 -0
- package/src/cli/commands/setup.ts +89 -0
- package/src/cli/commands/shared-refusals.ts +25 -0
- package/src/cli/commands/smoke.ts +44 -0
- package/src/cli/commands/source.ts +64 -0
- package/src/cli/commands/specs.ts +13 -0
- package/src/cli/commands/status.ts +28 -0
- package/src/cli/commands/stop.ts +17 -0
- package/src/cli/commands/structure.ts +60 -0
- package/src/cli/commands/study.ts +39 -0
- package/src/cli/commands/tail.ts +19 -0
- package/src/cli/commands/task.ts +114 -0
- package/src/cli/commands/title.ts +17 -0
- package/src/cli/commands/turns.ts +10 -0
- package/src/cli/commands/ui.ts +47 -0
- package/src/cli/commands/undo.ts +77 -0
- package/src/cli/commands/up.ts +39 -0
- package/src/cli/commands/upgrade.ts +5 -0
- package/src/cli/commands/usage.ts +33 -0
- package/src/cli/commands/version.ts +5 -0
- package/src/cli/commands/watch.ts +30 -0
- package/src/cli/commands/worktrees.ts +31 -0
- package/src/cli/console-state.ts +5 -138
- package/src/cli/console-versions.ts +1 -1
- package/src/cli/help.ts +37 -15
- package/src/cli/identity.ts +23 -4
- package/src/cli/launch-check.ts +1 -2
- package/src/cli/launch.ts +13 -82
- package/src/cli/light-dispatch.ts +29 -0
- package/src/cli/main.js +8 -1
- package/src/cli/main.ts +233 -2816
- package/src/cli/orca-probe.ts +119 -0
- package/src/cli/output.ts +31 -2
- package/src/cli/preview.ts +10 -5
- package/src/cli/recovery-version-preflight.ts +28 -9
- package/src/cli/replace-process.ts +22 -0
- package/src/cli/report-layout.ts +142 -0
- package/src/cli/roadmap-usage.ts +16 -0
- package/src/cli/roadmap.ts +3 -16
- package/src/cli/sdlc-doctor.ts +27 -0
- package/src/cli/sdlc-output.ts +55 -1
- package/src/cli/setup-homes.ts +1 -1
- package/src/cli/start-agents-run.ts +1 -1
- package/src/cli/statusline-tee.ts +25 -4
- package/src/cli/terminal-recovery.ts +53 -10
- package/src/cli/upgrade-interactive.ts +1 -0
- package/src/cli/upgrade-runtime.ts +11 -0
- package/src/cli/upgrade.ts +4 -15
- package/src/hub/accounts.ts +148 -0
- package/src/hub/addons.ts +20 -0
- package/src/hub/agent-drift.ts +2 -1
- package/src/hub/budget-projection.ts +39 -7
- package/src/hub/budget.ts +231 -16
- package/src/hub/channel-project.ts +3 -3
- package/src/hub/conductor-peer.ts +24 -0
- package/src/hub/conductor.ts +2 -21
- package/src/hub/config-apply.ts +24 -13
- package/src/hub/config-edit.ts +1 -1
- package/src/hub/config-tier.ts +2 -0
- package/src/hub/config.ts +31 -14
- package/src/hub/control-client.ts +48 -0
- package/src/hub/daemon.ts +421 -61
- package/src/hub/events.ts +3 -0
- package/src/hub/home-tag.ts +12 -0
- package/src/hub/host.ts +217 -0
- package/src/hub/hub-tools.ts +2 -1
- package/src/hub/instance-budget.ts +2 -2
- package/src/hub/instance-config.ts +15 -126
- package/src/hub/instances.ts +22 -6
- package/src/hub/instruction-receipt.ts +2 -2
- package/src/hub/kimi-usage.ts +38 -11
- package/src/hub/lifecycle.ts +86 -4
- package/src/hub/mcp-bridge-core.ts +98 -0
- package/src/hub/mcp-channel-push.ts +20 -0
- package/src/hub/mcp-endpoint-serve.ts +178 -0
- package/src/hub/mcp-endpoint.ts +226 -0
- package/src/hub/mcp-tool-call.ts +181 -0
- package/src/hub/operational-settings.ts +2 -0
- package/src/hub/orca-env.ts +6 -0
- package/src/hub/orca-state.ts +84 -0
- package/src/hub/peers.ts +5 -1
- package/src/hub/permission-mode.ts +2 -1
- package/src/hub/project.ts +20 -0
- package/src/hub/protocol-window.ts +58 -0
- package/src/hub/quota-origin.ts +20 -0
- package/src/hub/registry.ts +36 -2
- package/src/hub/report.ts +1 -1
- package/src/hub/research.ts +1 -1
- package/src/hub/review-brief.ts +47 -2
- package/src/hub/roster.ts +6 -3
- package/src/hub/routing.ts +9 -2
- package/src/hub/sdlc-check.ts +205 -0
- package/src/hub/sdlc-sync.ts +146 -0
- package/src/hub/sdlc.ts +33 -4
- package/src/hub/settings.ts +7 -4
- package/src/hub/start-agents.ts +1 -1
- package/src/hub/start-mode.ts +11 -4
- package/src/hub/structure-budget.ts +131 -0
- package/src/hub/structure-scan.ts +149 -0
- package/src/hub/tasks-experiment.ts +455 -0
- package/src/hub/tasks-guidance.ts +606 -0
- package/src/hub/tasks-roadmap-plan.ts +419 -0
- package/src/hub/tasks-roadmap.ts +491 -0
- package/src/hub/tasks-study.ts +661 -0
- package/src/hub/tasks-survey.ts +192 -0
- package/src/hub/tasks.ts +319 -2548
- package/src/hub/terminal-open.ts +5 -3
- package/src/hub/tooling.ts +3 -19
- package/src/hub/usage-rollup.ts +9 -3
- package/src/local/tools.ts +5 -0
- package/src/ui/index.html +1 -1
- package/src/ui/needs.ts +17 -5
- package/src/ui/peer-palette.ts +2 -4
- package/templates/presets/agents.json +60 -0
- package/templates/presets/confirmation-matrix.json +8 -8
package/src/hub/daemon.ts
CHANGED
|
@@ -53,6 +53,8 @@ import { parseReleaseGuardArgv, parseReleasePushUpdates } from "../cli/sdlc-rele
|
|
|
53
53
|
import type { DocEvidence, ReleaseReportPolicy } from "./sdlc-release.ts";
|
|
54
54
|
import { loadExternalAdapterDefinitions, readAdapterModuleDeclarations, externalModuleIdentity, externalModuleIdentityCurrent } from "../adapters/external-modules.ts";
|
|
55
55
|
import { WsPeer, isWsPeer } from "../adapters/channel-peer.ts";
|
|
56
|
+
import { homeTag } from "./home-tag.ts";
|
|
57
|
+
import { accountKey, accountKeyFor, baseAccount, handoffEvents, handoffSiblings, instanceAccountEnv as instanceAccountEnvOf, isClaudeAccountKind, isDeclaredReading, DEFAULT_ACCOUNT_LABEL, labelForHome } from "./accounts.ts";
|
|
56
58
|
import { ownerToolEffect, canonicalWriteUnknown } from "./no-writes.ts";
|
|
57
59
|
import { NativeHookLaunches, type NativeHookLaunch } from "./native-hook-launch.ts";
|
|
58
60
|
import { InstructionReceipts, MAX_PROMPT_BYTES } from "./instruction-receipt.ts";
|
|
@@ -84,6 +86,8 @@ import { policyPaths, policyRealPath, matchesPolicy } from "./path-policy.ts";
|
|
|
84
86
|
import { CodeFacts, type CodeFactResult, type CodeSymbol } from "./code-facts.ts";
|
|
85
87
|
import { gitAuditSource, checkoutAuditSource } from "./audit-source.ts";
|
|
86
88
|
import { buildReviewBrief, withCodeSymbols } from "./review-brief.ts";
|
|
89
|
+
import { structureNotice } from "./structure-budget.ts";
|
|
90
|
+
import { readStructureBaseline, scanStructure } from "./structure-scan.ts";
|
|
87
91
|
import { profileName, projectProfile, resolveProfile } from "./profiles.ts";
|
|
88
92
|
import { catalogAssignments, loadRoleCatalog, selectedRoles, roleIdentity } from "./roles.ts";
|
|
89
93
|
import { ActivityRing } from "./activity.ts";
|
|
@@ -93,7 +97,13 @@ import { VERSION_REFUSAL, configuredCommands, describe, isCompatId } from "../ad
|
|
|
93
97
|
import { agentVersionsAsync, type AgentVersionRow } from "../cli/agents.ts";
|
|
94
98
|
import { driftedAgents, noticeDrift, type DriftedAgent } from "./agent-drift.ts";
|
|
95
99
|
import { jcodeMcpReady } from "../cli/jcode-mcp.ts";
|
|
96
|
-
import { loadSdlc, readSpecEdit, sdlcGh, type SdlcConfig, type SdlcGh } from "./sdlc.ts";
|
|
100
|
+
import { loadSdlc, readSpecEdit, sdlcConfig, sdlcGh, type SdlcConfig, type SdlcGh } from "./sdlc.ts";
|
|
101
|
+
import { runSdlcCheck } from "./sdlc-check.ts";
|
|
102
|
+
import { planSdlcSync } from "./sdlc-sync.ts";
|
|
103
|
+
import { startMcpEndpoint, type McpEndpoint, type McpHello, type McpSessionServer } from "./mcp-endpoint.ts";
|
|
104
|
+
import { ListedTools, PushBuffers, serveMcpSession } from "./mcp-endpoint-serve.ts";
|
|
105
|
+
import { requiredChecksFor } from "./sdlc-merge.ts";
|
|
106
|
+
import { discoverInitChecks } from "../cli/init-required-checks.ts";
|
|
97
107
|
import { claudePeer as defaultChannelPeer, claudeStateFile, isClaudeSessionUuid, ownTerminalRow, pathEvidence, transcriptPersisted } from "./claude-state.ts";
|
|
98
108
|
import { peerRosterConfig, rosterAllows, staleInstanceKey, type PeerRoster } from "./roster.ts";
|
|
99
109
|
import { KNOWN_PEERS, OPTIONAL_PEERS, PLANNER_PEERS, SUPPORTED_PEERS, START_MODE_PEERS, isSupportedPeer, STARTABLE_PEERS, isStartablePeer } from "../adapters/registry.ts";
|
|
@@ -107,6 +117,7 @@ import { checkJcodeInstanceHomes, instanceDefinitionOf, effectiveInstanceRoles,
|
|
|
107
117
|
import { readInstanceConfig, readInstanceConfigLayers, readInstanceRoleConfig } from "./instance-config.ts";
|
|
108
118
|
import { instanceBudgetHooks, projectBudgetHeadroom } from "./instance-budget.ts";
|
|
109
119
|
import { resolveInstanceExecutionCwd } from "./instance-execution.ts";
|
|
120
|
+
import { presetStatusById } from "../adapters/presets.ts";
|
|
110
121
|
import { ProgressObserver, normalizeCodexObservation, normalizeClaudeObservation } from "./progress.ts";
|
|
111
122
|
import type { NativeToolObservation as ToolObservation } from "./progress.ts";
|
|
112
123
|
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
@@ -156,9 +167,9 @@ import { budgetNotes, type BudgetPeerNote } from "./budget-notes.ts";
|
|
|
156
167
|
import { kimiRowTotal } from "../adapters/kimi-wire-usage.ts";
|
|
157
168
|
import { ExecutionBudget } from "./execution-budget.ts";
|
|
158
169
|
import { claudeReportedTokens, readClaudeTranscriptCompletion, readClaudeTranscriptUsage, waitForClaudeCompletion } from "./usage.ts";
|
|
159
|
-
import type { ServerWebSocket } from "bun";
|
|
170
|
+
import type { ServerWebSocket, WebSocketHandler } from "bun";
|
|
160
171
|
import { isAcpPeer, managedAcpLaunch, verifyManagedAcpLaunch, type AcpOptions, type AcpPeer, QwenIdentityError, ACTION_BUDGET_OPTION, type PermissionRequest, type ActionGateVerdict } from "../adapters/acp.ts";
|
|
161
|
-
import { isCodexPeer, type CodexPeer } from "../adapters/codex-appserver.ts";
|
|
172
|
+
import { compareNextCodexQuotaHome, isCodexPeer, type CodexPeer } from "../adapters/codex-appserver.ts";
|
|
162
173
|
import { isPiPeer, PiVersionRefusal, type PiPeer } from "../adapters/pi.ts";
|
|
163
174
|
import { isQwenDualPeer, qwenDualVersionAsync, type QwenDualPeer } from "../adapters/qwen-dual.ts";
|
|
164
175
|
import { startModelRelay, type ModelRelay } from "../models/relay.ts";
|
|
@@ -200,18 +211,18 @@ import { Briefs, preferRecordItems, type NativeItem, type BriefTask } from "../m
|
|
|
200
211
|
import { Board, isClosedTaskState, taskProposalAt, taskHasStarted, CLASSES, type Task, type TaskClass } from "./board.ts";
|
|
201
212
|
import { UsageRollup, USAGE_GROUPS, LIMITS_MAX, type UsageGroup } from "./usage-rollup.ts";
|
|
202
213
|
import { Budget, readNativeQuota } from "./budget.ts";
|
|
203
|
-
import { projectExhaustion, windowLeft, WINDOW_MINS, type ExhaustionProjection } from "./budget-projection.ts";
|
|
214
|
+
import { earlyBudgetWarning, projectExhaustion, windowLeft, WINDOW_MINS, type ExhaustionProjection } from "./budget-projection.ts";
|
|
204
215
|
import { remoteEnvelope, HUB } from "./envelope.ts";
|
|
205
216
|
import { applyTurnAttribution, turnAttribution } from "./turn-attribution.ts";
|
|
206
217
|
import { recallMemoryLines, trimToTokens, aggregateUse, orderByUse } from "../memory/recall.ts";
|
|
207
218
|
import { closeSync, constants as fsConstants, openSync, lstatSync, readSync, statSync } from "node:fs";
|
|
208
219
|
import { basename, isAbsolute } from "node:path";
|
|
209
220
|
import { fileURLToPath } from "node:url";
|
|
210
|
-
import { canonicalPath, realPath, hubHome } from "./project.ts";
|
|
221
|
+
import { canonicalPath, realPath, hubHome, daemonProjectContext, projectChildEnv, type DaemonProjectContext } from "./project.ts";
|
|
211
222
|
import { HandoffRefusal, checkTarget, handoffAge, handoffCatchUpRow, handoffChunks, handoffConnectFailure, handoffLogGate, handoffOutcomeUnknown, handoffReach, handoffStateGate, handoffTargetStopped, parseHandoff, resolveTarget, handoffEventFor, type HandoffEvent } from "./handoff.ts";
|
|
212
223
|
import { mainCheckoutBranch, mainCheckoutWarning } from "./main-checkout.ts";
|
|
213
224
|
import type { BusEvent, PublishResult } from "./bus.ts";
|
|
214
|
-
import { QUESTION_TOOLS, CONDUCTOR_TOOLS, CONDUCTOR_TOOL_NAMES, IMPLEMENTER_HUB_TOOL_NAMES, roleContract, TASK_TOOL_NAMES, TASK_TOOLS, BOUNDED_TASK_TOOLS, LINEAGE_TOOL_NAMES, GUIDANCE_TOOL_NAMES, CAPABILITY_TOOLS, profileTaskTools, sessionTitleTools } from "./hub-tools.ts";
|
|
225
|
+
import { QUESTION_TOOLS, CONDUCTOR_TOOLS, CONDUCTOR_TOOL_NAMES, IMPLEMENTER_HUB_TOOL_NAMES, roleContract, TASK_TOOL_NAMES, TASK_TOOLS, BOUNDED_TASK_TOOLS, LINEAGE_TOOL_NAMES, GUIDANCE_TOOL_NAMES, CAPABILITY_TOOLS, DEFAULT_ROLES, profileTaskTools, sessionTitleTools } from "./hub-tools.ts";
|
|
215
226
|
import { effectiveClass, listedCapabilities, PublishRefusal, readShare, shareView, validatePublished, type CapabilityManifest } from "./capabilities.ts";
|
|
216
227
|
import { invocationApproval, checkArgs, DEFAULT_TIMEOUT_S, InvocationLedger, invocationRefusal, refusedBy, renderInvocationResult, requestText, type InvocationOutcome, type InvocationRow } from "./invocations.ts";
|
|
217
228
|
import { Conductor, ConductorHolds, conductorPeer, requireConductor, conductorProgressSink, publicConductorTask, publicPeerBudget, taskShowAllowed, type ConductEvent } from "./conductor.ts";
|
|
@@ -243,7 +254,7 @@ import { assertHubDbCompatible } from "./db-schema.ts";
|
|
|
243
254
|
import { startDashboard, dashboardView, type DashboardSession } from "./ui.ts";
|
|
244
255
|
import { codeGroup } from "./task-code-group.ts";
|
|
245
256
|
import { ControlClient, DAEMON_FEATURES, HANDOFF_CONNECT_MS, HANDOFF_LOOKUP_CONNECT_MS, HANDOFF_LOOKUP_REQUEST_MS, HANDOFF_REQUEST_MS, PROTOCOL, PROTOCOL_MIN, readControl, stateDirFor } from "./control-client.ts";
|
|
246
|
-
import { negotiateProtocol, protocolWindow } from "./protocol-window.ts";
|
|
257
|
+
import { BRIDGE_PROTOCOL_RELEASES, DEFAULT_BRIDGE_WINDOW, bridgeProtocolWindow, bridgeWindowSettings, negotiateProtocol, protocolWindow } from "./protocol-window.ts";
|
|
247
258
|
import { attachEvent, originOf, type Origin } from "./provenance.ts";
|
|
248
259
|
import { mintSessionId, sessionGate } from "./session-identity.ts";
|
|
249
260
|
import { MAX_HOP, isInvocationKind, newEnvelope, parseMarker, replyParent, sanitize, USER, type Envelope, type PeerId, type Priority } from "./envelope.ts";
|
|
@@ -267,7 +278,8 @@ import { Limiter, PROJECT_LIMITS, type LimitsConfig } from "./limits.ts";
|
|
|
267
278
|
import { soleWorktree, branchHeads, changedPaths, dirtySubmodules, submodulePaths, knownChangedPaths, hasTree, headState, headMoveCursor, incomingHeadPaths, repoOf, snapshot, SnapshotBudgetExceeded, SnapshotCooldown, budgetNow, Turns, type SnapshotBudget, type HeadMoveCursor, type Repo, type TurnRecord } from "./snapshots.ts";
|
|
268
279
|
import { archiveRestartSnapshot, compactRestartBus, readRecoveryWaivers, readRestartSnapshot, removeRestartSnapshot, restartPath, writeRestartSnapshot, type RecoveryPhase, type RestartPeerSnapshot, type RestartSnapshot } from "./restart.ts";
|
|
269
280
|
import { consumeRecoveryContinuity, readRecoveryContinuity, retireRecoveryContinuity } from "./recovery-continuity.ts";
|
|
270
|
-
import { shellQuote, publishTerminalLaunch, terminalLaunchCandidate, launcherOf } from "../cli/terminal-recovery.ts";
|
|
281
|
+
import { shellQuote, publishTerminalLaunch, terminalLaunchCandidate, launcherOf, orcaExecutable } from "../cli/terminal-recovery.ts";
|
|
282
|
+
import { OrcaPaneWatch, orcaAgentRunner } from "./orca-state.ts";
|
|
271
283
|
import { TerminalLaunches, terminalOwnerReads } from "./terminal-launch.ts";
|
|
272
284
|
|
|
273
285
|
import { peerStartConfig, PEER_START_RETRY_MS, startModeOf, type PeerStartConfig, type StartMode } from "./start-mode.ts";
|
|
@@ -290,9 +302,14 @@ import { hostPlacementAttestation, memorySyncErrorText, writerRefusalOf, type Wr
|
|
|
290
302
|
import { classifyMemorySyncFailure, initialMemorySyncState, memorySyncDeclinedDetails, memorySyncFailureDetailHash, memorySyncView, memorySyncNextStep, memorySyncPlacementCounts, reduceMemorySync } from "./memory-sync-state.ts";
|
|
291
303
|
import { createMemorySyncPolicy, inspectDeclinedMemoryRows } from "./memory-sync-policy.ts";
|
|
292
304
|
|
|
293
|
-
import { CONFIG_FILES, DEFAULT_CONFIG, loadConfig, loadConductorPolicy, mlxLaunchProblem, type HubConfig } from "./config.ts";
|
|
305
|
+
import { CONFIG_FILES, DEFAULT_CONFIG as declarationDefaults, loadConfig as loadDeclarationConfig, loadConductorPolicy, mlxLaunchProblem, type HubConfig } from "./config.ts";
|
|
294
306
|
|
|
295
|
-
export {
|
|
307
|
+
export { loadConductorPolicy, type ConfigLayer, type HubConfig } from "./config.ts";
|
|
308
|
+
export const DEFAULT_CONFIG: HubConfig = { ...declarationDefaults, roles: DEFAULT_ROLES };
|
|
309
|
+
export function loadConfig(...[cwd, layers, routingRetired, externalDefinitions]: Parameters<typeof loadDeclarationConfig>): HubConfig {
|
|
310
|
+
const loaded = loadDeclarationConfig(cwd, layers, routingRetired, externalDefinitions, DEFAULT_ROLES);
|
|
311
|
+
return loaded === declarationDefaults ? DEFAULT_CONFIG : loaded;
|
|
312
|
+
}
|
|
296
313
|
|
|
297
314
|
export { stateDirFor };
|
|
298
315
|
|
|
@@ -342,6 +359,10 @@ function mlxPinProblem(routing: Routing, project: boolean): string | undefined {
|
|
|
342
359
|
}
|
|
343
360
|
|
|
344
361
|
export interface DaemonOptions {
|
|
362
|
+
/** Explicit project context; defaults to `cwd`, `stateDir` and the process environment at start. */
|
|
363
|
+
context?: DaemonProjectContext;
|
|
364
|
+
/** #1779 T3a: set by a host process; reported in `status.json` and the status reply. */
|
|
365
|
+
hostId?: string;
|
|
345
366
|
/** Host-only fixture override; production reads the active memory home's and execution repository's public Record policy. */
|
|
346
367
|
effectiveRecordPolicy?: (cwd: string) => { enabled: boolean; version: string } | undefined;
|
|
347
368
|
/** Host-only test trigger; production schedules its own unreferenced settlement interval. */
|
|
@@ -382,12 +403,22 @@ export interface DaemonOptions {
|
|
|
382
403
|
kimiHome?: string;
|
|
383
404
|
/** Host-only delayed-drain scheduler; tests fire it explicitly. Production leaves it unset and uses unreferenced timers. */
|
|
384
405
|
kimiUsageScheduler?: KimiUsageScheduler;
|
|
406
|
+
/** Test seam for the Claude usage-file poll only. Production uses the default interval. */
|
|
407
|
+
claudeUsagePollMs?: number;
|
|
385
408
|
/** Host-only replay-window test ceiling (1..512); never read from project config or a tool. */
|
|
386
409
|
toolWriteReplayMaxEntries?: number;
|
|
387
410
|
/** Host-only evidence seam; never supplied by project config or control messages. */
|
|
388
411
|
releaseDocEvidence?: (root: string) => Promise<DocEvidence | undefined>;
|
|
389
412
|
projectId?: string;
|
|
413
|
+
/** #1780 T1: the hub home that holds `run/<projectId>/mcp.sock`. Only the lifecycle passes it, so a test daemon never writes into the person's hub home. */
|
|
414
|
+
mcpHome?: string;
|
|
415
|
+
/** #1780 T2a-2c: serve MCP on that socket. Off by default and set by no production caller until the relay and channel pushes land (T2b, T4); without it a valid hello still gets -32601. */
|
|
416
|
+
mcpServe?: boolean;
|
|
417
|
+
/** #1780 T2b: the channel evidence of an endpoint session, from the hub's own check of the reported parent (T3 supplies it). Without it every session reads "unknown" and is pull-only, as a bridge without proof is (AC3). */
|
|
418
|
+
mcpChannelEvidence?: (hello: McpHello) => "development-channel-launch" | "inherited-marker" | "launch-unverified" | "unknown";
|
|
390
419
|
instanceId?: string;
|
|
420
|
+
/** #1811 T2: how often a peer with an unaccepted delivery is checked for a pane that waits for the person; default 30 s. */
|
|
421
|
+
orcaPaneEveryMs?: number;
|
|
391
422
|
cwd: string;
|
|
392
423
|
stateDir: string;
|
|
393
424
|
controlPort: number;
|
|
@@ -497,6 +528,8 @@ interface Client {
|
|
|
497
528
|
channel?: boolean;
|
|
498
529
|
channelEvidence?: "development-channel-launch" | "inherited-marker" | "launch-unverified" | "unknown" | "unreported";
|
|
499
530
|
clientPid?: number;
|
|
531
|
+
/** #1810: the declared account label of the session home; absent for an undeclared home. Never a path. */
|
|
532
|
+
accountLabel?: string;
|
|
500
533
|
/** #1385: the agent-hub version the client's hello reported, kept only when `displayVersion` accepts it. Display only. */
|
|
501
534
|
clientVersion?: string;
|
|
502
535
|
cwd?: string;
|
|
@@ -563,6 +596,8 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
563
596
|
// Refuse unknown formats before logs, session cleanup, module factories or any writable store is opened.
|
|
564
597
|
assertHubDbCompatible(join(opts.stateDir, "hub.db"));
|
|
565
598
|
startupTimings.mark("schema");
|
|
599
|
+
// #1779 T2: the project's identity and child environment, taken once; nothing below reads them from the process.
|
|
600
|
+
const ctx = opts.context ?? daemonProjectContext(opts.cwd, opts.stateDir, process.env);
|
|
566
601
|
if (opts.toolWriteReplayMaxEntries !== undefined && (!Number.isSafeInteger(opts.toolWriteReplayMaxEntries) || opts.toolWriteReplayMaxEntries < 1 || opts.toolWriteReplayMaxEntries > 512)) throw new Error("invalid host tool write replay capacity");
|
|
567
602
|
const resolveExecutionCwd = (peer: string, currentDeclarations: InstancesConfig | undefined, currentRoles: readonly string[], catalog: ReturnType<typeof createProjectAdapterCatalog>): string =>
|
|
568
603
|
resolveInstanceExecutionCwd(opts.cwd, peer, currentDeclarations, currentRoles, catalog, undefined, undefined, opts.instanceExecutionGit);
|
|
@@ -612,6 +647,22 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
612
647
|
const lifecycleConfig = opts.sdlc ?? loadSdlc(opts.cwd, VERSION);
|
|
613
648
|
/** The file's lifecycle as the status and settings views report it; a supplied fixture config stands in for it. */
|
|
614
649
|
const readSdlcFile = () => opts.sdlc ?? loadSdlc(opts.cwd, VERSION);
|
|
650
|
+
function planStructureNotice(task: Task): string | undefined {
|
|
651
|
+
try {
|
|
652
|
+
const rules = readSdlcFile().structure;
|
|
653
|
+
if (!rules) return;
|
|
654
|
+
const plan = tasks.publicView(task).plan as { paths?: string[] } | undefined;
|
|
655
|
+
if (!plan?.paths?.length) return;
|
|
656
|
+
const baseline = readStructureBaseline(join(opts.cwd, rules.baseline));
|
|
657
|
+
if (!baseline) return;
|
|
658
|
+
const paths = plan.paths.filter(path => Object.hasOwn(baseline.sizes, path));
|
|
659
|
+
if (!paths.length) return;
|
|
660
|
+
return structureNotice(rules, baseline, scanStructure(opts.cwd, { ...rules, roots: paths, shared: [] }), paths);
|
|
661
|
+
} catch {
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
|
|
615
666
|
// Preserve embedding-owned policy references, but never publish reloads into shared defaults.
|
|
616
667
|
const ownedConfig = Object.fromEntries(Object.entries(loadedConfig).map(([key, value]) => [key, !opts.config || value === (DEFAULT_CONFIG as unknown as Record<string, unknown>)[key] ? structuredClone(value) : value])) as unknown as HubConfig;
|
|
617
668
|
const adapterCatalog = createProjectAdapterCatalog(loadedConfig.adapters, externalDefinitions);
|
|
@@ -675,6 +726,13 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
675
726
|
peers: { ...startModesFromInstances, ...peerStartConfig(loadedConfig.peers, declarations, adapterCatalog) },
|
|
676
727
|
...(extraIds.length ? { permission_default_sources: { ...instancePermissionSources, ...loadedConfig.permission_default_sources } } : {}),
|
|
677
728
|
roles, conductor: { ...DEFAULT_CONFIG.conductor, ...loadedConfig.conductor } };
|
|
729
|
+
const [[oldestBridgeProtocol]] = BRIDGE_PROTOCOL_RELEASES;
|
|
730
|
+
const bridgeSettings = bridgeWindowSettings(config.upgrade);
|
|
731
|
+
const requestedBridgeWindow = bridgeProtocolWindow(bridgeSettings, oldestBridgeProtocol, Date.now());
|
|
732
|
+
const bridgeProtocolFloorLimited = requestedBridgeWindow.vMin < PROTOCOL_MIN
|
|
733
|
+
&& (bridgeSettings.bridge_window_days > DEFAULT_BRIDGE_WINDOW.bridge_window_days
|
|
734
|
+
|| bridgeSettings.bridge_window_min > DEFAULT_BRIDGE_WINDOW.bridge_window_min);
|
|
735
|
+
const acceptedBridgeWindow = { v: PROTOCOL, vMin: Math.max(PROTOCOL_MIN, requestedBridgeWindow.vMin) };
|
|
678
736
|
// The resolver and catalogs are bound to this daemon, never published into the process-global builtin registry.
|
|
679
737
|
const definitionOf = (peer: string) => adapterCatalog.definitionOf(peer, declarations);
|
|
680
738
|
const externalInstanceIds = extraIds.filter(id => externalIds.has(declarations[id]!.kind));
|
|
@@ -718,7 +776,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
718
776
|
const current = readInstanceConfig(opts.cwd, undefined, externalDefinitions);
|
|
719
777
|
const declaration = current.instances?.[peer];
|
|
720
778
|
if (!declaration || declaration.kind !== declarations[peer]?.kind) throw new Error("external instance declaration changed");
|
|
721
|
-
const policy = loadConductorPolicy(opts.cwd, undefined, current);
|
|
779
|
+
const policy = loadConductorPolicy(opts.cwd, undefined, current, DEFAULT_ROLES);
|
|
722
780
|
const currentRoles = effectiveInstanceRoles(peer, current.instances, policy.roles, current.catalog);
|
|
723
781
|
const cwd = resolveExecutionCwd(peer, current.instances, currentRoles, current.catalog);
|
|
724
782
|
const binding = externalInstanceBinding(identity, peer, declaration, currentRoles, cwd);
|
|
@@ -742,7 +800,8 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
742
800
|
const STARTABLE_PEERS: readonly string[] = [...BASE_STARTABLE_PEERS, ...configuredIds, ...extraIds.filter(id => !channelExtras.includes(id))];
|
|
743
801
|
const isSupportedPeer = (peer: unknown): peer is string => adapterCatalog.isSupportedPeer(peer, declarations);
|
|
744
802
|
const isStartablePeer = (peer: unknown): peer is string => typeof peer === "string" && !channelExtras.includes(peer) && definitionOf(peer)?.start.conductorStartable === true;
|
|
745
|
-
|
|
803
|
+
// #1809: a configured pull kind attaches from the person's terminal (externalHello), so its id is no more reserved than a builtin pull peer's.
|
|
804
|
+
const RESERVED_IDS = new Set([...BASE_RESERVED_IDS, ...configuredIds.filter(id => definitionOf(id)?.attach?.externalHello !== true), ...extraIds.filter(id => !channelExtras.includes(id))]);
|
|
746
805
|
// #223 R2: a declared instance whose effective roles are exactly reviewer gets review requests and its own task notices only.
|
|
747
806
|
const reviewOnlyPeer = (peer: string): boolean => Object.hasOwn(declarations, peer) && config.roles[peer]?.length === 1 && config.roles[peer]![0] === "reviewer";
|
|
748
807
|
/** Display the same runtime form/role ceilings used by declarations; these fields grant no authority. */
|
|
@@ -797,8 +856,17 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
797
856
|
};
|
|
798
857
|
// #514b: undo resolves the managed checklist key, which is not a settings row, and every other key through the project-scoped lookup above (declared instances, the adapter catalog, a stale roster key).
|
|
799
858
|
const undoableDef = (key: unknown): SettingDef | string => key === AUTONOMY_UNDO.key ? AUTONOMY_UNDO : key === LEARN_CHECKLIST.key ? LEARN_CHECKLIST : settingDef(key);
|
|
800
|
-
|
|
801
|
-
|
|
859
|
+
// #1810: the budget key of a peer is its account, plus `:<label>` when its session runs under a declared account. An undeclared home keeps the bare key (today's), a key built here
|
|
860
|
+
// resolves to itself (the budget requires an idempotent resolver), and no peer id contains a colon.
|
|
861
|
+
// Any peer that carries an `accountLabel` (the channel peer does) reports it; this is a read of a display label, not a host branch on the peer class.
|
|
862
|
+
// A session's label comes from its home; a daemon-owned instance's from its declared `account` (#1810 AC3), so both budget under `<kind>:<label>`.
|
|
863
|
+
const peerAccountLabel = (peer: string): string | undefined => (bus.peers.get(peer) as { accountLabel?: string } | undefined)?.accountLabel ?? declarations[peer]?.account;
|
|
864
|
+
const accountOf = (peer: string): string => accountKeyFor(peer, definitionOf(peer)?.budget?.account, declarations[peer]?.kind, peerAccountLabel(peer));
|
|
865
|
+
// The account a handoff compares: the budget key, or just its kind when `budget.cross_account_handoff` is off (two labels of one kind are then siblings).
|
|
866
|
+
const handoffAccountOf = (peer: string): string => config.budget.cross_account_handoff === false ? baseAccount(accountOf(peer)) : accountOf(peer);
|
|
867
|
+
// #1810 AC3: a daemon-owned instance that names an account starts with that account's home in its kind's own variable. The home is read here from the loaded config and goes only into the child's environment.
|
|
868
|
+
const instanceAccountEnv = (peer: string): NodeJS.ProcessEnv | undefined => instanceAccountEnvOf(declarations[peer]?.account, config.accounts, definitionOf(peer)?.session.configDirEnv);
|
|
869
|
+
const accountMembers = (account: string) => [...new Set([...SUPPORTED_PEERS, ...Object.keys(declarations)])].filter(peer => accountOf(peer) === account);
|
|
802
870
|
let rosterChanging: string | undefined;
|
|
803
871
|
let kimiSessionMode: StartMode | undefined;
|
|
804
872
|
let kimiAdmissionId: string | undefined;
|
|
@@ -1016,6 +1084,8 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
1016
1084
|
const token = randomBytes(24).toString("hex");
|
|
1017
1085
|
const nativeHookLaunches = new NativeHookLaunches();
|
|
1018
1086
|
|
|
1087
|
+
// #1780 T2a-2c: the control handlers by name, so an MCP endpoint session's Sock-shaped link runs the same `message` and `close` code a WebSocket does.
|
|
1088
|
+
let controlWebsocket!: WebSocketHandler<Client>;
|
|
1019
1089
|
const server = listenWithoutPortCollision(() => Bun.serve<Client>({
|
|
1020
1090
|
hostname: "127.0.0.1",
|
|
1021
1091
|
port: opts.controlPort,
|
|
@@ -1024,7 +1094,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
1024
1094
|
if (new URL(req.url).pathname === "/healthz") return new Response("ok");
|
|
1025
1095
|
return srv.upgrade(req, { data: { authed: false } }) ? undefined : new Response("agent-hub control");
|
|
1026
1096
|
},
|
|
1027
|
-
websocket: {
|
|
1097
|
+
websocket: controlWebsocket = {
|
|
1028
1098
|
message(sock, data) {
|
|
1029
1099
|
let parsed: any;
|
|
1030
1100
|
try {
|
|
@@ -1217,6 +1287,12 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
1217
1287
|
* #685: the provider, model and profile names an extra Jcode instance was declared with, for status, doctor and the dashboard,
|
|
1218
1288
|
* exactly as the person wrote them (they authenticate inside Jcode). Never a URL, a token or the native home path.
|
|
1219
1289
|
*/
|
|
1290
|
+
// #1809: a configured kind written from a preset shows that preset and its status in `ahub status`.
|
|
1291
|
+
const presetStatusRow = (id: string): { preset?: { id: string; status: "verified" | "untested" } } => {
|
|
1292
|
+
const declared = config.adapters?.[id];
|
|
1293
|
+
const preset = declared && "preset" in declared ? declared.preset : undefined;
|
|
1294
|
+
return preset ? { preset: { id: preset, status: presetStatusById(preset) } } : {};
|
|
1295
|
+
};
|
|
1220
1296
|
const jcodeModelSource = (id: string): { modelSource?: string } => {
|
|
1221
1297
|
const instance = declarations[id];
|
|
1222
1298
|
if (!instance) return {};
|
|
@@ -2886,8 +2962,10 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
2886
2962
|
offerPullOnly: (id) => { const peer = bus.peers.get(id); return peer?.pullOnly === true; },
|
|
2887
2963
|
stallNotice: stall => { supervision.taskStalled(stall); },
|
|
2888
2964
|
get roles() {
|
|
2889
|
-
|
|
2890
|
-
|
|
2965
|
+
// #1809: a kind that declares `tasks: false` (a configured pull kind) is read by the board as having no role at all, so no ownership check can admit it.
|
|
2966
|
+
const owns = (id: string): boolean => definitionOf(id)?.start.daemonPort !== "configured-print" && definitionOf(id)?.tasks !== false;
|
|
2967
|
+
if (configuredIds.every(id => owns(id))) return config.roles;
|
|
2968
|
+
return Object.fromEntries(Object.entries(config.roles).filter(([id]) => owns(id)));
|
|
2891
2969
|
},
|
|
2892
2970
|
turnFree,
|
|
2893
2971
|
coordination: () => config.coordination === "turn-free",
|
|
@@ -3107,6 +3185,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
3107
3185
|
const briefPolicy = (root: string) => ({
|
|
3108
3186
|
privatePath: (path: string) => isDenied(path, config.local.deny) || matchesPolicy(root, path, config.pii?.paths ?? [], true),
|
|
3109
3187
|
nameable: tasks.nameable,
|
|
3188
|
+
structureRules: (config: unknown) => sdlcConfig(config, VERSION).structure,
|
|
3110
3189
|
});
|
|
3111
3190
|
const projectionsFor = (peer: string): TextProjections => {
|
|
3112
3191
|
const root = executionRoot(peer);
|
|
@@ -3782,6 +3861,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
3782
3861
|
const quotaEvents = new QuotaEventFilter(event);
|
|
3783
3862
|
const budget = new Budget(join(opts.stateDir, "hub.db"), config.budget, instanceBudgetHooks({
|
|
3784
3863
|
definitionOf,
|
|
3864
|
+
allowSwitchedReading: (peer, _at, origin) => definitionOf(peer)?.start.daemonPort === "codex-appserver" && !!origin?.processStamp,
|
|
3785
3865
|
pause: (peer) => bus.pause(peer),
|
|
3786
3866
|
resume: (peer) => {
|
|
3787
3867
|
if (!manualPaused.has(peer) && !conductorHolds.has(peer)) bus.resume(peer);
|
|
@@ -3796,13 +3876,19 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
3796
3876
|
},
|
|
3797
3877
|
attached: (peer) => bus.peers.has(peer),
|
|
3798
3878
|
// Somebody other than the paused peer has to be there, or the handoff would only leave its tasks without an owner.
|
|
3799
|
-
canHandOff: (peer) => ![...unsettledReviewerQuota.values()].some(row => row.account === accountOf(peer)) && [...bus.peers.keys()].some((id) =>
|
|
3879
|
+
canHandOff: (peer) => ![...unsettledReviewerQuota.values()].some(row => row.account === accountOf(peer)) && [...bus.peers.keys()].some((id) => handoffAccountOf(id) !== handoffAccountOf(peer) && ["idle", "busy"].includes(bus.stateOf(id))),
|
|
3800
3880
|
// A reading that arrived through a file carries the file's time; a stale one must not look fresh in the export.
|
|
3801
3881
|
// #683 U1: pauses, resumes and derived resets go to the event log, ids and numbers only.
|
|
3802
3882
|
ledger: entry => event(entry),
|
|
3803
3883
|
reading: (peer, windows, hard, at) => { queueMicrotask(() => tasks.refreshReviewerQuotaWaits()); quotaEvents.record(peer, windows.map((w) => ({ id: w.id, used: w.used, ...(w.resetsAt ? { resetsAt: w.resetsAt } : {}) })), hard, at); },
|
|
3804
|
-
handoff: (peer, context, urgentOnly) =>
|
|
3805
|
-
|
|
3884
|
+
handoff: async (peer, context, urgentOnly) => {
|
|
3885
|
+
// #1810: with `budget.cross_account_handoff` off, a peer of the same kind on another declared account is a sibling and never a target (owner or reviewer work).
|
|
3886
|
+
const siblings = handoffSiblings(peer, [...bus.peers.keys()], accountOf, config.budget.cross_account_handoff !== false);
|
|
3887
|
+
const moves = (await tasks.reassignForPause(peer, context, urgentOnly, siblings)).map(move => ({ ...move, from: peer }));
|
|
3888
|
+
for (const entry of handoffEvents(peer, moves, peerAccountLabel, accountOf)) event(entry);
|
|
3889
|
+
return moves;
|
|
3890
|
+
},
|
|
3891
|
+
resumed: (record, renewal) => {
|
|
3806
3892
|
// Coalesce unread notices without forgetting the public moves they carried.
|
|
3807
3893
|
const moves = new Map<string, typeof record.moved[number]>();
|
|
3808
3894
|
const earlier: string[] = [];
|
|
@@ -3817,9 +3903,9 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
3817
3903
|
}
|
|
3818
3904
|
for (const move of record.moved) moves.set(JSON.stringify([move.id, move.role, move.to, move.title]), move);
|
|
3819
3905
|
const unreadMoves = [...moves.values()];
|
|
3820
|
-
if (definitionOf(record.peer)?.budget?.resetSoftTokensOnResume) kimiUsage.reset(); // a new window: the old counts would pause it again at once
|
|
3906
|
+
if (!renewal && definitionOf(record.peer)?.budget?.resetSoftTokensOnResume) kimiUsage.reset(); // a new window: the old counts would pause it again at once
|
|
3821
3907
|
const moved = unreadMoves.length ? `While you were paused these moved: ${unreadMoves.map((m) => `${m.title} (${m.role} -> ${m.to ?? "nobody"})`).join("; ")}. They stay where they are; ask the user if you should take one back.` : earlier.length ? "Moves from earlier pauses are preserved in the unread notices below." : "Nothing was moved while you were paused.";
|
|
3822
|
-
bus.publish(newEnvelope(HUB,
|
|
3908
|
+
bus.publish(newEnvelope(HUB, `${renewal ? "Your quota readings were renewed and the hub has resumed you" : "Your quota window has reset and the hub has resumed you"} (paused since ${new Date(record.since).toLocaleTimeString()}, ${record.reason}). ${moved}${earlier.length ? ` Earlier unread resume notices: ${earlier.join("\n")}` : ""} Messages queued for you follow.`, { to: [record.peer], kind: "budget", priority: "important", refs: { budgetResume: record.peer, budgetResumeMoves: unreadMoves, ...(earlier.length ? { budgetResumeEarlier: earlier } : {}) } }));
|
|
3823
3909
|
// Publish the complete replacement before removing its evidence. A failed write keeps the old notices.
|
|
3824
3910
|
for (const id of superseded) bus.withdraw(id);
|
|
3825
3911
|
},
|
|
@@ -3831,12 +3917,15 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
3831
3917
|
const startupEvents = startupSeeds.events;
|
|
3832
3918
|
budget.seedResets(startupEvents.flatMap(e => e.type === "quota_reset" ? [{ peer: e.peer, window: e.window, ...(e.resetsAt !== undefined ? { resetsAt: e.resetsAt } : {}) }] : []));
|
|
3833
3919
|
// #285 phase 2: Kimi's consumption is the hub's own count of its session wire log (`src/adapters/kimi-wire-usage.ts`), not an ACP total.
|
|
3834
|
-
const softTokenAccount = (peer: string): boolean => definitionOf(accountOf(peer))?.budget?.resetSoftTokensOnResume === true;
|
|
3920
|
+
const softTokenAccount = (peer: string): boolean => definitionOf(baseAccount(accountOf(peer)))?.budget?.resetSoftTokensOnResume === true;
|
|
3921
|
+
const softTokenBudget = adapterCatalog.definitions.find(def => def.budget?.resetSoftTokensOnResume)?.budget;
|
|
3922
|
+
const softTokenRenewalAt = () => softTokenBudget && budget.renewalAt(softTokenBudget.account);
|
|
3835
3923
|
const kimiEvents = new KimiEventWriter({ append: event, read: () => readEvents(join(opts.stateDir, "events.jsonl")) }, startupEvents);
|
|
3836
3924
|
const kimiUsage = new KimiUsage({
|
|
3837
3925
|
home: opts.kimiHome ?? process.env.KIMI_CODE_HOME ?? join(homedir(), ".kimi-code"),
|
|
3838
3926
|
now: () => Date.now(),
|
|
3839
3927
|
ceiling: () => config.budget.kimi_tokens_5h,
|
|
3928
|
+
renewalAt: softTokenRenewalAt,
|
|
3840
3929
|
session: peer => contextSession(peer),
|
|
3841
3930
|
schedule: opts.kimiUsageScheduler ?? ((delay, run) => {
|
|
3842
3931
|
const timer = setTimeout(run, delay); timer.unref?.();
|
|
@@ -3846,12 +3935,13 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
3846
3935
|
kimiEvents.write(peer, row, counted, attributed);
|
|
3847
3936
|
applyKimiTokens(peer, counted, attributed);
|
|
3848
3937
|
},
|
|
3849
|
-
report: (peer, window) => budget.
|
|
3938
|
+
report: (peer, window) => budget.reportKimiCount(peer, window),
|
|
3850
3939
|
forget: peer => budget.forget(peer, "tokens", "count"),
|
|
3851
3940
|
notice: line => notify(line),
|
|
3852
3941
|
});
|
|
3853
3942
|
startupCleanup.push(() => kimiUsage.stop());
|
|
3854
|
-
|
|
3943
|
+
const kimiResumedAt = Math.max(0, ...startupEvents.flatMap(e => e.type === "budget_resume" && definitionOf(e.peer)?.budget?.resetSoftTokensOnResume ? [Date.parse(e.at)] : []).filter(Number.isFinite));
|
|
3944
|
+
kimiUsage.seed(kimiSeedRows(startupEvents, kimiResumedAt, softTokenRenewalAt()));
|
|
3855
3945
|
if (!reviewerJournalComplete) {
|
|
3856
3946
|
// ponytail: a damaged journal cannot prove which owned attempts settled. Keep soft counts unknown;
|
|
3857
3947
|
// recovery needs a verified settlement, not a guessed expiry from a host start/cap timestamp.
|
|
@@ -3944,13 +4034,15 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
3944
4034
|
const windowStart = resetsAt !== null && windowMins > 0 ? resetsAt - windowMins * 60_000 : null;
|
|
3945
4035
|
// A stale reading is no usable reading, so its forecast is never served from the cache, never cached, and never
|
|
3946
4036
|
// computed from points it would not look at (the page polls every second, and a stale row is what a pause leaves).
|
|
3947
|
-
const
|
|
4037
|
+
const renewedAt = budget.renewalAt(peer);
|
|
4038
|
+
const key = `${peer}\0${window.id}\0${window.kind}\0${window.at}\0${window.used}\0${resetsAt ?? ""}\0${renewedAt ?? ""}\0${budget.forecastReadingVersion(window) ?? ""}`;
|
|
3948
4039
|
const cached = window.stale ? undefined : projectionCache.get(key);
|
|
3949
4040
|
const projection = cached && now - cached.at < PROJECTION_TTL_MS ? cached.value : (() => {
|
|
3950
4041
|
const value = projectExhaustion({
|
|
3951
|
-
used: window.used, windowStart, resetsAt, now, stale: window.stale,
|
|
4042
|
+
used: window.used, windowStart, resetsAt, now, stale: window.stale, renewedAt, baseline: budget.forecastBaseline(peer, window),
|
|
3952
4043
|
lookbackMs: windowMins > 0 ? Math.min(PROJECTION_LOOKBACK_MS, windowMins * 60_000) : PROJECTION_LOOKBACK_MS,
|
|
3953
|
-
points: windowStart === null || window.stale
|
|
4044
|
+
points: windowStart === null || window.stale || (renewedAt !== undefined && windowStart < renewedAt)
|
|
4045
|
+
? [] : usageRollup.points(peer, windowStart, now),
|
|
3954
4046
|
});
|
|
3955
4047
|
/* ponytail: the cache is per reading and cleared whole past 256 entries; a per-window expiry is the upgrade if a project ever holds more. */
|
|
3956
4048
|
if (!window.stale) {
|
|
@@ -3963,7 +4055,16 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
3963
4055
|
}
|
|
3964
4056
|
/** The same view for one peer's row and for a whole status: `left` and the projection ride each window, never the summary. */
|
|
3965
4057
|
function windowRow(peer: string, row: BudgetRowStatus) {
|
|
3966
|
-
|
|
4058
|
+
const now = Date.now();
|
|
4059
|
+
const windows = row.windows.map(window => windowView(peer, window));
|
|
4060
|
+
const warnings = row.paused ? [] : windows.flatMap(window => {
|
|
4061
|
+
if (window.stale || window.superseded) return [];
|
|
4062
|
+
const at = earlyBudgetWarning(window.projection, window.resetsAt, now);
|
|
4063
|
+
return at === undefined ? [] : [{ window: window.id, at }];
|
|
4064
|
+
});
|
|
4065
|
+
const def = definitionOf(peer);
|
|
4066
|
+
return { ...row, windows, ...(warnings.length ? { warnings } : {}),
|
|
4067
|
+
...(def?.budget && !def.budget.quotaExempt ? { renewable: true } : {}) };
|
|
3967
4068
|
}
|
|
3968
4069
|
function budgetViews(status: ReturnType<Budget["status"]>): ReturnType<Budget["status"]> {
|
|
3969
4070
|
return Object.fromEntries(Object.entries(status).map(([peer, row]) => [peer, windowRow(peer, row)]));
|
|
@@ -4639,6 +4740,26 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
4639
4740
|
};
|
|
4640
4741
|
// Claude's numbers arrive through the status line tee `ahub claude` installs (src/cli/statusline-tee.ts).
|
|
4641
4742
|
let claudeUsageSeen = 0;
|
|
4743
|
+
const accountUsageSeen = new Map<string, number>();
|
|
4744
|
+
const pollAccountUsage = () => {
|
|
4745
|
+
// #1810: one reading per declared claude account, from the file its home's sessions tee. Keyed `claude:<label>`; a reading for an undeclared home stays with the bare key above.
|
|
4746
|
+
for (const [label, declared] of Object.entries(config.accounts ?? {})) {
|
|
4747
|
+
if (!isClaudeAccountKind(declared.kind)) continue;
|
|
4748
|
+
try {
|
|
4749
|
+
const file = join(opts.stateDir, `claude-usage.${homeTag(declared.home)}.json`);
|
|
4750
|
+
const mtime = statSync(file).mtimeMs;
|
|
4751
|
+
if (accountUsageSeen.get(label) === mtime) continue;
|
|
4752
|
+
accountUsageSeen.set(label, mtime);
|
|
4753
|
+
const usage = JSON.parse(readFileSync(file, "utf8"));
|
|
4754
|
+
for (const adapter of ADAPTERS.filter(adapter => adapter.transport === "claude-channel")) {
|
|
4755
|
+
const windows = readNativeQuota(adapter, usage.rate_limits);
|
|
4756
|
+
if (windows) budget.report(accountKey(adapter.kind, label), windows, false, Number(usage.at) || mtime, undefined);
|
|
4757
|
+
}
|
|
4758
|
+
} catch {
|
|
4759
|
+
// this account has no session yet, or a half-written file: next round
|
|
4760
|
+
}
|
|
4761
|
+
}
|
|
4762
|
+
};
|
|
4642
4763
|
let bandsRevision = ""; // #481 S7: the board revision and band configuration the last band evaluation that ran saw
|
|
4643
4764
|
let bandEvaluations = 0; // evaluations that ran (not skipped for an unchanged board); read by tests through the daemon
|
|
4644
4765
|
const claudeContextSeen = new Map<string, string>();
|
|
@@ -4727,7 +4848,26 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
4727
4848
|
if (mergeReadbackTimer) clearInterval(mergeReadbackTimer);
|
|
4728
4849
|
};
|
|
4729
4850
|
startupCleanup.push(async () => { stopMergeReadbackSchedule(); await mergeReadbackPass; });
|
|
4851
|
+
// #1811 T2: a delivery unaccepted for two minutes in a peer's recorded Orca pane asks Orca for that pane's state, at most once a minute per peer.
|
|
4852
|
+
const paneWatch = new OrcaPaneWatch({ run: orcaAgentRunner(orcaExecutable) });
|
|
4853
|
+
const paneTick = async () => {
|
|
4854
|
+
if (stopping || recoveryActive()) return;
|
|
4855
|
+
const before = JSON.stringify(paneWatch.blocked());
|
|
4856
|
+
for (const id of [...bus.peers.keys()]) {
|
|
4857
|
+
const oldest = bus.queueSummary(id).oldestQueuedAt;
|
|
4858
|
+
let pane: { handle: string; paneKey: string; worktreeId: string } | undefined;
|
|
4859
|
+
if (stopping || recoveryActive()) return;
|
|
4860
|
+
if (paneWatch.due(oldest)) {
|
|
4861
|
+
const found = await launcherOf(id, opts.cwd, { stateDir: opts.stateDir, instanceId }).catch(() => undefined);
|
|
4862
|
+
const record = found?.state === "live" ? found.record : undefined;
|
|
4863
|
+
if (record?.paneKey) pane = { handle: record.handle, paneKey: record.paneKey, worktreeId: record.worktreeId };
|
|
4864
|
+
}
|
|
4865
|
+
await paneWatch.check(id, oldest, pane);
|
|
4866
|
+
}
|
|
4867
|
+
if (before !== JSON.stringify(paneWatch.blocked())) writeStatus();
|
|
4868
|
+
};
|
|
4730
4869
|
const intervals = [
|
|
4870
|
+
setInterval(() => { void paneTick().catch(() => log("orca pane check failed; the item keeps its state")); }, opts.orcaPaneEveryMs ?? 30_000),
|
|
4731
4871
|
setInterval(() => {
|
|
4732
4872
|
try { sweepInvocations(); } catch { log("invocation deadline sweep failed; the rows keep their state"); }
|
|
4733
4873
|
try { sweepAcceptedChannelDeliveries(); } catch { log("accepted channel delivery sweep failed; the rows keep their state"); }
|
|
@@ -4806,21 +4946,24 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
4806
4946
|
// A verified context path whose hooks stopped altogether has no boundary left to notice it at (issue #108).
|
|
4807
4947
|
setInterval(() => { for (const peer of [...capable]) checkCapability(peer); }, 30_000),
|
|
4808
4948
|
setInterval(() => {
|
|
4949
|
+
pollAccountUsage();
|
|
4809
4950
|
try {
|
|
4810
4951
|
const file = join(opts.stateDir, "claude-usage.json");
|
|
4811
4952
|
const mtime = statSync(file).mtimeMs;
|
|
4812
4953
|
if (mtime === claudeUsageSeen) return;
|
|
4813
4954
|
claudeUsageSeen = mtime;
|
|
4814
4955
|
const usage = JSON.parse(readFileSync(file, "utf8"));
|
|
4956
|
+
if (isDeclaredReading(usage.home, config.accounts, homeTag)) return; // a declared home has its own key; it must not pause the default one
|
|
4815
4957
|
// The file's own timestamp, not "now": a file left behind by yesterday's session is a stale reading, not a fresh one.
|
|
4816
4958
|
for (const adapter of ADAPTERS.filter(adapter => adapter.transport === "claude-channel")) {
|
|
4817
4959
|
const windows = readNativeQuota(adapter, usage.rate_limits);
|
|
4818
|
-
if (windows) budget.report(adapter.kind, windows, false, Number(usage.at) || mtime
|
|
4960
|
+
if (windows) budget.report(adapter.kind, windows, false, Number(usage.at) || mtime, undefined,
|
|
4961
|
+
{ forecastSession: { sessionId: usage.sessionId, launchId: usage.launchId } });
|
|
4819
4962
|
}
|
|
4820
4963
|
} catch {
|
|
4821
4964
|
// no tee in this session, or a half-written file: next round
|
|
4822
4965
|
}
|
|
4823
|
-
}, 5_000),
|
|
4966
|
+
}, opts.claudeUsagePollMs ?? 5_000),
|
|
4824
4967
|
];
|
|
4825
4968
|
let sweepTimer: ReturnType<typeof setInterval> | undefined;
|
|
4826
4969
|
const rescheduleSweep = () => {
|
|
@@ -4925,7 +5068,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
4925
5068
|
// names are answered by the hub; every call still passes daemon role/capability checks before its effects.
|
|
4926
5069
|
const HUB_TOOLS = ["hub_send", ...[...TASK_TOOL_NAMES].filter(name => name !== "hub_set_title" && (!["hub_evidence_record", "hub_evidence_read"].includes(name) || resolvedProfile.name === "research")), ...CONDUCTOR_TOOLS.map((t) => t.name)];
|
|
4927
5070
|
const HUB_TOOL_TITLES = new Set(HUB_TOOLS.map((name) => `mcp__agent-hub__${name}`));
|
|
4928
|
-
const toolEnv = (peer: PeerId, deliveryOnly = false) => ({ ...(deliveryOnly ? { AGENTHUB_DELIVERY_ONLY: "true" } : {}), AGENTHUB_MODE: "tools", AGENTHUB_PEER_ID: peer,
|
|
5071
|
+
const toolEnv = (peer: PeerId, deliveryOnly = false) => ({ ...(deliveryOnly ? { AGENTHUB_DELIVERY_ONLY: "true" } : {}), AGENTHUB_MODE: "tools", AGENTHUB_PEER_ID: peer, ...projectChildEnv(ctx) });
|
|
4929
5072
|
|
|
4930
5073
|
/** One entry point for the task tools, whoever calls them: MCP clients, the local worker, the console. */
|
|
4931
5074
|
// A task op can write the board across awaits (triage, briefs, the dependents an approval releases): a recovery
|
|
@@ -5641,7 +5784,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
5641
5784
|
return { ok: true, guidance: excluded || stopping || recoveryActive() || bus.isRecoveryHeld ? { state: "unavailable" }
|
|
5642
5785
|
: op === "list" ? tasks.guidanceVariantList(by, input) : tasks.guidanceVariantDiff(by, input) };
|
|
5643
5786
|
}
|
|
5644
|
-
async function taskOpBody(by: PeerId, op: string, a: Record<string, any>, inProcess = false, piiTurn = false): Promise<string> {
|
|
5787
|
+
async function taskOpBody(by: PeerId, op: string, a: Record<string, any>, inProcess = false, piiTurn = false, toolSocket?: Sock): Promise<string> {
|
|
5645
5788
|
if (startupSpecPending() && specRoutingOps.has(op)) {
|
|
5646
5789
|
await firstSpecProbe;
|
|
5647
5790
|
// refusal:by-design world-action: routing is held by the hub until it finishes stopping or recovering.
|
|
@@ -6114,20 +6257,22 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
6114
6257
|
const repoHint = tasks.refsRepoHint(t); // #723: advice only; never part of the write
|
|
6115
6258
|
const submodules = tasks.submoduleNotice(t); // #798 D1: advice only too
|
|
6116
6259
|
const specs = tasks.specNotice(t, by);
|
|
6117
|
-
|
|
6260
|
+
const structure = planStructureNotice(t);
|
|
6261
|
+
if (t.state === "backlog") return [line(t), specs, structure, repoHint, submodules].filter(Boolean).join("\n");
|
|
6118
6262
|
const overlap = tasks.overlaps(t, t.owner === by);
|
|
6119
6263
|
if (t.owner === by && tasks.silentFor(t.id) && factsOn()) factsFor(by).sawPlans(by, tasks.overlapTasks(t)); // as for an accept
|
|
6120
|
-
return [line(t), specs, tasks.namedOwnerNote(t, a.owner as PeerId | undefined, by), overlap, tasks.claimRoleGuidance(t, by), t.owner === by ? tasks.planGuardText(t) : "", repoHint, submodules].filter(Boolean).join("\n");
|
|
6264
|
+
return [line(t), specs, structure, tasks.namedOwnerNote(t, a.owner as PeerId | undefined, by), overlap, tasks.claimRoleGuidance(t, by), t.owner === by ? tasks.planGuardText(t) : "", repoHint, submodules].filter(Boolean).join("\n");
|
|
6121
6265
|
}
|
|
6122
6266
|
case "hub_task_accept": {
|
|
6123
6267
|
// S1 spec acceptance and S9 plan review are checked against one task snapshot before acceptance.
|
|
6124
6268
|
const t = await tasks.acceptReviewed(by, a.id, a.plan, a.refs);
|
|
6125
6269
|
const specs = tasks.specNotice(t, by);
|
|
6270
|
+
const structure = planStructureNotice(t);
|
|
6126
6271
|
// A silent cohort (issue #107): the owners' plans come with every accept, as what the newcomer works from.
|
|
6127
6272
|
const silent = tasks.silentFor(t.id);
|
|
6128
6273
|
const overlap = a.plan == null && a.refs == null && !silent ? "" : tasks.overlaps(t);
|
|
6129
6274
|
if (silent && factsOn()) factsFor(by).sawPlans(by, tasks.overlapTasks(t)); // the plans in this answer need no fact later
|
|
6130
|
-
return [line(t), specs, overlap, tasks.planGuardText(t), tasks.submoduleNotice(t), tasks.worktreeNote(t, by)].filter(Boolean).join("\n"); // #798 D1
|
|
6275
|
+
return [line(t), specs, structure, overlap, tasks.planGuardText(t), tasks.submoduleNotice(t), tasks.worktreeNote(t, by)].filter(Boolean).join("\n"); // #798 D1
|
|
6131
6276
|
}
|
|
6132
6277
|
case "hub_task_cancel": {
|
|
6133
6278
|
if (!a || typeof a !== "object" || Array.isArray(a) || Object.keys(a).some(key => !["id", "reason", "superseded_by", "revision"].includes(key))
|
|
@@ -6185,7 +6330,12 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
6185
6330
|
}
|
|
6186
6331
|
case "hub_remember": {
|
|
6187
6332
|
const reviewCard = reviewTurnCard(by);
|
|
6188
|
-
const
|
|
6333
|
+
const owner = by === USER ? undefined : bus.peers.get(by);
|
|
6334
|
+
// Socket-owned sessions must come from the active attachment. The native adapters publish their session through host-owned metadata.
|
|
6335
|
+
const writerSession = owner && owner.state !== "offline" && (!owner.ownsSocket || (toolSocket && owner.ownsSocket(toolSocket)))
|
|
6336
|
+
? recordOwners.get(owner)?.session() ?? owner.nativeSession
|
|
6337
|
+
: undefined;
|
|
6338
|
+
const { message: saved, outcome } = await tasks.rememberOutcome(by, a, reviewCard, writerSession);
|
|
6189
6339
|
// #1329 AC4: on a review card a note is a proposal, and the done report counts it by kind.
|
|
6190
6340
|
if (reviewCard && outcome === "candidate") reviewCount(reviewCard.id, "remembered");
|
|
6191
6341
|
// #1279: a saved note that names another entry cites it. `tasks.remember` already refused a PII task, a private path and a secret, so only a note it saved gets here.
|
|
@@ -7486,6 +7636,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
7486
7636
|
if (crashLostIds.size) { try { for (const row of bus.queueList(undefined, true)) if (row.state === "needs_review" && crashLostIds.has(row.id)) inFlight++; } catch { inFlight = crashLostIds.size; } }
|
|
7487
7637
|
return openCrashNotices(crashNotices, { attached, inFlight });
|
|
7488
7638
|
};
|
|
7639
|
+
let mcpEndpoint: McpEndpoint | undefined;
|
|
7489
7640
|
const status = (includeAttentionItems = false, includeAttentionInput = false, includeDoing = false, includeIncomingLabels = false, includeActivity = false) => {
|
|
7490
7641
|
const taskNeeds = board.statusTasks();
|
|
7491
7642
|
const ownerIsolation = ownerIsolationProjection();
|
|
@@ -7505,6 +7656,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
7505
7656
|
...(crashLines.length ? { crash: crashLines } : {}),
|
|
7506
7657
|
projectId,
|
|
7507
7658
|
instanceId,
|
|
7659
|
+
...(opts.hostId ? { hostId: opts.hostId } : {}), // #1779: the host process this project runs in; `pid` is then the host's
|
|
7508
7660
|
...roomCommands.statusSnapshot(),
|
|
7509
7661
|
version: VERSION,
|
|
7510
7662
|
pluginBundle: SERVER_JS,
|
|
@@ -7525,7 +7677,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
7525
7677
|
...(taskSweepConfig(config.task_sweep).enabled ? { taskWait: true } : {}),
|
|
7526
7678
|
// Every supported peer's membership, for launchers that run outside the console role (#484).
|
|
7527
7679
|
roster: [...KNOWN_PEERS, ...OPTIONAL_PEERS].map(peer => ({ peer, on: onRoster(peer) })),
|
|
7528
|
-
protocol:
|
|
7680
|
+
protocol: acceptedBridgeWindow.vMin, protocolMin: acceptedBridgeWindow.vMin, protocolMax: acceptedBridgeWindow.v, bridgeProtocolFloorLimited,
|
|
7529
7681
|
features: DAEMON_FEATURES,
|
|
7530
7682
|
configuredAdapters: configuredIds,
|
|
7531
7683
|
...(externalAdapters.length ? { externalAdapters } : {}),
|
|
@@ -7548,10 +7700,11 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
7548
7700
|
pid: process.pid,
|
|
7549
7701
|
cwd: opts.cwd,
|
|
7550
7702
|
controlPort: server.port,
|
|
7703
|
+
...(mcpEndpoint ? { mcpSocket: mcpEndpoint.path } : {}),
|
|
7551
7704
|
...(dashboard ? { uiOrigin: dashboard.origin } : {}),
|
|
7552
7705
|
codexProxyPort: opts.codexProxyPort,
|
|
7553
7706
|
peers: Object.fromEntries(
|
|
7554
|
-
peerIds.map((id) => { const p = bus.peers.get(id); const summary = bus.queueSummary(id); const pressure = queueBackpressure?.peers[id]; const oldestQueuedAt = pressure ? pressure.oldestQueuedAt : summary.oldestQueuedAt; const context = contexts.view(id, contextSession(id), !!p && ["idle", "busy", "paused"].includes(bus.stateOf(id))); const statusNotice = isFixedBuiltinDefinition(definitionOf(id)) ? p?.statusNotice : undefined; const reviewObserverHoldNote = reviewObserverSessionIdentityHoldNote(id); const detached = jcodeDetached.get(id); return [id, { state: bus.stateOf(id), ...(includeAttentionItems && isExternalInstance(id) && !externalRefusedRows.has(id) && retainedExternalBinding(id) ? { externalInstance: retainedExternalBinding(id) } : {}), ...(!membershipAllowed(id) ? { rostered: false, rosterNote: "off roster" } : {}), ...permissionStatus(id, p), ...(statusNotice ? { statusNotice } : {}), ...(detached ? { detached } : {}), ...(jcodeRefusedHello.has(id) && ownedLaunchServing(id) ? { refusedHello: jcodeRefusedHello.get(id) } : {}), ...(reviewObserverHoldNote ? { reviewObserverHoldNote } : {}), ...(context.source !== null || context.measuredAt !== null ? { context } : {}), queued: bus.queued(id), ...(p ? {} : { attached: false }), ...(includeAttentionItems && p?.standbySessions?.length ? { standbySessions: p.standbySessions } : {}), ...(includeAttentionItems && p?.ownerAttachment ? { ownerAttachment: p.ownerAttachment } : {}), ...(declarations[id] && config.roles[id]?.includes("implementer") && definitionOf(id)?.transport === "claude-channel" ? { ownerIsolation: ownerIsolation[id] === true, ...(ownerIsolation[id] !== true ? { ownerIsolationNote: "terminal execution root not verified; owner admission refused" } : {}) } : {}), ...(summary.needsReview ? { needsReview: summary.needsReview } : {}), ...(summary.liveAccepted ? { liveAccepted: summary.liveAccepted, settlementNote: "awaiting adapter completion (Claude: correlated reply or hub_delivery_done); task state is independent" } : {}), ...queueHoldStatus(id, summary.heldBy), ...(typeof oldestQueuedAt === "number" ? { oldestQueuedAt } : {}), ...(bus.queuedImportant(id) ? { queuedImportant: bus.queuedImportant(id) } : {}), ...importantWaitingStatus(id, p), ...pausedNote(id), ...(reviewerUnavailable.has(id) ? { reviewerUnavailable: reviewerUnavailable.get(id) } : {}), ...jcodeModelSource(id), ...(reviewOnlyPeer(id) ? { reviewScope: reviewScopeOf(id) } : {}), ...(isLocalPeer(p) && p.lastServedBy ? { servedBy: p.lastServedBy } : {}), ...(isWsPeer(p) ? { ...(p.claiming ? { claiming: true } : {}), ...(definitionOf(id)?.transport === "claude-channel" && p.attached ? { attachMode: p.attachMode, attachEvidence: p.attachEvidence } : {}) } : {}), ...(isWsPeer(p) && p.pullOnly ? { pullOnly: true, toolsOnly: definitionOf(id)?.attach?.pullOnlyNotice ?? "tools-only: messages wait for hub_inbox; for pushes restart Claude with ahub claude", lastInboxAt: p.lastInboxAt ?? null } : {}), ...(isPiPeer(p) ? { requestedModel: p.getRequestedModel(), backends: modelRelays.get(id)?.status().backends ?? [] } : {}) }]; }),
|
|
7707
|
+
peerIds.map((id) => { const p = bus.peers.get(id); const summary = bus.queueSummary(id); const pressure = queueBackpressure?.peers[id]; const oldestQueuedAt = pressure ? pressure.oldestQueuedAt : summary.oldestQueuedAt; const context = contexts.view(id, contextSession(id), !!p && ["idle", "busy", "paused"].includes(bus.stateOf(id))); const statusNotice = isFixedBuiltinDefinition(definitionOf(id)) ? p?.statusNotice : undefined; const reviewObserverHoldNote = reviewObserverSessionIdentityHoldNote(id); const detached = jcodeDetached.get(id); return [id, { state: bus.stateOf(id), ...(includeAttentionItems && isExternalInstance(id) && !externalRefusedRows.has(id) && retainedExternalBinding(id) ? { externalInstance: retainedExternalBinding(id) } : {}), ...(!membershipAllowed(id) ? { rostered: false, rosterNote: "off roster" } : {}), ...permissionStatus(id, p), ...(statusNotice ? { statusNotice } : {}), ...(detached ? { detached } : {}), ...(jcodeRefusedHello.has(id) && ownedLaunchServing(id) ? { refusedHello: jcodeRefusedHello.get(id) } : {}), ...(reviewObserverHoldNote ? { reviewObserverHoldNote } : {}), ...(context.source !== null || context.measuredAt !== null ? { context } : {}), queued: bus.queued(id), ...(p ? {} : { attached: false }), ...(includeAttentionItems && p?.standbySessions?.length ? { standbySessions: p.standbySessions } : {}), ...(includeAttentionItems && p?.ownerAttachment ? { ownerAttachment: p.ownerAttachment } : {}), ...(declarations[id] && config.roles[id]?.includes("implementer") && definitionOf(id)?.transport === "claude-channel" ? { ownerIsolation: ownerIsolation[id] === true, ...(ownerIsolation[id] !== true ? { ownerIsolationNote: "terminal execution root not verified; owner admission refused" } : {}) } : {}), ...presetStatusRow(id), ...(summary.needsReview ? { needsReview: summary.needsReview } : {}), ...(summary.liveAccepted ? { liveAccepted: summary.liveAccepted, settlementNote: "awaiting adapter completion (Claude: correlated reply or hub_delivery_done); task state is independent" } : {}), ...queueHoldStatus(id, summary.heldBy), ...(typeof oldestQueuedAt === "number" ? { oldestQueuedAt } : {}), ...(bus.queuedImportant(id) ? { queuedImportant: bus.queuedImportant(id) } : {}), ...importantWaitingStatus(id, p), ...pausedNote(id), ...(reviewerUnavailable.has(id) ? { reviewerUnavailable: reviewerUnavailable.get(id) } : {}), ...jcodeModelSource(id), ...(reviewOnlyPeer(id) ? { reviewScope: reviewScopeOf(id) } : {}), ...(isLocalPeer(p) && p.lastServedBy ? { servedBy: p.lastServedBy } : {}), ...(isWsPeer(p) ? { ...(p.claiming ? { claiming: true } : {}), ...(definitionOf(id)?.transport === "claude-channel" && p.attached ? { attachMode: p.attachMode, attachEvidence: p.attachEvidence } : {}) } : {}), ...(isWsPeer(p) && p.pullOnly ? { pullOnly: true, toolsOnly: definitionOf(id)?.attach?.pullOnlyNotice ?? "tools-only: messages wait for hub_inbox; for pushes restart Claude with ahub claude", lastInboxAt: p.lastInboxAt ?? null } : {}), ...(isPiPeer(p) ? { requestedModel: p.getRequestedModel(), backends: modelRelays.get(id)?.status().backends ?? [] } : {}) }]; }),
|
|
7555
7708
|
),
|
|
7556
7709
|
peerVersions,
|
|
7557
7710
|
taskWip: tasks.wipBreakdown(peerIds),
|
|
@@ -7611,8 +7764,11 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
7611
7764
|
recovery: recoveryOperationId ? { id: recoveryOperationId, running: true } : undefined,
|
|
7612
7765
|
tasks: taskNeeds,
|
|
7613
7766
|
results: unreadResults().map(result => ({ id: result.id, peer: result.peer, since: result.settledAt })),
|
|
7767
|
+
panes: paneWatch.blocked().map(pane => ({ peer: pane.peer, handle: pane.handle, since: pane.since })),
|
|
7614
7768
|
facts: [...taskStalls.map(stall => ({ kind: "stall" as const, id: stall.task })), ...pendingTaskOffers.map(offer => ({ kind: "offer" as const, id: offer.task, peer: offer.peer }))],
|
|
7615
|
-
budget: Object.fromEntries(Object.entries(budget.status()).map(([peer, row]) => [peer, row.paused
|
|
7769
|
+
budget: Object.fromEntries(Object.entries(budget.status()).map(([peer, row]) => [peer, row.paused
|
|
7770
|
+
? { paused: { since: row.paused.since, resetsAt: row.paused.resetsAt } }
|
|
7771
|
+
: includeAttentionItems || includeAttentionInput ? { warnings: windowRow(peer, row).warnings } : {}])),
|
|
7616
7772
|
};
|
|
7617
7773
|
const attention = needs(attentionInput, Date.now());
|
|
7618
7774
|
// #1798: the one hub check, built from the finished peer rows; every surface renders this result.
|
|
@@ -8496,7 +8652,10 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
8496
8652
|
opening.set(peer, Date.now());
|
|
8497
8653
|
if (resume && (stopping || recoveryActive() || !membershipAllowed(peer) || rosterChanging === peer || requestedPeerStops.has(peer))) { opening.delete(peer); return { ok: false, error: "Pi lifecycle changed before its continuity terminal opened; bookmark retained" }; }
|
|
8498
8654
|
// Every word is the hub's own: its runtime, its entry point, this project and a peer from the closed list.
|
|
8499
|
-
|
|
8655
|
+
// #1811: an extra implementer's terminal lands in the Orca workspace of its own worktree; the base peer, and any peer whose root cannot be resolved, use the project root.
|
|
8656
|
+
let terminalRoot: string | undefined;
|
|
8657
|
+
try { const root = resolveExecutionCwd(peer, declarations, config.roles[peer] ?? [], adapterCatalog); if (root !== opts.cwd) terminalRoot = root; } catch { /* the opener falls back to the project root */ }
|
|
8658
|
+
const opened = await opener.open(`${peer} (agent-hub)`, [process.execPath, CLI_ENTRY, "--project", opts.cwd, ...words], terminalRoot).catch((error: Error) => ({ ok: false as const, why: "the terminal provider failed", detail: error.message }));
|
|
8500
8659
|
if (!opened.ok) {
|
|
8501
8660
|
opening.delete(peer); // nothing was opened: the next request may try again at once
|
|
8502
8661
|
if (opened.detail) log(`terminal provider for ${peer}: ${opened.detail}`);
|
|
@@ -8705,7 +8864,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
8705
8864
|
if (!onRoster(peer)) return { ok: false, error: "qwen is off roster; a person can add it with ahub roster add qwen" };
|
|
8706
8865
|
if (existing && existing.state !== "offline") return { ok: false, error: "Qwen is running headless; run ahub stop qwen before starting its TUI" };
|
|
8707
8866
|
// The compat entry of the dual-output contract, not the headless ACP entry: 0.26.1 only.
|
|
8708
|
-
const verdict = await qwenDualVersionAsync(config.qwen_cmd, executionCwd);
|
|
8867
|
+
const verdict = await qwenDualVersionAsync(config.qwen_cmd, executionCwd, ctx.env);
|
|
8709
8868
|
startCurrent?.();
|
|
8710
8869
|
if (!verdict.ok) return { ok: false, error: verdict.reason };
|
|
8711
8870
|
if (verdict.note) log(verdict.note);
|
|
@@ -8756,7 +8915,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
8756
8915
|
...(isFixedBuiltinDefinition(adapter) && adapter.modelOverride?.acp ? { modelPolicy: adapter.modelOverride.acp } : {}),
|
|
8757
8916
|
providerProfile: (args.providerProfile ?? instance?.provider_profile ?? config.jcode_provider_profile) || undefined,
|
|
8758
8917
|
...(instance?.provider ? { provider: instance.provider } : {}),
|
|
8759
|
-
...(args.model ?? instance?.model ? { launchModel: (args.model ?? instance?.model)! } : {}), ...(args.sessionId ? { resumeSessionId: args.sessionId } : {}), cwd: executionCwd, watchdogMs: config.watchdog_ms,
|
|
8918
|
+
...(args.model ?? instance?.model ? { launchModel: (args.model ?? instance?.model)! } : {}), ...(args.sessionId ? { resumeSessionId: args.sessionId } : {}), cwd: executionCwd, env: ctx.env, watchdogMs: config.watchdog_ms,
|
|
8760
8919
|
toolCeilingMs: adapterTiming.acpToolCeilingMs(), activityBatchMs: adapterTiming.acpActivityBatchMs(), steerTimeoutMs: adapterTiming.jcodeSteerTimeoutMs(),
|
|
8761
8920
|
tuiHintContext: () => ({ tui: startMode(peer) === "tui", afterCrash: crashReported }),
|
|
8762
8921
|
preamble: sessionRoleContract(peer), log: () => log("Jcode native diagnostic: details withheld"),
|
|
@@ -8803,7 +8962,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
8803
8962
|
permissionMode: permissionMode(peer),
|
|
8804
8963
|
...(args.model ? { launchModel: args.model } : {}),
|
|
8805
8964
|
...(args.sessionId ? { resumeSessionId: args.sessionId } : {}),
|
|
8806
|
-
cwd: executionCwd,
|
|
8965
|
+
cwd: executionCwd, env: ctx.env,
|
|
8807
8966
|
watchdogMs: config.watchdog_ms,
|
|
8808
8967
|
onPermission,
|
|
8809
8968
|
// The hub's own tools pass without a console prompt, as Codex's do (approval_mode below; issue #72).
|
|
@@ -8814,7 +8973,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
8814
8973
|
log,
|
|
8815
8974
|
// Pause synchronously before the adapter requeues a provider-refused prompt (#306).
|
|
8816
8975
|
onQuotaRefusal: (window) => {
|
|
8817
|
-
budget.report(peer, [window], true);
|
|
8976
|
+
budget.report(peer, [window], true, Date.now(), undefined, { turnStartedAt: turns.get(peer)?.start });
|
|
8818
8977
|
return !!budget.record(peer) && bus.isPaused(peer);
|
|
8819
8978
|
},
|
|
8820
8979
|
// Kimi's usage_update is context occupancy ({used, size}), not consumption (#167): it becomes the peer's
|
|
@@ -8949,7 +9108,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
8949
9108
|
actionBudgets.revoke(peer);
|
|
8950
9109
|
startCurrent?.();
|
|
8951
9110
|
const codex: CodexPeer = adapter!.start.create!({ instance: peer, projectRoot: opts.cwd, stateDir: opts.stateDir, kindConfig: config, permission: permissionMode(peer), mcpServers: [], daemon: DAEMON_PORTS["codex-appserver"]({
|
|
8952
|
-
activityServers: codexActivityServers(process.env.CODEX_HOME?.trim() || join(homedir(), ".codex"), executionCwd),
|
|
9111
|
+
activityServers: codexActivityServers(instanceAccountEnv(peer)?.CODEX_HOME || process.env.CODEX_HOME?.trim() || join(homedir(), ".codex"), executionCwd),
|
|
8953
9112
|
getModelOverride: () => modelSelection(peer),
|
|
8954
9113
|
onNativeModelApplied: model => { if (!stopping && bus.peers.get(peer) === codex && isNativeModelToken(model)) {
|
|
8955
9114
|
try { modelLatches.observeNative(peer, codex, model); } catch { modelLatches.forget(peer); }
|
|
@@ -9021,10 +9180,11 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
9021
9180
|
...HUB_TOOLS.map((name) => [`tools.${name}.approval_mode`, '"approve"']),
|
|
9022
9181
|
].flatMap(([k, v]) => ["-c", `mcp_servers.agent-hub.${k}=${v}`]),
|
|
9023
9182
|
preamble: sessionRoleContract(peer),
|
|
9024
|
-
onUsage: (rateLimits, hard, accountUsage) => { const windows = readNativeQuota(adapter, rateLimits); if (windows) budget.report(peer, windows, hard, Date.now(), accountUsage); },
|
|
9183
|
+
onUsage: (rateLimits, hard, accountUsage, origin) => { const windows = readNativeQuota(adapter, rateLimits); if (windows) budget.report(peer, windows, hard, Date.now(), accountUsage, origin); },
|
|
9025
9184
|
usagePause: { current: () => budget.record(peer) !== undefined, subscribe: changed => budget.watchPause(peer, changed) },
|
|
9026
9185
|
usagePollMs: config.budget.poll_min * 60_000,
|
|
9027
9186
|
cwd: executionCwd,
|
|
9187
|
+
env: { ...ctx.env, ...(instanceAccountEnv(peer) ?? {}) },
|
|
9028
9188
|
watchdogMs: config.watchdog_ms,
|
|
9029
9189
|
log,
|
|
9030
9190
|
}) }) as CodexPeer;
|
|
@@ -9457,7 +9617,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
9457
9617
|
const implementer = adapter.start.create!({ instance: peer, projectRoot: opts.cwd, stateDir: opts.stateDir, kindConfig: config, permission: selected, mcpServers: [], daemon: DAEMON_PORTS["claude-implementer"]({
|
|
9458
9618
|
getModelOverride: () => modelSelection(peer),
|
|
9459
9619
|
cwd: executionCwd, stateDir: opts.stateDir, projectRoot: opts.cwd, instanceId, server: SERVER_JS,
|
|
9460
|
-
factsHook: join(import.meta.dir, "..", "cli", "facts-hook.ts"), systemPrompt: sessionRoleContract(peer), mode: selected, watchdogMs: config.watchdog_ms, ...(declarations[peer]?.model ? { model: declarations[peer].model } : {}),
|
|
9620
|
+
factsHook: join(import.meta.dir, "..", "cli", "facts-hook.ts"), systemPrompt: sessionRoleContract(peer), mode: selected, watchdogMs: config.watchdog_ms, ...(declarations[peer]?.model ? { model: declarations[peer].model } : {}), ...(instanceAccountEnv(peer) ? { accountEnv: instanceAccountEnv(peer)! } : {}),
|
|
9461
9621
|
beforeInput: (context, envs) => beforeOwnedObserverInput(peer, implementer, context, envs),
|
|
9462
9622
|
inputReleased: (context, envs) => ownedObserverInputReleased(peer, implementer, context, envs),
|
|
9463
9623
|
admit: env => {
|
|
@@ -9555,11 +9715,13 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
9555
9715
|
},
|
|
9556
9716
|
facts: env => env.private ? undefined : reviewDiff(executionCwd, env.refs?.commit, { privatePath: path => isDenied(path, config.local.deny) || matchesPolicy(executionCwd, path, config.pii?.paths ?? [], true), nameable: tasks.nameable }),
|
|
9557
9717
|
verdictSince: (task, since) => board.get(task)?.history.some(h => h.by === peer && h.at >= since && (h.event === "approved" || h.event === "changes_requested")) === true,
|
|
9558
|
-
onQuota: (value, attempt, current) => {
|
|
9718
|
+
onQuota: (value, attempt, current, turnStartedAt) => {
|
|
9559
9719
|
const reading = nativeReviewerQuota(value);
|
|
9560
9720
|
if (!reading || !current() || bus.peers.get(peer) !== reviewer || !/^[a-f0-9]{32}$/.test(attempt)) return false;
|
|
9721
|
+
const renewedAt = budget.renewalAt(peer);
|
|
9722
|
+
if (renewedAt !== undefined && turnStartedAt < renewedAt) return false;
|
|
9561
9723
|
unsettledReviewerQuota.set(attempt, { account: accountOf(peer), peer });
|
|
9562
|
-
budget.report(peer, [reading], true);
|
|
9724
|
+
budget.report(peer, [reading], true, Date.now(), undefined, { turnStartedAt });
|
|
9563
9725
|
return budget.record(peer) !== undefined;
|
|
9564
9726
|
},
|
|
9565
9727
|
quotaSettled: attempt => {
|
|
@@ -9594,14 +9756,14 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
9594
9756
|
const safe = visible && hostSafe && diagnostic.refusal !== undefined && boundedSafe(diagnostic.refusal) && tasks.publicMetadataText(diagnostic.refusal) ? diagnostic.refusal : undefined;
|
|
9595
9757
|
log(reviewerNoVerdictLine(peer, diagnostic, safe, !visible));
|
|
9596
9758
|
},
|
|
9597
|
-
onUnavailable: (failure, current) => {
|
|
9759
|
+
onUnavailable: (failure, current, turnStartedAt) => {
|
|
9598
9760
|
const attached = () => current() && bus.peers.get(peer) === reviewer;
|
|
9599
9761
|
if (!attached()) return false;
|
|
9600
9762
|
if (failure.cause === "quota") {
|
|
9601
9763
|
const readings = (failure.quota ?? []).map(nativeReviewerQuota).filter((row): row is NonNullable<typeof row> => row !== undefined);
|
|
9602
9764
|
// ponytail: reviewer-only children have no attached native quota transport. Only an attached account sibling
|
|
9603
9765
|
// or Budget's existing evaluate/expiry paths can end a pause; never infer an early reset here.
|
|
9604
|
-
if (readings.length && !budget.record(peer)) budget.report(peer, readings, true);
|
|
9766
|
+
if (readings.length && !budget.record(peer)) budget.report(peer, readings, true, Date.now(), undefined, { turnStartedAt });
|
|
9605
9767
|
// Canonical account handoff may already have moved this exact review while applying the hard pause.
|
|
9606
9768
|
if (!tasks.reviewBindingCurrent(peer, failure.task, failure)) return true;
|
|
9607
9769
|
}
|
|
@@ -11747,7 +11909,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
11747
11909
|
let child: ReturnType<typeof Bun.spawn>;
|
|
11748
11910
|
const inherited = { data: client, get readyState() { return open ? WebSocket.OPEN : WebSocket.CLOSED; }, send: (text: string) => child.send(JSON.parse(text)), close: () => { open = false; child.disconnect(); }, getBufferedAmount: () => 0 } as unknown as Sock;
|
|
11749
11911
|
child = Bun.spawn({ cmd: [instructedRuntime.bun, join(instructedRuntime.root, "src/cli/main.js"), ...argv],
|
|
11750
|
-
cwd: opts.cwd, env: { ...personEnv(
|
|
11912
|
+
cwd: opts.cwd, env: { ...personEnv(ctx.env), AGENTHUB_INSTRUCTED_IPC: "1", ...projectChildEnv(ctx) },
|
|
11751
11913
|
stdin: "ignore", stdout: "pipe", stderr: "pipe", serialization: "json",
|
|
11752
11914
|
ipc(message) {
|
|
11753
11915
|
try {
|
|
@@ -11908,10 +12070,16 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
11908
12070
|
if (!c.authed) {
|
|
11909
12071
|
if (msg.t !== "hello" || msg.token !== token) return sock.close(4401, "bad token");
|
|
11910
12072
|
if (typeof msg.peer === "string" && msg.peer.includes("@")) return sock.close(4403, "remote identities have no control connection");
|
|
11911
|
-
const offered = protocolWindow(msg.v, msg.vMin), selectedProtocol = offered && negotiateProtocol(
|
|
12073
|
+
const offered = protocolWindow(msg.v, msg.vMin), selectedProtocol = offered && negotiateProtocol(acceptedBridgeWindow, offered);
|
|
11912
12074
|
if (selectedProtocol === undefined) {
|
|
11913
12075
|
// An outdated plugin would drop every digest without a trace. Refuse it loudly instead.
|
|
11914
|
-
|
|
12076
|
+
const implemented = offered && negotiateProtocol({ v: PROTOCOL, vMin: PROTOCOL_MIN }, offered) !== undefined;
|
|
12077
|
+
const next = implemented
|
|
12078
|
+
? "check upgrade.bridge_window_days and upgrade.bridge_window_min"
|
|
12079
|
+
: "update the agent-hub plugin (claude plugin update agent-hub@agent-hub)";
|
|
12080
|
+
const wire = offered ? `bridge wire offer ${offered.vMin}–${offered.v}`
|
|
12081
|
+
: msg.v === undefined ? "wire version 1" : "bridge wire offer invalid";
|
|
12082
|
+
log(`refused ${msg.role} ${msg.peer ?? ""}: ${wire}; hub accepts ${acceptedBridgeWindow.vMin}–${acceptedBridgeWindow.v}; ${next}`);
|
|
11915
12083
|
return sock.close(4426, `wire version mismatch: hub speaks ${PROTOCOL}; update the agent-hub plugin`);
|
|
11916
12084
|
}
|
|
11917
12085
|
if ((msg.projectId && msg.projectId !== projectId) || (msg.instanceId && msg.instanceId !== instanceId) ||
|
|
@@ -12004,6 +12172,8 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
12004
12172
|
if (typeof msg.cwd === "string" && msg.cwd.length <= 4096) sock.data.cwd = msg.cwd;
|
|
12005
12173
|
const clientPid = Number.isSafeInteger(msg.clientPid) && msg.clientPid > 0 && msg.clientPid <= 2_147_483_647 ? msg.clientPid as number : undefined;
|
|
12006
12174
|
sock.data.clientPid = clientPid;
|
|
12175
|
+
// #1810: the session's home becomes a declared label here and the path goes no further; an undeclared home is the default label, which sets nothing.
|
|
12176
|
+
{ const label = labelForHome(msg.home, definitionOf(c.peer)?.budget?.account ?? declarations[c.peer]?.kind ?? c.peer, config.accounts); if (label !== DEFAULT_ACCOUNT_LABEL) sock.data.accountLabel = label; else delete sock.data.accountLabel; }
|
|
12007
12177
|
sock.data.clientVersion = c.clientVersion;
|
|
12008
12178
|
const pushOverPullOnly = msg.channel !== false && ws.attached && ws.pullOnly && !ws.claiming;
|
|
12009
12179
|
const hasLiveHolder = ws.attached || ws.claiming;
|
|
@@ -12035,7 +12205,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
12035
12205
|
// #604 PR B: one attach event per admitted peer or tools hello, with the same fields an envelope's `origin` carries. A refused hello returned above and writes none.
|
|
12036
12206
|
if (c.role === "tools" && !c.session) toolsSockets.add(sock);
|
|
12037
12207
|
if (c.role === "peer" || c.role === "tools") event(attachEvent({ role: c.role, peer: c.peer, launchId: c.launchId, ...(c.session ? { session: true } : {}) }));
|
|
12038
|
-
return void reply({ t: "welcome", projectId, instanceId, cwd: opts.cwd, protocol: c.protocol, protocolMin:
|
|
12208
|
+
return void reply({ t: "welcome", projectId, instanceId, cwd: opts.cwd, protocol: c.protocol, protocolMin: acceptedBridgeWindow.vMin, protocolMax: acceptedBridgeWindow.v, features: DAEMON_FEATURES,
|
|
12039
12209
|
...(c.session ? { session: c.peer } : {}), ...(c.standbyId ? { standby: true, standbyId: c.standbyId } : {}) });
|
|
12040
12210
|
}
|
|
12041
12211
|
const committedSourceProof = c.role === "tools" && msg.t === "recovery_authority" && msg.op === "verify" && recoveryCommitted
|
|
@@ -13231,6 +13401,57 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
13231
13401
|
})().catch(() => reply({ ok: false, error: "public lifecycle readback unavailable" }));
|
|
13232
13402
|
return;
|
|
13233
13403
|
}
|
|
13404
|
+
if (msg.op === "sync") {
|
|
13405
|
+
// #1856 T3: a preview writes nothing; apply re-plans and refuses before any write unless the fingerprint still matches.
|
|
13406
|
+
if (c.role !== "console" && c.role !== "tools") return void reply({ ok: false, error: "ahub sdlc sync is for the person or a tools session; run it from a terminal" });
|
|
13407
|
+
if (c.peer && (!!turns.get(c.peer)?.private || contextPii(c.peer))) return void reply({ ok: false, error: "ahub sdlc sync is unavailable in a private turn; finish it and retry" });
|
|
13408
|
+
const apply = msg.apply === true, asker = c.role === "console" ? USER : c.peer;
|
|
13409
|
+
if (apply && (!asker || typeof msg.confirm !== "string" || !/^[a-f0-9]{64}$/.test(msg.confirm))) return void reply({ ok: false, error: "apply needs the fingerprint of a preview; run ahub sdlc sync, then ahub sdlc sync --apply --confirm <fingerprint>" });
|
|
13410
|
+
const repository = githubOriginRepository(opts.cwd);
|
|
13411
|
+
const writeRoadmap = msg.writeRoadmap === true, closeSettled = msg.closeSettled === true;
|
|
13412
|
+
if (closeSettled) { try { tasks.closeSettledGate(asker ?? USER); } catch (error) { return void reply({ ok: false, error: sanitize(error instanceof Error ? error.message : "closing settled issues is not permitted") }); } }
|
|
13413
|
+
const planNow = () => planSdlcSync({
|
|
13414
|
+
...(writeRoadmap ? { roadmap: { tracked: msg.roadmapTracked === true, render: () => tasks.roadmapExport(asker ?? USER) } } : {}),
|
|
13415
|
+
...(closeSettled ? { closeSettled: { cards: board.list().map(task => ({ id: task.id, state: task.state, pii: tasks.isPii(task), ...(task.sdlc?.repo ? { repo: task.sdlc.repo } : {}), ...(task.sdlc?.issue ? { issue: task.sdlc.issue } : {}), ...(task.sdlc?.pr ? { pr: task.sdlc.pr } : {}) })) } } : {}),
|
|
13416
|
+
repository, authority: asker === USER ? "person" : `conductor:${asker ?? "none"}:${lifecycleConfig.mode}`,
|
|
13417
|
+
gh: (args, timeout, _cwd, bound) => sdlcGh(args, timeout, opts.cwd, bound),
|
|
13418
|
+
tasks: board.list().filter(task => ["proposed", "in_progress", "in_review", "changes_requested"].includes(task.state)).map(task => {
|
|
13419
|
+
const pii = tasks.isPii(task);
|
|
13420
|
+
return { id: task.id, state: task.state, // not tasks.publicTitle: it prefixes `#<id> `, which the title parser would read as an issue.
|
|
13421
|
+
title: pii ? "" : task.title, pii, ...(task.refs.repo && !pii ? { refsRepo: task.refs.repo } : {}),
|
|
13422
|
+
branches: !pii && task.refs.branch ? [task.refs.branch] : [], historyLength: task.history.length,
|
|
13423
|
+
...(task.sdlc && !pii ? { sdlc: { ...(task.sdlc.repo ? { repo: task.sdlc.repo } : {}), ...(task.sdlc.issue ? { issue: task.sdlc.issue } : {}), ...(task.sdlc.pr ? { pr: task.sdlc.pr } : {}), ...(task.sdlc.localHead ? { localHead: task.sdlc.localHead } : {}), ...(task.sdlc.reviewedHead ? { reviewedHead: task.sdlc.reviewedHead } : {}) } } : {}) };
|
|
13424
|
+
}),
|
|
13425
|
+
});
|
|
13426
|
+
if (!apply) {
|
|
13427
|
+
void planNow().then(plan => reply({ ok: true, apply: false, options: { writeRoadmap, closeSettled }, ...plan }), error => reply({ ok: false, error: `sync plan unavailable (${error instanceof Error ? error.name : "unknown error"}); run ahub sdlc check and retry` }));
|
|
13428
|
+
return;
|
|
13429
|
+
}
|
|
13430
|
+
taskOpsInFlight++;
|
|
13431
|
+
void (async () => {
|
|
13432
|
+
const plan = await planNow();
|
|
13433
|
+
if (plan.fingerprint !== msg.confirm) return reply({ ok: false, error: `the board, origin or authority changed since the preview; review ahub sdlc sync and confirm the new fingerprint ${plan.fingerprint}`, fingerprint: plan.fingerprint });
|
|
13434
|
+
const results: { task: number; kind: string; ok: boolean; error?: string }[] = [];
|
|
13435
|
+
for (const op of plan.operations) {
|
|
13436
|
+
try {
|
|
13437
|
+
if (op.kind === "link") tasks.recordSyncRepair(asker!, op.task, { repo: op.repo, issue: op.issue });
|
|
13438
|
+
else if (op.kind === "bind") tasks.recordSyncRepair(asker!, op.task, { repo: op.repo, pr: op.pr, localHead: op.localHead });
|
|
13439
|
+
else await tasks.adoptMerge(asker!, op.task, op.pr);
|
|
13440
|
+
results.push({ task: op.task, kind: op.kind, ok: true });
|
|
13441
|
+
} catch (error) { results.push({ task: op.task, kind: op.kind, ok: false, error: sanitize(error instanceof Error ? error.message : "refused") }); }
|
|
13442
|
+
}
|
|
13443
|
+
for (const close of plan.closes) {
|
|
13444
|
+
try { await tasks.closeSettledIssue(asker!, close.repo, close.issue); results.push({ task: 0, kind: `close #${close.issue}`, ok: true }); }
|
|
13445
|
+
catch (error) { results.push({ task: 0, kind: `close #${close.issue}`, ok: false, error: sanitize(error instanceof Error ? error.message : "refused") }); }
|
|
13446
|
+
}
|
|
13447
|
+
let roadmapFiles: { json: string; markdown: string } | undefined;
|
|
13448
|
+
if (plan.roadmap) {
|
|
13449
|
+
try { const files = await tasks.roadmapExport(asker!); roadmapFiles = { json: files.json, markdown: files.markdown }; } catch { results.push({ task: 0, kind: "roadmap refresh", ok: false, error: "the roadmap could not be rendered; run ahub roadmap export" }); }
|
|
13450
|
+
}
|
|
13451
|
+
reply({ ok: true, apply: true, fingerprint: plan.fingerprint, results, ambiguous: plan.ambiguous, headMoved: plan.headMoved, withheld: plan.withheld, ...(roadmapFiles ? { roadmapFiles } : {}) });
|
|
13452
|
+
})().catch((error: Error) => reply({ ok: false, error: sanitize(error.message) })).finally(() => { taskOpsInFlight--; });
|
|
13453
|
+
return;
|
|
13454
|
+
}
|
|
13234
13455
|
if (c.role !== "console") return void reply({ ok: false, error: "SDLC readback is console only; task owners record ids through hub_sdlc_record" });
|
|
13235
13456
|
if (msg.op === "queue" || msg.op === "release") {
|
|
13236
13457
|
if (typeof msg.repo !== "string" || !Array.isArray(msg.liveIssues ?? []) || (msg.liveIssues ?? []).length > 32) return void reply({ ok: false, error: "invalid delivery readback arguments" });
|
|
@@ -13274,9 +13495,35 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
13274
13495
|
}, () => reply({ ok: false, error: "issue edit time unavailable; nothing was recorded" }));
|
|
13275
13496
|
return;
|
|
13276
13497
|
}
|
|
13498
|
+
// #1856 T2: the read-only audit. Open to the person and to agents; it writes nothing, shows public titles only and counts private tasks.
|
|
13499
|
+
if (msg.op === "check") {
|
|
13500
|
+
const offline = msg.offline === true, repository = githubOriginRepository(opts.cwd);
|
|
13501
|
+
const checkGh: SdlcGh = (args, timeout, _cwd, bound) => sdlcGh(args, timeout, opts.cwd, bound);
|
|
13502
|
+
const roleHolders = (role: string) => Object.keys(config.roles).filter(peer => config.roles[peer]!.includes(role) && projectRosterAllows(config.roster, peer, config.pi.enabled)).sort();
|
|
13503
|
+
const unsettled = board.list().filter(task => ["proposed", "in_progress", "in_review", "changes_requested"].includes(task.state));
|
|
13504
|
+
const tracked = hubGitSync(["ls-files", "--error-unmatch", "docs/roadmap.json"], { cwd: opts.cwd, encoding: "utf8", timeout: 5000 }).status === 0;
|
|
13505
|
+
void runSdlcCheck({
|
|
13506
|
+
offline, repository, gh: checkGh,
|
|
13507
|
+
running: { mode: lifecycleConfig.mode, requiredChecks: lifecycleConfig.requiredChecks, effectiveChecks: requiredChecksFor(lifecycleConfig, repository) },
|
|
13508
|
+
file: () => { const exists = existsSync(join(opts.cwd, ".agenthub", "sdlc.toml")); return { present: exists, config: loadSdlc(opts.cwd, VERSION) }; },
|
|
13509
|
+
holders: { planner: roleHolders("planner"), reviewer: roleHolders("reviewer"), conductor: roleHolders("conductor") },
|
|
13510
|
+
discover: run => discoverInitChecks(opts.cwd, run),
|
|
13511
|
+
securityScan: () => ({ configured: !!lifecycleConfig.securityScan, counts: tasks.securityScanCounts() }),
|
|
13512
|
+
tasks: unsettled.map(task => { const pii = tasks.isPii(task); return { id: task.id, state: task.state, title: pii ? "" : tasks.publicTitle(task), pii, ...(task.refs.branch && !pii ? { branch: task.refs.branch } : {}), ...(task.sdlc && !pii ? { sdlc: { ...(task.sdlc.repo ? { repo: task.sdlc.repo } : {}), ...(task.sdlc.issue ? { issue: task.sdlc.issue } : {}), ...(task.sdlc.pr ? { pr: task.sdlc.pr } : {}), ...(task.sdlc.localHead ? { localHead: task.sdlc.localHead } : {}) } } : {}) }; }),
|
|
13513
|
+
...(board.milestones().length || tracked ? { roadmap: {
|
|
13514
|
+
drift: () => tasks.roadmapCheck(USER),
|
|
13515
|
+
unplaced: () => tasks.roadmapUnplaced(USER, {}, checkGh),
|
|
13516
|
+
} } : {}),
|
|
13517
|
+
}).then(report => reply({ ok: true, ...report }), error => reply({ ok: false, error: `lifecycle audit unavailable (${error instanceof Error ? error.name : "unknown error"}); run ahub sdlc status and retry` }));
|
|
13518
|
+
return;
|
|
13519
|
+
}
|
|
13277
13520
|
if (msg.op !== "status" && msg.op !== "explain") return void reply({ ok: false, error: "unknown SDLC operation" });
|
|
13278
|
-
const
|
|
13279
|
-
if (msg.id !== undefined && (!Number.isSafeInteger(msg.id) || msg.id <= 0 || !
|
|
13521
|
+
const listed = msg.id === undefined ? board.list().filter(task => task.state !== "backlog" && (task.sdlc || lifecycleConfig.mode !== "off" || lifecycleConfig.workflow === "gsd-lite")) : [board.get(Number(msg.id))].filter((task): task is Task => !!task);
|
|
13522
|
+
if (msg.id !== undefined && (!Number.isSafeInteger(msg.id) || msg.id <= 0 || !listed.length)) return void reply({ ok: false, error: "invalid lifecycle task id" });
|
|
13523
|
+
// #1856 T1: a bare status lists the unsettled tasks and those of a release train not yet shipped; `all` keeps the historical first-100 slice, a task id is unchanged.
|
|
13524
|
+
const unsettledOnly = msg.op === "status" && msg.id === undefined && msg.all !== true;
|
|
13525
|
+
const openTrains = unsettledOnly ? new Set(board.releases().filter(release => release.state !== "shipped" && release.state !== "dropped").map(release => release.id)) : undefined;
|
|
13526
|
+
const selected = unsettledOnly ? listed.filter(task => ["proposed", "in_progress", "in_review", "changes_requested"].includes(task.state) || (task.release != null && openTrains!.has(task.release))) : listed;
|
|
13280
13527
|
void (async () => {
|
|
13281
13528
|
const rows = [];
|
|
13282
13529
|
for (const task of selected.slice(0, 100)) {
|
|
@@ -13284,7 +13531,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
13284
13531
|
const current = board.get(task.id) ?? task;
|
|
13285
13532
|
rows.push({ id: task.id, title: tasks.publicTitle(current), ...(tasks.isPii(current) ? {} : { receipt: tasks.publicView(current).sdlc }), ...status });
|
|
13286
13533
|
}
|
|
13287
|
-
reply({ ok: true, mode: lifecycleConfig.mode, rows, ...(tasks.securityScanCounts() ? { securityScan: tasks.securityScanCounts() } : {}), truncated: selected.length > 100 });
|
|
13534
|
+
reply({ ok: true, mode: lifecycleConfig.mode, rows, ...(tasks.securityScanCounts() ? { securityScan: tasks.securityScanCounts() } : {}), truncated: selected.length > 100, ...(unsettledOnly ? { unsettledOnly: true, hiddenSettled: listed.length - selected.length } : {}) });
|
|
13288
13535
|
})().catch(() => reply({ ok: false, error: "lifecycle readback unavailable" }));
|
|
13289
13536
|
return;
|
|
13290
13537
|
}
|
|
@@ -13710,7 +13957,8 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
13710
13957
|
if (c.closed || sock.readyState !== WebSocket.OPEN || c.invocationRequests.size >= 64) return void reply({ t: "task", ok: false, error: "invocation request connection unavailable" });
|
|
13711
13958
|
invocation = new AbortController(); c.invocationRequests.set(msg.rid, invocation);
|
|
13712
13959
|
}
|
|
13713
|
-
const
|
|
13960
|
+
const dispatch = () => taskOp(c.peer ?? USER, String(msg.op), msg.args ?? {}, false, false, sock);
|
|
13961
|
+
const run = async () => c.externalOwner ? childToolAuthority.run({ by: c.peer!, current: () => currentExternalTools(c, true) }, dispatch) : c.toolsOwner ? childToolAuthority.run({ by: c.peer!, current: captureImplementerTools(c) }, dispatch) : dispatch();
|
|
13714
13962
|
const execute = () => (invocation ? invocationRequestSignal.run({ signal: invocation.signal, current: () => {
|
|
13715
13963
|
const live = !c.closed && sock.readyState === WebSocket.OPEN && c.invocationRequests?.get(msg.rid) === invocation;
|
|
13716
13964
|
if (!live) invocation?.abort();
|
|
@@ -13800,6 +14048,66 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
13800
14048
|
.catch((e: Error) => reply({ t: "ask", ok: false, error: e.message }));
|
|
13801
14049
|
return;
|
|
13802
14050
|
}
|
|
14051
|
+
case "budget_renew": {
|
|
14052
|
+
// Authenticate the person before reading even the shape of the optional home field.
|
|
14053
|
+
if (c.role !== "console" || c.instructed) {
|
|
14054
|
+
return void reply({ t: "budget_renew", ok: false, error: "only the person may renew quota; run ahub budget renew in a person terminal" });
|
|
14055
|
+
}
|
|
14056
|
+
const peer = typeof msg.peer === "string" && PEER_ID.test(msg.peer) ? msg.peer : undefined;
|
|
14057
|
+
const mode = msg.mode;
|
|
14058
|
+
if (!peer || (mode !== "reset" && mode !== "switched")) {
|
|
14059
|
+
return void reply({ t: "budget_renew", ok: false, error: "renew requires a peer and exactly one mode; run ahub budget renew <peer> --reset or --switched" });
|
|
14060
|
+
}
|
|
14061
|
+
const def = definitionOf(peer);
|
|
14062
|
+
if (!def) return void reply({ t: "budget_renew", ok: false, error: "unknown peer; choose a peer shown by ahub budget" });
|
|
14063
|
+
if (!def.budget || def.budget.quotaExempt) return void reply({ t: "budget_renew", ok: false, error: "this peer has no renewable quota; inspect ahub budget" });
|
|
14064
|
+
const account = accountOf(peer);
|
|
14065
|
+
const accountBase = def.budget.account;
|
|
14066
|
+
const compareHomes = mode === "switched" && definitionOf(accountBase)?.start.daemonPort === "codex-appserver";
|
|
14067
|
+
const quotaRuntime = (id: string) => isFixedBuiltinDefinition(definitionOf(id)) ? bus.peers.get(id) : undefined;
|
|
14068
|
+
const compare = () => {
|
|
14069
|
+
if (!compareHomes) return [];
|
|
14070
|
+
const caller = typeof msg.callerHome === "string" ? msg.callerHome : undefined;
|
|
14071
|
+
return accountMembers(account).map(id => {
|
|
14072
|
+
try {
|
|
14073
|
+
const result = quotaRuntime(id)?.compareQuotaHome?.(caller) ?? compareNextCodexQuotaHome(id, caller);
|
|
14074
|
+
return { peer: id, result };
|
|
14075
|
+
} catch {
|
|
14076
|
+
return { peer: id, result: "unknown" as const };
|
|
14077
|
+
}
|
|
14078
|
+
});
|
|
14079
|
+
};
|
|
14080
|
+
const refused = (matches: ReturnType<typeof compare>) => {
|
|
14081
|
+
const mismatches = matches.filter(match => match.result !== "same");
|
|
14082
|
+
if (!mismatches.length) return false;
|
|
14083
|
+
reply({ t: "budget_renew", ok: false, homes: mismatches, error: "Codex home differs or could not be verified; quota was not renewed" });
|
|
14084
|
+
return true;
|
|
14085
|
+
};
|
|
14086
|
+
if (recoveryActive() || stopping) return void reply({ t: "budget_renew", ok: false, error: "quota was not renewed during recovery or shutdown; retry when the hub is ready" });
|
|
14087
|
+
if (refused(compare())) return;
|
|
14088
|
+
const changed = new Error("renewal home comparison changed");
|
|
14089
|
+
void budget.renew(peer, mode, () => {
|
|
14090
|
+
if (refused(compare())) throw changed;
|
|
14091
|
+
}).then(result => {
|
|
14092
|
+
const members = accountMembers(account);
|
|
14093
|
+
if (definitionOf(accountBase)?.start.daemonPort === "codex-appserver") {
|
|
14094
|
+
for (const id of members) {
|
|
14095
|
+
try { quotaRuntime(id)?.readQuotaNow?.(); }
|
|
14096
|
+
catch { /* The renewal is already saved. A failed read must not replace its reply. */ }
|
|
14097
|
+
}
|
|
14098
|
+
}
|
|
14099
|
+
reply({ t: "budget_renew", ok: true, ...result, ...(compareHomes ? { homeComparison: "same" } : {}),
|
|
14100
|
+
...(compareHomes ? { pending: members.filter(id => definitionOf(id)?.start.daemonPort === "codex-appserver") } : {}),
|
|
14101
|
+
...(mode === "switched" && definitionOf(accountBase)?.transport === "claude-channel" ? {
|
|
14102
|
+
softQuota: "Claude quota stays unknown after switching. Its soft gate is off. A hard refusal still pauses Claude, and you can supply a value with ahub budget set.",
|
|
14103
|
+
} : {}) });
|
|
14104
|
+
}, error => {
|
|
14105
|
+
if (error === changed) return;
|
|
14106
|
+
const stalled = error instanceof Error && error.message.startsWith("budget renewal was not saved;");
|
|
14107
|
+
reply({ t: "budget_renew", ok: false, error: stalled ? error.message : "quota renewal did not finish; inspect ahub budget and retry when the hub is ready" });
|
|
14108
|
+
});
|
|
14109
|
+
return;
|
|
14110
|
+
}
|
|
13803
14111
|
case "budget":
|
|
13804
14112
|
if (c.role !== "console") {
|
|
13805
14113
|
if (msg.resume !== undefined || msg.set !== undefined) return void reply({ t: "budget", ok: false, error: "budget mutations are console commands" });
|
|
@@ -13809,8 +14117,9 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
13809
14117
|
if (msg.resume) {
|
|
13810
14118
|
if (!budget.override(String(msg.resume))) return void reply({ t: "budget", ok: false, error: `${msg.resume} is not paused by the budget coordinator` });
|
|
13811
14119
|
} else if (msg.set) {
|
|
14120
|
+
if (c.instructed) return void reply({ t: "budget", ok: false, error: "only the person may set quota; use ahub budget in a person terminal" });
|
|
13812
14121
|
const used = Number(msg.set.used);
|
|
13813
|
-
if (!bus.peers.has(String(msg.set.peer)) && !budget.record(String(msg.set.peer))) return void reply({ t: "budget", ok: false, error: `unknown peer: ${msg.set.peer}` });
|
|
14122
|
+
if (!bus.peers.has(String(msg.set.peer)) && !budget.record(String(msg.set.peer)) && budget.renewalAt(String(msg.set.peer)) === undefined) return void reply({ t: "budget", ok: false, error: `unknown peer: ${msg.set.peer}` });
|
|
13814
14123
|
if (!(used >= 0 && used <= 1)) return void reply({ t: "budget", ok: false, error: "used must be between 0 and 1" });
|
|
13815
14124
|
budget.report(String(msg.set.peer), [{ id: msg.set.window === "week" ? "week" : "5h", kind: "manual", used, ...(msg.set.resetsInMs ? { resetsAt: Date.now() + Number(msg.set.resetsInMs) } : {}), source: "ahub budget set" }]);
|
|
13816
14125
|
}
|
|
@@ -14051,6 +14360,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
14051
14360
|
board.close();
|
|
14052
14361
|
turnLog?.close();
|
|
14053
14362
|
server.stop(true);
|
|
14363
|
+
try { await mcpEndpoint?.stop(); } catch { /* the socket is gone with the directory */ }
|
|
14054
14364
|
try { bus.closeJournal(); } catch { /* the state dir is gone; the journal went with it */ }
|
|
14055
14365
|
} finally {
|
|
14056
14366
|
// State removal and the stopped notification run no matter what failed above,
|
|
@@ -14077,9 +14387,59 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
14077
14387
|
orphanWatch.unref?.();
|
|
14078
14388
|
intervals.push(orphanWatch);
|
|
14079
14389
|
|
|
14390
|
+
/**
|
|
14391
|
+
* #1780 T2a-2c: one endpoint session, admitted by the control path itself. The link is a Sock-shaped object over the endpoint's connection: the hello goes through `onControlMessage` as a bridge's would, so peer admission,
|
|
14392
|
+
* launch proof, account label (#1810) and attachment are the control code, not a copy of it. A session is pull-only for now (`channel: false`): pushes and receipts are the next task. Nothing here logs the hello's home.
|
|
14393
|
+
*/
|
|
14394
|
+
/** Failed pushes of a peer that had no delivery id, kept per peer id so a reconnect finds them (the bridge's buffer, up to 200 each, now in the hub). Cleared with the daemon. */
|
|
14395
|
+
const mcpPushBuffers = new PushBuffers(), mcpListedTools = new ListedTools();
|
|
14396
|
+
async function openMcpSession(session: { peer: string; mode: "channel" | "tools" }, hello: McpHello, write: (line: string) => boolean, closeEndpoint: () => void): Promise<McpSessionServer | undefined> {
|
|
14397
|
+
const tools = hello.mode === "tools" || hello.session !== undefined;
|
|
14398
|
+
const evidence = hello.mode === "tools" ? "unknown" : opts.mcpChannelEvidence?.(hello) ?? "unknown";
|
|
14399
|
+
const channel = hello.mode !== "tools" && hello.session === undefined && evidence === "development-channel-launch";
|
|
14400
|
+
// The endpoint ends a refused connection itself, after the refusal line is written: closing it first would drop that line.
|
|
14401
|
+
let open = true, established = false, sock!: Sock;
|
|
14402
|
+
const refuse = (reason: string) => { write(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32000, message: `the hub refused this session: ${sanitize(reason)}` } })); };
|
|
14403
|
+
let cwd: string | undefined;
|
|
14404
|
+
if (hello.mode !== "tools") { try { cwd = realPath(hello.cwd); } catch { /* an unresolvable cwd withholds root evidence only, as in the bridge */ } }
|
|
14405
|
+
let client;
|
|
14406
|
+
try {
|
|
14407
|
+
client = await ControlClient.inProcess((receive, closed) => {
|
|
14408
|
+
sock = {
|
|
14409
|
+
data: { authed: false } as Client,
|
|
14410
|
+
get readyState() { return open ? WebSocket.OPEN : WebSocket.CLOSED; },
|
|
14411
|
+
send: (text: string) => { let msg: unknown; try { msg = JSON.parse(text); } catch { return; } queueMicrotask(() => receive(msg)); },
|
|
14412
|
+
close: (code?: number, reason?: string) => { if (!open) return; open = false; try { controlWebsocket.close!(sock, code ?? 1000, reason ?? ""); } finally { if (established) closeEndpoint(); closed(code ?? 1000, reason ?? ""); } },
|
|
14413
|
+
getBufferedAmount: () => 0,
|
|
14414
|
+
} as unknown as Sock;
|
|
14415
|
+
// Every client message takes the WebSocket handler's own path, errors included.
|
|
14416
|
+
return { get readyState() { return open ? WebSocket.OPEN : WebSocket.CLOSED; }, send: (text: string) => controlWebsocket.message!(sock, text), close: () => sock.close(1000, "") } as never;
|
|
14417
|
+
}, {
|
|
14418
|
+
token, role: tools ? "tools" : "peer", peer: hello.peer, v: acceptedBridgeWindow.v, vMin: acceptedBridgeWindow.vMin, projectId, instanceId, projectRoot: hello.projectRoot ?? opts.cwd, clientVersion: VERSION, clientPid: hello.pid,
|
|
14419
|
+
...(tools ? {} : { channel, channelEvidence: evidence, retainStandby: false, ...(hello.home !== undefined ? { home: hello.home } : {}) }),
|
|
14420
|
+
...(hello.session !== undefined ? { session: hello.session } : {}),
|
|
14421
|
+
...(hello.claudeSessionId !== undefined ? { claudeSessionId: hello.claudeSessionId } : {}),
|
|
14422
|
+
...(hello.launchId !== undefined ? { launchId: hello.launchId } : {}),
|
|
14423
|
+
...(cwd !== undefined ? { cwd } : {}),
|
|
14424
|
+
});
|
|
14425
|
+
} catch (error) { refuse((error as Error).message.replace(/^hub closed the connection: /, "")); return undefined; }
|
|
14426
|
+
established = true;
|
|
14427
|
+
const surface = () => ({ peerId: hello.peer, toolsMode: hello.mode === "tools", channel, permissionTool: hello.mode === "tools" && hello.permissionTool === true, deliveryOnly: hello.deliveryOnly === true,
|
|
14428
|
+
roles: config.roles, sessionRoles: hello.mode === "tools" ? [] : selectedRoles(hello.peer, config.roles, roleAssignments, catalog), profile: resolvedProfile });
|
|
14429
|
+
const buffer = mcpPushBuffers.forSession(hello.peer, hello.session !== undefined);
|
|
14430
|
+
return serveMcpSession({ client, channel, buffer, listed: mcpListedTools.forSession(hello.peer, hello.session !== undefined), log, mode: session.mode, peer: hello.peer, permissionTool: hello.permissionTool === true && hello.mode === "tools", deliveryOnly: hello.deliveryOnly === true, sessionJoin: hello.session !== undefined, surface, write, close: closeEndpoint });
|
|
14431
|
+
}
|
|
14432
|
+
|
|
14080
14433
|
const tokenFile = join(opts.stateDir, "control-token");
|
|
14081
14434
|
writeFileSync(tokenFile, token, { mode: 0o600 });
|
|
14082
14435
|
chmodSync(tokenFile, 0o600);
|
|
14436
|
+
// #1780 T1: the per-project MCP socket. A refusal (a group-accessible directory, a stale or live socket, a path too long) is logged with its fix and the hub runs without the endpoint.
|
|
14437
|
+
if (opts.mcpHome) {
|
|
14438
|
+
const started = await startMcpEndpoint({ home: opts.mcpHome, projectId, token, log, exclusiveOwner: opts.controlPort !== 0,
|
|
14439
|
+
...(opts.mcpServe ? { serve: openMcpSession } : {}),
|
|
14440
|
+
accountLabel: (home, peer) => { const label = labelForHome(home, definitionOf(peer)?.budget?.account ?? declarations[peer]?.kind ?? peer, config.accounts); return label === DEFAULT_ACCOUNT_LABEL ? undefined : label; } });
|
|
14441
|
+
if (started.ok) mcpEndpoint = started.endpoint; else log(`mcp endpoint unavailable: ${started.refusal}`);
|
|
14442
|
+
}
|
|
14083
14443
|
budget.restore(); // pauses recorded by an earlier hub run stay in force; unfinished handoffs wait for peers to attach
|
|
14084
14444
|
bus.onQueues(); // initial restored holds are reported only after the listener is bound; writes status.json too
|
|
14085
14445
|
log(`${RUN_START}${process.pid} control=127.0.0.1:${server.port} cwd=${opts.cwd}`);
|