@wrongstack/core 0.277.1 → 0.280.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.
Files changed (83) hide show
  1. package/dist/{agent-bridge-BFJ2ODzI.d.ts → agent-bridge-DXC6QDJ4.d.ts} +1 -1
  2. package/dist/{agent-subagent-runner-BimKihiC.d.ts → agent-subagent-runner-PoqNKiR4.d.ts} +563 -471
  3. package/dist/{compactor-D3BGw26y.d.ts → compactor-U3agvUIG.d.ts} +1 -1
  4. package/dist/{config-DAOjriz9.d.ts → config-Cr3312zc.d.ts} +102 -4
  5. package/dist/coordination/index.d.ts +1087 -998
  6. package/dist/coordination/index.js +12235 -12052
  7. package/dist/coordination/index.js.map +1 -1
  8. package/dist/defaults/index.d.ts +31 -30
  9. package/dist/defaults/index.js +403 -189
  10. package/dist/defaults/index.js.map +1 -1
  11. package/dist/{brain-CCfuEOdp.d.ts → events-Bs2fmldo.d.ts} +117 -112
  12. package/dist/execution/index.d.ts +27 -19
  13. package/dist/execution/index.js +216 -63
  14. package/dist/execution/index.js.map +1 -1
  15. package/dist/execution/prompt-enhancer.d.ts +1 -1
  16. package/dist/execution/prompt-enhancer.js.map +1 -1
  17. package/dist/extension/index.d.ts +8 -7
  18. package/dist/{global-mailbox-Dr4cTKqL.d.ts → global-mailbox-Ct7IorLJ.d.ts} +84 -6
  19. package/dist/{goal-store-C1uH4srH.d.ts → goal-store-C4F6DjC0.d.ts} +1 -1
  20. package/dist/hq/index.d.ts +504 -7
  21. package/dist/hq/index.js +1069 -20
  22. package/dist/hq/index.js.map +1 -1
  23. package/dist/{index-DJXj-dcr.d.ts → index-kidebiDh.d.ts} +8 -5
  24. package/dist/{index-cMEmzCVN.d.ts → index-nP09-oP2.d.ts} +2 -2
  25. package/dist/index.d.ts +153 -76
  26. package/dist/index.js +5791 -3163
  27. package/dist/index.js.map +1 -1
  28. package/dist/infrastructure/index.d.ts +7 -6
  29. package/dist/kernel/index.d.ts +14 -13
  30. package/dist/kernel/index.js +31 -15
  31. package/dist/kernel/index.js.map +1 -1
  32. package/dist/{mailbox-types-DTl7bRH3.d.ts → mailbox-types-BGZWrYTJ.d.ts} +38 -0
  33. package/dist/{mcp-servers-CFb60-pH.d.ts → mcp-servers-D910X5_r.d.ts} +3 -3
  34. package/dist/models/index.d.ts +5 -5
  35. package/dist/models/index.js.map +1 -1
  36. package/dist/{models-registry-5Ufn7f2m.d.ts → models-registry-CLkoOcHk.d.ts} +1 -1
  37. package/dist/{multi-agent-coordinator-CcrcncvG.d.ts → multi-agent-coordinator-CieyUoEL.d.ts} +1 -1
  38. package/dist/{null-fleet-bus-C9KsYyrI.d.ts → null-fleet-bus-DkdmZJ_W.d.ts} +464 -464
  39. package/dist/observability/index.d.ts +3 -2
  40. package/dist/{path-resolver-CEeX9I7O.d.ts → path-resolver-XfZ9eLxG.d.ts} +3 -3
  41. package/dist/{permission-DbsGOA1C.d.ts → permission-Dx6dIqS2.d.ts} +2 -7
  42. package/dist/{permission-policy-BpEea3r7.d.ts → permission-policy-C8vJcnX5.d.ts} +2 -2
  43. package/dist/{pipeline-CEjBjzVA.d.ts → pipeline-BwAP21_4.d.ts} +9 -4
  44. package/dist/{provider-model-resolve-BpfXp3Jj.d.ts → provider-model-resolve-CwQNZWt_.d.ts} +3 -3
  45. package/dist/{provider-runner-CnOSr5BN.d.ts → provider-runner-CYHFImzV.d.ts} +3 -3
  46. package/dist/{retry-policy-Git9WF6d.d.ts → retry-policy-D4feSLk3.d.ts} +1 -1
  47. package/dist/sdd/index.d.ts +11 -10
  48. package/dist/sdd/index.js +2 -2
  49. package/dist/sdd/index.js.map +1 -1
  50. package/dist/secret-scrubber-3MHDDAtm.d.ts +6 -0
  51. package/dist/{secret-vault-DDSMHqIm.d.ts → secret-vault-CImt2XrR.d.ts} +1 -1
  52. package/dist/security/index.d.ts +6 -5
  53. package/dist/security/index.js.map +1 -1
  54. package/dist/{selector-Cq72C0Oy.d.ts → selector-Dy-MzKp1.d.ts} +1 -1
  55. package/dist/{session-event-bridge-DG94B3Bk.d.ts → session-event-bridge-CqdiGnfU.d.ts} +1 -1
  56. package/dist/{session-reader-BzT-iMQT.d.ts → session-reader-Hk0WbNm9.d.ts} +1 -1
  57. package/dist/{skill-DGIXCtdv.d.ts → skill-DHniprNl.d.ts} +15 -1
  58. package/dist/skills/index.d.ts +472 -26
  59. package/dist/skills/index.js +872 -129
  60. package/dist/skills/index.js.map +1 -1
  61. package/dist/storage/index.d.ts +27 -14
  62. package/dist/storage/index.js +264 -85
  63. package/dist/storage/index.js.map +1 -1
  64. package/dist/{strategy-compactor-Bt_ZH6R0.d.ts → strategy-compactor-CQwhbErd.d.ts} +32 -17
  65. package/dist/{todos-checkpoint-CH1pcua9.d.ts → todos-checkpoint-Bk2uP7Ex.d.ts} +6 -6
  66. package/dist/{context-DPlA6kid.d.ts → tool-BkOgs_KL.d.ts} +306 -286
  67. package/dist/{tool-executor-SVFq7IOR.d.ts → tool-executor-SiE1wlZo.d.ts} +9 -9
  68. package/dist/tools/index.d.ts +2 -2
  69. package/dist/tools/index.js.map +1 -1
  70. package/dist/types/index.d.ts +22 -21
  71. package/dist/types/index.js +7 -9
  72. package/dist/types/index.js.map +1 -1
  73. package/dist/utils/index.d.ts +30 -4
  74. package/dist/utils/index.js +50 -1
  75. package/dist/utils/index.js.map +1 -1
  76. package/dist/{worktree-manager-C4YIf1Fa.d.ts → worktree-manager-BjOFF6bt.d.ts} +1 -1
  77. package/dist/{wstack-paths-_NrRovdr.d.ts → wstack-paths-CMl_cYgq.d.ts} +8 -0
  78. package/package.json +1 -1
  79. package/skills/mailbox-bridge/SKILL.md +1 -0
  80. package/skills/plugin-author/SKILL.md +350 -0
  81. package/skills/sdd/SKILL.md +134 -134
  82. package/skills/skill-creator/SKILL.md +45 -7
  83. package/skills/wrongstack-mailbox/SKILL.md +40 -21
