@staix/agent-hub 0.45.0 → 0.46.1
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 +32 -0
- package/README.md +10 -4
- package/docs/adding-an-ai-tool.md +1 -0
- package/docs/agent-notes/adapters.md +33 -4
- package/docs/agent-notes/budget.md +2 -1
- package/docs/agent-notes/daemon.md +5 -1
- package/docs/agent-notes/security-review.md +3 -2
- package/docs/agent-notes/tasks.md +3 -1
- package/docs/agent-notes/tests.md +1 -1
- package/docs/design/adapters.md +16 -0
- package/docs/design/agent-hub-architecture.md +12 -0
- package/docs/design/cli-output.md +2 -0
- package/docs/design/roadmap.md +86 -5
- package/docs/design/task-board.md +2 -2
- package/docs/dogfood.md +15 -0
- package/docs/events.md +2 -2
- package/docs/operations.md +103 -21
- package/docs/quickstart.md +15 -3
- package/docs/security.md +7 -5
- package/docs/smoke.md +1 -1
- package/docs/verification/2026-11-05-hardcoded-values-classification-rules.md +28 -0
- package/docs/verification/2026-11-22-agy-1.5.14.md +27 -0
- package/docs/verification/2026-11-22-claude-instruction-hook.md +35 -0
- package/docs/verification/2026-11-22-instructed-ipc.md +9 -0
- package/docs/verification/2026-11-22-jcode-1.0.3.md +71 -0
- package/docs/verification/2026-11-22-jcode-separate-home.md +14 -0
- package/docs/verification/2026-11-22-qwen-0283-acp.md +28 -0
- package/docs/verification/2026-11-22-qwen-0283-dual-output.md +33 -0
- package/docs/verification/2026-11-22-roadmap-r5-view-receipt.md +63 -0
- package/docs/verification/2026-11-23-0.46.0.md +44 -0
- package/docs/verification/2026-11-24-0.46.1.md +48 -0
- package/docs/verification/assets/1483-r5-detail-1440-light.png +0 -0
- package/docs/verification/assets/1483-r5-detail-390-light.png +0 -0
- package/docs/verification/assets/1483-r5-view-1440-dark.png +0 -0
- package/docs/verification/assets/1483-r5-view-1440-light.png +0 -0
- package/docs/verification/assets/1483-r5-view-390-dark.png +0 -0
- package/docs/verification/assets/1483-r5-view-390-light.png +0 -0
- package/docs/verification/assets/1483-r5-view-820-dark.png +0 -0
- package/docs/verification/assets/1483-r5-view-820-light.png +0 -0
- package/docs/verified.json +23 -23
- package/package.json +3 -2
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +6053 -5509
- package/plugins/agent-hub/server.js +1300 -1087
- package/plugins/agent-hub/skills/ahub/SKILL.md +17 -0
- package/plugins/agent-hub/skills/ahub-manage/SKILL.md +37 -0
- package/plugins/agent-hub/skills/ahub-status/SKILL.md +14 -0
- package/plugins/agent-hub/skills/ahub-use/SKILL.md +12 -0
- package/src/adapters/claude-channel.ts +2 -1
- package/src/adapters/compat.ts +12 -11
- package/src/adapters/definitions/native-cli-claude-setup.ts +9 -1
- package/src/adapters/definitions/native-cli-doctor.ts +8 -5
- package/src/adapters/definitions/native-cli-jcode-home-init.ts +158 -0
- package/src/adapters/definitions/native-cli-jcode-home.ts +72 -0
- package/src/adapters/definitions/native-cli-jcode-mcp.ts +20 -0
- package/src/adapters/definitions/native-cli-skills.ts +29 -0
- package/src/cli/claude-profile-hook.ts +40 -3
- package/src/cli/console-state.ts +55 -26
- package/src/cli/console-usage.ts +5 -3
- package/src/cli/console.ts +35 -4
- package/src/cli/help.ts +15 -10
- package/src/cli/identity.ts +2 -1
- package/src/cli/instruction-hook.ts +28 -0
- package/src/cli/jcode-mcp.ts +2 -1
- package/src/cli/main.js +8 -0
- package/src/cli/main.ts +138 -18
- package/src/cli/output-standard.ts +3 -55
- package/src/cli/output.ts +8 -2
- package/src/cli/recovery-package.ts +53 -12
- package/src/cli/roadmap.ts +37 -3
- package/src/cli/setup-homes.ts +1 -0
- package/src/cli/setup.ts +1 -1
- package/src/cli/skills-install.ts +463 -0
- package/src/cli/task-output.ts +1 -1
- package/src/cli/upgrade-presentation-flags.ts +1 -1
- package/src/hub/board.ts +42 -4
- package/src/hub/budget-projection.ts +99 -0
- package/src/hub/claude-launch-proof.ts +5 -1
- package/src/hub/conductor.ts +8 -3
- package/src/hub/config-apply.ts +3 -2
- package/src/hub/config-tier.ts +1 -1
- package/src/hub/config-trust.ts +1 -1
- package/src/hub/control-client.ts +9 -2
- package/src/hub/daemon.ts +457 -26
- package/src/hub/events.ts +1 -1
- package/src/hub/execution-budget.ts +29 -8
- package/src/hub/hub-tools.ts +2 -2
- package/src/hub/inference.ts +1 -1
- package/src/hub/instances.ts +10 -1
- package/src/hub/instructed-exact.ts +95 -0
- package/src/hub/instructed-intent.ts +64 -0
- package/src/hub/instructed-ipc.ts +33 -0
- package/src/hub/instructed-runtime.ts +19 -0
- package/src/hub/instruction-receipt.ts +218 -0
- package/src/hub/manager.ts +46 -3
- package/src/hub/registry.ts +1 -1
- package/src/hub/roadmap-decompose.ts +60 -1
- package/src/hub/roadmap-sync.ts +2 -2
- package/src/hub/roadmap.ts +19 -1
- package/src/hub/routing.ts +18 -1
- package/src/hub/runtime-capture-prune.ts +2 -1
- package/src/hub/settings.ts +2 -1
- package/src/hub/tasks.ts +194 -12
- package/src/hub/ui.ts +6 -2
- package/src/hub/usage-rollup.ts +42 -2
- package/src/ui/index.html +342 -8
- package/src/ui/plugin.ts +6 -2
- package/src/ui/roadmap-model.ts +70 -0
package/src/hub/daemon.ts
CHANGED
|
@@ -53,6 +53,9 @@ import { loadExternalAdapterDefinitions, readAdapterModuleDeclarations, external
|
|
|
53
53
|
import { WsPeer, isWsPeer } from "../adapters/channel-peer.ts";
|
|
54
54
|
import { ownerToolEffect, canonicalWriteUnknown } from "./no-writes.ts";
|
|
55
55
|
import { NativeHookLaunches, type NativeHookLaunch } from "./native-hook-launch.ts";
|
|
56
|
+
import { InstructionReceipts, MAX_PROMPT_BYTES } from "./instruction-receipt.ts";
|
|
57
|
+
import { Registry } from "./registry.ts";
|
|
58
|
+
import { usedClaudeHomes } from "../cli/autonomy-homes.ts";
|
|
56
59
|
import { readReleaseHostAdmission, type ReleaseHostAdmission } from "./release-admission.ts";
|
|
57
60
|
import { MERGE_READBACK_INTERVAL_MS } from "./sdlc-merge.ts";
|
|
58
61
|
import { ContainerRunner, RemoteRunner, remoteRunnerConfig, type RemoteRunnerConfig, type RunnerOptions, type RunnerState, type RunReceipt } from "./check-runner.ts";
|
|
@@ -107,7 +110,7 @@ import { appendFileSync, chmodSync, existsSync, fstatSync, mkdirSync, readFileSy
|
|
|
107
110
|
import { join, relative, resolve } from "node:path";
|
|
108
111
|
import { homedir } from "node:os";
|
|
109
112
|
import { spawn } from "node:child_process";
|
|
110
|
-
import { childEnv } from "./child-process.ts";
|
|
113
|
+
import { childEnv, personEnv } from "./child-process.ts";
|
|
111
114
|
import { runCheck } from "./checks.ts";
|
|
112
115
|
import { DEFAULT_TASK_SWEEP, taskSweepConfig, type TaskSweepConfig } from "./task-sweep.ts";
|
|
113
116
|
import { CONTRADICTION_WINDOW_SETTING, DEMOTE_AT_SETTING, DEMOTION_HALF_LIFE_SETTING, GROOM_FYI_WINDOW_SETTING, RESCREEN_MAX_SETTING, SPLIT_FAILURE_SHARE_SETTING, SPLIT_MIN_SETTING, taskOperationalReaders } from "./operational-settings.ts";
|
|
@@ -124,8 +127,13 @@ import { CompletionStore } from "./completions-store.ts";
|
|
|
124
127
|
import { QuestionDesk } from "./question-desk.ts";
|
|
125
128
|
import type { ScannedFile } from "./schedules.ts";
|
|
126
129
|
import { corpusConfig } from "./corpus-config.ts";
|
|
127
|
-
import { roadmapConfig, type RoadmapConfig } from "./roadmap.ts";
|
|
130
|
+
import { roadmapConfig, type MilestoneLinkKind, type MilestoneState, type RoadmapConfig } from "./roadmap.ts";
|
|
131
|
+
import { mcpAllowNames } from "./instances.ts";
|
|
128
132
|
import { ALL_MACHINE_LOCAL, configRefusal, configRepositoryPresent, configTracked, stripUntrusted } from "./config-trust.ts";
|
|
133
|
+
import { instructedMode, parseExactInstruction, exactForm, instructedExecution, INSTRUCTION_CHILD_TIMEOUT_MS, type ExactForm, type InstructedExecution } from "./instructed-exact.ts";
|
|
134
|
+
import { intentForm, intentRefusal, literalInstructionIds } from "./instructed-intent.ts";
|
|
135
|
+
import { instructedRuntimeAllowed } from "./instructed-runtime.ts";
|
|
136
|
+
import { classifyPeerCommand, cliCommandLabel } from "../cli/identity.ts";
|
|
129
137
|
import { authorizeConfigLeaf, configApply, configIdentityScope, configChanges, validateRawConfig, validateEffectiveConfig, validateOperationalConfig, validatePetConfig } from "./config-apply.ts";
|
|
130
138
|
import { resolveSettledRoles } from "./settled-roles.ts";
|
|
131
139
|
import { CONFIG_SOURCE_FILES, configFingerprint, configSourceTexts, parseConfigSources, type ConfigSourceTexts, type ConfigSources } from "./config-reload.ts";
|
|
@@ -189,6 +197,7 @@ import { Briefs, preferRecordItems, type NativeItem, type BriefTask } from "../m
|
|
|
189
197
|
import { Board, isClosedTaskState, taskProposalAt, taskHasStarted, CLASSES, type Task, type TaskClass } from "./board.ts";
|
|
190
198
|
import { UsageRollup, USAGE_GROUPS, LIMITS_MAX, type UsageGroup } from "./usage-rollup.ts";
|
|
191
199
|
import { Budget, readNativeQuota, DEFAULT_BUDGET, type BudgetConfig } from "./budget.ts";
|
|
200
|
+
import { projectExhaustion, windowLeft, WINDOW_MINS, type ExhaustionProjection } from "./budget-projection.ts";
|
|
192
201
|
import { remoteEnvelope, HUB } from "./envelope.ts";
|
|
193
202
|
import { applyTurnAttribution, turnAttribution } from "./turn-attribution.ts";
|
|
194
203
|
import { recallMemoryLines, trimToTokens, aggregateUse, orderByUse } from "../memory/recall.ts";
|
|
@@ -209,7 +218,7 @@ import { ProposalStore, SupervisionProposals, type SupervisionProposal } from ".
|
|
|
209
218
|
import { drainCliAudits } from "../cli/identity-audit.ts";
|
|
210
219
|
import { launcherPreview } from "../cli/preview.ts";
|
|
211
220
|
import { AssignmentUndeliveredError, ESCALATE_AFTER, Tasks } from "./tasks.ts";
|
|
212
|
-
import { DEFAULT_INFERENCE, DIGEST, Inference, screenPii, type InferenceConfig, type PiiVerdict } from "./inference.ts";
|
|
221
|
+
import { DEFAULT_INFERENCE, DIGEST, Inference, SCREEN_MAX_BYTES, SCREEN_TIMEOUT_MS, screenPii, type InferenceConfig, type PiiVerdict } from "./inference.ts";
|
|
213
222
|
import { taskEvidencePrivacy, type TaskEvidencePrivacy, ask, ASK_NOTE_TITLE, RUN_START } from "./ask.ts";
|
|
214
223
|
import { currentRouting, loadRouting, detectSignals, OVERLAY_FILE, overlayToml, parseRouting, routingText, type Routing } from "./routing.ts";
|
|
215
224
|
import { withChecklistLine } from "./learning.ts";
|
|
@@ -290,10 +299,13 @@ export interface HubConfig {
|
|
|
290
299
|
qwen_cmd: string[];
|
|
291
300
|
jcode_cmd: string[];
|
|
292
301
|
jcode_home: string;
|
|
302
|
+
/** Machine-local names of jcode MCP servers `ahub doctor` accepts for the hub-owned jcode (#1621). Names only; launch is unchanged. */
|
|
303
|
+
jcode_mcp_allow?: string[];
|
|
293
304
|
jcode_provider_profile: string;
|
|
294
305
|
action_policy?: ActionPolicyConfig;
|
|
295
306
|
permission_modes: Record<string, PermissionMode>;
|
|
296
307
|
protect_instruction_files: boolean;
|
|
308
|
+
instructed?: { mode: "off" | "exact" | "intent" };
|
|
297
309
|
/** Loader-owned provenance of requested defaults, before machine-local filtering. */
|
|
298
310
|
permission_default_sources?: Record<string, { mode: PermissionMode; source: string }>;
|
|
299
311
|
codex_bin: string;
|
|
@@ -400,6 +412,7 @@ export const DEFAULT_CONFIG: HubConfig = {
|
|
|
400
412
|
action_policy: actionPolicyConfig(),
|
|
401
413
|
permission_modes: {},
|
|
402
414
|
protect_instruction_files: false,
|
|
415
|
+
instructed: { mode: "intent" },
|
|
403
416
|
...nativeDefaults.proxy,
|
|
404
417
|
batch_max: 3,
|
|
405
418
|
batch_ms: 15_000,
|
|
@@ -458,7 +471,7 @@ const PEER_ID = /^[a-z][a-z0-9-]{0,31}$/;
|
|
|
458
471
|
/** The shared project config, then the machine's own file, which overrides it block by block (issue #17). */
|
|
459
472
|
const CONFIG_FILES = INSTANCE_CONFIG_FILES;
|
|
460
473
|
export interface ConfigLayer { name: typeof CONFIG_FILES[number]; raw: Record<string, any> }
|
|
461
|
-
const CONFIG_BLOCKS = ["action_policy", "memory", "roster", "roles", "catalog_roles", "pii", "data", "conductor", "budget", "context", "inference", "omniroute", ...NATIVE_CONFIG_BLOCKS, "approvals", "tasks", "task_sweep", "bus", "adapter_timing", "model_relay", "console", "corpus", "specs", "checks", "snapshots", "worktrees", "visuals", "research", "bench", "limits", "review", "recovery", "capabilities", "mlx", "permission_modes", "peers", "terminal", "start", "pet", "questions"];
|
|
474
|
+
const CONFIG_BLOCKS = ["instructed", "action_policy", "memory", "roster", "roles", "catalog_roles", "pii", "data", "conductor", "budget", "context", "inference", "omniroute", ...NATIVE_CONFIG_BLOCKS, "approvals", "tasks", "task_sweep", "bus", "adapter_timing", "model_relay", "console", "corpus", "specs", "checks", "snapshots", "worktrees", "visuals", "research", "bench", "limits", "review", "recovery", "capabilities", "mlx", "permission_modes", "peers", "terminal", "start", "pet", "questions"];
|
|
462
475
|
|
|
463
476
|
/** Older targets parse raw keys before placement/trust checks, so even an empty or refused declaration needs the floor. */
|
|
464
477
|
function rawResearchRunnersPresent(cwd: string): boolean {
|
|
@@ -614,11 +627,16 @@ export function loadConfig(cwd: string, layers?: readonly ConfigLayer[], routing
|
|
|
614
627
|
}
|
|
615
628
|
if (file.jcode_cmd !== undefined && (!Array.isArray(file.jcode_cmd) || !file.jcode_cmd.length || file.jcode_cmd.some((word: unknown) => typeof word !== "string" || !word))) throw new Error("jcode_cmd must be a nonempty executable argv");
|
|
616
629
|
if (file.jcode_home !== undefined && (typeof file.jcode_home !== "string" || !isAbsolute(file.jcode_home))) throw new Error("jcode_home must be an absolute path");
|
|
630
|
+
if (file.jcode_mcp_allow !== undefined) mcpAllowNames(file.jcode_mcp_allow, "jcode_mcp_allow");
|
|
617
631
|
for (const key of ["jcode_home", "jcode_provider_profile"]) if (file[key] !== undefined && typeof file[key] !== "string") throw new Error(`${key} must be a string`);
|
|
618
632
|
if (file.qwen_cmd !== undefined && (!Array.isArray(file.qwen_cmd) || !file.qwen_cmd.length || file.qwen_cmd.some((word: unknown) => typeof word !== "string" || !word))) throw new Error("qwen_cmd must be a nonempty executable argv");
|
|
619
633
|
actionPolicyConfig(file.action_policy);
|
|
620
634
|
if (file.edit_governance !== undefined) parseEditGovernance(file.edit_governance);
|
|
621
635
|
instructionProtection(file.protect_instruction_files);
|
|
636
|
+
if (file.instructed !== undefined) {
|
|
637
|
+
if (!file.instructed || typeof file.instructed !== "object" || Array.isArray(file.instructed) || Object.keys(file.instructed).some(key => key !== "mode")) throw new Error("instructed must contain only mode");
|
|
638
|
+
instructedMode(file.instructed.mode);
|
|
639
|
+
}
|
|
622
640
|
permissionDefaults(file.permission_modes, instances, adapterCatalog); // malformed declarations fail even when trust would drop them
|
|
623
641
|
peerStartConfig(file.peers, instances, adapterCatalog);
|
|
624
642
|
if (file.terminal != null && (typeof file.terminal !== "object" || Array.isArray(file.terminal))) throw new Error("terminal must be an object");
|
|
@@ -709,6 +727,7 @@ export function loadConfig(cwd: string, layers?: readonly ConfigLayer[], routing
|
|
|
709
727
|
...(file.edit_governance !== undefined ? { edit_governance: parseEditGovernance(file.edit_governance) } : {}),
|
|
710
728
|
permission_modes: { ...instancePermissions, ...permissionDefaults(file.permission_modes, instances, adapterCatalog) },
|
|
711
729
|
protect_instruction_files: instructionProtection(file.protect_instruction_files),
|
|
730
|
+
instructed: { mode: instructedMode(file.instructed?.mode) },
|
|
712
731
|
permission_default_sources: appliedPermissionSources,
|
|
713
732
|
memory: { ...DEFAULT_CONFIG.memory, native: true, ...file.memory, ...(file.memory?.short_ttl_days !== undefined ? { short_ttl_days: ttlDays(file.memory.short_ttl_days) } : {}),
|
|
714
733
|
...(file.memory?.sync_interval_min !== undefined ? { sync_interval_min: syncMinutes(file.memory.sync_interval_min) } : {}) }, // the native store is on with any project config (#258)
|
|
@@ -861,6 +880,10 @@ export interface DaemonOptions {
|
|
|
861
880
|
questionSweepMs?: number;
|
|
862
881
|
/** Test seam (#1054): wraps the completion store so a test can make its writes throw, like a busy or locked database. */
|
|
863
882
|
completionStore?: (store: CompletionStore) => CompletionStore;
|
|
883
|
+
/** Test seam: fixture package root and runtime for isolated inherited-socket integration. */
|
|
884
|
+
instructedRuntimeForTest?: { root: string; bun: string };
|
|
885
|
+
/** Test seam: capture the host-only receipt store without publishing it as a control operation. */
|
|
886
|
+
instructionReceiptStore?: (store: InstructionReceipts) => InstructionReceipts;
|
|
864
887
|
/** Test seam: an extra hold on the SDLC band evaluation, like a storage error. */
|
|
865
888
|
bandsHeld?: () => boolean;
|
|
866
889
|
/** Test seam: the schedules clock and the period of the due check (default Date.now and one minute). */
|
|
@@ -910,6 +933,7 @@ export interface DaemonOptions {
|
|
|
910
933
|
|
|
911
934
|
interface Client {
|
|
912
935
|
authed: boolean;
|
|
936
|
+
instructed?: InstructedExecution;
|
|
913
937
|
protocol?: number;
|
|
914
938
|
role?: "peer" | "console" | "tools";
|
|
915
939
|
peer?: PeerId;
|
|
@@ -986,6 +1010,8 @@ function capturedRecoverySourceDigest(): string | undefined {
|
|
|
986
1010
|
const STARTUP_RUNNER_WAIT_MS = 500;
|
|
987
1011
|
|
|
988
1012
|
export async function startDaemon(opts: DaemonOptions) {
|
|
1013
|
+
// Capture the daemon's own load location once; no caller supplies or later resolves it.
|
|
1014
|
+
const instructedRuntime = (() => { try { return { root: realPath(opts.instructedRuntimeForTest?.root ?? resolve(import.meta.dir, "../..")), bun: realPath(opts.instructedRuntimeForTest?.bun ?? process.execPath) }; } catch { return undefined; } })();
|
|
989
1015
|
const startupTimings = new StartupTimings();
|
|
990
1016
|
// Refuse unknown formats before logs, session cleanup, module factories or any writable store is opened.
|
|
991
1017
|
assertHubDbCompatible(join(opts.stateDir, "hub.db"));
|
|
@@ -1243,7 +1269,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
1243
1269
|
const operationalLogSubscribers=new Map<Sock,()=>void>();
|
|
1244
1270
|
const operationalContext=new AsyncLocalStorage<{actor:string;current:()=>void}|undefined>();
|
|
1245
1271
|
const guidanceProbeRequestContext = new AsyncLocalStorage<GuidanceProbeRequestContext>();
|
|
1246
|
-
const checkOperational=(authority:SettingAuthority)=>{if(authority==="conductor"){const scope=operationalContext.getStore();if(!scope)throw new OperationalAuthorityError("operational conductor authority unavailable");scope.current();}};
|
|
1272
|
+
const checkOperational=(authority:SettingAuthority)=>{const instruction=instructedExecution.getStore();if(instruction?.active)instruction.current();if(authority==="conductor"){const scope=operationalContext.getStore();if(!scope)throw new OperationalAuthorityError("operational conductor authority unavailable");scope.current();}};
|
|
1247
1273
|
const logFile = join(opts.stateDir, "hub.log");
|
|
1248
1274
|
// The state dir can vanish under a running hub (issue #56): a log line must never take a handler down with it.
|
|
1249
1275
|
const rotateHubLog = textLogRotator(logFile); // #1546: copy-truncate, because the daemon's own stderr also appends to this file
|
|
@@ -3069,6 +3095,8 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
3069
3095
|
// #223: a headless reviewer's verdict holds only while the same child it started with still runs for that task.
|
|
3070
3096
|
reviewAuthority: runningReviewAuthority,
|
|
3071
3097
|
requestAuthority: by => {
|
|
3098
|
+
const instruction = instructedExecution.getStore();
|
|
3099
|
+
if (by === USER && instruction?.active) return () => { try { instruction.current(); return undefined; } catch { return "the instruction is no longer current"; } };
|
|
3072
3100
|
const scope = childToolAuthority.getStore();
|
|
3073
3101
|
return scope?.by === by ? () => scope.current() ? undefined : "Claude child generation or execution root changed" : undefined;
|
|
3074
3102
|
},
|
|
@@ -3991,7 +4019,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
3991
4019
|
};
|
|
3992
4020
|
const titlePreface = (peer: PeerId): string | undefined => definitionOf(peer)?.title === "hub" && bus.peers.get(peer)?.sessionTitle === "" && !titlePrivate(peer) ? SESSION_TITLE_HINT : undefined;
|
|
3993
4021
|
type TitleResult = { ok: true } | { ok: false; reason: "already_named" | "private" | "invalid"; error: string; mayHaveApplied?: true };
|
|
3994
|
-
async function setSessionTitle(peer: PeerId, value: unknown, onlyIfUnnamed: boolean, privateTurn = false): Promise<TitleResult> {
|
|
4022
|
+
async function setSessionTitle(peer: PeerId, value: unknown, onlyIfUnnamed: boolean, privateTurn = false, instructionCurrent?: () => boolean): Promise<TitleResult> {
|
|
3995
4023
|
const owner = bus.peers.get(peer);
|
|
3996
4024
|
if (definitionOf(peer)?.title !== "hub") return { ok: false, reason: "invalid", error: "this peer has no hub-owned title slot; choose a Pi/local peer from ahub status or rename its session in its own UI" };
|
|
3997
4025
|
if (!owner?.setSessionTitle || owner.state === "offline") return { ok: false, reason: "invalid", error: "peer title slot is offline or unavailable; start or reconnect the peer, then retry hub_set_title" };
|
|
@@ -4010,7 +4038,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
4010
4038
|
if (!title) return { ok: false, reason: "invalid", error: "title needs 1-80 normalized characters; enter a short public title" };
|
|
4011
4039
|
if (owner.sessionTitle === undefined) return { ok: false, reason: "invalid", error: "native title state is unknown; reconnect the peer, check ahub status, then retry" };
|
|
4012
4040
|
if (onlyIfUnnamed && owner.sessionTitle !== "") return { ok: false, reason: "already_named", error: "this session already has a title; keep it, or ask the person to replace it with ahub title" };
|
|
4013
|
-
const admitted = () => current() && !privateTurn && !titlePrivate(peer, title);
|
|
4041
|
+
const admitted = () => current() && !privateTurn && !titlePrivate(peer, title) && instructionCurrent?.() !== false;
|
|
4014
4042
|
let result: Awaited<ReturnType<NonNullable<PeerAdapter["setSessionTitle"]>>>;
|
|
4015
4043
|
try { result = await owner.setSessionTitle!(title, onlyIfUnnamed, admitted); } catch { return uncertain(titlePrivate(peer, title) ? "private" : "invalid"); }
|
|
4016
4044
|
if (privateTurn || titlePrivate(peer, title)) return uncertain("private");
|
|
@@ -4253,6 +4281,44 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
4253
4281
|
// #683 U2: events.jsonl folded into hub.db, a bounded pass at a time, so `usage` never rescans the log.
|
|
4254
4282
|
const usageRollup = new UsageRollup(join(opts.stateDir, "hub.db"), join(opts.stateDir, "events.jsonl"));
|
|
4255
4283
|
startupCleanup.push(() => usageRollup.close());
|
|
4284
|
+
// #1513 AC2: one window view feeds the `budget` reply, the dashboard snapshot and therefore `ahub budget` and the
|
|
4285
|
+
// console, so the three cannot disagree. The burn series is hourly and an answer is kept for a minute per reading:
|
|
4286
|
+
// the page polls every second and must not query the roll-up that often.
|
|
4287
|
+
type BudgetRowStatus = ReturnType<Budget["status"]>[string];
|
|
4288
|
+
const projectionCache = new Map<string, { at: number; value: ExhaustionProjection }>();
|
|
4289
|
+
const PROJECTION_TTL_MS = 60_000, PROJECTION_LOOKBACK_MS = 86_400_000;
|
|
4290
|
+
type WindowView = BudgetRowStatus["windows"][number] & { left: number | null; projection: ExhaustionProjection };
|
|
4291
|
+
function windowView(peer: string, window: BudgetRowStatus["windows"][number]): WindowView {
|
|
4292
|
+
const now = Date.now();
|
|
4293
|
+
const resetsAt = typeof window.resetsAt === "number" ? window.resetsAt : null;
|
|
4294
|
+
const windowMins = window.windowMins ?? WINDOW_MINS[window.id] ?? 0;
|
|
4295
|
+
const windowStart = resetsAt !== null && windowMins > 0 ? resetsAt - windowMins * 60_000 : null;
|
|
4296
|
+
// A stale reading is no usable reading, so its forecast is never served from the cache, never cached, and never
|
|
4297
|
+
// computed from points it would not look at (the page polls every second, and a stale row is what a pause leaves).
|
|
4298
|
+
const key = `${peer}\0${window.id}\0${window.at}`;
|
|
4299
|
+
const cached = window.stale ? undefined : projectionCache.get(key);
|
|
4300
|
+
const projection = cached && now - cached.at < PROJECTION_TTL_MS ? cached.value : (() => {
|
|
4301
|
+
const value = projectExhaustion({
|
|
4302
|
+
used: window.used, windowStart, resetsAt, now, stale: window.stale,
|
|
4303
|
+
lookbackMs: windowMins > 0 ? Math.min(PROJECTION_LOOKBACK_MS, windowMins * 60_000) : PROJECTION_LOOKBACK_MS,
|
|
4304
|
+
points: windowStart === null || window.stale ? [] : usageRollup.points(peer, windowStart, now),
|
|
4305
|
+
});
|
|
4306
|
+
/* 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. */
|
|
4307
|
+
if (!window.stale) {
|
|
4308
|
+
if (projectionCache.size > 256) projectionCache.clear();
|
|
4309
|
+
projectionCache.set(key, { at: now, value });
|
|
4310
|
+
}
|
|
4311
|
+
return value;
|
|
4312
|
+
})();
|
|
4313
|
+
return { ...window, left: windowLeft(window.used), projection };
|
|
4314
|
+
}
|
|
4315
|
+
/** The same view for one peer's row and for a whole status: `left` and the projection ride each window, never the summary. */
|
|
4316
|
+
function windowRow(peer: string, row: BudgetRowStatus) {
|
|
4317
|
+
return { ...row, windows: row.windows.map(window => windowView(peer, window)) };
|
|
4318
|
+
}
|
|
4319
|
+
function budgetViews(status: ReturnType<Budget["status"]>): ReturnType<Budget["status"]> {
|
|
4320
|
+
return Object.fromEntries(Object.entries(status).map(([peer, row]) => [peer, windowRow(peer, row)]));
|
|
4321
|
+
}
|
|
4256
4322
|
/**
|
|
4257
4323
|
* #1546: the event log rotates by size. The oldest segment is kept while something still needs its events, so the log grows past its bound until that ends: (1) a task that has started and is open
|
|
4258
4324
|
* (a card still in backlog or proposed has only its proposal in the log), (2) a task that closed but still waits for its research record (`researchPending`), (3) a segment with a line that does not parse (the
|
|
@@ -6212,9 +6278,14 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
6212
6278
|
case "hub_roadmap_triage":
|
|
6213
6279
|
if (!a || typeof a !== "object" || Array.isArray(a) || Object.keys(a).some(key => key !== "repo" && key !== "list") || a.list !== undefined && typeof a.list !== "boolean") throw new PreEffectToolRefusal("roadmap triage takes an optional repo and list true or false; use ahub roadmap triage");
|
|
6214
6280
|
return JSON.stringify(a.list === true ? { suggestions: tasks.milestoneSuggestions(by, "pending") } : await tasks.roadmapTriage(by, { repo: a.repo }));
|
|
6215
|
-
case "hub_roadmap_decompose":
|
|
6216
|
-
if (!a || typeof a !== "object" || Array.isArray(a) || Object.keys(a).some(key =>
|
|
6281
|
+
case "hub_roadmap_decompose": {
|
|
6282
|
+
if (!a || typeof a !== "object" || Array.isArray(a) || Object.keys(a).some(key => !["id", "accept", "publish", "apply", "confirm"].includes(key))) throw new PreEffectToolRefusal("roadmap decompose takes a milestone id, an optional part number, or a publish preview; use ahub roadmap decompose <id> [--accept <n> | --publish [--apply --confirm <fingerprint>]]");
|
|
6283
|
+
if (a.publish !== undefined && a.publish !== true) throw new PreEffectToolRefusal("roadmap decompose publish needs publish true; use ahub roadmap decompose <id> --publish");
|
|
6284
|
+
if (a.publish === true && a.accept !== undefined) throw new PreEffectToolRefusal("roadmap decompose takes --accept <part> or --publish, not both");
|
|
6285
|
+
if ((a.apply !== undefined || a.confirm !== undefined) && a.publish !== true) throw new PreEffectToolRefusal("roadmap decompose apply needs its publish preview; use ahub roadmap decompose <id> --publish first");
|
|
6286
|
+
if (a.publish === true) return JSON.stringify(await tasks.roadmapDecomposePublish(by, a.id, { ...(a.apply === undefined ? {} : { apply: a.apply }), ...(a.confirm === undefined ? {} : { confirm: a.confirm }) }));
|
|
6217
6287
|
return JSON.stringify(a.accept === undefined ? await tasks.roadmapDecompose(by, a.id) : await tasks.roadmapDecomposePart(by, a.id, a.accept));
|
|
6288
|
+
}
|
|
6218
6289
|
case "hub_roadmap_edit": {
|
|
6219
6290
|
const fields: Record<string, readonly string[]> = { new: ["op", "fields"], edit: ["op", "id", "revision", "fields"], link: ["op", "id", "kind", "ref"], unlink: ["op", "id", "kind", "ref"], order: ["op", "id", "order"], state: ["op", "id", "state"], accept: ["op", "suggestion"], reject: ["op", "suggestion"] };
|
|
6220
6291
|
if (!a || typeof a !== "object" || Array.isArray(a) || typeof a.op !== "string" || !Object.hasOwn(fields, a.op)) throw new PreEffectToolRefusal("unknown roadmap operation; use new, edit, link, unlink, order, state, accept or reject with hub_roadmap_edit");
|
|
@@ -7237,6 +7308,43 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
7237
7308
|
};
|
|
7238
7309
|
} catch { return {}; }
|
|
7239
7310
|
};
|
|
7311
|
+
// Host-only confirmation re-reads the native session and the same managed-home inventory as setup.
|
|
7312
|
+
const instructionReceipts = (opts.instructionReceiptStore ?? (store => store))(new InstructionReceipts(join(opts.stateDir, "hub.db"), async (session, peer) => {
|
|
7313
|
+
const first = claudeSession(peer), owner = claudeLaunchProof.owner(peer), launch = readClaudeLaunchProof(opts.stateDir, peer, instanceId);
|
|
7314
|
+
if (!owner || !owner.attached || owner.claiming || owner.state === "offline" || first.sessionId !== session || !first.transcriptPath || !first.launchId
|
|
7315
|
+
|| !launch?.privateRecord || launch.launchId !== first.launchId || !launch.launcherPid || !launch.launcherSignature
|
|
7316
|
+
|| processLiveness(launch.launcherPid, launch.launcherSignature) !== "live") return;
|
|
7317
|
+
const generation = owner.sessionGeneration;
|
|
7318
|
+
if (!generation) return;
|
|
7319
|
+
let registry: Registry | undefined;
|
|
7320
|
+
try {
|
|
7321
|
+
registry = new Registry();
|
|
7322
|
+
const found = await usedClaudeHomes(registry, homedir(), process.env);
|
|
7323
|
+
if (!found.complete) return;
|
|
7324
|
+
const current = claudeSession(peer);
|
|
7325
|
+
if (stopping || bus.peers.get(peer) !== owner || !owner.attached || owner.claiming || bus.stateOf(peer) === "offline" || owner.sessionGeneration !== generation
|
|
7326
|
+
|| current.sessionId !== first.sessionId || current.transcriptPath !== first.transcriptPath || current.launchId !== first.launchId) return;
|
|
7327
|
+
const currentLaunch = readClaudeLaunchProof(opts.stateDir, peer, instanceId);
|
|
7328
|
+
if (!currentLaunch?.privateRecord || currentLaunch.launchId !== launch.launchId || currentLaunch.executionCwd !== launch.executionCwd
|
|
7329
|
+
|| currentLaunch.launcherPid !== launch.launcherPid || currentLaunch.launcherSignature !== launch.launcherSignature
|
|
7330
|
+
|| processLiveness(launch.launcherPid, launch.launcherSignature) !== "live") return;
|
|
7331
|
+
const cwd = realPath(currentLaunch.executionCwd ?? opts.cwd);
|
|
7332
|
+
for (const home of found.homes) {
|
|
7333
|
+
const root = realPath(home.path), expected = join(root, "projects", cwd.replace(/[^a-zA-Z0-9]/g, "-"), `${session}.jsonl`);
|
|
7334
|
+
if (first.transcriptPath === expected && realPath(expected) === expected) return { session, transcript: expected, home: root, cwd, peer };
|
|
7335
|
+
}
|
|
7336
|
+
} catch { /* Unknown native session or home never confirms a receipt. */ }
|
|
7337
|
+
finally { registry?.close(); }
|
|
7338
|
+
}));
|
|
7339
|
+
startupCleanup.push(() => instructionReceipts.close());
|
|
7340
|
+
instructionReceipts.seedMode(() => {
|
|
7341
|
+
try {
|
|
7342
|
+
const instructionDisplay = readEditable(opts.cwd, "config.local.json");
|
|
7343
|
+
const value = instructionDisplay === null ? undefined : JSON.parse(instructionDisplay)?.instructed?.mode;
|
|
7344
|
+
return value === "off" || value === "exact" || value === "intent" || value === undefined ? value : "off";
|
|
7345
|
+
} catch { return "off"; } // Unknown display state cannot re-enable a lost witness.
|
|
7346
|
+
});
|
|
7347
|
+
const effectiveInstructionMode = () => instructionReceipts.mode();
|
|
7240
7348
|
/**
|
|
7241
7349
|
* Claude Code's version, from the last row of its transcript that names one (its rows carry it): the last MiB is read,
|
|
7242
7350
|
* opened without blocking and only as a regular file, and the last version found is kept for a tail of big rows.
|
|
@@ -9758,7 +9866,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
9758
9866
|
const summary = bus.queueSummary(peer);
|
|
9759
9867
|
return { peer, state: bus.stateOf(peer), attached: !!bus.peers.get(peer) && bus.peers.get(peer)!.state !== "offline", queued: bus.queued(peer), needsReview: summary.needsReview,
|
|
9760
9868
|
manualHeld: manualPaused.has(peer), hold: conductorHolds.get(peer), budgetPause: quota[accountOf(peer)]?.paused ?? null, doing: doing[peer] ?? null,
|
|
9761
|
-
...(quota[accountOf(peer)] ? { windows: quota[accountOf(peer)]
|
|
9869
|
+
...(quota[accountOf(peer)] ? { windows: windowRow(accountOf(peer), quota[accountOf(peer)]!).windows.map(w => ({ id: w.id, ...(w.stale || (w.resetsAt !== undefined && w.resetsAt <= Date.now()) ? {} : { used: w.used }), resetsAt: w.resetsAt, at: w.at, source: w.source, kind: w.kind, ...(w.superseded ? { superseded: true } : {}), ...(w.left === undefined ? {} : { left: w.left }), ...(w.projection === undefined ? {} : { projection: w.projection }) })) } : {}) };
|
|
9762
9870
|
}),
|
|
9763
9871
|
taskCounts: board.counts(), approvals: [...permissions.values()].map(p => ({ peer: p.peer, tool: p.tool, at: p.createdAt })),
|
|
9764
9872
|
};
|
|
@@ -10075,6 +10183,42 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
10075
10183
|
return view;
|
|
10076
10184
|
}
|
|
10077
10185
|
|
|
10186
|
+
// #1483 R5: the dashboard's roadmap view. The last drift check is kept in memory only, so a card can show a count
|
|
10187
|
+
// without reading GitHub on the page's 1 s poll; `roadmap_check` is the one bounded read that fills it, and its
|
|
10188
|
+
// absence reads as "not checked", never as zero findings.
|
|
10189
|
+
let roadmapDrift: { at: number; findings: { rule: number; milestone: number | null; items: string[]; cause: string; remedy: string }[]; unknown: number[]; truncated?: true } | undefined;
|
|
10190
|
+
/** A dashboard roadmap refusal is the only text the page may echo: a `PreEffectToolRefusal` sentence is canned and
|
|
10191
|
+
* carries refs or an id, never task text. Anything else is reported without its message (the terminal has it). */
|
|
10192
|
+
function roadmapRefusal(error: unknown): string {
|
|
10193
|
+
return error instanceof PreEffectToolRefusal ? error.message : "roadmap action failed; see ahub ui in the terminal";
|
|
10194
|
+
}
|
|
10195
|
+
/** The revision the page rendered, checked before any write: a stale page is refused with its cause named. */
|
|
10196
|
+
function roadmapFresh(rawId: unknown, rawRevision: unknown): number {
|
|
10197
|
+
if (typeof rawId !== "number" || !Number.isSafeInteger(rawId) || rawId < 1) throw new PreEffectToolRefusal("roadmap milestone id is missing; reload the dashboard");
|
|
10198
|
+
if (typeof rawRevision !== "number" || !Number.isSafeInteger(rawRevision) || rawRevision < 0) throw new PreEffectToolRefusal("roadmap revision is missing; reload the dashboard");
|
|
10199
|
+
let current: number;
|
|
10200
|
+
try { current = tasks.milestoneShow(USER, rawId).revision; } catch { throw new PreEffectToolRefusal("roadmap milestone is gone; reload the dashboard"); }
|
|
10201
|
+
if (current !== rawRevision) throw new PreEffectToolRefusal("roadmap changed since this page loaded; reload the dashboard before editing");
|
|
10202
|
+
return rawId;
|
|
10203
|
+
}
|
|
10204
|
+
/** One move renumbers its lane, so a card's `order` is its position and a drag and a Move button agree. */
|
|
10205
|
+
async function roadmapMove(id: number, horizon: string | undefined, order: number) {
|
|
10206
|
+
const view = tasks.milestoneShow(USER, id), fields: Record<string, unknown> = { order };
|
|
10207
|
+
if (horizon === "now" || horizon === "next" || horizon === "later") if (horizon !== view.horizon) fields.horizon = horizon;
|
|
10208
|
+
if (Object.keys(fields).length) await tasks.milestoneEdit(USER, id, view.revision, fields);
|
|
10209
|
+
const lane = (fields.horizon === undefined ? view.horizon : fields.horizon) as string;
|
|
10210
|
+
const others = tasks.milestoneList(USER).filter(row => row.id !== id && row.horizon === lane).sort((left, right) => left.order - right.order || left.id - right.id).map(row => row.id);
|
|
10211
|
+
const at = Math.min(Math.max(order, 0), others.length);
|
|
10212
|
+
// ponytail: one write per card, so a failure partway leaves gaps in this lane's `order`; the next move renumbers it
|
|
10213
|
+
// from scratch, and a board transaction is the upgrade if a gap ever has to survive without one.
|
|
10214
|
+
for (const [index, cardId] of [...others.slice(0, at), id, ...others.slice(at)].entries())
|
|
10215
|
+
if (tasks.milestoneShow(USER, cardId).order !== index) tasks.milestoneOrder(USER, cardId, index);
|
|
10216
|
+
}
|
|
10217
|
+
/** The dashboard's roadmap payload: the same public projection `ahub roadmap show` renders, plus who may act. */
|
|
10218
|
+
function roadmapSnapshot(session?: DashboardSession) {
|
|
10219
|
+
try { return { milestones: tasks.milestoneList(USER), person: session?.liveTest !== true }; }
|
|
10220
|
+
catch { return { unavailable: true, person: false }; }
|
|
10221
|
+
}
|
|
10078
10222
|
async function uiMemorySnapshot(after: number, input?: Record<string, unknown>, session?: DashboardSession) {
|
|
10079
10223
|
const query = input?.memory as Record<string, unknown> | undefined;
|
|
10080
10224
|
const start = input?.view === "memory" && query && query.codeNeighbours === true && typeof query.node === "string" && query.node.startsWith("symbol:") && Buffer.byteLength(query.node) <= 512 ? query.node : undefined;
|
|
@@ -10109,7 +10253,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
10109
10253
|
}
|
|
10110
10254
|
return snapshot;
|
|
10111
10255
|
}
|
|
10112
|
-
function uiSnapshot(after: number,
|
|
10256
|
+
function uiSnapshot(after: number, input?: Record<string, unknown>, session?: DashboardSession) {
|
|
10113
10257
|
const quota = budget.status();
|
|
10114
10258
|
const peers = [...new Set([...Object.keys(quota), ...bus.knownPeers()])];
|
|
10115
10259
|
const budgetNoteOf = new Map(budgetPeerNotes().map(note => [note.peer, note] as const));
|
|
@@ -10187,6 +10331,12 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
10187
10331
|
// #1144: source metadata only, including private records; never expose origins or stored text.
|
|
10188
10332
|
sources: sourceRegistry.list().map(({ id, kind, bytes, sha256, added_at }) => ({ id, kind, bytes, hashPrefix: sha256.slice(0, 12), added_at })),
|
|
10189
10333
|
releases: tasks.releaseList(USER),
|
|
10334
|
+
// #1483 R5: the roadmap block is the read that computes spec freshness, so it rides only the view that shows it and
|
|
10335
|
+
// never another view's 1 s poll. The board's Milestone filter reads the same rows here, and its placement is the
|
|
10336
|
+
// explicit task link only (the projection above also places a task through the issue it came from).
|
|
10337
|
+
...(input?.view === "roadmap" ? { roadmap: { ...roadmapSnapshot(session), drift: roadmapDrift } } : {}),
|
|
10338
|
+
milestones: board.milestones().map(row => ({ id: row.id, title: row.title, horizon: row.horizon, state: row.state, order: row.order })),
|
|
10339
|
+
milestoneOfTask: Object.fromEntries(board.milestoneLinks().filter(link => link.kind === "task").map(link => [link.ref, link.milestone] as const)),
|
|
10190
10340
|
// #335: each schedule's next run, ids and times only (a title or detail is task text). Absent when none is configured, so an older page and an unconfigured project see no change.
|
|
10191
10341
|
...(config.schedules.length ? { schedules: scheduleViews(config.schedules, schedulesStore.rows(), scheduleNow(), tasks.openScheduled(), tasks.schedulesHeld() || opts.schedulesHeld?.() === true) } : {}),
|
|
10192
10342
|
boardLegend: Object.entries(peerView).map(([id, peer]) => ({
|
|
@@ -10211,7 +10361,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
10211
10361
|
return { id: task.id, title: view.title, detail: view.detail, class: task.class, ...(task.profile ? { profile: task.profile, profileClass: task.profileClass } : {}), ...(task.role ? { role: task.role } : {}), state: task.state, owner: task.owner, planner: view.planner ?? null, reviewer: task.reviewer, ...holderReasons(view), deps: view.deps ?? [], ...(task.reserved ? { reserved: task.reserved } : {}), planningRevision: task.planningRevision ?? 0, rank: task.rank ?? null, priority: task.priority ?? null, release: task.release ?? null, plannedStart: task.plannedStart ?? null, due: task.due ?? null, pinned: task.pinned === true, actualDates: view.actualDates, ...(view.codeSymbols ? { codeSymbols: view.codeSymbols } : {}), ...(() => { const group = codeGroup(task, view.codeSymbols, task.plan?.symbols, tasks.publicMetadataText, tasks.isPii(task)); return group ? { codeGroup: group } : {}; })(), ...(view.cancelled ? { cancelled: view.cancelled } : {}), ...(view.external ? { external: view.external } : {}), started: taskHasStarted(task), urgent: task.signals.includes("urgent"), updated: task.updated, flowRevision: task.history.length, reviewStateKey, reworkRound: task.history.filter(entry => entry.event === "changes_requested").length, checking: tasks.isChecking(task.id), ...(view.lifecycle ? { lifecycle: view.lifecycle } : {}), ...(() => { const deliverables = tasks.deliverableBadge(task); return deliverables ? { deliverables } : {}; })() };
|
|
10212
10362
|
}),
|
|
10213
10363
|
links: links.filter(link => link.tasks.every(id => { const task = board.get(id); return task && !tasks.isPii(task); })),
|
|
10214
|
-
budget: Object.fromEntries(peers.map((id) => [id, { ...(quota[accountOf(id)]
|
|
10364
|
+
budget: Object.fromEntries(peers.map((id) => [id, { ...(quota[accountOf(id)] ? windowRow(accountOf(id), quota[accountOf(id)]!) : { windows: [] }), ...(budgetNoteOf.get(id) ? { note: budgetNoteOf.get(id)!.note, noteKind: budgetNoteOf.get(id)!.kind } : {}), context: contexts.view(id, contextSession(id), bus.peers.has(id) && ["idle", "busy", "paused"].includes(bus.stateOf(id))) }])),
|
|
10215
10365
|
permissions: [...permissions.values()].map(({ push }) => {
|
|
10216
10366
|
const req = JSON.parse(push);
|
|
10217
10367
|
// Local tool titles quote file contents and commands, including those of PII turns.
|
|
@@ -10224,7 +10374,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
10224
10374
|
questions: session?.liveTest ? [] : questionStore.list({ state: "open" }, 64).map(row => ({ set: row.set, peer: row.peer, created: row.created, private: row.private, questions: row.questions })),
|
|
10225
10375
|
answeredQuestions: session?.liveTest ? [] : instructedQuestionViews(),
|
|
10226
10376
|
// #1054 T6: unread results for the person's surfaces (the panel and the acon inbox), only for the Agents view the inbox and the Results section read.
|
|
10227
|
-
...(
|
|
10377
|
+
...(input?.view === "agents" ? { results: resultsView(session) } : {}),
|
|
10228
10378
|
events: uiEvents.filter((e) => e.seq > after),
|
|
10229
10379
|
cursor: uiSequence,
|
|
10230
10380
|
memorySync: memoryProfileStatus(true).sync,
|
|
@@ -10232,9 +10382,9 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
10232
10382
|
starts: startPlans(),
|
|
10233
10383
|
roster: rosterView(),
|
|
10234
10384
|
...benchView(),
|
|
10235
|
-
...memoryView(
|
|
10236
|
-
usage: usageView(
|
|
10237
|
-
worktrees: worktreesView(
|
|
10385
|
+
...memoryView(input?.memory),
|
|
10386
|
+
usage: usageView(input?.view === "agents"),
|
|
10387
|
+
worktrees: worktreesView(input?.view === "agents"),
|
|
10238
10388
|
};
|
|
10239
10389
|
}
|
|
10240
10390
|
|
|
@@ -10549,7 +10699,12 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
10549
10699
|
});
|
|
10550
10700
|
const undo = pendingUndo(opts.stateDir);
|
|
10551
10701
|
const planner = `In force: ${plannerPeers().join(", ") || "nobody"} (${plannerSource}). Setting it pins the listed peers as the only planners; new tasks select one of those holders. Agents cannot change this setting.`;
|
|
10552
|
-
return { pendingRestart: allPendingRestart(), retainedConfig, rows: rows.map(row =>
|
|
10702
|
+
return { pendingRestart: allPendingRestart(), retainedConfig, rows: rows.map(row => {
|
|
10703
|
+
if (row.key === "planner") return { ...row, hint: planner };
|
|
10704
|
+
if (row.key !== "instructed.mode") return row;
|
|
10705
|
+
const { pending: _pending, ...rest } = row;
|
|
10706
|
+
return { ...rest, file: "hub.db", source: "person witness", value: instructionReceipts.mode(), fileValue: stored?.instructed?.mode ?? null, note: "Only the person's terminal changes the witness; config.local.json is a display copy." };
|
|
10707
|
+
}), ...(undo ? { undo } : {}) };
|
|
10553
10708
|
}
|
|
10554
10709
|
/** The same announcement whatever surface made the change: events.jsonl, hub.log and every open console. */
|
|
10555
10710
|
const recordSetting = (key: string, from: SettingValue, to: SettingValue, source: SettingSource, undo = false, reason?: string) => {
|
|
@@ -10701,6 +10856,20 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
10701
10856
|
const refusal = settingRefusal(def, value, authority);
|
|
10702
10857
|
if (refusal) return { ok: false, error: refusal };
|
|
10703
10858
|
const source = settingSource(authority);
|
|
10859
|
+
if (def.key === "instructed.mode") {
|
|
10860
|
+
if (authority !== "terminal" || instructedExecution.getStore()?.active || (value !== "off" && value !== "exact" && value !== "intent")) return { ok: false, error: "instructed.mode is changed only by the person in a terminal, to off, exact or intent" };
|
|
10861
|
+
const before = instructionReceipts.mode();
|
|
10862
|
+
if (value === "off") instructionReceipts.setMode(value);
|
|
10863
|
+
try {
|
|
10864
|
+
writeConfigSetting(opts.cwd, opts.stateDir, def, value, scratch => configWriteCheck(scratch, authority, def.path.join(".")));
|
|
10865
|
+
} catch (error) {
|
|
10866
|
+
if (value === "off" && before !== value) recordSetting(def.key, before, value, source);
|
|
10867
|
+
return { ok: false, error: `instructed.mode: ${value === "off" ? "witness is off; " : "witness unchanged; "}display copy could not be written: ${(error as Error).message}` };
|
|
10868
|
+
}
|
|
10869
|
+
if (value === "exact" || value === "intent") instructionReceipts.setMode(value);
|
|
10870
|
+
if (before !== value) recordSetting(def.key, before, value, source);
|
|
10871
|
+
return { ok: true, text: `instructed.mode: witness ${value}; config.local.json is a display copy` };
|
|
10872
|
+
}
|
|
10704
10873
|
// #1408 R2: the conductor needs an interactive session, so its start mode cannot be set to headless while it holds the role. The refusal comes before any write, from the running policy.
|
|
10705
10874
|
const modeRefusal = conductorStartModeRefusal(def, value);
|
|
10706
10875
|
if (modeRefusal) return { ok: false, error: modeRefusal };
|
|
@@ -10925,6 +11094,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
10925
11094
|
return { ok: true, lines: [`${peer}: ${onRoster(peer) ? "on" : "off"} -> ${on ? "on" : "off"} roster`, ...(on ? ["Admission, starts and new work become available; any existing pause or held delivery remains."] : [`${bus.queued(peer)} queued messages are retained until the peer returns.`, "Owned runtimes stop; native terminal sessions detach. Open tasks are offered to another eligible peer.", `For a busy peer, use ahub roster remove ${peer} --now explicitly; this stops its owned runtime or detaches its native session during the active turn.`, ...(retainedTerminalNotice(peer) ? [retainedTerminalNotice(peer)!] : []), ...tasks.rosterPreview(peer).map(move => sanitize(`task ${move.title}: ${move.to ? `${move.role} offered to ${move.to} if removed now` : `${move.role} stays with ${peer}; no eligible replacement`}`)), ...(rosterRemovalRefusal(peer, false) ? [rosterRemovalRefusal(peer, false)!] : [])])], ...(on ? {} : { confirm: peer }) };
|
|
10926
11095
|
} catch (error) { return { ok: false, error: sanitize((error as Error).message) }; }
|
|
10927
11096
|
}
|
|
11097
|
+
if (def.key === "instructed.mode") return { ok: true, lines: [`The person witness and effective mode are ${instructionReceipts.mode()}.`, "Only a person's terminal changes the witness; config.local.json is a display copy."] };
|
|
10928
11098
|
if (def.key === "scoped_grants.protect_instructions") return { ok: true, lines: ["Applies now to scoped writes and edits of AGENTS.md, CLAUDE.md and QWEN.md, including symlinks and folded spellings.", "true asks a person; false keeps these documents grantable (the default). Explicit approval and never-ask keep their meaning."] };
|
|
10929
11099
|
if (def.group === "Permissions") {
|
|
10930
11100
|
const peer = def.path.at(-1)!;
|
|
@@ -11013,6 +11183,66 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
11013
11183
|
return { ok: true, report };
|
|
11014
11184
|
}
|
|
11015
11185
|
switch (a.action) {
|
|
11186
|
+
// #1483 R5: the dashboard's roadmap writes. Each one carries the revision the page rendered (checked by
|
|
11187
|
+
// `roadmapFresh`), so a stale page is refused with its cause named instead of overwriting a newer edit.
|
|
11188
|
+
case "roadmap_new":
|
|
11189
|
+
case "roadmap_edit":
|
|
11190
|
+
case "roadmap_link":
|
|
11191
|
+
case "roadmap_unlink":
|
|
11192
|
+
case "roadmap_move":
|
|
11193
|
+
case "roadmap_state":
|
|
11194
|
+
case "roadmap_accept":
|
|
11195
|
+
case "roadmap_reject":
|
|
11196
|
+
case "roadmap_check":
|
|
11197
|
+
case "roadmap_unplaced":
|
|
11198
|
+
case "roadmap_triage":
|
|
11199
|
+
try {
|
|
11200
|
+
switch (a.action) {
|
|
11201
|
+
case "roadmap_new":
|
|
11202
|
+
if (stopping || recoveryActive()) return { ok: false, error: "recovery or shutdown is holding roadmap changes" };
|
|
11203
|
+
return { ok: true, milestone: await tasks.milestoneNew(USER, { title: a.title, outcome: a.outcome, ...(a.horizon === undefined ? {} : { horizon: a.horizon }), ...(a.target === undefined ? {} : { target: a.target }) }) };
|
|
11204
|
+
case "roadmap_edit": {
|
|
11205
|
+
if (stopping || recoveryActive()) return { ok: false, error: "recovery or shutdown is holding roadmap changes" };
|
|
11206
|
+
const id = roadmapFresh(a.id, a.revision);
|
|
11207
|
+
if (!a.fields || typeof a.fields !== "object" || Array.isArray(a.fields)) return bad;
|
|
11208
|
+
return { ok: true, milestone: await tasks.milestoneEdit(USER, id, tasks.milestoneShow(USER, id).revision, a.fields) };
|
|
11209
|
+
}
|
|
11210
|
+
case "roadmap_link":
|
|
11211
|
+
case "roadmap_unlink": {
|
|
11212
|
+
if (stopping || recoveryActive()) return { ok: false, error: "recovery or shutdown is holding roadmap changes" };
|
|
11213
|
+
const id = roadmapFresh(a.id, a.revision);
|
|
11214
|
+
if (typeof a.kind !== "string" || typeof a.ref !== "string") return bad;
|
|
11215
|
+
const kind = a.kind as MilestoneLinkKind;
|
|
11216
|
+
return { ok: true, milestone: a.action === "roadmap_link" ? tasks.milestoneLink(USER, id, kind, a.ref) : tasks.milestoneUnlink(USER, id, kind, a.ref) };
|
|
11217
|
+
}
|
|
11218
|
+
case "roadmap_move": {
|
|
11219
|
+
if (stopping || recoveryActive()) return { ok: false, error: "recovery or shutdown is holding roadmap changes" };
|
|
11220
|
+
const id = roadmapFresh(a.id, a.revision);
|
|
11221
|
+
if (typeof a.order !== "number" || !Number.isSafeInteger(a.order) || a.order < 0) return bad;
|
|
11222
|
+
await roadmapMove(id, typeof a.horizon === "string" ? a.horizon : undefined, a.order);
|
|
11223
|
+
return { ok: true, milestones: tasks.milestoneList(USER) };
|
|
11224
|
+
}
|
|
11225
|
+
case "roadmap_state": {
|
|
11226
|
+
if (stopping || recoveryActive()) return { ok: false, error: "recovery or shutdown is holding roadmap changes" };
|
|
11227
|
+
const id = roadmapFresh(a.id, a.revision);
|
|
11228
|
+
if (typeof a.state !== "string") return bad;
|
|
11229
|
+
return { ok: true, milestone: tasks.milestoneState(USER, id, a.state as MilestoneState) };
|
|
11230
|
+
}
|
|
11231
|
+
case "roadmap_accept":
|
|
11232
|
+
case "roadmap_reject": {
|
|
11233
|
+
if (stopping || recoveryActive()) return { ok: false, error: "recovery or shutdown is holding roadmap changes" };
|
|
11234
|
+
if (a.suggestion === undefined) return bad;
|
|
11235
|
+
return a.action === "roadmap_accept" ? { ok: true, milestone: await tasks.roadmapAccept(USER, a.suggestion) } : { ok: true, rejected: await tasks.roadmapReject(USER, a.suggestion) };
|
|
11236
|
+
}
|
|
11237
|
+
case "roadmap_check":
|
|
11238
|
+
roadmapDrift = { at: Date.now(), ...(await tasks.roadmapCheck(USER)) };
|
|
11239
|
+
return { ok: true, drift: roadmapDrift };
|
|
11240
|
+
case "roadmap_triage":
|
|
11241
|
+
return { ok: true, suggestions: (await tasks.roadmapTriage(USER)).suggestions };
|
|
11242
|
+
default:
|
|
11243
|
+
return { ok: true, unplaced: await tasks.roadmapUnplaced(USER) };
|
|
11244
|
+
}
|
|
11245
|
+
} catch (error) { return { ok: false, error: roadmapRefusal(error) }; }
|
|
11016
11246
|
case "intake": {
|
|
11017
11247
|
if (session?.liveTest) return { ok: false, error: "live-test dashboard cannot write person-attributed content; use peer tools" };
|
|
11018
11248
|
if (stopping || recoveryActive()) return { ok: false, error: "recovery or shutdown is holding mutations" };
|
|
@@ -11192,6 +11422,11 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
11192
11422
|
try { if (board.hasMilestoneState()) return "target lacks roadmap; retained milestones require a supporting daemon; choose a target advertising roadmap"; }
|
|
11193
11423
|
catch { return "roadmap compatibility is unknown; inspect retained milestone state or choose a supporting target"; }
|
|
11194
11424
|
}
|
|
11425
|
+
// #1622 family 4: a milestone history row that carries instructed provenance throws in a daemon that predates it, so the floor holds only while such a row exists.
|
|
11426
|
+
if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("roadmap_instructed")) {
|
|
11427
|
+
try { if (board.hasInstructedMilestoneHistory()) return "target lacks roadmap_instructed; retained instructed milestone verdicts require a supporting daemon; choose a target advertising roadmap_instructed"; }
|
|
11428
|
+
catch { return "roadmap instructed compatibility is unknown; inspect retained milestone history or choose a supporting target"; }
|
|
11429
|
+
}
|
|
11195
11430
|
if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("reviewer_quota")) {
|
|
11196
11431
|
const proof = reviewerQuotaIntegrity();
|
|
11197
11432
|
let explicit = config.review.gate !== undefined && config.review.gate !== DEFAULT_REVIEW_GATE || config.review.max_minutes !== undefined && config.review.max_minutes !== DEFAULT_REVIEW_MAX_MINUTES || config.review.unknown_quota !== undefined && config.review.unknown_quota !== DEFAULT_REVIEW_UNKNOWN_QUOTA;
|
|
@@ -11207,6 +11442,18 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
11207
11442
|
return "target lacks reviewer_quota; retained accounting, wait deadlines or explicit reviewer quota policy require a supporting daemon";
|
|
11208
11443
|
}
|
|
11209
11444
|
|
|
11445
|
+
if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("instructed_exact")) {
|
|
11446
|
+
try { if (instructionReceipts.mode() === "off") return "target lacks instructed_exact; the retained person-disabled mode requires a supporting daemon"; }
|
|
11447
|
+
catch { return "instructed mode compatibility is unknown; choose a supporting daemon"; }
|
|
11448
|
+
}
|
|
11449
|
+
if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("instructed_intent")) {
|
|
11450
|
+
try {
|
|
11451
|
+
const texts = configSourceTexts(opts.cwd);
|
|
11452
|
+
const rawIntent = CONFIG_FILES.some(name => texts[name] !== null && JSON.parse(texts[name]!).instructed?.mode === "intent");
|
|
11453
|
+
if (instructionReceipts.hasIntentWitness() || rawIntent) return "target lacks instructed_intent; the retained or configured intent mode requires a supporting daemon";
|
|
11454
|
+
}
|
|
11455
|
+
catch { return "instructed mode compatibility is unknown; choose a supporting daemon"; }
|
|
11456
|
+
}
|
|
11210
11457
|
if (!Array.isArray(msg.targetFeatures) || !msg.targetFeatures.includes("guidance_probes")) {
|
|
11211
11458
|
try { if (guidanceProbeStore.hasRecords()) return "target lacks guidance_probes; retained probe declarations or held work require a supporting daemon; choose a target advertising guidance_probes"; }
|
|
11212
11459
|
catch { return "guidance probe compatibility is unknown; inspect retained probe state or choose a supporting target"; }
|
|
@@ -11611,8 +11858,62 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
11611
11858
|
if (!result.ok) throw new Error(String(result.error));
|
|
11612
11859
|
}
|
|
11613
11860
|
|
|
11861
|
+
function instructedRuntimeReady(): boolean {
|
|
11862
|
+
if (!instructedRuntime) return false;
|
|
11863
|
+
let registry: Registry | undefined;
|
|
11864
|
+
try {
|
|
11865
|
+
registry = new Registry();
|
|
11866
|
+
const roots = [opts.cwd, ...registry.list().map(project => project.root), ...executionRoots.values(), ...Object.values(declarations).flatMap(instance => instance.worktree ? [resolve(opts.cwd, instance.worktree)] : [])];
|
|
11867
|
+
return instructedRuntimeAllowed(instructedRuntime.root, roots);
|
|
11868
|
+
} catch { return false; }
|
|
11869
|
+
finally { registry?.close(); }
|
|
11870
|
+
}
|
|
11871
|
+
|
|
11872
|
+
async function launchInstructed(argv: string[], binding: InstructedExecution): Promise<Record<string, unknown>> {
|
|
11873
|
+
binding.current();
|
|
11874
|
+
if (!instructedRuntime || !instructedRuntimeReady()) return { ok: false, error: "instructed execution requires an installed hub outside project and peer write roots; install the hub package and restart this session with ahub claude" };
|
|
11875
|
+
const client: Client = { authed: false, instructed: binding };
|
|
11876
|
+
let open = true;
|
|
11877
|
+
let child: ReturnType<typeof Bun.spawn>;
|
|
11878
|
+
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;
|
|
11879
|
+
child = Bun.spawn({ cmd: [instructedRuntime.bun, join(instructedRuntime.root, "src/cli/main.js"), ...argv],
|
|
11880
|
+
cwd: opts.cwd, env: { ...personEnv(process.env), AGENTHUB_INSTRUCTED_IPC: "1", AGENTHUB_STATE_DIR: opts.stateDir, AGENTHUB_PROJECT_DIR: opts.cwd },
|
|
11881
|
+
stdin: "ignore", stdout: "pipe", stderr: "pipe", serialization: "json",
|
|
11882
|
+
ipc(message) {
|
|
11883
|
+
try {
|
|
11884
|
+
if (!open || !message || typeof message !== "object" || Buffer.byteLength(JSON.stringify(message)) > 1024 * 1024) throw new Error("invalid instruction control message");
|
|
11885
|
+
onControlMessage(inherited, message);
|
|
11886
|
+
} catch { open = false; child.disconnect(); }
|
|
11887
|
+
},
|
|
11888
|
+
});
|
|
11889
|
+
let output = Buffer.alloc(0), overflow = false, timedOut = false;
|
|
11890
|
+
const readers = [(child.stdout as ReadableStream<Uint8Array>).getReader(), (child.stderr as ReadableStream<Uint8Array>).getReader()];
|
|
11891
|
+
const cancel = () => { for (const reader of readers) void reader.cancel().catch(() => {}); };
|
|
11892
|
+
const drain = async (reader: (typeof readers)[number]) => {
|
|
11893
|
+
try {
|
|
11894
|
+
for (;;) {
|
|
11895
|
+
const part = await reader.read(); if (part.done) break;
|
|
11896
|
+
const bytes = Buffer.from(part.value);
|
|
11897
|
+
if (output.length + bytes.length > 64 * 1024) { overflow = true; child.kill(); cancel(); break; }
|
|
11898
|
+
output = Buffer.concat([output, bytes]);
|
|
11899
|
+
}
|
|
11900
|
+
} finally { reader.releaseLock(); }
|
|
11901
|
+
};
|
|
11902
|
+
const timer = setTimeout(() => { timedOut = true; child.kill("SIGKILL"); cancel(); }, INSTRUCTION_CHILD_TIMEOUT_MS);
|
|
11903
|
+
let code: number;
|
|
11904
|
+
try { [code] = await Promise.all([child.exited, ...readers.map(drain)]); }
|
|
11905
|
+
finally { clearTimeout(timer); open = false; client.closed = true; child.disconnect(); }
|
|
11906
|
+
if (timedOut) return { ok: false, error: "instruction timed out; inspect the target before retrying because the effect may have occurred" };
|
|
11907
|
+
return overflow ? { ok: false, error: "instruction output exceeded its limit; inspect the target before retrying because the effect may have occurred" } : { ok: code === 0, exitCode: code, output: output.toString("utf8") };
|
|
11908
|
+
}
|
|
11909
|
+
|
|
11614
11910
|
function onControlMessage(sock: Sock, msg: any): void {
|
|
11615
11911
|
const client = sock.data;
|
|
11912
|
+
if (client.instructed && instructedExecution.getStore() !== client.instructed) {
|
|
11913
|
+
try { client.instructed.current(); }
|
|
11914
|
+
catch (error) { if (sock.readyState === WebSocket.OPEN) sock.send(JSON.stringify({ rid: msg.rid, ok: false, error: "instructed session is no longer current" })); return; }
|
|
11915
|
+
return instructedExecution.run(client.instructed, () => onControlMessage(sock, msg));
|
|
11916
|
+
}
|
|
11616
11917
|
const admittedAtReceive = client.authed && !!client.role, peer = client.peer;
|
|
11617
11918
|
if (!admittedAtReceive) return onMessage(sock, msg);
|
|
11618
11919
|
const metadata = controlWriteMetadata(msg);
|
|
@@ -11734,7 +12035,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
11734
12035
|
}
|
|
11735
12036
|
if ((msg.projectId && msg.projectId !== projectId) || (msg.instanceId && msg.instanceId !== instanceId) ||
|
|
11736
12037
|
(msg.projectRoot && msg.projectRoot !== opts.cwd)) return sock.close(4404, "project or instance mismatch");
|
|
11737
|
-
if (!["peer", "tools", "console"].includes(msg.role)) return sock.close(4403, "invalid client role");
|
|
12038
|
+
if (!["peer", "tools", "console"].includes(msg.role) || c.instructed && msg.role !== "console") return sock.close(4403, "invalid client role");
|
|
11738
12039
|
try { refreshConductorPolicy(); } catch { return sock.close(4403, "invalid conductor role/feed configuration"); }
|
|
11739
12040
|
if (stopping && msg.role !== "console") return sock.close(1013, "hub is stopping");
|
|
11740
12041
|
c.authed = true;
|
|
@@ -11742,7 +12043,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
11742
12043
|
c.role = msg.role;
|
|
11743
12044
|
c.guidanceProbeConnectionId = randomUUID(); // Private comparator only; never sent, persisted separately or accepted from hello.
|
|
11744
12045
|
c.clientVersion = displayVersion(msg.clientVersion);
|
|
11745
|
-
if (c.role === "console") consoles.add(sock);
|
|
12046
|
+
if (c.role === "console") { if (!c.instructed) consoles.add(sock); }
|
|
11746
12047
|
else if (c.role === "tools" && sessionHello(msg)) {
|
|
11747
12048
|
// agent-hub#1036: a connection that names a peer id but is not that peer's current session gets an id of its own instead of becoming the peer. It can send and read; it holds none of the
|
|
11748
12049
|
// peer's board roles, is never a bus peer (no delivery, no push) and replaces nobody. Nothing is refused: a hello that worked before still works, as a session.
|
|
@@ -11961,7 +12262,11 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
11961
12262
|
if (!bus.peers.has(msg.peer) || bus.stateOf(msg.peer) === "offline") return void reply({ ok: false, reason: "invalid", error: `peer is offline; start it with ahub ${msg.peer}, then retry ahub title` });
|
|
11962
12263
|
if (stopping || recoveryActive()) return void reply({ ok: false, reason: "invalid", error: "recovery or shutdown is holding titles; wait for ahub status to settle, then retry" });
|
|
11963
12264
|
if (!sessionTitleText(msg.title)) return void reply({ ok: false, reason: "invalid", error: "title needs 1-80 normalized characters; enter a short public title" });
|
|
11964
|
-
|
|
12265
|
+
const instruction = c.instructed;
|
|
12266
|
+
const titleOwner = bus.peers.get(msg.peer), previousTitle = titleOwner?.sessionTitle;
|
|
12267
|
+
if (instruction && (!isLocalPeer(titleOwner) || !previousTitle || titlePrivate(msg.peer, previousTitle))) return void reply({ ok: false, reason: "invalid", error: "this title cannot be safely restored or fenced; run the command in a terminal" });
|
|
12268
|
+
const instructionCurrent = instruction ? () => { try { instruction.current(); return titleOwner?.sessionTitle === previousTitle; } catch { return false; } } : undefined;
|
|
12269
|
+
void setSessionTitle(msg.peer, msg.title, false, false, instructionCurrent).then(result => reply(result.ok && instruction ? { ...result, previousTitle } : result), () => reply({ ok: false, reason: "invalid", mayHaveApplied: true, error: "session title result is unconfirmed; the title may have been applied; check ahub status before retrying" }));
|
|
11965
12270
|
return;
|
|
11966
12271
|
}
|
|
11967
12272
|
case "queue": {
|
|
@@ -12113,7 +12418,9 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
12113
12418
|
const cfg = msg.config;
|
|
12114
12419
|
if (!cfg || !Array.isArray(cfg.peers) || cfg.peers.some((p: unknown) => (typeof p !== "string" || definitionOf(p)?.budget?.instrumented !== true))) throw new Error("strict execution budgets support local and Pi only; native Codex/Claude calls are not instrumented");
|
|
12115
12420
|
if (cfg.kind === "task" && !board.get(cfg.taskId)) throw new Error("task not found");
|
|
12116
|
-
|
|
12421
|
+
// #1513 AC3: the reason is a person's, bounded, and kept with the actor and the time. Never task text.
|
|
12422
|
+
if (msg.reason !== undefined && (typeof msg.reason !== "string" || msg.reason.length > 280)) throw new Error("execution budget reason is at most 280 characters");
|
|
12423
|
+
return void reply({ ok: true, budget: tasks.configureExecutionBudget(cfg, { ...(typeof msg.reason === "string" ? { reason: msg.reason } : {}), by: "person" }) });
|
|
12117
12424
|
}
|
|
12118
12425
|
if (msg.op === "disable" && typeof msg.id === "string") return void reply({ ok: true, disabled: tasks.disableExecutionBudget(msg.id) });
|
|
12119
12426
|
return void reply({ ok: false, error: "unknown execution budget operation" });
|
|
@@ -12495,6 +12802,129 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
12495
12802
|
}
|
|
12496
12803
|
return apply();
|
|
12497
12804
|
}
|
|
12805
|
+
case "instruction_execute": {
|
|
12806
|
+
if (c.role !== "tools" || !c.peer || c.toolsOwner || c.externalOwner || Object.keys(msg).some(key => !["t", "rid", "session", "argv"].includes(key)) || typeof msg.session !== "string" || msg.argv !== undefined && (!Array.isArray(msg.argv) || msg.argv.some((word: unknown) => typeof word !== "string") || Buffer.byteLength(JSON.stringify(msg.argv)) > MAX_PROMPT_BYTES)) return void reply({ ok: false, error: "instruction unavailable" });
|
|
12807
|
+
const peer = c.peer, session = msg.session, socket = sock;
|
|
12808
|
+
let initialMode: ReturnType<typeof effectiveInstructionMode>;
|
|
12809
|
+
try { initialMode = effectiveInstructionMode(); }
|
|
12810
|
+
catch { return void reply({ ok: false, error: "instructed.mode is unavailable; inspect hub status and run the command in a terminal" }); }
|
|
12811
|
+
const initialSession = claudeSession(peer), owner = claudeLaunchProof.owner(peer), generation = owner?.sessionGeneration;
|
|
12812
|
+
const launch = readClaudeLaunchProof(opts.stateDir, peer, instanceId);
|
|
12813
|
+
class InstructionRefusal extends Error {}
|
|
12814
|
+
const sessionRefusal = `this Claude session changed or was not started by ahub claude. The person starts a managed session in this project:\n\n\`\`\`sh\ncd ${shellQuote(opts.cwd)} && ahub claude\n\`\`\`\n\nSuccess: a new managed Claude session starts; type the instruction again there.`;
|
|
12815
|
+
const requestedMode = msg.argv === undefined ? "exact" : "intent";
|
|
12816
|
+
const modeRefusal = `instructed.mode is off. The person turns it on in a terminal:\n\n\`\`\`sh\ncd ${shellQuote(opts.cwd)} && ahub settings set instructed.mode ${requestedMode}\n\`\`\`\n\nSuccess: the command reports witness ${requestedMode}; type the instruction again.`;
|
|
12817
|
+
const receiptRefusal = "no usable instruction receipt; type the /agent-hub:ahub command again. A receipt is used once and expires after 10 minutes.";
|
|
12818
|
+
const runtimeRefusal = "the installed hub runtime is unavailable or inside a project or peer write root; install the hub package and start a new managed session with ahub claude";
|
|
12819
|
+
const current = () => {
|
|
12820
|
+
const observed = claudeSession(peer), latest = readClaudeLaunchProof(opts.stateDir, peer, instanceId);
|
|
12821
|
+
const checks = { socket: socket.readyState === WebSocket.OPEN && socket.data === c && !c.closed && c.role === "tools" && c.peer === peer, lifecycle: !stopping && !recoveryActive() && !bus.isRecoveryHeld, policy: membershipAllowed(peer) && !readOnlyPeer(peer) && !turns.get(peer)?.private && !contextPii(peer) && !board.peerTaskSignals(peer).some(task => !isClosedTaskState(task.state) && (task.signals.includes("pii") || task.signals.includes("pii_path"))), owner: !!owner && owner.attached && owner.state !== "offline" && !owner.claiming && bus.peers.get(peer) === owner && !!generation && owner.sessionGeneration === generation, session: observed.sessionId === session && observed.sessionId === initialSession.sessionId && observed.transcriptPath === initialSession.transcriptPath && observed.launchId === initialSession.launchId, launch: !!launch?.privateRecord && !!launch.launcherPid && !!launch.launcherSignature && launch.launchId === observed.launchId && !!latest?.privateRecord && latest.launchId === launch.launchId && latest.launcherPid === launch.launcherPid && latest.launcherSignature === launch.launcherSignature && processLiveness(launch.launcherPid, launch.launcherSignature) === "live", mode: initialMode !== "off" && effectiveInstructionMode() === initialMode };
|
|
12822
|
+
if (!checks.mode) throw new InstructionRefusal(effectiveInstructionMode() === "off" ? modeRefusal : "instructed.mode changed; type the instruction again in the current mode");
|
|
12823
|
+
if (!checks.lifecycle) throw new InstructionRefusal("the hub is stopping or recovering; retry after ahub status shows it running");
|
|
12824
|
+
if (!checks.policy) throw new InstructionRefusal("a private turn or private task is active for this peer, or its access is restricted; run the command in a terminal");
|
|
12825
|
+
if (!checks.socket || !checks.owner || !checks.session || !checks.launch) throw new InstructionRefusal(sessionRefusal);
|
|
12826
|
+
};
|
|
12827
|
+
void (async () => {
|
|
12828
|
+
try {
|
|
12829
|
+
if (!launch?.privateRecord || !launch.launcherPid || !launch.launcherSignature || processLiveness(launch.launcherPid, launch.launcherSignature) !== "live") return { ok: false, error: `this Claude session was not started by ahub claude. The person starts a managed session in this project:\n\n\`\`\`sh\ncd ${shellQuote(opts.cwd)} && ahub claude\n\`\`\`\n\nSuccess: a new Claude session starts under the hub; type the instruction again there.` };
|
|
12830
|
+
if (!initialSession.sessionId || !initialSession.transcriptPath) return { ok: false, error: "no session evidence for this Claude session yet; send one ordinary prompt in this session, then type the /agent-hub:ahub command again" };
|
|
12831
|
+
current();
|
|
12832
|
+
if (!instructedRuntimeReady()) return { ok: false, error: `the loaded hub runtime is inside a project or peer write root, or its location is unknown. The person installs the hub package before restarting the session:\n\n\`\`\`sh\ncd ${shellQuote(opts.cwd)} && bun add -g @staix/agent-hub\n\`\`\`\n\nSuccess: the package is installed globally. The person then starts the managed session:\n\n\`\`\`sh\ncd ${shellQuote(opts.cwd)} && ahub claude\n\`\`\`\n\nSuccess: the installed hub starts Claude; type the instruction again.` };
|
|
12833
|
+
if (initialMode === "exact" && msg.argv !== undefined) return { ok: false, error: "exact mode takes no agent-selected command; type the exact /agent-hub:ahub run command again" };
|
|
12834
|
+
const receipt = await (initialMode === "intent" ? instructionReceipts.forPeer(peer).confirmIntent(session, Date.now()) : instructionReceipts.forPeer(peer).confirmReceipt(session, Date.now()));
|
|
12835
|
+
current();
|
|
12836
|
+
if (!receipt) return { ok: false, error: receiptRefusal };
|
|
12837
|
+
const typedExact = /^run(?:\s|$)/u.test(receipt.args);
|
|
12838
|
+
if (typedExact && msg.argv !== undefined) return { ok: false, error: "the person typed an exact command; run it without an agent-selected command" };
|
|
12839
|
+
const argv: string[] | undefined = typedExact || initialMode === "exact" ? parseExactInstruction(receipt.args) : msg.argv;
|
|
12840
|
+
const form = argv && (typedExact || initialMode === "exact" ? exactForm(argv) : intentForm(argv));
|
|
12841
|
+
if (!argv) {
|
|
12842
|
+
const raw = receipt.args.startsWith("run ") ? receipt.args.slice("run ".length).trim() : "";
|
|
12843
|
+
if (!raw || /[\p{Cc}\p{Cf}]/u.test(raw) || raw.includes("~~~")) return { ok: false, error: "instruction syntax is not supported for exact mode; the original command cannot be rendered safely" };
|
|
12844
|
+
return { ok: false, error: `this syntax is not proven for instructed exact mode. The person runs the original command in a terminal:\n\n~~~sh\ncd ${shellQuote(opts.cwd)} && ahub ${raw}\n~~~\n\nSuccess: the command reports its result in that terminal.` };
|
|
12845
|
+
}
|
|
12846
|
+
if (!form || (typedExact || initialMode === "exact") && !["console", "conductor"].includes(classifyPeerCommand(argv[0]!, argv.slice(1), adapterCatalog))) return { ok: false, error: `${typedExact || initialMode === "exact" ? "this form is not proven for instructed exact mode" : intentRefusal(argv)}. The person runs the same command in a terminal:\n\n\`\`\`sh\ncd ${shellQuote(opts.cwd)} && ahub ${argv.map(shellQuote).join(" ")}\n\`\`\`\n\nSuccess: the command reports its result in that terminal.` };
|
|
12847
|
+
if ("verdictIds" in form && Array.isArray(form.verdictIds) && !literalInstructionIds(receipt.args, form.verdictIds)) return { ok: false, error: "the verdict's item id or slot is not written in the person's instruction; type it in a new instruction" };
|
|
12848
|
+
if (initialMode === "intent" && !typedExact && !tasks.publicMetadataText(JSON.stringify(argv))) return { ok: false, error: "the selected command may contain private information; run the command in a terminal" };
|
|
12849
|
+
const screened = "screen" in form && form.screen === true;
|
|
12850
|
+
const screenRefusal = `instruction privacy screening did not clear the command. The person runs it in a terminal:\n\n\`\`\`sh\ncd ${shellQuote(opts.cwd)} && ahub ${argv.map(shellQuote).join(" ")}\n\`\`\`\n\nSuccess: the command reports its result in that terminal.`;
|
|
12851
|
+
const titleOwner = (form as ExactForm).titleTarget && form.targetPeer ? bus.peers.get(form.targetPeer) : undefined;
|
|
12852
|
+
const previousTitle = titleOwner?.sessionTitle;
|
|
12853
|
+
const titleSession = titleOwner?.titleSession;
|
|
12854
|
+
if ((form as ExactForm).titleTarget && (!isLocalPeer(titleOwner) || !previousTitle || titlePrivate(form.targetPeer!, previousTitle))) throw new InstructionRefusal("this title cannot be safely restored or fenced; run the command in a terminal");
|
|
12855
|
+
const study = (form as ExactForm).study;
|
|
12856
|
+
const campaign = study ? board.researchCampaign(study.id, study.revision) : undefined;
|
|
12857
|
+
if (study && (!campaign || campaign.project !== chain.at(-1) || campaign.private)) throw new InstructionRefusal("the study is unavailable or private; run the command in a terminal");
|
|
12858
|
+
const taskId = form.taskId ?? campaign?.parentTaskId;
|
|
12859
|
+
const studySources = campaign ? [...new Set([...campaign.contract.sourceIds, ...campaign.contract.units.flatMap(unit => unit.sourceIds)])] : [];
|
|
12860
|
+
const studyBindings = () => campaign ? JSON.stringify(campaign.contract.units.map(unit => board.researchLatestUnitBinding(campaign.id, unit.id))) : "";
|
|
12861
|
+
const initialStudyBindings = studyBindings();
|
|
12862
|
+
const studyTasks = campaign ? [...new Set([campaign.parentTaskId, ...campaign.contract.units.flatMap(unit => { const previous = board.researchLatestUnitBinding(campaign.id, unit.id); return [...(unit.adoptTaskId === undefined ? [] : [unit.adoptTaskId]), ...(previous ? [previous.taskId] : [])]; }), ...board.researchCampaignBindings(campaign.id, campaign.revision).map(unit => unit.taskId)])] : [];
|
|
12863
|
+
const studyHash = campaign?.hash;
|
|
12864
|
+
const screenedInputs = screened ? [receipt.args, JSON.stringify(argv), ...(campaign ? [JSON.stringify(campaign.contract)] : previousTitle ? [previousTitle] : [])] : [];
|
|
12865
|
+
let studyEffectStarted = false;
|
|
12866
|
+
const guarded = () => {
|
|
12867
|
+
current();
|
|
12868
|
+
if (!instructedRuntimeReady()) throw new InstructionRefusal(runtimeRefusal);
|
|
12869
|
+
if (screenedInputs.some(input => Buffer.byteLength(input) > SCREEN_MAX_BYTES || !tasks.publicMetadataText(input))) throw new InstructionRefusal(screenRefusal);
|
|
12870
|
+
if (taskId !== undefined) { const task = board.get(taskId); if (!task || task.signals.includes("pii") || task.signals.includes("pii_path") || tasks.isPii(task)) throw new InstructionRefusal("the command targets unavailable or private work; run the command in a terminal"); }
|
|
12871
|
+
if (study && (!campaign || (() => { const latest = board.researchCampaign(study.id, study.revision); return !latest || latest.private || latest.hash !== studyHash; })() || !studyEffectStarted && studyBindings() !== initialStudyBindings || studyTasks.some(id => { const task = board.get(id); return !task || task.signals.includes("pii") || task.signals.includes("pii_path") || tasks.isPii(task) || !tasks.publicMetadataText(JSON.stringify(task.refs)); }) || studySources.some(id => { const source = sourceRegistry.get(id); return !source || source.private; }))) throw new InstructionRefusal("the study changed or refers to private work; run the command in a terminal");
|
|
12872
|
+
if ((form as ExactForm).titleTarget && (!form.targetPeer || !isLocalPeer(titleOwner) || bus.peers.get(form.targetPeer) !== titleOwner || titleOwner.titleSession !== titleSession || titleOwner.sessionTitle !== previousTitle || titlePrivate(form.targetPeer, previousTitle))) throw new InstructionRefusal("the session or previous title changed; run the command in a terminal");
|
|
12873
|
+
if ("review" in form && form.review && (taskId === undefined || board.get(taskId)?.reviewer !== USER)) throw new InstructionRefusal("only a task assigned to the person as reviewer can receive this verdict; run the command in a terminal");
|
|
12874
|
+
if (form.targetPeer && board.list().some(task => (task.signals.includes("pii") || task.signals.includes("pii_path") || tasks.isPii(task)) && (task.owner === form.targetPeer || task.reviewer === form.targetPeer || task.reserved === form.targetPeer))) throw new InstructionRefusal("the command targets private work; run the command in a terminal");
|
|
12875
|
+
};
|
|
12876
|
+
guarded();
|
|
12877
|
+
if (screened) {
|
|
12878
|
+
const screen = opts.piiScreen ?? ((text: string) => screenPii(text, { ...(config.mlx.enabled === false ? {} : { device: () => ensureMlx(config.mlx) }), onCampus, omni, fixedModel: () => activeRouting().local.fixed_model }));
|
|
12879
|
+
for (const input of screenedInputs) {
|
|
12880
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
12881
|
+
const verdict = await Promise.race([screen(input).catch(() => undefined), new Promise<undefined>(resolve => { timer = setTimeout(() => resolve(undefined), SCREEN_TIMEOUT_MS); })]).finally(() => clearTimeout(timer));
|
|
12882
|
+
guarded();
|
|
12883
|
+
if (verdict?.label !== "clear") throw new InstructionRefusal(screenRefusal);
|
|
12884
|
+
const fresh = await instructionReceipts.forPeer(peer).confirmIntent(session, Date.now());
|
|
12885
|
+
guarded();
|
|
12886
|
+
if (!fresh || fresh.id !== receipt.id || fresh.args !== receipt.args) throw new InstructionRefusal(receiptRefusal);
|
|
12887
|
+
}
|
|
12888
|
+
}
|
|
12889
|
+
if (!(initialMode === "intent" && !typedExact ? instructionReceipts.consumeIntent(receipt.id, Date.now()) : instructionReceipts.consumeExact(receipt.id, Date.now()))) return { ok: false, error: receiptRefusal };
|
|
12890
|
+
if (!event({ type: "agent_cli", peer, command: cliCommandLabel(argv[0]!, argv.slice(1), adapterCatalog), refused: false, instructed: true, instructionReceipt: receipt.id })) { instructionReceipts.finishExact(receipt.id); return { ok: false, error: "instruction audit is unavailable; check hub status and run the command in a terminal" }; }
|
|
12891
|
+
let revoked = false;
|
|
12892
|
+
const binding: InstructedExecution = { peer, receipt: receipt.id, active: true, ...(taskId === undefined ? {} : { taskId }), ...(study ? { beginStudy: () => { guarded(); studyEffectStarted = true; } } : {}), current: () => {
|
|
12893
|
+
if (revoked) throw new Error("instruction authority revoked");
|
|
12894
|
+
try { guarded(); if (!instructionReceipts.exactCurrent(receipt.id, Date.now())) throw new InstructionRefusal(receiptRefusal); }
|
|
12895
|
+
catch (error) { revoked = true; throw error; }
|
|
12896
|
+
} };
|
|
12897
|
+
try { return await launchInstructed(argv, binding); }
|
|
12898
|
+
catch (error) {
|
|
12899
|
+
if (error instanceof InstructionRefusal) throw error;
|
|
12900
|
+
throw new InstructionRefusal("the hub could not complete instructed execution; inspect the target before running the command in a terminal because an effect may have occurred");
|
|
12901
|
+
}
|
|
12902
|
+
finally { binding.active = false; instructionReceipts.finishExact(receipt.id); }
|
|
12903
|
+
} catch (error) { return { ok: false, error: error instanceof InstructionRefusal ? error.message : "instruction execution failed unexpectedly; inspect hub status and run the command in a terminal" }; }
|
|
12904
|
+
})().then(reply, () => reply({ ok: false, error: "instruction unavailable" }));
|
|
12905
|
+
return;
|
|
12906
|
+
}
|
|
12907
|
+
case "instruction_hook": {
|
|
12908
|
+
const peer = c.peer;
|
|
12909
|
+
const adapter = peer ? definitionOf(peer) : undefined;
|
|
12910
|
+
const fields = msg.op === "stop" ? ["t", "rid", "op", "session"] : ["t", "rid", "op", "session", "promptId", "transcript", "home", "cwd", "hash"];
|
|
12911
|
+
if (Object.keys(msg).some(key => !fields.includes(key))) return void reply({ ok: false });
|
|
12912
|
+
if (c.role !== "tools" || !peer || !isFixedBuiltinDefinition(adapter) || adapter?.transport !== "claude-channel" || stopping || recoveryActive()) return void reply({ ok: false });
|
|
12913
|
+
if (msg.op === "stop") {
|
|
12914
|
+
if (typeof msg.session !== "string" || claudeSession(peer).sessionId !== msg.session || bus.stateOf(peer) === "offline") return void reply({ ok: false });
|
|
12915
|
+
instructionReceipts.stop(msg.session, peer);
|
|
12916
|
+
return void reply({ ok: true });
|
|
12917
|
+
}
|
|
12918
|
+
if (msg.op !== "pending" || typeof msg.session !== "string" || typeof msg.promptId !== "string" || typeof msg.transcript !== "string"
|
|
12919
|
+
|| typeof msg.home !== "string" || typeof msg.cwd !== "string" || typeof msg.hash !== "string") return void reply({ ok: false });
|
|
12920
|
+
const current = claudeSession(peer);
|
|
12921
|
+
const attached = current.sessionId === msg.session && current.transcriptPath === msg.transcript && bus.stateOf(peer) !== "offline";
|
|
12922
|
+
try {
|
|
12923
|
+
const ok = instructionReceipts.pending({ session: msg.session, promptId: msg.promptId, transcript: msg.transcript, home: msg.home, cwd: msg.cwd, project: opts.cwd,
|
|
12924
|
+
hash: msg.hash, ...(attached ? { peer } : {}) }, Date.now());
|
|
12925
|
+
return void reply({ ok });
|
|
12926
|
+
} catch { return void reply({ ok: false }); }
|
|
12927
|
+
}
|
|
12498
12928
|
case "facts": {
|
|
12499
12929
|
// Turn-free facts (issue #108) for Claude's hooks: `pre` before a tool runs (the fact rides back as additional
|
|
12500
12930
|
// context), `post` after it (its effect, and the readback of what went in before), `stop` when its turn ends.
|
|
@@ -13200,7 +13630,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
13200
13630
|
}
|
|
13201
13631
|
case "model":
|
|
13202
13632
|
if (c.role !== "console") return void reply(modelFailure("model overrides are person-only; run ahub model in a person's terminal"));
|
|
13203
|
-
return void reply(modelCommandSafe(msg, { source: "cli", scope: c, current: () => c.authed === true && !c.closed && c.role === "console" && sock.readyState === WebSocket.OPEN }));
|
|
13633
|
+
return void reply(modelCommandSafe(msg, { source: "cli", scope: c, current: () => { try { c.instructed?.current(); } catch { return false; } return c.authed === true && !c.closed && c.role === "console" && sock.readyState === WebSocket.OPEN; } }));
|
|
13204
13634
|
case "settings_get":
|
|
13205
13635
|
if (c.role !== "console") {
|
|
13206
13636
|
try { const current = publicReadCurrent(sock); current(); const view = publicSettingsView(); current(); return void reply({ ok: true, ...view }); }
|
|
@@ -13269,9 +13699,9 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
13269
13699
|
void hubStart(msg.peer, "the console", true).then(result => reply(includeRetainedLaunchConfig(String(msg.peer), result)), (error) => { log(`peer_start ${String(msg.peer)} failed: ${(error as Error).message}`); reply({ ok: false, error: "peer start failed; inspect ahub status and hub.log" }); });
|
|
13270
13700
|
return;
|
|
13271
13701
|
case "peer_stop":
|
|
13272
|
-
let stopCurrent:(()=>void)|undefined;
|
|
13702
|
+
let stopCurrent:(()=>void)|undefined = c.instructed?.current;
|
|
13273
13703
|
if(c.role!=="console")try{stopCurrent=admitOperational(sock,"stop");}catch(error){return void reply(operationalFailure(error));}
|
|
13274
|
-
void stopPeer(msg.peer,false,stopCurrent?{actor:c.peer!,current:stopCurrent}:undefined).then(reply).catch(error => reply(operationalFailure(error,"peer stop failed; inspect ahub status and logs before retrying")));
|
|
13704
|
+
void stopPeer(msg.peer,false,stopCurrent?{actor:c.instructed ? USER : c.peer!,current:stopCurrent}:undefined).then(reply).catch(error => reply(operationalFailure(error,"peer stop failed; inspect ahub status and logs before retrying")));
|
|
13275
13705
|
return;
|
|
13276
13706
|
case "start":
|
|
13277
13707
|
if (c.role !== "console") return void reply({ t: "started", ok: false, error: "start is a console command; use hub_peer_start with the conductor role" });
|
|
@@ -13417,7 +13847,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
13417
13847
|
case "budget":
|
|
13418
13848
|
if (c.role !== "console") {
|
|
13419
13849
|
if (msg.resume !== undefined || msg.set !== undefined) return void reply({ t: "budget", ok: false, error: "budget mutations are console commands" });
|
|
13420
|
-
return void reply({ t: "budget", ok: true, budget: publicPeerBudget(budget.status(), text => tasks.nameable(text)), peers: budgetPeerNotes(), kimiSource: kimiUsage.status(), gate: config.budget.gate, review: reviewerBudgetView() });
|
|
13850
|
+
return void reply({ t: "budget", ok: true, budget: publicPeerBudget(budgetViews(budget.status()), text => tasks.nameable(text)), peers: budgetPeerNotes(), kimiSource: kimiUsage.status(), gate: config.budget.gate, review: reviewerBudgetView() });
|
|
13421
13851
|
}
|
|
13422
13852
|
if (recoveryActive()) return void reply({ t: "budget", ok: false, error: "recovery is holding mutations" });
|
|
13423
13853
|
if (msg.resume) {
|
|
@@ -13428,7 +13858,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
13428
13858
|
if (!(used >= 0 && used <= 1)) return void reply({ t: "budget", ok: false, error: "used must be between 0 and 1" });
|
|
13429
13859
|
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" }]);
|
|
13430
13860
|
}
|
|
13431
|
-
return void reply({ t: "budget", ok: true, budget: budget.status(), peers: budgetPeerNotes(), kimiSource: kimiUsage.status(), gate: config.budget.gate, review: reviewerBudgetView() });
|
|
13861
|
+
return void reply({ t: "budget", ok: true, budget: budgetViews(budget.status()), peers: budgetPeerNotes(), kimiSource: kimiUsage.status(), gate: config.budget.gate, review: reviewerBudgetView() });
|
|
13432
13862
|
case "usage": {
|
|
13433
13863
|
// #683 U2: the console, the person and a configured planner read usage; every other agent is refused. Always answered (rid).
|
|
13434
13864
|
const planner = c.role === "tools" && !!c.peer && !!config.roles[c.peer]?.includes("planner");
|
|
@@ -13656,6 +14086,7 @@ export async function startDaemon(opts: DaemonOptions) {
|
|
|
13656
14086
|
modelPreviews.clear(); modelOverrides.close();
|
|
13657
14087
|
visuals.close();
|
|
13658
14088
|
guidanceProbeStore.close();
|
|
14089
|
+
instructionReceipts.close();
|
|
13659
14090
|
board.close();
|
|
13660
14091
|
turnLog?.close();
|
|
13661
14092
|
server.stop(true);
|