@zyaochen/weaverbird 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.en.md +418 -0
- package/README.md +418 -2
- package/apps/wb-bot/README.md +118 -0
- package/dist/apps/wb-bot/src/agent-display.js +24 -0
- package/dist/apps/wb-bot/src/agent-registry.js +188 -0
- package/dist/apps/wb-bot/src/approval-gate/audit.js +37 -0
- package/dist/apps/wb-bot/src/approval-gate/cards.js +94 -0
- package/dist/apps/wb-bot/src/approval-gate/hook-env.js +15 -0
- package/dist/apps/wb-bot/src/approval-gate/hook-files.js +311 -0
- package/dist/apps/wb-bot/src/approval-gate/hook-main.js +147 -0
- package/dist/apps/wb-bot/src/approval-gate/notifier.js +29 -0
- package/dist/apps/wb-bot/src/approval-gate/store.js +157 -0
- package/dist/apps/wb-bot/src/binding/migration-runner.js +35 -0
- package/dist/apps/wb-bot/src/binding/migrations/001-add-run-id-agent-id.js +8 -0
- package/dist/apps/wb-bot/src/binding/migrations/002-add-bot-id.js +34 -0
- package/dist/apps/wb-bot/src/binding/migrations/003-inflight-card-agent-id-pk.js +31 -0
- package/dist/apps/wb-bot/src/binding/migrations/004-thread-alias-topic-key.js +31 -0
- package/dist/apps/wb-bot/src/binding/migrations/005-card-entity.js +21 -0
- package/dist/apps/wb-bot/src/binding/migrations/006-group-setting.js +17 -0
- package/dist/apps/wb-bot/src/binding/schema.js +58 -0
- package/dist/apps/wb-bot/src/binding/sleep-sync.js +5 -0
- package/dist/apps/wb-bot/src/binding/store.js +270 -0
- package/dist/apps/wb-bot/src/binding/task-index.js +127 -0
- package/dist/apps/wb-bot/src/boot/entry-path.js +9 -0
- package/dist/apps/wb-bot/src/boot/integrity.js +47 -0
- package/dist/apps/wb-bot/src/boot/logger.js +44 -0
- package/dist/apps/wb-bot/src/captain/bot-discovery.js +42 -0
- package/dist/apps/wb-bot/src/captain/captain-context.js +26 -0
- package/dist/apps/wb-bot/src/captain/captain-gate.js +9 -0
- package/dist/apps/wb-bot/src/captain/captain-status.js +101 -0
- package/dist/apps/wb-bot/src/captain/captain-stop-all.js +72 -0
- package/dist/apps/wb-bot/src/captain/list-bots.js +39 -0
- package/dist/apps/wb-bot/src/cli/doctor.js +105 -0
- package/dist/apps/wb-bot/src/cli/init.js +122 -0
- package/dist/apps/wb-bot/src/cli/parse-args.js +31 -0
- package/dist/apps/wb-bot/src/cli/preflight.js +9 -0
- package/dist/apps/wb-bot/src/cli/setup-checklist.js +10 -0
- package/dist/apps/wb-bot/src/commands/health.js +328 -0
- package/dist/apps/wb-bot/src/commands/history.js +100 -0
- package/dist/apps/wb-bot/src/commands/logs.js +91 -0
- package/dist/apps/wb-bot/src/commands/parser.js +43 -0
- package/dist/apps/wb-bot/src/commands/queue-metrics.js +24 -0
- package/dist/apps/wb-bot/src/commands/resume.js +48 -0
- package/dist/apps/wb-bot/src/commands/router.js +299 -0
- package/dist/apps/wb-bot/src/commands/status.js +77 -0
- package/dist/apps/wb-bot/src/commands/tasks.js +106 -0
- package/dist/apps/wb-bot/src/commands/wb-approval.js +86 -0
- package/dist/apps/wb-bot/src/commands/wb-audit.js +46 -0
- package/dist/apps/wb-bot/src/commands/wb-mute.js +84 -0
- package/dist/apps/wb-bot/src/commands/wb-sync.js +58 -0
- package/dist/apps/wb-bot/src/config/approval-code-owners.js +95 -0
- package/dist/apps/wb-bot/src/config/bot-env.js +80 -0
- package/dist/apps/wb-bot/src/config/config-paths.js +16 -0
- package/dist/apps/wb-bot/src/config/env.js +43 -0
- package/dist/apps/wb-bot/src/config/lark-credentials.js +14 -0
- package/dist/apps/wb-bot/src/e2e/preflight-env.js +147 -0
- package/dist/apps/wb-bot/src/e2e/preflight-main.js +12 -0
- package/dist/apps/wb-bot/src/feishu/admin-alert.js +94 -0
- package/dist/apps/wb-bot/src/feishu/artifacts.js +95 -0
- package/dist/apps/wb-bot/src/feishu/bot-identity.js +38 -0
- package/dist/apps/wb-bot/src/feishu/card-pipeline.js +121 -0
- package/dist/apps/wb-bot/src/feishu/card-renderer.js +360 -0
- package/dist/apps/wb-bot/src/feishu/card-transport.js +294 -0
- package/dist/apps/wb-bot/src/feishu/chat-mode-cache.js +47 -0
- package/dist/apps/wb-bot/src/feishu/completion-push.js +30 -0
- package/dist/apps/wb-bot/src/feishu/doc-comment.js +183 -0
- package/dist/apps/wb-bot/src/feishu/event-handler.js +2634 -0
- package/dist/apps/wb-bot/src/feishu/events-file-reader.js +162 -0
- package/dist/apps/wb-bot/src/feishu/inbound-context.js +53 -0
- package/dist/apps/wb-bot/src/feishu/keepalive.js +85 -0
- package/dist/apps/wb-bot/src/feishu/log-redact.js +20 -0
- package/dist/apps/wb-bot/src/feishu/markdown-style.js +95 -0
- package/dist/apps/wb-bot/src/feishu/media-cache.js +92 -0
- package/dist/apps/wb-bot/src/feishu/message-parser.js +126 -0
- package/dist/apps/wb-bot/src/feishu/pending-queue.js +133 -0
- package/dist/apps/wb-bot/src/feishu/reaction.js +44 -0
- package/dist/apps/wb-bot/src/feishu/reverse-at-im-handler.js +345 -0
- package/dist/apps/wb-bot/src/feishu/run-state.js +30 -0
- package/dist/apps/wb-bot/src/feishu/session-short-id.js +9 -0
- package/dist/apps/wb-bot/src/feishu/stream-state.js +72 -0
- package/dist/apps/wb-bot/src/feishu/topic-key.js +34 -0
- package/dist/apps/wb-bot/src/feishu/transport.js +768 -0
- package/dist/apps/wb-bot/src/feishu/wb-runner-spawner.js +84 -0
- package/dist/apps/wb-bot/src/heartbeat/bot-heartbeat.js +20 -0
- package/dist/apps/wb-bot/src/main.js +144 -0
- package/dist/apps/wb-bot/src/multi/discovery.js +53 -0
- package/dist/apps/wb-bot/src/multi/main.js +57 -0
- package/dist/apps/wb-bot/src/multi/parse-args.js +17 -0
- package/dist/apps/wb-bot/src/multi/supervisor.js +288 -0
- package/dist/apps/wb-bot/src/run-observability/orchestrator.js +61 -0
- package/dist/apps/wb-bot/src/security/bot-id-validator.js +18 -0
- package/dist/apps/wb-bot/src/security/cwd-guard.js +72 -0
- package/dist/apps/wb-bot/src/security/env-whitelist.js +94 -0
- package/dist/apps/wb-bot/src/server/wire-up.js +125 -0
- package/dist/apps/wb-cli/src/commands/approval.js +101 -0
- package/dist/apps/wb-cli/src/commands/attach.js +31 -0
- package/dist/apps/wb-cli/src/commands/audit.js +71 -0
- package/dist/apps/wb-cli/src/commands/captain.js +72 -0
- package/dist/apps/wb-cli/src/commands/debug.js +22 -0
- package/dist/apps/wb-cli/src/commands/history.js +75 -0
- package/dist/apps/wb-cli/src/commands/list.js +24 -0
- package/dist/apps/wb-cli/src/commands/logs.js +122 -0
- package/dist/apps/wb-cli/src/commands/resume.js +50 -0
- package/dist/apps/wb-cli/src/commands/runs.js +75 -0
- package/dist/apps/wb-cli/src/commands/status.js +35 -0
- package/dist/apps/wb-cli/src/commands/watch.js +73 -0
- package/dist/apps/wb-cli/src/main.js +312 -0
- package/dist/packages/core/src/agent/claude-code.js +354 -0
- package/dist/packages/core/src/agent/cli-subprocess.js +244 -0
- package/dist/packages/core/src/agent/codex.js +231 -0
- package/dist/packages/core/src/agent/index.js +5 -0
- package/dist/packages/core/src/agent/registry.js +47 -0
- package/dist/packages/core/src/agent/types.js +1 -0
- package/dist/packages/core/src/approval-gate/audit.js +16 -0
- package/dist/packages/core/src/approval-gate/contracts.js +26 -0
- package/dist/packages/core/src/approval-gate/matcher.js +112 -0
- package/dist/packages/core/src/audit-pipe/audit-pipe-main.js +38 -0
- package/dist/packages/core/src/audit-pipe/bitable-sink.js +156 -0
- package/dist/packages/core/src/audit-pipe/config.js +105 -0
- package/dist/packages/core/src/audit-pipe/contracts.js +33 -0
- package/dist/packages/core/src/audit-pipe/index.js +2 -0
- package/dist/packages/core/src/audit-pipe/mirror-sink.js +21 -0
- package/dist/packages/core/src/audit-pipe/normalizer.js +129 -0
- package/dist/packages/core/src/audit-pipe/orchestrator.js +252 -0
- package/dist/packages/core/src/audit-pipe/parser.js +24 -0
- package/dist/packages/core/src/audit-pipe/tailer.js +46 -0
- package/dist/packages/core/src/audit-pipe/wal.js +71 -0
- package/dist/packages/core/src/calendar-hook/config.js +45 -0
- package/dist/packages/core/src/calendar-hook/contracts.js +66 -0
- package/dist/packages/core/src/calendar-hook/index.js +5 -0
- package/dist/packages/core/src/calendar-hook/scheduler.js +169 -0
- package/dist/packages/core/src/calendar-hook/service.js +189 -0
- package/dist/packages/core/src/calendar-hook/transport.js +66 -0
- package/dist/packages/core/src/captain/captain-service.js +160 -0
- package/dist/packages/core/src/captain/command-catalog.js +41 -0
- package/dist/packages/core/src/captain/concurrency-config.js +10 -0
- package/dist/packages/core/src/captain/concurrency-queue-index.js +94 -0
- package/dist/packages/core/src/captain/concurrency-queue-store.js +43 -0
- package/dist/packages/core/src/captain/contracts.js +102 -0
- package/dist/packages/core/src/captain/cwd-inference.js +29 -0
- package/dist/packages/core/src/captain/enqueue-or-spawn.js +63 -0
- package/dist/packages/core/src/captain/index.js +27 -0
- package/dist/packages/core/src/captain/queue-metrics/aggregator.js +98 -0
- package/dist/packages/core/src/captain/queue-metrics/contracts.js +42 -0
- package/dist/packages/core/src/captain/queue-metrics/event-store.js +26 -0
- package/dist/packages/core/src/captain/session-store.js +429 -0
- package/dist/packages/core/src/captain/toml-loader.js +86 -0
- package/dist/packages/core/src/config/errors.js +15 -0
- package/dist/packages/core/src/config/registry.js +34 -0
- package/dist/packages/core/src/errors/codes.js +98 -0
- package/dist/packages/core/src/group-sync/autodoc.js +166 -0
- package/dist/packages/core/src/group-sync/config.js +45 -0
- package/dist/packages/core/src/group-sync/contracts.js +126 -0
- package/dist/packages/core/src/group-sync/dispatch.js +163 -0
- package/dist/packages/core/src/group-sync/index.js +9 -0
- package/dist/packages/core/src/group-sync/revdiff.js +138 -0
- package/dist/packages/core/src/group-sync/scheduler.js +93 -0
- package/dist/packages/core/src/group-sync/service.js +79 -0
- package/dist/packages/core/src/group-sync/transport.js +97 -0
- package/dist/packages/core/src/group-sync/xref.js +139 -0
- package/dist/packages/core/src/index.js +23 -0
- package/dist/packages/core/src/minutes/adapter.js +187 -0
- package/dist/packages/core/src/minutes/client.js +46 -0
- package/dist/packages/core/src/minutes/contracts.js +36 -0
- package/dist/packages/core/src/minutes/index.js +3 -0
- package/dist/packages/core/src/paths.js +158 -0
- package/dist/packages/core/src/periodic-tasks/config.js +45 -0
- package/dist/packages/core/src/periodic-tasks/contracts.js +75 -0
- package/dist/packages/core/src/periodic-tasks/index.js +4 -0
- package/dist/packages/core/src/periodic-tasks/orchestrator.js +249 -0
- package/dist/packages/core/src/periodic-tasks/state.js +29 -0
- package/dist/packages/core/src/reverse-channel/attach-handler.js +108 -0
- package/dist/packages/core/src/reverse-channel/audit-encoder.js +61 -0
- package/dist/packages/core/src/reverse-channel/contracts.js +136 -0
- package/dist/packages/core/src/reverse-channel/echo-tailer.js +36 -0
- package/dist/packages/core/src/reverse-channel/handoff.js +238 -0
- package/dist/packages/core/src/reverse-channel/index.js +5 -0
- package/dist/packages/core/src/reverse-channel/ipc-client.js +110 -0
- package/dist/packages/core/src/reverse-channel/ipc-control-handler.js +27 -0
- package/dist/packages/core/src/reverse-channel/ipc-server.js +127 -0
- package/dist/packages/core/src/reverse-channel/mute-registry.js +113 -0
- package/dist/packages/core/src/reverse-channel/pid-resolver.js +41 -0
- package/dist/packages/core/src/reverse-channel/reverse-at-handler.js +19 -0
- package/dist/packages/core/src/reverse-channel/sla-tracker.js +51 -0
- package/dist/packages/core/src/run-observability/alert-card-renderer.js +24 -0
- package/dist/packages/core/src/run-observability/alert-pusher.js +47 -0
- package/dist/packages/core/src/run-observability/card-refresher.js +31 -0
- package/dist/packages/core/src/run-observability/card-renderer-progress.js +33 -0
- package/dist/packages/core/src/run-observability/config-loader.js +23 -0
- package/dist/packages/core/src/run-observability/contracts.js +107 -0
- package/dist/packages/core/src/run-observability/exit-code-detector.js +16 -0
- package/dist/packages/core/src/run-observability/finalizer.js +114 -0
- package/dist/packages/core/src/run-observability/index.js +12 -0
- package/dist/packages/core/src/run-observability/obs-toggle-handler.js +29 -0
- package/dist/packages/core/src/run-observability/progress-collector.js +53 -0
- package/dist/packages/core/src/run-observability/progress-store.js +100 -0
- package/dist/packages/core/src/run-observability/silent-timeout-detector.js +12 -0
- package/dist/packages/core/src/run-registry/bitable-writer.js +308 -0
- package/dist/packages/core/src/run-registry/config.js +77 -0
- package/dist/packages/core/src/run-registry/contracts.js +114 -0
- package/dist/packages/core/src/run-registry/doc-sink-classifier.js +0 -0
- package/dist/packages/core/src/run-registry/doc-sink-transport.js +63 -0
- package/dist/packages/core/src/run-registry/doc-sink.js +200 -0
- package/dist/packages/core/src/run-registry/extractor.js +40 -0
- package/dist/packages/core/src/run-registry/index.js +11 -0
- package/dist/packages/core/src/run-registry/inherit.js +11 -0
- package/dist/packages/core/src/run-registry/orchestrator.js +86 -0
- package/dist/packages/core/src/run-registry/run-registry-main.js +38 -0
- package/dist/packages/core/src/run-registry/tailer.js +390 -0
- package/dist/packages/core/src/run-registry/wal.js +106 -0
- package/dist/packages/core/src/runner/event-replay.js +65 -0
- package/dist/packages/core/src/runner/wb-runner-main.js +27 -0
- package/dist/packages/core/src/runner/wb-runner.js +237 -0
- package/dist/packages/core/src/util/entry-module.js +21 -0
- package/dist/packages/core/src/util/ndjson-rotation.js +99 -0
- package/package.json +76 -4
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname } from 'node:path';
|
|
3
|
+
import { runCalendarHookStatePath } from '../paths.js';
|
|
4
|
+
import { CalendarHookStateSchema } from './contracts.js';
|
|
5
|
+
import { withTimeout } from './transport.js';
|
|
6
|
+
function atomicWrite(path, content) {
|
|
7
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
8
|
+
const temp = `${path}.tmp`;
|
|
9
|
+
writeFileSync(temp, content);
|
|
10
|
+
renameSync(temp, path);
|
|
11
|
+
}
|
|
12
|
+
function readState(path, runId, dueAt) {
|
|
13
|
+
if (!existsSync(path)) {
|
|
14
|
+
return CalendarHookStateSchema.parse({
|
|
15
|
+
run_id: runId,
|
|
16
|
+
session_id: null,
|
|
17
|
+
open_revision_applied: null,
|
|
18
|
+
close_revision_applied: null,
|
|
19
|
+
calendar_block_id: null,
|
|
20
|
+
calendar_hook_failed: false,
|
|
21
|
+
desired_state: 'open',
|
|
22
|
+
due_at: dueAt,
|
|
23
|
+
overdue_escalated_at: null,
|
|
24
|
+
last_error: null,
|
|
25
|
+
updated_at: new Date().toISOString(),
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
return CalendarHookStateSchema.parse(JSON.parse(readFileSync(path, 'utf8')));
|
|
29
|
+
}
|
|
30
|
+
function writeState(path, state) {
|
|
31
|
+
atomicWrite(path, JSON.stringify(state, null, 2));
|
|
32
|
+
}
|
|
33
|
+
function lockPath(statePath) {
|
|
34
|
+
return `${statePath}.lock`;
|
|
35
|
+
}
|
|
36
|
+
function acquireLock(path) {
|
|
37
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
38
|
+
try {
|
|
39
|
+
return openSync(path, 'wx');
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function releaseLock(path, fd) {
|
|
46
|
+
if (fd === null)
|
|
47
|
+
return;
|
|
48
|
+
try {
|
|
49
|
+
closeSync(fd);
|
|
50
|
+
}
|
|
51
|
+
finally {
|
|
52
|
+
try {
|
|
53
|
+
unlinkSync(path);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
// ignore cleanup failure
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
export async function openCalendarBlock(options) {
|
|
61
|
+
const statePath = runCalendarHookStatePath(options.dataDir, options.runId, options.botId ?? 'default');
|
|
62
|
+
const state = readState(statePath, options.runId, options.endsAt);
|
|
63
|
+
if (state.open_revision_applied !== null && state.open_revision_applied >= options.revision && state.calendar_block_id) {
|
|
64
|
+
return { calendar_block_id: state.calendar_block_id, calendar_hook_failed: state.calendar_hook_failed, state };
|
|
65
|
+
}
|
|
66
|
+
const fd = acquireLock(lockPath(statePath));
|
|
67
|
+
if (fd === null) {
|
|
68
|
+
return { calendar_block_id: state.calendar_block_id, calendar_hook_failed: state.calendar_hook_failed, state };
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
writeState(statePath, CalendarHookStateSchema.parse({
|
|
72
|
+
...state,
|
|
73
|
+
session_id: options.sessionId,
|
|
74
|
+
desired_state: 'open',
|
|
75
|
+
due_at: options.endsAt,
|
|
76
|
+
updated_at: new Date().toISOString(),
|
|
77
|
+
}));
|
|
78
|
+
const result = await withTimeout(options.transport.openBlock({
|
|
79
|
+
run_id: options.runId,
|
|
80
|
+
session_id: options.sessionId,
|
|
81
|
+
revision: options.revision,
|
|
82
|
+
title: options.title,
|
|
83
|
+
starts_at: options.startsAt,
|
|
84
|
+
ends_at: options.endsAt,
|
|
85
|
+
}), options.config.rpc_timeout_ms, 'calendar open timeout');
|
|
86
|
+
const latestState = readState(statePath, options.runId, options.endsAt);
|
|
87
|
+
const nextState = CalendarHookStateSchema.parse({
|
|
88
|
+
...latestState,
|
|
89
|
+
session_id: options.sessionId,
|
|
90
|
+
open_revision_applied: options.revision,
|
|
91
|
+
calendar_block_id: result.calendar_block_id,
|
|
92
|
+
calendar_hook_failed: false,
|
|
93
|
+
desired_state: latestState.desired_state,
|
|
94
|
+
due_at: options.endsAt,
|
|
95
|
+
last_error: null,
|
|
96
|
+
updated_at: new Date().toISOString(),
|
|
97
|
+
});
|
|
98
|
+
writeState(statePath, nextState);
|
|
99
|
+
if (nextState.desired_state === 'closed' && nextState.close_revision_applied !== null) {
|
|
100
|
+
try {
|
|
101
|
+
await withTimeout(options.transport.closeBlock({
|
|
102
|
+
run_id: options.runId,
|
|
103
|
+
revision: nextState.close_revision_applied,
|
|
104
|
+
calendar_block_id: result.calendar_block_id,
|
|
105
|
+
}), options.config.rpc_timeout_ms, 'calendar close timeout');
|
|
106
|
+
const closedState = CalendarHookStateSchema.parse({
|
|
107
|
+
...nextState,
|
|
108
|
+
calendar_hook_failed: false,
|
|
109
|
+
last_error: null,
|
|
110
|
+
updated_at: new Date().toISOString(),
|
|
111
|
+
});
|
|
112
|
+
writeState(statePath, closedState);
|
|
113
|
+
return { calendar_block_id: closedState.calendar_block_id, calendar_hook_failed: false, state: closedState };
|
|
114
|
+
}
|
|
115
|
+
catch (closeError) {
|
|
116
|
+
const failedClosedState = CalendarHookStateSchema.parse({
|
|
117
|
+
...nextState,
|
|
118
|
+
calendar_hook_failed: true,
|
|
119
|
+
last_error: closeError instanceof Error ? closeError.message : String(closeError),
|
|
120
|
+
updated_at: new Date().toISOString(),
|
|
121
|
+
});
|
|
122
|
+
writeState(statePath, failedClosedState);
|
|
123
|
+
return { calendar_block_id: failedClosedState.calendar_block_id, calendar_hook_failed: true, state: failedClosedState };
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return { calendar_block_id: nextState.calendar_block_id, calendar_hook_failed: false, state: nextState };
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
const nextState = CalendarHookStateSchema.parse({
|
|
130
|
+
...state,
|
|
131
|
+
session_id: options.sessionId,
|
|
132
|
+
desired_state: 'open',
|
|
133
|
+
due_at: options.endsAt,
|
|
134
|
+
calendar_hook_failed: true,
|
|
135
|
+
last_error: error instanceof Error ? error.message : String(error),
|
|
136
|
+
updated_at: new Date().toISOString(),
|
|
137
|
+
});
|
|
138
|
+
writeState(statePath, nextState);
|
|
139
|
+
return { calendar_block_id: nextState.calendar_block_id, calendar_hook_failed: true, state: nextState };
|
|
140
|
+
}
|
|
141
|
+
finally {
|
|
142
|
+
releaseLock(lockPath(statePath), fd);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
export async function closeCalendarBlock(options) {
|
|
146
|
+
const statePath = runCalendarHookStatePath(options.dataDir, options.runId, options.botId ?? 'default');
|
|
147
|
+
const state = readState(statePath, options.runId, null);
|
|
148
|
+
if (!state.calendar_block_id) {
|
|
149
|
+
return { calendar_block_id: null, calendar_hook_failed: state.calendar_hook_failed, state };
|
|
150
|
+
}
|
|
151
|
+
if (state.close_revision_applied !== null && state.close_revision_applied >= options.revision) {
|
|
152
|
+
return { calendar_block_id: state.calendar_block_id, calendar_hook_failed: state.calendar_hook_failed, state };
|
|
153
|
+
}
|
|
154
|
+
const fd = acquireLock(lockPath(statePath));
|
|
155
|
+
if (fd === null) {
|
|
156
|
+
return { calendar_block_id: state.calendar_block_id, calendar_hook_failed: state.calendar_hook_failed, state };
|
|
157
|
+
}
|
|
158
|
+
try {
|
|
159
|
+
await withTimeout(options.transport.closeBlock({
|
|
160
|
+
run_id: options.runId,
|
|
161
|
+
revision: options.revision,
|
|
162
|
+
calendar_block_id: state.calendar_block_id,
|
|
163
|
+
}), options.config.rpc_timeout_ms, 'calendar close timeout');
|
|
164
|
+
const nextState = CalendarHookStateSchema.parse({
|
|
165
|
+
...state,
|
|
166
|
+
close_revision_applied: options.revision,
|
|
167
|
+
calendar_hook_failed: false,
|
|
168
|
+
desired_state: 'closed',
|
|
169
|
+
last_error: null,
|
|
170
|
+
updated_at: new Date().toISOString(),
|
|
171
|
+
});
|
|
172
|
+
writeState(statePath, nextState);
|
|
173
|
+
return { calendar_block_id: nextState.calendar_block_id, calendar_hook_failed: false, state: nextState };
|
|
174
|
+
}
|
|
175
|
+
catch (error) {
|
|
176
|
+
const nextState = CalendarHookStateSchema.parse({
|
|
177
|
+
...state,
|
|
178
|
+
calendar_hook_failed: true,
|
|
179
|
+
desired_state: 'closed',
|
|
180
|
+
last_error: error instanceof Error ? error.message : String(error),
|
|
181
|
+
updated_at: new Date().toISOString(),
|
|
182
|
+
});
|
|
183
|
+
writeState(statePath, nextState);
|
|
184
|
+
return { calendar_block_id: nextState.calendar_block_id, calendar_hook_failed: true, state: nextState };
|
|
185
|
+
}
|
|
186
|
+
finally {
|
|
187
|
+
releaseLock(lockPath(statePath), fd);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname } from 'node:path';
|
|
3
|
+
import { calendarMockTriggersPath } from '../paths.js';
|
|
4
|
+
import { CalendarBlockResultSchema } from './contracts.js';
|
|
5
|
+
function atomicWrite(path, content) {
|
|
6
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
7
|
+
const temp = `${path}.tmp`;
|
|
8
|
+
writeFileSync(temp, content);
|
|
9
|
+
renameSync(temp, path);
|
|
10
|
+
}
|
|
11
|
+
function readMockBlocks(path) {
|
|
12
|
+
if (!existsSync(path))
|
|
13
|
+
return {};
|
|
14
|
+
try {
|
|
15
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return {};
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export function createMockCalendarTransport(dataDir) {
|
|
22
|
+
const statePath = calendarMockTriggersPath(dataDir).replace('mock-triggers.json', 'mock-blocks.json');
|
|
23
|
+
return {
|
|
24
|
+
async openBlock(input) {
|
|
25
|
+
const blocks = readMockBlocks(statePath);
|
|
26
|
+
const existing = blocks[input.run_id];
|
|
27
|
+
if (existing?.open) {
|
|
28
|
+
return CalendarBlockResultSchema.parse({ calendar_block_id: existing.calendar_block_id });
|
|
29
|
+
}
|
|
30
|
+
const calendar_block_id = `cal_${input.run_id}`;
|
|
31
|
+
blocks[input.run_id] = { calendar_block_id, open: true };
|
|
32
|
+
atomicWrite(statePath, JSON.stringify(blocks, null, 2));
|
|
33
|
+
return CalendarBlockResultSchema.parse({ calendar_block_id });
|
|
34
|
+
},
|
|
35
|
+
async closeBlock(input) {
|
|
36
|
+
const blocks = readMockBlocks(statePath);
|
|
37
|
+
const existing = blocks[input.run_id];
|
|
38
|
+
if (existing) {
|
|
39
|
+
blocks[input.run_id] = { ...existing, open: false };
|
|
40
|
+
atomicWrite(statePath, JSON.stringify(blocks, null, 2));
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
export function withTimeout(promise, timeoutMs, message) {
|
|
46
|
+
return new Promise((resolve, reject) => {
|
|
47
|
+
const timer = setTimeout(() => reject(new Error(message)), timeoutMs);
|
|
48
|
+
void promise.then((value) => {
|
|
49
|
+
clearTimeout(timer);
|
|
50
|
+
resolve(value);
|
|
51
|
+
}, (error) => {
|
|
52
|
+
clearTimeout(timer);
|
|
53
|
+
reject(error);
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
export function createGuardedCliCalendarTransport() {
|
|
58
|
+
return {
|
|
59
|
+
async openBlock() {
|
|
60
|
+
throw new Error('calendar cli transport requires explicit real-device authorization');
|
|
61
|
+
},
|
|
62
|
+
async closeBlock() {
|
|
63
|
+
throw new Error('calendar cli transport requires explicit real-device authorization');
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import { mkdirSync } from 'node:fs';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { captainStatePath } from '../paths.js';
|
|
4
|
+
import { appendNdjsonLine, readNdjsonSegments } from '../util/ndjson-rotation.js';
|
|
5
|
+
import { CAPTAIN_ERROR_CODES, CaptainError, } from './contracts.js';
|
|
6
|
+
function ensureDir(path) {
|
|
7
|
+
mkdirSync(path, { recursive: true });
|
|
8
|
+
}
|
|
9
|
+
export class CaptainService {
|
|
10
|
+
sessions = new Map();
|
|
11
|
+
mirrorPath;
|
|
12
|
+
store;
|
|
13
|
+
nowFn;
|
|
14
|
+
constructor(options) {
|
|
15
|
+
this.mirrorPath = options.mirrorPath ?? captainStatePath(options.dataDir);
|
|
16
|
+
this.store = options.store;
|
|
17
|
+
this.nowFn = options.nowFn ?? (() => new Date().toISOString());
|
|
18
|
+
ensureDir(join(this.mirrorPath, '..'));
|
|
19
|
+
}
|
|
20
|
+
getSession(sessionId) {
|
|
21
|
+
const entry = this.sessions.get(sessionId);
|
|
22
|
+
return entry ? { record: { ...entry.record }, run_ids: [...entry.run_ids], dirty: entry.dirty } : undefined;
|
|
23
|
+
}
|
|
24
|
+
listActiveSessions() {
|
|
25
|
+
return [...this.sessions.values()]
|
|
26
|
+
.filter((entry) => entry.record.status === 'active' || entry.record.status === 'suspended')
|
|
27
|
+
.map((entry) => ({ record: { ...entry.record }, run_ids: [...entry.run_ids], dirty: entry.dirty }));
|
|
28
|
+
}
|
|
29
|
+
createSession(input) {
|
|
30
|
+
const record = {
|
|
31
|
+
...input,
|
|
32
|
+
status: 'idle',
|
|
33
|
+
closed_at: null,
|
|
34
|
+
revision: input.revision ?? 0,
|
|
35
|
+
};
|
|
36
|
+
const entry = { record, run_ids: [], dirty: true };
|
|
37
|
+
this.sessions.set(record.session_id, entry);
|
|
38
|
+
this.writeMirror({ ts: this.nowFn(), op: 'upsert', session: record });
|
|
39
|
+
return this.getSession(record.session_id);
|
|
40
|
+
}
|
|
41
|
+
updateSession(sessionId, patch) {
|
|
42
|
+
const entry = this.requireSession(sessionId);
|
|
43
|
+
entry.record = { ...entry.record, ...patch };
|
|
44
|
+
entry.dirty = true;
|
|
45
|
+
this.writeMirror({ ts: this.nowFn(), op: 'upsert', session: entry.record });
|
|
46
|
+
return this.getSession(sessionId);
|
|
47
|
+
}
|
|
48
|
+
bindRun(sessionId, runId) {
|
|
49
|
+
const entry = this.requireSession(sessionId);
|
|
50
|
+
if (entry.record.status === 'closed') {
|
|
51
|
+
throw new CaptainError(CAPTAIN_ERROR_CODES.E_SESSION_NOT_FOUND, `session ${sessionId} already closed`);
|
|
52
|
+
}
|
|
53
|
+
if (entry.record.status !== 'idle' && entry.record.status !== 'suspended' && entry.record.status !== 'active') {
|
|
54
|
+
throw new CaptainError(CAPTAIN_ERROR_CODES.E_SESSION_NOT_FOUND, `session ${sessionId} cannot bind run from ${entry.record.status}`);
|
|
55
|
+
}
|
|
56
|
+
if (!entry.run_ids.includes(runId))
|
|
57
|
+
entry.run_ids.push(runId);
|
|
58
|
+
entry.record = {
|
|
59
|
+
...entry.record,
|
|
60
|
+
status: 'active',
|
|
61
|
+
latest_run_id: runId,
|
|
62
|
+
last_active_at: this.nowFn(),
|
|
63
|
+
closed_at: null,
|
|
64
|
+
};
|
|
65
|
+
entry.dirty = true;
|
|
66
|
+
this.writeMirror({ ts: this.nowFn(), op: 'upsert', session: entry.record });
|
|
67
|
+
}
|
|
68
|
+
suspendSession(sessionId) {
|
|
69
|
+
const entry = this.requireSession(sessionId);
|
|
70
|
+
if (entry.record.status !== 'active') {
|
|
71
|
+
throw new CaptainError(CAPTAIN_ERROR_CODES.E_SESSION_NOT_FOUND, `session ${sessionId} cannot suspend from ${entry.record.status}`);
|
|
72
|
+
}
|
|
73
|
+
entry.record = { ...entry.record, status: 'suspended', last_active_at: this.nowFn() };
|
|
74
|
+
entry.dirty = true;
|
|
75
|
+
this.writeMirror({ ts: this.nowFn(), op: 'upsert', session: entry.record });
|
|
76
|
+
}
|
|
77
|
+
closeSession(sessionId) {
|
|
78
|
+
const entry = this.requireSession(sessionId);
|
|
79
|
+
if (entry.record.status !== 'active' && entry.record.status !== 'suspended') {
|
|
80
|
+
throw new CaptainError(CAPTAIN_ERROR_CODES.E_SESSION_NOT_FOUND, `session ${sessionId} cannot close from ${entry.record.status}`);
|
|
81
|
+
}
|
|
82
|
+
entry.record = {
|
|
83
|
+
...entry.record,
|
|
84
|
+
status: 'closed',
|
|
85
|
+
closed_at: this.nowFn(),
|
|
86
|
+
last_active_at: this.nowFn(),
|
|
87
|
+
};
|
|
88
|
+
entry.dirty = true;
|
|
89
|
+
this.writeMirror({ ts: this.nowFn(), op: 'close', session: entry.record });
|
|
90
|
+
}
|
|
91
|
+
async flush() {
|
|
92
|
+
const store = this.store;
|
|
93
|
+
if (!store?.upsert)
|
|
94
|
+
return;
|
|
95
|
+
for (const entry of this.sessions.values()) {
|
|
96
|
+
if (!entry.dirty)
|
|
97
|
+
continue;
|
|
98
|
+
// M12-A (2026-08-04 owner-authorized, resolves PRD Q5 last-write-wins):
|
|
99
|
+
// Cross-device attach relies on CAS to detect "the other host already moved the
|
|
100
|
+
// row". If the store surface does not offer upsertWithRevision, fall back to the
|
|
101
|
+
// simple upsert to preserve legacy single-host behaviour.
|
|
102
|
+
const storeWithCas = store;
|
|
103
|
+
if (typeof storeWithCas.upsertWithRevision === 'function') {
|
|
104
|
+
const expected = entry.record.revision;
|
|
105
|
+
const result = await storeWithCas.upsertWithRevision(entry.record, expected);
|
|
106
|
+
entry.record = { ...entry.record, revision: result.newRevision };
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
await store.upsert(entry.record);
|
|
110
|
+
}
|
|
111
|
+
entry.dirty = false;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
async reconcile() {
|
|
115
|
+
const storeSessions = this.store?.reconcile ? await this.store.reconcile() : [];
|
|
116
|
+
const mirrorSessions = this.readMirrorSnapshot();
|
|
117
|
+
const merged = new Map();
|
|
118
|
+
for (const record of mirrorSessions.values())
|
|
119
|
+
merged.set(record.session_id, record);
|
|
120
|
+
for (const record of storeSessions) {
|
|
121
|
+
const existing = merged.get(record.session_id);
|
|
122
|
+
if (!existing || Date.parse(record.last_active_at) > Date.parse(existing.last_active_at)) {
|
|
123
|
+
merged.set(record.session_id, record);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
for (const record of merged.values()) {
|
|
127
|
+
const entry = this.sessions.get(record.session_id);
|
|
128
|
+
this.sessions.set(record.session_id, {
|
|
129
|
+
record,
|
|
130
|
+
run_ids: entry?.run_ids ?? (record.latest_run_id ? [record.latest_run_id] : []),
|
|
131
|
+
dirty: false,
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
requireSession(sessionId) {
|
|
136
|
+
const entry = this.sessions.get(sessionId);
|
|
137
|
+
if (!entry) {
|
|
138
|
+
throw new CaptainError(CAPTAIN_ERROR_CODES.E_SESSION_NOT_FOUND, `session ${sessionId} not found`);
|
|
139
|
+
}
|
|
140
|
+
return entry;
|
|
141
|
+
}
|
|
142
|
+
writeMirror(entry) {
|
|
143
|
+
appendNdjsonLine(this.mirrorPath, JSON.stringify(entry), { fsync: true });
|
|
144
|
+
}
|
|
145
|
+
readMirrorSnapshot() {
|
|
146
|
+
const latest = new Map();
|
|
147
|
+
for (const line of readNdjsonSegments(this.mirrorPath)) {
|
|
148
|
+
if (!line.trim())
|
|
149
|
+
continue;
|
|
150
|
+
try {
|
|
151
|
+
const parsed = JSON.parse(line);
|
|
152
|
+
latest.set(parsed.session.session_id, parsed.session);
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return latest;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { CAPTAIN_ERROR_CODES, CaptainError, CommandCatalogEntrySchema } from './contracts.js';
|
|
2
|
+
export const COMMAND_CATALOG = {
|
|
3
|
+
history: CommandCatalogEntrySchema.parse({ name: 'history', aliases: ['/wb history', 'wb history'], belongs_to: 'both', capability_tags: ['run-registry', 'read-only'], im_visible: true, cli_visible: true, description: 'Query run history from Run Registry' }),
|
|
4
|
+
resume: CommandCatalogEntrySchema.parse({ name: 'resume', aliases: ['/wb resume --inherit', 'wb resume --inherit'], belongs_to: 'both', capability_tags: ['run-registry', 'session'], im_visible: true, cli_visible: true, description: 'Resume from an inherited run' }),
|
|
5
|
+
health: CommandCatalogEntrySchema.parse({ name: 'health', aliases: ['/health', 'wb health'], belongs_to: 'both', capability_tags: ['ops', 'health'], im_visible: true, cli_visible: true, description: 'Show health checks' }),
|
|
6
|
+
status: CommandCatalogEntrySchema.parse({ name: 'status', aliases: ['/status', 'wb status'], belongs_to: 'both', capability_tags: ['ops', 'session'], im_visible: true, cli_visible: true, description: 'Show current session status' }),
|
|
7
|
+
logs: CommandCatalogEntrySchema.parse({ name: 'logs', aliases: ['/logs', 'wb logs'], belongs_to: 'both', capability_tags: ['ops', 'read-only'], im_visible: true, cli_visible: true, description: 'Show run logs' }),
|
|
8
|
+
'list-agents': CommandCatalogEntrySchema.parse({ name: 'list-agents', aliases: ['/list-agents', '/agents', 'wb list-agents'], belongs_to: 'both', capability_tags: ['agent-registry'], im_visible: true, cli_visible: true, description: 'List registered agents' }),
|
|
9
|
+
use: CommandCatalogEntrySchema.parse({ name: 'use', aliases: ['/use', 'wb use'], belongs_to: 'both', capability_tags: ['agent-binding'], im_visible: true, cli_visible: true, description: 'Switch current agent' }),
|
|
10
|
+
help: CommandCatalogEntrySchema.parse({ name: 'help', aliases: ['/help', 'wb --help'], belongs_to: 'both', capability_tags: ['discoverability'], im_visible: true, cli_visible: true, description: 'Show command help' }),
|
|
11
|
+
captain: CommandCatalogEntrySchema.parse({ name: 'captain', aliases: ['/wb captain', 'wb captain'], belongs_to: 'both', capability_tags: ['captain'], im_visible: true, cli_visible: true, description: 'List known captains and current binding' }),
|
|
12
|
+
list: CommandCatalogEntrySchema.parse({ name: 'list', aliases: ['wb list', 'wb list --all-captains'], belongs_to: 'cli', capability_tags: ['captain', 'aggregation'], im_visible: false, cli_visible: true, description: 'Aggregate captain-visible runs (all captains)' }),
|
|
13
|
+
audit: CommandCatalogEntrySchema.parse({ name: 'audit', aliases: ['wb audit', '/wb audit'], belongs_to: 'both', capability_tags: ['audit-pipe', 'read-only'], im_visible: true, cli_visible: true, description: 'View local audit mirror tail (M12-D / M13-F)' }),
|
|
14
|
+
approval: CommandCatalogEntrySchema.parse({ name: 'approval', aliases: ['wb approval', '/wb approval'], belongs_to: 'both', capability_tags: ['approval-gate', 'read-only'], im_visible: true, cli_visible: true, description: 'List local approval gate queue (M12-D / M13-F)' }),
|
|
15
|
+
watch: CommandCatalogEntrySchema.parse({ name: 'watch', aliases: ['wb watch', '/wb watch'], belongs_to: 'cli', capability_tags: ['reverse-channel', 'stream'], im_visible: false, cli_visible: true, description: 'Tail reverse-channel IPC events for a session (M12-D)' }),
|
|
16
|
+
'captain-use': CommandCatalogEntrySchema.parse({ name: 'captain-use', aliases: ['wb captain use'], belongs_to: 'cli', capability_tags: ['captain', 'binding'], im_visible: false, cli_visible: true, description: 'Bind current CLI session to a captain' }),
|
|
17
|
+
attach: CommandCatalogEntrySchema.parse({ name: 'attach', aliases: ['wb attach'], belongs_to: 'cli', capability_tags: ['reverse-channel.attach'], im_visible: false, cli_visible: true, description: 'Attach a CLI session to an existing captain session' }),
|
|
18
|
+
'pause-im': CommandCatalogEntrySchema.parse({ name: 'pause-im', aliases: ['@wb pause <run_id>'], belongs_to: 'bot', capability_tags: ['reverse-channel.pause'], im_visible: false, cli_visible: false, description: 'Reverse @ pause trigger from IM sender' }),
|
|
19
|
+
'resume-im': CommandCatalogEntrySchema.parse({ name: 'resume-im', aliases: ['@wb resume <run_id>'], belongs_to: 'bot', capability_tags: ['reverse-channel.resume'], im_visible: false, cli_visible: false, description: 'Reverse @ resume trigger from IM sender' }),
|
|
20
|
+
'cancel-im': CommandCatalogEntrySchema.parse({ name: 'cancel-im', aliases: ['@wb cancel <run_id>'], belongs_to: 'bot', capability_tags: ['reverse-channel.cancel'], im_visible: false, cli_visible: false, description: 'Reverse @ cancel trigger from IM sender' }),
|
|
21
|
+
runs: CommandCatalogEntrySchema.parse({ name: 'runs', aliases: ['wb runs'], belongs_to: 'cli', capability_tags: ['run-registry'], im_visible: false, cli_visible: true, description: 'List recent runs' }),
|
|
22
|
+
debug: CommandCatalogEntrySchema.parse({ name: 'debug', aliases: ['wb debug'], belongs_to: 'cli', capability_tags: ['debug'], im_visible: false, cli_visible: true, description: 'Run an agent in foreground debug mode' }),
|
|
23
|
+
now: CommandCatalogEntrySchema.parse({ name: 'now', aliases: ['/now'], belongs_to: 'bot', capability_tags: ['session'], im_visible: true, cli_visible: false, description: 'Show current thread binding' }),
|
|
24
|
+
'reset-context': CommandCatalogEntrySchema.parse({ name: 'reset-context', aliases: ['/reset-context'], belongs_to: 'bot', capability_tags: ['session'], im_visible: true, cli_visible: false, description: 'Clear current continuation token' }),
|
|
25
|
+
stop: CommandCatalogEntrySchema.parse({ name: 'stop', aliases: ['/stop'], belongs_to: 'bot', capability_tags: ['ops'], im_visible: true, cli_visible: false, description: 'Stop current run' }),
|
|
26
|
+
'stop-all': CommandCatalogEntrySchema.parse({ name: 'stop-all', aliases: ['/stop-all'], belongs_to: 'bot', capability_tags: ['ops', 'captain'], im_visible: true, cli_visible: false, description: 'Send stop signal to all active runs' }),
|
|
27
|
+
follow: CommandCatalogEntrySchema.parse({ name: 'follow', aliases: ['/follow'], belongs_to: 'bot', capability_tags: ['notifications'], im_visible: true, cli_visible: false, description: 'Notify when current thread finishes' }),
|
|
28
|
+
tasks: CommandCatalogEntrySchema.parse({ name: 'tasks', aliases: ['/tasks'], belongs_to: 'bot', capability_tags: ['history'], im_visible: true, cli_visible: false, description: 'Show task history' }),
|
|
29
|
+
'list-bots': CommandCatalogEntrySchema.parse({ name: 'list-bots', aliases: ['/list-bots'], belongs_to: 'bot', capability_tags: ['captain'], im_visible: true, cli_visible: false, description: 'List configured bots' }),
|
|
30
|
+
cwd: CommandCatalogEntrySchema.parse({ name: 'cwd', aliases: ['/cwd'], belongs_to: 'bot', capability_tags: ['cwd'], im_visible: true, cli_visible: false, description: 'Set thread cwd' }),
|
|
31
|
+
'cwd-add': CommandCatalogEntrySchema.parse({ name: 'cwd-add', aliases: ['/cwd-add'], belongs_to: 'bot', capability_tags: ['cwd'], im_visible: true, cli_visible: false, description: 'Add cwd alias' }),
|
|
32
|
+
'cwd-list': CommandCatalogEntrySchema.parse({ name: 'cwd-list', aliases: ['/cwd-list'], belongs_to: 'bot', capability_tags: ['cwd'], im_visible: true, cli_visible: false, description: 'List cwd aliases' }),
|
|
33
|
+
'cwd-rm': CommandCatalogEntrySchema.parse({ name: 'cwd-rm', aliases: ['/cwd-rm'], belongs_to: 'bot', capability_tags: ['cwd'], im_visible: true, cli_visible: false, description: 'Remove cwd alias' }),
|
|
34
|
+
sync: CommandCatalogEntrySchema.parse({ name: 'sync', aliases: ['/wb sync'], belongs_to: 'bot', capability_tags: ['group-sync'], im_visible: true, cli_visible: false, description: 'Trigger a one-shot group sync mock run (M11-C)' }),
|
|
35
|
+
};
|
|
36
|
+
export function validateCatalog(registeredCommands) {
|
|
37
|
+
const missing = registeredCommands.filter((command) => !COMMAND_CATALOG[command]);
|
|
38
|
+
if (missing.length > 0) {
|
|
39
|
+
throw new CaptainError(CAPTAIN_ERROR_CODES.E_CATALOG_INCOMPLETE, `missing commands in catalog: ${missing.join(', ')}`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { loadConfig } from '../config/registry.js';
|
|
3
|
+
export const ConcurrencyConfigSchema = z.object({
|
|
4
|
+
max_concurrent_runs: z.number().int().positive().default(1),
|
|
5
|
+
queue_max_depth: z.number().int().nonnegative().default(10),
|
|
6
|
+
});
|
|
7
|
+
export function loadConcurrencyConfig(dataDir) {
|
|
8
|
+
const defaults = ConcurrencyConfigSchema.parse({});
|
|
9
|
+
return loadConfig(dataDir, 'captain', ConcurrencyConfigSchema, defaults);
|
|
10
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { ConcurrencyQueueEntryStatus, } from './concurrency-queue-store.js';
|
|
2
|
+
function getSessionState(state, sessionId) {
|
|
3
|
+
const existing = state.get(sessionId);
|
|
4
|
+
if (existing)
|
|
5
|
+
return existing;
|
|
6
|
+
const created = { queued: [], running: [], entries: new Map() };
|
|
7
|
+
state.set(sessionId, created);
|
|
8
|
+
return created;
|
|
9
|
+
}
|
|
10
|
+
function removeRun(runs, runId) {
|
|
11
|
+
const index = runs.indexOf(runId);
|
|
12
|
+
if (index >= 0)
|
|
13
|
+
runs.splice(index, 1);
|
|
14
|
+
}
|
|
15
|
+
function sumCounts(state, key, sessionId) {
|
|
16
|
+
if (sessionId)
|
|
17
|
+
return getSessionState(state, sessionId)[key].length;
|
|
18
|
+
return [...state.values()].reduce((total, item) => total + item[key].length, 0);
|
|
19
|
+
}
|
|
20
|
+
export function createConcurrencyQueueIndex(metrics) {
|
|
21
|
+
const state = new Map();
|
|
22
|
+
function publishGauges(sessionId) {
|
|
23
|
+
if (!metrics)
|
|
24
|
+
return;
|
|
25
|
+
const session = getSessionState(state, sessionId);
|
|
26
|
+
metrics.record({
|
|
27
|
+
metric: 'captain_queue_depth',
|
|
28
|
+
value: session.queued.length,
|
|
29
|
+
labels: { session_id: sessionId },
|
|
30
|
+
});
|
|
31
|
+
metrics.record({
|
|
32
|
+
metric: 'captain_queue_running_total',
|
|
33
|
+
value: session.running.length,
|
|
34
|
+
labels: { session_id: sessionId },
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
function apply(entry) {
|
|
38
|
+
const session = getSessionState(state, entry.session_id);
|
|
39
|
+
session.entries.set(entry.run_id, entry);
|
|
40
|
+
if (entry.status === ConcurrencyQueueEntryStatus.QUEUED) {
|
|
41
|
+
removeRun(session.running, entry.run_id);
|
|
42
|
+
if (!session.queued.includes(entry.run_id))
|
|
43
|
+
session.queued.push(entry.run_id);
|
|
44
|
+
publishGauges(entry.session_id);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
if (entry.status === ConcurrencyQueueEntryStatus.RUNNING) {
|
|
48
|
+
removeRun(session.queued, entry.run_id);
|
|
49
|
+
if (!session.running.includes(entry.run_id))
|
|
50
|
+
session.running.push(entry.run_id);
|
|
51
|
+
publishGauges(entry.session_id);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
removeRun(session.queued, entry.run_id);
|
|
55
|
+
removeRun(session.running, entry.run_id);
|
|
56
|
+
publishGauges(entry.session_id);
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
enqueue(sessionId, runId, ts) {
|
|
60
|
+
apply({ session_id: sessionId, run_id: runId, status: ConcurrencyQueueEntryStatus.QUEUED, ts });
|
|
61
|
+
},
|
|
62
|
+
markRunning(sessionId, runId, ts) {
|
|
63
|
+
apply({ session_id: sessionId, run_id: runId, status: ConcurrencyQueueEntryStatus.RUNNING, ts });
|
|
64
|
+
},
|
|
65
|
+
markEnded(sessionId, runId, ts) {
|
|
66
|
+
apply({ session_id: sessionId, run_id: runId, status: ConcurrencyQueueEntryStatus.ENDED, ts });
|
|
67
|
+
},
|
|
68
|
+
listQueued(sessionId) {
|
|
69
|
+
return [...getSessionState(state, sessionId).queued];
|
|
70
|
+
},
|
|
71
|
+
listRunning(sessionId) {
|
|
72
|
+
return [...getSessionState(state, sessionId).running];
|
|
73
|
+
},
|
|
74
|
+
listQueuedEntries(sessionId) {
|
|
75
|
+
const session = getSessionState(state, sessionId);
|
|
76
|
+
return session.queued.map((runId) => session.entries.get(runId)).filter(Boolean);
|
|
77
|
+
},
|
|
78
|
+
listRunningEntries(sessionId) {
|
|
79
|
+
const session = getSessionState(state, sessionId);
|
|
80
|
+
return session.running.map((runId) => session.entries.get(runId)).filter(Boolean);
|
|
81
|
+
},
|
|
82
|
+
countQueued(sessionId) {
|
|
83
|
+
return sumCounts(state, 'queued', sessionId);
|
|
84
|
+
},
|
|
85
|
+
countRunning(sessionId) {
|
|
86
|
+
return sumCounts(state, 'running', sessionId);
|
|
87
|
+
},
|
|
88
|
+
replay(entries) {
|
|
89
|
+
state.clear();
|
|
90
|
+
for (const entry of entries)
|
|
91
|
+
apply(entry);
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { mkdirSync } from 'node:fs';
|
|
2
|
+
import { appendNdjsonLine, readNdjsonSegments } from '../util/ndjson-rotation.js';
|
|
3
|
+
import { captainDir, captainQueuePath } from '../paths.js';
|
|
4
|
+
import { getCaptainProcessQueueMetrics } from './index.js';
|
|
5
|
+
export const ConcurrencyQueueEntryStatus = {
|
|
6
|
+
QUEUED: 'queued',
|
|
7
|
+
RUNNING: 'running',
|
|
8
|
+
ENDED: 'ended',
|
|
9
|
+
};
|
|
10
|
+
export function createConcurrencyQueueStore(dataDir) {
|
|
11
|
+
const dir = captainDir(dataDir);
|
|
12
|
+
const path = captainQueuePath(dataDir);
|
|
13
|
+
mkdirSync(dir, { recursive: true });
|
|
14
|
+
return {
|
|
15
|
+
path,
|
|
16
|
+
append(entry) {
|
|
17
|
+
appendNdjsonLine(path, JSON.stringify(entry));
|
|
18
|
+
},
|
|
19
|
+
readAll() {
|
|
20
|
+
const entries = [];
|
|
21
|
+
for (const line of readNdjsonSegments(path)) {
|
|
22
|
+
if (!line.trim())
|
|
23
|
+
continue;
|
|
24
|
+
try {
|
|
25
|
+
entries.push(JSON.parse(line));
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
try {
|
|
29
|
+
getCaptainProcessQueueMetrics()?.record({
|
|
30
|
+
metric: 'captain_queue_store_read_errors_total',
|
|
31
|
+
value: 1,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
// best-effort metrics hook only
|
|
36
|
+
}
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
return entries;
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
}
|