@@ -1,9 +1,10 @@
1
- import { Z as HqRedactionPolicy, r as HqEventEnvelope, U as HqPublisher, n as HqClientIdentity, aa as HqSocketFactory, G as GlobalMailbox, ah as HqTranscriptEntry } from '../global-mailbox-Dr4cTKqL.js';
2
- export { D as DEFAULT_HQ_REDACTION_POLICY, H as HQ_PROTOCOL_VERSION, a as HqAgentMessagePayload, b as HqAgentStatusPayload, c as HqAlertMessage, d as HqBrowserEventMessage, e as HqBrowserMessage, f as HqBrowserSnapshotMessage, g as HqClientCapability, h as HqClientCommandAckMessage, i as HqClientCommandPollMessage, j as HqClientEventMessage, k as HqClientHeartbeatPayload, l as HqClientHelloMessage, m as HqClientHelloPayload, o as HqClientKind, p as HqClientMessage, q as HqClientRecord, s as HqEventPayloadResult, t as HqEventType, u as HqFleetEventPayload, v as HqFleetSnapshotPayload, w as HqFleetSummary, x as HqGitSnapshotPayload, y as HqMachineRecord, z as HqMailboxAgentStatus, A as HqMailboxAgentSummary, B as HqMailboxEventAction, C as HqMailboxEventPayload, E as HqMailboxMappingOptions, F as HqMailboxMessageSummary, I as HqMailboxMessageType, J as HqMailboxPriority, K as HqMailboxSnapshotOptions, L as HqMailboxSnapshotPayload, M as HqMailboxSummary, N as HqParseResult, O as HqPathPolicy, P as HqProjectIdentity, Q as HqProjectRecord, R as HqProjectStatus, S as HqProtocolVersion, T as HqPublishEventOptions, V as HqPublisherCommandHandler, W as HqPublisherCommandResult, X as HqPublisherOptions, Y as HqQueuedCommand, _ as HqServerCommandBatchMessage, $ as HqServerMessage, a0 as HqSessionAgentLiveStatus, a1 as HqSessionAgentSummary, a2 as HqSessionEndedPayload, a3 as HqSessionLiveStatus, a4 as HqSessionSnapshotPayload, a5 as HqSessionStartedPayload, a6 as HqSessionStatus, a7 as HqSessionStatusPayload, a8 as HqSessionSummary, a9 as HqSnapshot, ab as HqSocketLike, ac as HqSubagentSummary, ad as HqToolArgsPolicy, ae as HqToolCompletedPayload, af as HqToolStartedPayload, ag as HqTranscriptAppendPayload, ai as HqTranscriptRole, aj as HqUsagePayload, ak as HqWelcomePayload, al as HqWorklistCounts, am as HqWorklistSnapshotPayload, an as HqWorkspaceKind, ao as createHqEventEnvelope, ap as createMailboxEventPayload, aq as createMailboxSnapshotPayload, ar as createMailboxSnapshotPayloadFromMailbox, as as mapMailboxAgentToHqSummary, at as mapMailboxMessageToHqSummary, au as parseHqEventPayload, av as parseHqFrame } from '../global-mailbox-Dr4cTKqL.js';
3
- import { E as EventBus, T as TrackedAgentSnapshot } from '../brain-CCfuEOdp.js';
4
- import { z as HqClientConfig } from '../config-DAOjriz9.js';
5
- import '../mailbox-types-DTl7bRH3.js';
6
- import '../context-DPlA6kid.js';
1
+ import { $ as HqRedactionPolicy, t as HqEventEnvelope, W as HqPublisher, p as HqClientIdentity, ac as HqSocketFactory, i as HqClientCapability, X as HqPublisherCommandHandler, G as GlobalMailbox, ab as HqSnapshot, _ as HqQueuedCommand, c as HqAlertMessage, aj as HqTranscriptEntry } from '../global-mailbox-Ct7IorLJ.js';
2
+ export { D as DEFAULT_HQ_REDACTION_POLICY, H as HQ_PROTOCOL_VERSION, a as HqAgentMessagePayload, b as HqAgentStatusPayload, d as HqBrainEventKind, e as HqBrainEventPayload, f as HqBrowserEventMessage, g as HqBrowserMessage, h as HqBrowserSnapshotMessage, j as HqClientCommandAckMessage, k as HqClientCommandPollMessage, l as HqClientEventMessage, m as HqClientHeartbeatPayload, n as HqClientHelloMessage, o as HqClientHelloPayload, q as HqClientKind, r as HqClientMessage, s as HqClientRecord, u as HqEventPayloadResult, v as HqEventType, w as HqFleetEventPayload, x as HqFleetSnapshotPayload, y as HqFleetSummary, z as HqGitSnapshotPayload, A as HqMachineRecord, B as HqMailboxAgentStatus, C as HqMailboxAgentSummary, E as HqMailboxEventAction, F as HqMailboxEventPayload, I as HqMailboxMappingOptions, J as HqMailboxMessageSummary, K as HqMailboxMessageType, L as HqMailboxPriority, M as HqMailboxSnapshotOptions, N as HqMailboxSnapshotPayload, O as HqMailboxSummary, P as HqParseResult, Q as HqPathPolicy, R as HqProjectIdentity, S as HqProjectRecord, T as HqProjectStatus, U as HqProtocolVersion, V as HqPublishEventOptions, Y as HqPublisherCommandResult, Z as HqPublisherOptions, a0 as HqServerCommandBatchMessage, a1 as HqServerMessage, a2 as HqSessionAgentLiveStatus, a3 as HqSessionAgentSummary, a4 as HqSessionEndedPayload, a5 as HqSessionLiveStatus, a6 as HqSessionSnapshotPayload, a7 as HqSessionStartedPayload, a8 as HqSessionStatus, a9 as HqSessionStatusPayload, aa as HqSessionSummary, ad as HqSocketLike, ae as HqSubagentSummary, af as HqToolArgsPolicy, ag as HqToolCompletedPayload, ah as HqToolStartedPayload, ai as HqTranscriptAppendPayload, ak as HqTranscriptRole, al as HqUsagePayload, am as HqWelcomePayload, an as HqWorklistCounts, ao as HqWorklistSnapshotPayload, ap as HqWorkspaceKind, aq as HqWorktreeEventKind, ar as HqWorktreeEventPayload, as as createHqEventEnvelope, at as createMailboxEventPayload, au as createMailboxSnapshotPayload, av as createMailboxSnapshotPayloadFromMailbox, aw as mapMailboxAgentToHqSummary, ax as mapMailboxMessageToHqSummary, ay as parseHqEventPayload, az as parseHqFrame } from '../global-mailbox-Ct7IorLJ.js';
3
+ import { E as EventBus, T as TrackedAgentSnapshot } from '../events-Bs2fmldo.js';
4
+ import { G as HqClientConfig } from '../config-Cr3312zc.js';
5
+ import '../mailbox-types-BGZWrYTJ.js';
6
+ import '../tool-BkOgs_KL.js';
7
+ import '../permission-Dx6dIqS2.js';
7
8
 
8
9
  interface HqRedactOptions {
9
10
  policy?: Partial<HqRedactionPolicy>;
@@ -33,7 +34,29 @@ interface HqPublisherEnvConfig {
33
34
  enabled?: boolean;
34
35
  rawContent?: boolean;
35
36
  projectAlias?: string;
37
+ /**
38
+ * Same-machine auto-discovery mode: no explicit URL was configured, so the
39
+ * publisher should re-resolve the endpoint from `<dataDir>/runtime.json`
40
+ * (+ the first client token in `auth.json`) before every connect attempt.
41
+ * This lets every client on the machine attach to a `wstack --hq` that is
42
+ * already running, starts later, or restarts on a different port.
43
+ */
44
+ discover?: boolean;
45
+ /** Resolved HQ data dir the discovery reads from. */
46
+ dataDir?: string;
36
47
  }
48
+ /**
49
+ * Discover a locally running `wstack --hq` endpoint: reads the runtime
50
+ * marker (pid-liveness-checked) and the first client token. Returns
51
+ * `undefined` when no live HQ is advertised on this machine.
52
+ */
53
+ declare function discoverLocalHqEndpoint(options?: {
54
+ dataDir?: string | undefined;
55
+ env?: NodeJS.ProcessEnv | undefined;
56
+ }): {
57
+ url: string;
58
+ token?: string | undefined;
59
+ } | undefined;
37
60
  declare function resolveHqConfigFromEnv(env?: NodeJS.ProcessEnv): HqPublisherEnvConfig | undefined;
38
61
  declare function resolveHqConfig(options?: {
39
62
  env?: NodeJS.ProcessEnv | undefined;
@@ -51,6 +74,12 @@ interface CreateHqPublisherOptions {
51
74
  hq?: HqClientConfig | undefined;
52
75
  } | undefined;
53
76
  redactionPolicy?: Partial<HqRedactionPolicy>;
77
+ /** Forwarded to the HqPublisher constructor (Phase 4 control plane). */
78
+ capabilities?: readonly HqClientCapability[];
79
+ /** Forwarded to the HqPublisher constructor (Phase 4 control plane). */
80
+ onCommand?: HqPublisherCommandHandler;
81
+ /** Dormant discovery re-check interval override (tests / tight loops). */
82
+ discoveryPollMs?: number;
54
83
  }
55
84
  declare function createHqPublisherFromEnv(options: CreateHqPublisherOptions): HqPublisher | undefined;
56
85
  interface CreateGlobalMailboxOptions {
@@ -82,6 +111,13 @@ declare function resolveHqDataDir(override?: string, env?: NodeJS.ProcessEnv): s
82
111
  * `/ws/browser`) and client tokens (validated on `/ws/client`). The two
83
112
  * are stored in separate lists so a browser-only token cannot be replayed
84
113
  * against the client channel and vice versa.
114
+ *
115
+ * `capabilities` scopes what a token may do. When absent the token is
116
+ * unrestricted (backward-compat with tokens minted before Phase 3). Known
117
+ * capability strings:
118
+ * - `control.enqueue` — browser token may enqueue commands to clients
119
+ * - `control.execute` — client token may execute `run-command` commands
120
+ * - `telemetry.publish` — client token may publish telemetry
85
121
  */
86
122
  interface HqToken {
87
123
  id: string;
@@ -89,7 +125,19 @@ interface HqToken {
89
125
  label?: string;
90
126
  createdAt: string;
91
127
  lastUsedAt?: string;
128
+ /**
129
+ * Optional capability scope. When absent, the token is unrestricted
130
+ * (backward-compat). When present, only the listed capabilities are
131
+ * granted.
132
+ */
133
+ capabilities?: string[];
92
134
  }
135
+ /**
136
+ * Check whether a token grants a capability. A token with no `capabilities`
137
+ * field is unrestricted (backward-compat). Otherwise the capability must be
138
+ * explicitly listed.
139
+ */
140
+ declare function tokenHasCapability(token: HqToken | undefined, capability: string): boolean;
93
141
  /**
94
142
  * Alias kept for backward-compat with Phase 3 callers/tests. New code
95
143
  * should prefer `HqToken`.
@@ -254,6 +302,455 @@ interface SessionTelemetryBridgeOptions {
254
302
  */
255
303
  declare function startSessionTelemetryBridge(opts: SessionTelemetryBridgeOptions): () => void;
256
304
 
305
+ /**
306
+ * FleetTelemetryBridge — forwards local multi-agent coordinator stats to the
307
+ * HQ publisher as `fleet.snapshot` envelopes, so the command center can render
308
+ * a global fleet roll-up (queued/completed/failed tasks, per-subagent status,
309
+ * fleet cost) across every connected machine.
310
+ *
311
+ * Source: the `coordinator.stats` EventBus event (originating on the FleetBus
312
+ * and re-emitted onto the host EventBus by `fleet/host.ts`). All payload
313
+ * fields are plain serializable data — no closures, no decoupled relay needed.
314
+ *
315
+ * The snapshot is republished on every `coordinator.stats` change (hash-dedup,
316
+ * mirroring {@link startSessionTelemetryBridge}) so the HQ browser sees live
317
+ * fleet counters without polling.
318
+ *
319
+ * @module hq/fleet-bridge
320
+ */
321
+
322
+ interface FleetTelemetryBridgeOptions {
323
+ /** Local EventBus emitting `coordinator.stats` (host EventBus after the FleetBus hop). */
324
+ events: EventBus;
325
+ /** HQ publisher to forward envelopes to. */
326
+ publisher: HqPublisher;
327
+ /** Coordinator run id — identifies this fleet instance. Falls back to a stable per-session id. */
328
+ runId: string;
329
+ /** Optional sessionId to tag envelopes with. */
330
+ sessionId?: string;
331
+ /** Override `now()` for deterministic tests. */
332
+ now?: () => string;
333
+ }
334
+ /**
335
+ * Start forwarding coordinator stats to HQ. Returns a disposer that
336
+ * unsubscribes the listener — call on shutdown.
337
+ */
338
+ declare function startFleetTelemetryBridge(opts: FleetTelemetryBridgeOptions): () => void;
339
+
340
+ /**
341
+ * BrainTelemetryBridge — forwards local Brain (decision layer) events to the
342
+ * HQ publisher as `brain.event` envelopes, so the command center can observe
343
+ * decision requests, answers, denials, ask-human escalations, and
344
+ * self-activated interventions across every connected machine.
345
+ *
346
+ * Source: the `brain.*` EventBus events emitted by `ObservableBrainArbiter`
347
+ * (`coordination/brain.ts`) and `BrainMonitor` (`coordination/brain-monitor.ts`).
348
+ * All payloads are plain serializable data (request id, question, source, risk,
349
+ * decision kind, rationale) — no closures, no decoupled relay needed.
350
+ *
351
+ * The webui `setup-events.ts` already forwards these verbatim to its browser;
352
+ * this bridge does the same for the cross-machine HQ plane.
353
+ *
354
+ * @module hq/brain-bridge
355
+ */
356
+
357
+ interface BrainTelemetryBridgeOptions {
358
+ /** Local EventBus emitting `brain.*` events. */
359
+ events: EventBus;
360
+ /** HQ publisher to forward envelopes to. */
361
+ publisher: HqPublisher;
362
+ /** Optional sessionId to tag envelopes with. */
363
+ sessionId?: string;
364
+ /** Override `now()` for deterministic tests. */
365
+ now?: () => string;
366
+ }
367
+ /**
368
+ * Start forwarding brain events to HQ. Returns a disposer that unsubscribes
369
+ * all listeners — call on shutdown.
370
+ */
371
+ declare function startBrainTelemetryBridge(opts: BrainTelemetryBridgeOptions): () => void;
372
+
373
+ /**
374
+ * WorktreeTelemetryBridge — forwards local git-worktree lifecycle events to
375
+ * the HQ publisher as `worktree.event` envelopes, so the command center can
376
+ * render live build phase swim-lanes / DAG across every connected machine.
377
+ *
378
+ * Source: the `worktree.*` EventBus events emitted by `WorktreeManager`
379
+ * (`worktree/worktree-manager.ts`): allocated, committed, merged, conflict,
380
+ * released, failed. All payload fields are plain serializable data
381
+ * (handleId, ownerId, branch, diff stats, conflict files) — no closures, no
382
+ * decoupled relay needed.
383
+ *
384
+ * @module hq/worktree-bridge
385
+ */
386
+
387
+ interface WorktreeTelemetryBridgeOptions {
388
+ /** Local EventBus emitting `worktree.*` events. */
389
+ events: EventBus;
390
+ /** HQ publisher to forward envelopes to. */
391
+ publisher: HqPublisher;
392
+ /** Optional sessionId to tag envelopes with. */
393
+ sessionId?: string;
394
+ /** Override `now()` for deterministic tests. */
395
+ now?: () => string;
396
+ }
397
+ /**
398
+ * Start forwarding worktree lifecycle events to HQ. Returns a disposer that
399
+ * unsubscribes all listeners — call on shutdown.
400
+ */
401
+ declare function startWorktreeTelemetryBridge(opts: WorktreeTelemetryBridgeOptions): () => void;
402
+
403
+ /**
404
+ * ToolTelemetryBridge — forwards local tool execution events to the HQ
405
+ * publisher as `tool.started` and `tool.completed` envelopes, so the command
406
+ * center can surface live tool activity (what's running, durations, success
407
+ * rates) across every connected machine.
408
+ *
409
+ * Sources:
410
+ * - `tool.started` (EventBus) → `tool.started` envelope. Raw tool input is
411
+ * summarized via {@link summarizeHqToolArgs} so no secrets or oversized
412
+ * payloads leak to the HQ browser.
413
+ * - `tool.executed` (EventBus) → `tool.completed` envelope (carries the
414
+ * richer post-execution signal: duration, ok/error, output bytes).
415
+ *
416
+ * All payload fields are plain serializable data — no closures. The
417
+ * `tool.started.input` raw args are the only sensitive surface and are
418
+ * reduced to a summary before publishing.
419
+ *
420
+ * @module hq/tool-bridge
421
+ */
422
+
423
+ interface ToolTelemetryBridgeOptions {
424
+ /** Local EventBus emitting `tool.started` and `tool.executed` events. */
425
+ events: EventBus;
426
+ /** HQ publisher to forward envelopes to. */
427
+ publisher: HqPublisher;
428
+ /** Project root for path redaction in tool input summaries. */
429
+ projectRoot?: string;
430
+ /** Optional sessionId to tag envelopes with. */
431
+ sessionId?: string;
432
+ /** Override `now()` for deterministic tests. */
433
+ now?: () => string;
434
+ }
435
+ /**
436
+ * Start forwarding tool execution events to HQ. Returns a disposer that
437
+ * unsubscribes all listeners — call on shutdown.
438
+ */
439
+ declare function startToolTelemetryBridge(opts: ToolTelemetryBridgeOptions): () => void;
440
+
441
+ /**
442
+ * CostTelemetryBridge — forwards local token/cost accounting events to the HQ
443
+ * publisher as `session.usage` envelopes, giving the command center the
444
+ * granular per-call cost signal it needs to render live cost trends and
445
+ * roll-ups across every connected machine.
446
+ *
447
+ * Source: the `token.accounted` EventBus event, emitted by the TokenCounter
448
+ * (`infrastructure/token-counter.ts`) after every provider call. The payload
449
+ * is plain serializable data (usage counts + a cost breakdown) — no closures.
450
+ *
451
+ * This is the high-frequency cost feed; HQ's persistence layer (Phase 2)
452
+ * time-buckets these into trend series.
453
+ *
454
+ * @module hq/cost-bridge
455
+ */
456
+
457
+ interface CostTelemetryBridgeOptions {
458
+ /** Local EventBus emitting `token.accounted`. */
459
+ events: EventBus;
460
+ /** HQ publisher to forward envelopes to. */
461
+ publisher: HqPublisher;
462
+ /** Optional sessionId to tag envelopes with (overrides the event's, when set). */
463
+ sessionId?: string;
464
+ /** Override `now()` for deterministic tests. */
465
+ now?: () => string;
466
+ }
467
+ /**
468
+ * Start forwarding token/cost events to HQ. Returns a disposer that
469
+ * unsubscribes the listener — call on shutdown.
470
+ */
471
+ declare function startCostTelemetryBridge(opts: CostTelemetryBridgeOptions): () => void;
472
+
473
+ interface HqEventLogOptions {
474
+ dataDir: string;
475
+ maxLines?: number;
476
+ rotateKeep?: number;
477
+ }
478
+ /**
479
+ * Append-only JSONL event log. Every received event envelope is appended to
480
+ * `events.jsonl`; when the file exceeds `maxLines` it is rotated under a file
481
+ * lock to keep only the most recent `rotateKeep` lines.
482
+ *
483
+ * Writes are serialized through a FIFO chain so concurrent appends never
484
+ * interleave. All operations are best-effort: a rejected append resolves
485
+ * (never rejects) and the caller's `await` never breaks the server loop.
486
+ */
487
+ declare class HqEventLog {
488
+ private readonly filePath;
489
+ private readonly maxLines;
490
+ private readonly rotateKeep;
491
+ private writeChain;
492
+ private lineCount;
493
+ private counted;
494
+ constructor(opts: HqEventLogOptions);
495
+ /** Append an event envelope as one JSON line. Best-effort, never rejects. */
496
+ append(event: HqEventEnvelope): void;
497
+ /** Resolves once all queued appends have settled. For tests. */
498
+ drain(): Promise<void>;
499
+ private appendInternal;
500
+ private rotate;
501
+ private countLines;
502
+ /**
503
+ * Read the most recent `limit` events, optionally filtered by envelope
504
+ * `type`. Newest first. Returns `[]` if the file doesn't exist yet.
505
+ */
506
+ recent(limit: number, typeFilter?: string): Promise<HqEventEnvelope[]>;
507
+ /** Initialize the line count cache from disk (call once at boot). */
508
+ hydrate(): Promise<void>;
509
+ }
510
+ interface HqSnapshotStoreOptions {
511
+ dataDir: string;
512
+ }
513
+ /**
514
+ * Atomic checkpoint of the latest snapshot, written to `snapshot.json`.
515
+ * The HQ server writes on every debounced broadcast and reads on boot to
516
+ * re-seed its in-memory state. Best-effort, never rejects.
517
+ */
518
+ declare class HqSnapshotStore {
519
+ private readonly filePath;
520
+ private writeChain;
521
+ constructor(opts: HqSnapshotStoreOptions);
522
+ /** Persist a snapshot. Best-effort, never rejects. */
523
+ save(snapshot: HqSnapshot): void;
524
+ /** Resolves once all queued saves have settled. For tests. */
525
+ drain(): Promise<void>;
526
+ /** Read the last persisted snapshot, or `null` if none. */
527
+ load(): Promise<HqSnapshot | null>;
528
+ }
529
+ interface HqTimeseriesSample {
530
+ /** Bucket start (epoch ms, floored to the bucket width). */
531
+ ts: number;
532
+ /** Total cost (USD) accumulated in this bucket. */
533
+ costUsd: number;
534
+ /** Total input tokens in this bucket. */
535
+ inputTokens: number;
536
+ /** Total output tokens in this bucket. */
537
+ outputTokens: number;
538
+ /** Number of tool executions in this bucket. */
539
+ toolCalls: number;
540
+ /** Snapshot of active agents at bucket close (last-write per bucket). */
541
+ activeAgents?: number;
542
+ }
543
+ interface HqTimeseriesStoreOptions {
544
+ dataDir: string;
545
+ /** Bucket width in ms. Default 5 minutes. */
546
+ bucketMs?: number;
547
+ /** How many buckets to retain. Default 2016 (1 week of 5-min buckets). */
548
+ maxBuckets?: number;
549
+ }
550
+ /**
551
+ * Time-bucketed cost + activity samples for trend charts. Each {@link record}
552
+ * call folds a cost/tool signal into the current bucket; {@link flush} writes
553
+ * the accumulated buckets to `timeseries.jsonl` (append under lock) and prunes
554
+ * to `maxBuckets`.
555
+ *
556
+ * The store keeps an in-memory ring of buckets for cheap reads; {@link load}
557
+ * rehydrates them on boot.
558
+ */
559
+ declare class HqTimeseriesStore {
560
+ private readonly filePath;
561
+ private readonly bucketMs;
562
+ private readonly maxBuckets;
563
+ private readonly buckets;
564
+ private flushChain;
565
+ constructor(opts: HqTimeseriesStoreOptions);
566
+ private bucketStart;
567
+ /** Fold a cost/tool signal into the current bucket. Best-effort. */
568
+ record(signal: {
569
+ ts?: number;
570
+ costUsd?: number;
571
+ inputTokens?: number;
572
+ outputTokens?: number;
573
+ toolCalls?: number;
574
+ activeAgents?: number;
575
+ }): void;
576
+ /** Persist accumulated buckets to disk (append under lock), prune to maxBuckets. */
577
+ flush(): void;
578
+ /** Resolves once all queued flushes have settled. For tests. */
579
+ drain(): Promise<void>;
580
+ private flushInternal;
581
+ /** Read buckets within `[since, now]`, oldest-first. */
582
+ read(sinceMs?: number): Promise<HqTimeseriesSample[]>;
583
+ /** Rehydrate buckets from disk (deduped, latest-per-bucket wins). */
584
+ load(): Promise<void>;
585
+ }
586
+ interface HqPersistence {
587
+ eventLog: HqEventLog;
588
+ snapshotStore: HqSnapshotStore;
589
+ timeseries: HqTimeseriesStore;
590
+ }
591
+ declare function createHqPersistence(dataDir: string): HqPersistence;
592
+
593
+ /**
594
+ * HQ control-plane command definitions — typed payloads for the commands the
595
+ * HQ dashboard can enqueue to connected machines (Phase 3+ of the HQ command
596
+ * center). These are carried over the existing `HqQueuedCommand` wire shape
597
+ * (`{commandId, type, payload, …}`) whose `type`/`payload` were previously
598
+ * type-erased. This module gives them a discriminated union for type-safe
599
+ * dispatch on the client side (Phase 4).
600
+ *
601
+ * Security model: `run-command` (raw shell) is gated by a per-token
602
+ * `control.execute` capability AND an operator opt-in; the other four commands
603
+ * route through the agent's own decision loop / mailbox and inherit their
604
+ * existing guardrails. See `docs/plans/hq-command-center-2026-07.md`.
605
+ *
606
+ * @module hq/commands
607
+ */
608
+
609
+ /** HQ_COMMAND_TYPES — the full set of recognized command `type` strings. */
610
+ declare const HQ_COMMAND_TYPES: readonly ["steer", "abort", "spawn", "broadcast", "run-command"];
611
+ type HqCommandType = (typeof HQ_COMMAND_TYPES)[number];
612
+ /** Inject a steer text into a target agent's conversation. */
613
+ interface HqSteerCommand {
614
+ type: 'steer';
615
+ /** Target agent address: a unique id (`leader@<tag>`), an alias (`leader`), or `*` for all. */
616
+ to: string;
617
+ subject: string;
618
+ body: string;
619
+ priority?: 'low' | 'normal' | 'high';
620
+ }
621
+ /** Abort a running agent run or fleet. */
622
+ interface HqAbortCommand {
623
+ type: 'abort';
624
+ /** `'leader'` aborts the session leader; a subagentId aborts one agent; `'fleet'` stops all. */
625
+ target: 'leader' | 'fleet' | string;
626
+ }
627
+ /** Spawn a subagent of the given role. */
628
+ interface HqSpawnCommand {
629
+ type: 'spawn';
630
+ role: string;
631
+ /** Optional task description for dispatch routing. */
632
+ task?: string;
633
+ maxIterations?: number;
634
+ }
635
+ /** Broadcast a mailbox message to all agents on the target's project. */
636
+ interface HqBroadcastCommand {
637
+ type: 'broadcast';
638
+ subject: string;
639
+ body: string;
640
+ priority?: 'low' | 'normal' | 'high';
641
+ }
642
+ /** Run a shell command on the target machine. GATED by `control.execute`. */
643
+ interface HqRunCommandCommand {
644
+ type: 'run-command';
645
+ command: string;
646
+ /** Optional working directory (defaults to the agent's project root). */
647
+ cwd?: string;
648
+ }
649
+ type HqCommand = HqSteerCommand | HqAbortCommand | HqSpawnCommand | HqBroadcastCommand | HqRunCommandCommand;
650
+ /**
651
+ * Validate that an inbound `HqQueuedCommand` has a recognized `type` and a
652
+ * minimally well-formed payload. Returns the narrowed command on success, or
653
+ * `null` when the command should be rejected.
654
+ *
655
+ * This is a shape check, not a security gate — capability enforcement happens
656
+ * at enqueue time (browser token must have `control.enqueue`) and at execute
657
+ * time (`run-command` requires `control.execute`).
658
+ */
659
+ declare function validateHqCommand(queued: HqQueuedCommand): HqCommand | null;
660
+ interface HqCommandAuditEntry {
661
+ commandId: string;
662
+ type: HqCommandType;
663
+ clientId: string;
664
+ /** Who enqueued the command (browser token id, or 'anonymous' in open mode). */
665
+ enqueuedBy: string;
666
+ enqueuedAt: string;
667
+ status: 'queued' | 'delivered' | 'acked';
668
+ /** Ack status when the client has responded. */
669
+ ackStatus?: 'accepted' | 'completed' | 'failed' | 'rejected';
670
+ ackMessage?: string;
671
+ ackedAt?: string;
672
+ }
673
+ /**
674
+ * In-memory command audit ring. Capped; the Phase 2 persistence layer can
675
+ * sink entries to disk when wired (future). For now this gives the server a
676
+ * queryable history for `/api/commands` and snapshot enrichment.
677
+ */
678
+ declare class HqCommandAuditLog {
679
+ private readonly entries;
680
+ private readonly max;
681
+ constructor(max?: number);
682
+ record(entry: HqCommandAuditEntry): void;
683
+ update(commandId: string, patch: Partial<HqCommandAuditEntry>): void;
684
+ recent(limit?: number): HqCommandAuditEntry[];
685
+ }
686
+
687
+ /**
688
+ * HQ alerting engine — evaluates the current snapshot against a set of
689
+ * operator-configurable rules and emits `hq.alert` messages when a threshold
690
+ * is crossed. Mirrors the BrainMonitor's self-activation logic (tool-failure
691
+ * streaks, error storms) but at the fleet-wide command-center scope.
692
+ *
693
+ * Rules are evaluated on a periodic tick (default 15s, unref'd) against the
694
+ * latest in-memory snapshot. Deduplication prevents alert storms: a rule that
695
+ * is still firing is not re-emitted until it clears (state machine per rule).
696
+ *
697
+ * @module hq/alerts
698
+ */
699
+
700
+ /** Severity levels for alerts, mirroring {@link HqAlertMessage}. */
701
+ type HqAlertSeverity = HqAlertMessage['severity'];
702
+ interface HqAlert {
703
+ id: string;
704
+ ruleId: string;
705
+ severity: HqAlertSeverity;
706
+ message: string;
707
+ /** Epoch ms when the alert first fired in its current episode. */
708
+ firstFiredAt: number;
709
+ /** Epoch ms of the most recent evaluation that confirmed the alert. */
710
+ lastFiredAt: number;
711
+ }
712
+ interface HqAlertRuleConfig {
713
+ /** Maximum cost (USD) across the whole fleet before alerting. Default 50. */
714
+ costThresholdUsd?: number;
715
+ /** Seconds of silence from ALL machines before a stale alert fires. Default 120. */
716
+ staleMachineSeconds?: number;
717
+ /** Minimum number of active agents before concurrency alert fires. Default: disabled (0). */
718
+ maxAgents?: number;
719
+ }
720
+ /**
721
+ * In-memory alert state. Tracks which rules are currently firing so the same
722
+ * alert is not re-emitted every tick — only state transitions (cleared →
723
+ * firing) emit. Optionally persists to disk via a callback.
724
+ */
725
+ declare class HqAlertEngine {
726
+ private readonly active;
727
+ private readonly history;
728
+ private readonly maxHistory;
729
+ private timer;
730
+ private readonly onAlert;
731
+ constructor(opts: {
732
+ onAlert: (alert: HqAlert) => void;
733
+ maxHistory?: number;
734
+ });
735
+ /**
736
+ * Evaluate all rules against the snapshot. Emits (via the `onAlert`
737
+ * callback) only for rules that newly transition to firing. Clears rules
738
+ * that are no longer firing. Returns the list of newly-fired alerts.
739
+ */
740
+ evaluate(snapshot: HqSnapshot | null, config?: HqAlertRuleConfig, now?: number): HqAlert[];
741
+ /** Currently-active (firing) alerts. */
742
+ activeAlerts(): HqAlert[];
743
+ /** Historical alerts (newest-last), capped at maxHistory. */
744
+ recentAlerts(limit?: number): HqAlert[];
745
+ /**
746
+ * Start periodic evaluation against a snapshot getter. The timer is
747
+ * unref'd so it never keeps the process alive. Returns a disposer.
748
+ */
749
+ startPeriodic(getSnapshot: () => HqSnapshot | null, config?: HqAlertRuleConfig | (() => HqAlertRuleConfig | undefined), intervalMs?: number): () => void;
750
+ }
751
+ /** Map an internal {@link HqAlert} to the wire {@link HqAlertMessage}. */
752
+ declare function toAlertMessage(alert: HqAlert): HqAlertMessage;
753
+
257
754
  /**
258
755
  * Transcript mapper — converts raw session JSONL events into the canonical
259
756
  * {@link HqTranscriptEntry} shape used by HQ for full chat-history rendering.
@@ -290,4 +787,4 @@ declare function mergeToolResults(flat: readonly HqTranscriptEntry[]): HqTranscr
290
787
  */
291
788
  declare function buildTranscriptFromEvents(events: Iterable<Record<string, unknown>>): HqTranscriptEntry[];
292
789
 
293
- export { type AgentMonitorEventBridgeOptions, type CreateGlobalMailboxOptions, type CreateHqPublisherOptions, type EnsureHqFirstRunAuthResult, HQ_AUTH_FILE_VERSION, type HqAgentEventPublisher, type HqAuthFile, type HqBrowserToken, HqClientIdentity, HqEventEnvelope, HqPublisher, type HqPublisherEnvConfig, type HqRedactOptions, HqRedactionPolicy, type HqRedactionResult, type HqRuntimeFile, HqSocketFactory, type HqToken, HqTranscriptEntry, type SessionTelemetryBridgeOptions, buildTranscriptFromEvents, createGlobalMailbox, createHqPublisherFromEnv, defaultHqDataDir, emptyHqAuthFile, ensureHqFirstRunAuthFile, hqAuthFilePath, hqRuntimeFilePath, mapSessionEventToEntries, mergeToolResults, mintHqBrowserToken, mintHqToken, mutateHqAuthFile, readHqAuthFile, readHqRuntimeFileSync, redactHqEvent, redactHqValue, resolveHqConfig, resolveHqConfigFromEnv, resolveHqDataDir, scrubAndTruncateHqPreview, startAgentMonitorEventBridge, startSessionTelemetryBridge, summarizeHqToolArgs, watchHqAuthFile, writeHqAuthFile, writeHqRuntimeFile };
790
+ export { type AgentMonitorEventBridgeOptions, type BrainTelemetryBridgeOptions, type CostTelemetryBridgeOptions, type CreateGlobalMailboxOptions, type CreateHqPublisherOptions, type EnsureHqFirstRunAuthResult, type FleetTelemetryBridgeOptions, HQ_AUTH_FILE_VERSION, HQ_COMMAND_TYPES, type HqAbortCommand, type HqAgentEventPublisher, type HqAlert, HqAlertEngine, HqAlertMessage, type HqAlertRuleConfig, type HqAlertSeverity, type HqAuthFile, type HqBroadcastCommand, type HqBrowserToken, HqClientCapability, HqClientIdentity, type HqCommand, type HqCommandAuditEntry, HqCommandAuditLog, type HqCommandType, HqEventEnvelope, HqEventLog, type HqEventLogOptions, type HqPersistence, HqPublisher, HqPublisherCommandHandler, type HqPublisherEnvConfig, HqQueuedCommand, type HqRedactOptions, HqRedactionPolicy, type HqRedactionResult, type HqRunCommandCommand, type HqRuntimeFile, HqSnapshot, HqSnapshotStore, type HqSnapshotStoreOptions, HqSocketFactory, type HqSpawnCommand, type HqSteerCommand, type HqTimeseriesSample, HqTimeseriesStore, type HqTimeseriesStoreOptions, type HqToken, HqTranscriptEntry, type SessionTelemetryBridgeOptions, type ToolTelemetryBridgeOptions, type WorktreeTelemetryBridgeOptions, buildTranscriptFromEvents, createGlobalMailbox, createHqPersistence, createHqPublisherFromEnv, defaultHqDataDir, discoverLocalHqEndpoint, emptyHqAuthFile, ensureHqFirstRunAuthFile, hqAuthFilePath, hqRuntimeFilePath, mapSessionEventToEntries, mergeToolResults, mintHqBrowserToken, mintHqToken, mutateHqAuthFile, readHqAuthFile, readHqRuntimeFileSync, redactHqEvent, redactHqValue, resolveHqConfig, resolveHqConfigFromEnv, resolveHqDataDir, scrubAndTruncateHqPreview, startAgentMonitorEventBridge, startBrainTelemetryBridge, startCostTelemetryBridge, startFleetTelemetryBridge, startSessionTelemetryBridge, startToolTelemetryBridge, startWorktreeTelemetryBridge, summarizeHqToolArgs, toAlertMessage, tokenHasCapability, validateHqCommand, watchHqAuthFile, writeHqAuthFile, writeHqRuntimeFile };