@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,429 @@
|
|
|
1
|
+
import * as Lark from '@larksuiteoapi/node-sdk';
|
|
2
|
+
import { chmodSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join, resolve } from 'node:path';
|
|
5
|
+
import { loadConfig } from '../config/registry.js';
|
|
6
|
+
import { CODES, ConfigError } from '../config/errors.js';
|
|
7
|
+
import { captainSessionsWalDir, configFile, legacyConfigJsonPath, resolveDataDir } from '../paths.js';
|
|
8
|
+
import { CAPTAIN_ERROR_CODES, CaptainConfigSchema, CaptainError, SessionRecordSchema, } from './contracts.js';
|
|
9
|
+
import { DEFAULT_RETRY_POLICY } from '../audit-pipe/contracts.js';
|
|
10
|
+
function resolveConfigPath(env = process.env) {
|
|
11
|
+
return resolve(configFile(resolveDataDir({ dataDir: env['WB_DATA_DIR'] }), 'captain-store'));
|
|
12
|
+
}
|
|
13
|
+
function createClient(config) {
|
|
14
|
+
const domain = config.lark_domain === 'LarkSuite' ? Lark.Domain.Lark : config.lark_domain === 'LarkOffice' ? 'https://open.larkoffice.com' : Lark.Domain.Lark;
|
|
15
|
+
return new Lark.Client({
|
|
16
|
+
appId: config.app_id,
|
|
17
|
+
appSecret: config.app_secret,
|
|
18
|
+
domain,
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
function loadCaptainStoreConfig(options = {}) {
|
|
22
|
+
const env = options.env ?? process.env;
|
|
23
|
+
const dataDir = resolveDataDir({ dataDir: env['WB_DATA_DIR'] });
|
|
24
|
+
const configPath = resolve(options.configPath ?? resolveConfigPath(env));
|
|
25
|
+
const legacyPath = resolve(legacyConfigJsonPath(dataDir));
|
|
26
|
+
if (!options.configPath) {
|
|
27
|
+
if (existsSync(configPath)) {
|
|
28
|
+
const stat = statSync(configPath);
|
|
29
|
+
if ((stat.mode & 0o777) !== 0o600) {
|
|
30
|
+
console.warn('[captain] captain-store.json mode is not 0600, recommend chmod 600');
|
|
31
|
+
}
|
|
32
|
+
try {
|
|
33
|
+
return loadConfig(dataDir, 'captain-store', CaptainConfigSchema);
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
if (error instanceof ConfigError && error.code === CODES.E_CONFIG_MISSING) {
|
|
37
|
+
throw new CaptainError(CAPTAIN_ERROR_CODES.E_CONFIG_INCOMPLETE, 'captain-store config is missing', error);
|
|
38
|
+
}
|
|
39
|
+
throw new CaptainError(CAPTAIN_ERROR_CODES.E_CONFIG_INCOMPLETE, 'captain-store config is invalid', error);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if (existsSync(legacyPath)) {
|
|
43
|
+
const stat = statSync(legacyPath);
|
|
44
|
+
if ((stat.mode & 0o777) !== 0o600) {
|
|
45
|
+
console.warn('[captain] config.json mode is not 0600, recommend chmod 600');
|
|
46
|
+
}
|
|
47
|
+
let parsed;
|
|
48
|
+
try {
|
|
49
|
+
parsed = JSON.parse(readFileSync(legacyPath, 'utf8'));
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
throw new CaptainError(CAPTAIN_ERROR_CODES.E_CONFIG_INCOMPLETE, `failed to parse ${legacyPath}: ${error instanceof Error ? error.message : String(error)}`, error);
|
|
53
|
+
}
|
|
54
|
+
const captain = typeof parsed === 'object' && parsed !== null ? parsed.captain : undefined;
|
|
55
|
+
if (typeof captain !== 'object' || captain === null) {
|
|
56
|
+
throw new CaptainError(CAPTAIN_ERROR_CODES.E_CONFIG_INCOMPLETE, 'captain config is missing');
|
|
57
|
+
}
|
|
58
|
+
console.warn('[captain] deprecated legacy config.json path in use; migrate to config/captain-store.json');
|
|
59
|
+
try {
|
|
60
|
+
return CaptainConfigSchema.parse(captain);
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
throw new CaptainError(CAPTAIN_ERROR_CODES.E_CONFIG_INCOMPLETE, 'captain-store config is invalid', error);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
throw new CaptainError(CAPTAIN_ERROR_CODES.E_CONFIG_INCOMPLETE, 'captain-store config is missing');
|
|
67
|
+
}
|
|
68
|
+
const stat = statSync(configPath);
|
|
69
|
+
if ((stat.mode & 0o777) !== 0o600) {
|
|
70
|
+
console.warn('[captain] captain-store.json mode is not 0600, recommend chmod 600');
|
|
71
|
+
}
|
|
72
|
+
let parsed;
|
|
73
|
+
try {
|
|
74
|
+
parsed = JSON.parse(readFileSync(configPath, 'utf8'));
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
throw new CaptainError(CAPTAIN_ERROR_CODES.E_CONFIG_INCOMPLETE, `failed to parse ${configPath}: ${error instanceof Error ? error.message : String(error)}`, error);
|
|
78
|
+
}
|
|
79
|
+
if (typeof parsed !== 'object' || parsed === null) {
|
|
80
|
+
throw new CaptainError(CAPTAIN_ERROR_CODES.E_CONFIG_INCOMPLETE, 'captain-store config is missing');
|
|
81
|
+
}
|
|
82
|
+
const missing = ['bitable_base_id', 'sessions_table_id', 'app_id', 'app_secret', 'lark_domain', 'captain_state_path', 'captain_toml_path']
|
|
83
|
+
.filter((key) => !parsed[key]);
|
|
84
|
+
if (missing.length > 0) {
|
|
85
|
+
throw new CaptainError(CAPTAIN_ERROR_CODES.E_CONFIG_INCOMPLETE, `missing captain-store config: ${missing.join(', ')}`);
|
|
86
|
+
}
|
|
87
|
+
return CaptainConfigSchema.parse(parsed);
|
|
88
|
+
}
|
|
89
|
+
function sleep(ms) {
|
|
90
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
91
|
+
}
|
|
92
|
+
function nextDelay(retry, attempt) {
|
|
93
|
+
const base = Math.min(retry.baseMs * retry.factor ** (attempt - 1), retry.capMs);
|
|
94
|
+
const spread = base * retry.jitterRatio;
|
|
95
|
+
return Math.max(0, Math.round(base + (Math.random() * 2 - 1) * spread));
|
|
96
|
+
}
|
|
97
|
+
function isRetryableCode(code) {
|
|
98
|
+
return code === 99991663 || code === 99991661 || code >= 99990000;
|
|
99
|
+
}
|
|
100
|
+
function httpStatusFromError(error) {
|
|
101
|
+
if (typeof error !== 'object' || error === null)
|
|
102
|
+
return undefined;
|
|
103
|
+
const response = error.response;
|
|
104
|
+
return typeof response?.status === 'number' ? response.status : undefined;
|
|
105
|
+
}
|
|
106
|
+
function atomicWrite(path, content) {
|
|
107
|
+
const tmp = `${path}.tmp`;
|
|
108
|
+
writeFileSync(tmp, content);
|
|
109
|
+
renameSync(tmp, path);
|
|
110
|
+
}
|
|
111
|
+
function serializeSeq(seq) {
|
|
112
|
+
return `${seq}`.padStart(16, '0');
|
|
113
|
+
}
|
|
114
|
+
function formatSessionFields(record) {
|
|
115
|
+
const fields = {
|
|
116
|
+
session_id: record.session_id,
|
|
117
|
+
captain_id: record.captain_id,
|
|
118
|
+
created_at: Date.parse(record.created_at),
|
|
119
|
+
last_active_at: Date.parse(record.last_active_at),
|
|
120
|
+
status: record.status,
|
|
121
|
+
cwd: record.cwd,
|
|
122
|
+
scope: record.scope,
|
|
123
|
+
project: record.project,
|
|
124
|
+
home_group_id: record.home_group_id ?? '',
|
|
125
|
+
agent: record.agent,
|
|
126
|
+
latest_run_id: record.latest_run_id ?? '',
|
|
127
|
+
operator: [{ id: record.operator }],
|
|
128
|
+
entry_form: record.entry_form,
|
|
129
|
+
revision: record.revision,
|
|
130
|
+
};
|
|
131
|
+
if (record.closed_at)
|
|
132
|
+
fields['closed_at'] = Date.parse(record.closed_at);
|
|
133
|
+
return fields;
|
|
134
|
+
}
|
|
135
|
+
function asString(value) {
|
|
136
|
+
return typeof value === 'string' ? value : null;
|
|
137
|
+
}
|
|
138
|
+
function parseSessionRecord(fields) {
|
|
139
|
+
const operatorValue = fields['operator'];
|
|
140
|
+
const operator = Array.isArray(operatorValue) && operatorValue[0] && typeof operatorValue[0] === 'object' && operatorValue[0] !== null
|
|
141
|
+
? asString(operatorValue[0].id) ?? ''
|
|
142
|
+
: asString(operatorValue) ?? '';
|
|
143
|
+
return SessionRecordSchema.parse({
|
|
144
|
+
session_id: asString(fields['session_id']) ?? '',
|
|
145
|
+
captain_id: asString(fields['captain_id']) ?? '',
|
|
146
|
+
created_at: typeof fields['created_at'] === 'number' ? new Date(fields['created_at']).toISOString() : asString(fields['created_at']) ?? '',
|
|
147
|
+
last_active_at: typeof fields['last_active_at'] === 'number' ? new Date(fields['last_active_at']).toISOString() : asString(fields['last_active_at']) ?? '',
|
|
148
|
+
closed_at: typeof fields['closed_at'] === 'number' ? new Date(fields['closed_at']).toISOString() : asString(fields['closed_at']),
|
|
149
|
+
status: asString(fields['status']) ?? 'idle',
|
|
150
|
+
cwd: asString(fields['cwd']) ?? '',
|
|
151
|
+
scope: asString(fields['scope']) ?? 'dev',
|
|
152
|
+
project: asString(fields['project']) ?? 'weaverbird',
|
|
153
|
+
home_group_id: asString(fields['home_group_id']),
|
|
154
|
+
agent: asString(fields['agent']) ?? 'other',
|
|
155
|
+
latest_run_id: asString(fields['latest_run_id']),
|
|
156
|
+
operator,
|
|
157
|
+
entry_form: asString(fields['entry_form']) ?? 'cli',
|
|
158
|
+
revision: typeof fields['revision'] === 'number' ? fields['revision'] : 0,
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
function readMirrorSnapshot(path) {
|
|
162
|
+
const latest = new Map();
|
|
163
|
+
if (!existsSync(path))
|
|
164
|
+
return latest;
|
|
165
|
+
for (const line of readFileSync(path, 'utf8').split('\n')) {
|
|
166
|
+
if (!line.trim())
|
|
167
|
+
continue;
|
|
168
|
+
try {
|
|
169
|
+
const parsed = JSON.parse(line);
|
|
170
|
+
latest.set(parsed.session.session_id, parsed.session);
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return latest;
|
|
177
|
+
}
|
|
178
|
+
function createWal(dir) {
|
|
179
|
+
mkdirSync(dir, { recursive: true });
|
|
180
|
+
let counter = 0;
|
|
181
|
+
let lastSeq = 0;
|
|
182
|
+
for (const file of readdirSync(dir)) {
|
|
183
|
+
const match = file.match(/_(\d+)\.jsonl$/);
|
|
184
|
+
const seq = match ? Number.parseInt(match[1], 10) : Number.NaN;
|
|
185
|
+
if (Number.isFinite(seq))
|
|
186
|
+
lastSeq = Math.max(lastSeq, seq);
|
|
187
|
+
}
|
|
188
|
+
function filePath(entry) {
|
|
189
|
+
return join(dir, `${entry.session_id}_${serializeSeq(entry.seq)}.jsonl`);
|
|
190
|
+
}
|
|
191
|
+
function findPath(seq) {
|
|
192
|
+
const suffix = `_${serializeSeq(seq)}.jsonl`;
|
|
193
|
+
const file = readdirSync(dir).find((name) => name.endsWith(suffix));
|
|
194
|
+
return file ? join(dir, file) : null;
|
|
195
|
+
}
|
|
196
|
+
function parseEntry(path) {
|
|
197
|
+
try {
|
|
198
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
199
|
+
}
|
|
200
|
+
catch {
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
function writeEntry(entry) {
|
|
205
|
+
atomicWrite(filePath(entry), JSON.stringify(entry));
|
|
206
|
+
}
|
|
207
|
+
function nextSeq() {
|
|
208
|
+
counter += 1;
|
|
209
|
+
lastSeq = Math.max(lastSeq + 1, Date.now() * 1000 + counter);
|
|
210
|
+
return lastSeq;
|
|
211
|
+
}
|
|
212
|
+
return {
|
|
213
|
+
append(sessionId, record) {
|
|
214
|
+
const seq = nextSeq();
|
|
215
|
+
writeEntry({ seq, session_id: sessionId, record, attempts: 0, state: 'queued', enqueued_at: new Date().toISOString() });
|
|
216
|
+
return seq;
|
|
217
|
+
},
|
|
218
|
+
async *replay() {
|
|
219
|
+
for (const file of readdirSync(dir).filter((name) => name.endsWith('.jsonl')).sort()) {
|
|
220
|
+
const entry = parseEntry(join(dir, file));
|
|
221
|
+
if (entry)
|
|
222
|
+
yield entry;
|
|
223
|
+
}
|
|
224
|
+
},
|
|
225
|
+
ack(seq) {
|
|
226
|
+
const path = findPath(seq);
|
|
227
|
+
if (path)
|
|
228
|
+
unlinkSync(path);
|
|
229
|
+
},
|
|
230
|
+
markPendingSync(seq) {
|
|
231
|
+
const path = findPath(seq);
|
|
232
|
+
if (!path)
|
|
233
|
+
return;
|
|
234
|
+
const entry = parseEntry(path);
|
|
235
|
+
if (!entry)
|
|
236
|
+
return;
|
|
237
|
+
unlinkSync(path);
|
|
238
|
+
writeEntry({ ...entry, attempts: Math.max(entry.attempts, 5), state: 'pending-sync' });
|
|
239
|
+
},
|
|
240
|
+
bumpAttempts(seq) {
|
|
241
|
+
const path = findPath(seq);
|
|
242
|
+
if (!path)
|
|
243
|
+
return;
|
|
244
|
+
const entry = parseEntry(path);
|
|
245
|
+
if (!entry)
|
|
246
|
+
return;
|
|
247
|
+
unlinkSync(path);
|
|
248
|
+
writeEntry({ ...entry, attempts: entry.attempts + 1 });
|
|
249
|
+
},
|
|
250
|
+
listFiles() {
|
|
251
|
+
return readdirSync(dir).filter((name) => name.endsWith('.jsonl')).sort();
|
|
252
|
+
},
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
async function searchBySessionId(client, config, sessionId) {
|
|
256
|
+
const response = await client.bitable.appTableRecord.search({
|
|
257
|
+
path: { app_token: config.bitable_base_id, table_id: config.sessions_table_id },
|
|
258
|
+
params: { page_size: 1 },
|
|
259
|
+
data: { field_names: Object.keys(SessionRecordSchema.shape), filter: { conjunction: 'and', conditions: [{ field_name: 'session_id', operator: 'is', value: [sessionId] }] } },
|
|
260
|
+
});
|
|
261
|
+
const item = response.data?.items?.[0];
|
|
262
|
+
if (!item?.record_id || !item.fields)
|
|
263
|
+
return null;
|
|
264
|
+
return { recordId: item.record_id, record: parseSessionRecord(item.fields) };
|
|
265
|
+
}
|
|
266
|
+
export function createCaptainSessionStore(options = {}) {
|
|
267
|
+
const dataDir = resolveDataDir({ dataDir: options.env?.['WB_DATA_DIR'] });
|
|
268
|
+
const config = loadCaptainStoreConfig({ configPath: options.configPath, env: options.env });
|
|
269
|
+
const client = options._client ?? createClient(config);
|
|
270
|
+
const retry = options._retryOverride ?? DEFAULT_RETRY_POLICY;
|
|
271
|
+
const statePath = resolve(config.captain_state_path.replace(/^~\//, `${homedir()}/`));
|
|
272
|
+
const walDir = captainSessionsWalDir(dataDir);
|
|
273
|
+
const wal = createWal(walDir);
|
|
274
|
+
let syncTimer = null;
|
|
275
|
+
async function validateSchema() {
|
|
276
|
+
const response = await client.bitable.appTableField.list({
|
|
277
|
+
path: { app_token: config.bitable_base_id, table_id: config.sessions_table_id },
|
|
278
|
+
params: { page_size: 100 },
|
|
279
|
+
});
|
|
280
|
+
const fields = new Set((response.data?.items ?? []).map((item) => item.field_name).filter((name) => Boolean(name)));
|
|
281
|
+
const missing = Object.keys(SessionRecordSchema.shape).filter((name) => !fields.has(name));
|
|
282
|
+
if (missing.length > 0) {
|
|
283
|
+
throw new CaptainError(CAPTAIN_ERROR_CODES.E_STORE_WRITE, `missing session fields: ${missing.join(', ')}`);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
async function upsert(record) {
|
|
287
|
+
let seq = null;
|
|
288
|
+
let lastAttempt = 0;
|
|
289
|
+
for (let attempt = 1; attempt <= retry.maxAttempts; attempt += 1) {
|
|
290
|
+
lastAttempt = attempt;
|
|
291
|
+
try {
|
|
292
|
+
const existing = await searchBySessionId(client, config, record.session_id);
|
|
293
|
+
if (existing) {
|
|
294
|
+
const response = await client.bitable.appTableRecord.batchUpdate({
|
|
295
|
+
path: { app_token: config.bitable_base_id, table_id: config.sessions_table_id },
|
|
296
|
+
data: { records: [{ record_id: existing.recordId, fields: formatSessionFields(record) }] },
|
|
297
|
+
});
|
|
298
|
+
const code = response.code ?? 0;
|
|
299
|
+
if (code === 0) {
|
|
300
|
+
if (seq !== null)
|
|
301
|
+
wal.ack(seq);
|
|
302
|
+
return { ok: true, attempt };
|
|
303
|
+
}
|
|
304
|
+
if (seq === null)
|
|
305
|
+
seq = wal.append(record.session_id, record);
|
|
306
|
+
if (isRetryableCode(code)) {
|
|
307
|
+
wal.bumpAttempts(seq);
|
|
308
|
+
if (attempt < retry.maxAttempts)
|
|
309
|
+
await sleep(nextDelay(retry, attempt));
|
|
310
|
+
continue;
|
|
311
|
+
}
|
|
312
|
+
wal.markPendingSync(seq);
|
|
313
|
+
return { ok: false, attempt };
|
|
314
|
+
}
|
|
315
|
+
const response = await client.bitable.appTableRecord.batchCreate({
|
|
316
|
+
path: { app_token: config.bitable_base_id, table_id: config.sessions_table_id },
|
|
317
|
+
params: { client_token: record.session_id },
|
|
318
|
+
data: { records: [{ fields: formatSessionFields(record) }] },
|
|
319
|
+
});
|
|
320
|
+
const code = response.code ?? 0;
|
|
321
|
+
if (code === 0) {
|
|
322
|
+
if (seq !== null)
|
|
323
|
+
wal.ack(seq);
|
|
324
|
+
return { ok: true, attempt };
|
|
325
|
+
}
|
|
326
|
+
if (seq === null)
|
|
327
|
+
seq = wal.append(record.session_id, record);
|
|
328
|
+
if (isRetryableCode(code)) {
|
|
329
|
+
wal.bumpAttempts(seq);
|
|
330
|
+
if (attempt < retry.maxAttempts)
|
|
331
|
+
await sleep(nextDelay(retry, attempt));
|
|
332
|
+
continue;
|
|
333
|
+
}
|
|
334
|
+
wal.markPendingSync(seq);
|
|
335
|
+
return { ok: false, attempt };
|
|
336
|
+
}
|
|
337
|
+
catch (error) {
|
|
338
|
+
if (seq === null)
|
|
339
|
+
seq = wal.append(record.session_id, record);
|
|
340
|
+
const status = httpStatusFromError(error);
|
|
341
|
+
if (typeof status === 'number' && status >= 400 && status < 500) {
|
|
342
|
+
wal.markPendingSync(seq);
|
|
343
|
+
return { ok: false, attempt };
|
|
344
|
+
}
|
|
345
|
+
wal.bumpAttempts(seq);
|
|
346
|
+
if (attempt < retry.maxAttempts)
|
|
347
|
+
await sleep(nextDelay(retry, attempt));
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
if (seq !== null)
|
|
351
|
+
wal.markPendingSync(seq);
|
|
352
|
+
return { ok: false, attempt: lastAttempt || retry.maxAttempts };
|
|
353
|
+
}
|
|
354
|
+
async function reconcile() {
|
|
355
|
+
const mirror = readMirrorSnapshot(statePath);
|
|
356
|
+
const sessions = [...mirror.values()];
|
|
357
|
+
for (const record of sessions) {
|
|
358
|
+
const existing = await searchBySessionId(client, config, record.session_id);
|
|
359
|
+
if (!existing) {
|
|
360
|
+
await upsert(record);
|
|
361
|
+
continue;
|
|
362
|
+
}
|
|
363
|
+
if (Date.parse(record.last_active_at) > Date.parse(existing.record.last_active_at)) {
|
|
364
|
+
await upsert(record);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
return sessions;
|
|
368
|
+
}
|
|
369
|
+
async function syncOnce() {
|
|
370
|
+
let drained = 0;
|
|
371
|
+
for await (const entry of wal.replay()) {
|
|
372
|
+
const result = await upsert(entry.record);
|
|
373
|
+
if (result.ok) {
|
|
374
|
+
wal.ack(entry.seq);
|
|
375
|
+
drained += 1;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
return drained;
|
|
379
|
+
}
|
|
380
|
+
function startSyncWorker() {
|
|
381
|
+
if (syncTimer)
|
|
382
|
+
return syncTimer;
|
|
383
|
+
syncTimer = setInterval(() => { void syncOnce(); }, options._syncIntervalMs ?? 60_000);
|
|
384
|
+
return syncTimer;
|
|
385
|
+
}
|
|
386
|
+
function stopSyncWorker() {
|
|
387
|
+
if (!syncTimer)
|
|
388
|
+
return;
|
|
389
|
+
clearInterval(syncTimer);
|
|
390
|
+
syncTimer = null;
|
|
391
|
+
}
|
|
392
|
+
return {
|
|
393
|
+
config,
|
|
394
|
+
validateSchema,
|
|
395
|
+
upsert,
|
|
396
|
+
async upsertWithRevision(record, expectedRevision) {
|
|
397
|
+
const target = { ...record, revision: expectedRevision + 1 };
|
|
398
|
+
// fast path: no existing row → insert as revision=expectedRevision+1.
|
|
399
|
+
const existing = await searchBySessionId(client, config, record.session_id);
|
|
400
|
+
if (!existing) {
|
|
401
|
+
// 第一次创建;我们仍然标 revision=expectedRevision+1 保持单调.
|
|
402
|
+
const response = await client.bitable.appTableRecord.batchCreate({
|
|
403
|
+
path: { app_token: config.bitable_base_id, table_id: config.sessions_table_id },
|
|
404
|
+
params: { client_token: record.session_id },
|
|
405
|
+
data: { records: [{ fields: formatSessionFields(target) }] },
|
|
406
|
+
});
|
|
407
|
+
const code = response.code ?? 0;
|
|
408
|
+
if (code === 0)
|
|
409
|
+
return { ok: true, attempt: 1, newRevision: target.revision };
|
|
410
|
+
return { ok: false, attempt: 1, newRevision: expectedRevision };
|
|
411
|
+
}
|
|
412
|
+
if (existing.record.revision !== expectedRevision) {
|
|
413
|
+
throw new CaptainError(CAPTAIN_ERROR_CODES.E_REVISION_MISMATCH, `session ${record.session_id} revision mismatch: expected=${expectedRevision} actual=${existing.record.revision}`);
|
|
414
|
+
}
|
|
415
|
+
const response = await client.bitable.appTableRecord.batchUpdate({
|
|
416
|
+
path: { app_token: config.bitable_base_id, table_id: config.sessions_table_id },
|
|
417
|
+
data: { records: [{ record_id: existing.recordId, fields: formatSessionFields(target) }] },
|
|
418
|
+
});
|
|
419
|
+
const code = response.code ?? 0;
|
|
420
|
+
if (code === 0)
|
|
421
|
+
return { ok: true, attempt: 1, newRevision: target.revision };
|
|
422
|
+
return { ok: false, attempt: 1, newRevision: expectedRevision };
|
|
423
|
+
},
|
|
424
|
+
reconcile,
|
|
425
|
+
syncOnce,
|
|
426
|
+
startSyncWorker,
|
|
427
|
+
stopSyncWorker,
|
|
428
|
+
};
|
|
429
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join, resolve } from 'node:path';
|
|
4
|
+
import { CAPTAIN_ERROR_CODES, CaptainError, CaptainTomlSchema } from './contracts.js';
|
|
5
|
+
function isRecord(value) {
|
|
6
|
+
return typeof value === 'object' && value !== null;
|
|
7
|
+
}
|
|
8
|
+
function resolveCaptainMappingPaths(opts = {}) {
|
|
9
|
+
const cwd = resolve(opts.cwd ?? process.cwd());
|
|
10
|
+
const homeDir = resolve(opts.homeDir ?? homedir());
|
|
11
|
+
return {
|
|
12
|
+
repoJsonPath: join(cwd, 'captain.json'),
|
|
13
|
+
repoTomlPath: join(cwd, 'captain.toml'),
|
|
14
|
+
localJsonPath: join(homeDir, '.weaverbird', 'captain.json'),
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
function parseJsonConfig(path) {
|
|
18
|
+
try {
|
|
19
|
+
return CaptainTomlSchema.parse(JSON.parse(readFileSync(path, 'utf8')));
|
|
20
|
+
}
|
|
21
|
+
catch (error) {
|
|
22
|
+
throw new CaptainError(CAPTAIN_ERROR_CODES.E_TOML_INVALID, `failed to parse ${path}: ${error instanceof Error ? error.message : String(error)}`, error);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
// Minimal TOML subset parser for the captain mapping shape.
|
|
26
|
+
// Supports: `#` comments, `key = "string"` scalars at root (only `version` is honored),
|
|
27
|
+
// and `[[mapping]]` array-of-tables entries with scalar values.
|
|
28
|
+
// Anything outside that subset throws E_TOML_INVALID so users cannot silently drift.
|
|
29
|
+
function parseTomlConfig(path) {
|
|
30
|
+
const raw = readFileSync(path, 'utf8');
|
|
31
|
+
const out = { mapping: [] };
|
|
32
|
+
let current = null;
|
|
33
|
+
for (const rawLine of raw.split('\n')) {
|
|
34
|
+
const line = rawLine.replace(/#.*$/, '').trim();
|
|
35
|
+
if (!line)
|
|
36
|
+
continue;
|
|
37
|
+
if (line === '[[mapping]]') {
|
|
38
|
+
current = {};
|
|
39
|
+
out.mapping.push(current);
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
const match = /^([A-Za-z0-9_]+)\s*=\s*"([^"]*)"\s*$/.exec(line) ?? /^([A-Za-z0-9_]+)\s*=\s*(\d+)\s*$/.exec(line);
|
|
43
|
+
if (!match || match[1] === undefined || match[2] === undefined) {
|
|
44
|
+
throw new CaptainError(CAPTAIN_ERROR_CODES.E_TOML_INVALID, `unsupported TOML line in ${path}: ${line}`);
|
|
45
|
+
}
|
|
46
|
+
const key = match[1];
|
|
47
|
+
const value = match[2];
|
|
48
|
+
if (!current) {
|
|
49
|
+
if (key === 'version')
|
|
50
|
+
out.version = Number(value);
|
|
51
|
+
else
|
|
52
|
+
throw new CaptainError(CAPTAIN_ERROR_CODES.E_TOML_INVALID, `unsupported root key in ${path}: ${key}`);
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
current[key] = value;
|
|
56
|
+
}
|
|
57
|
+
try {
|
|
58
|
+
return CaptainTomlSchema.parse({ version: out.version ?? 1, mapping: out.mapping });
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
throw new CaptainError(CAPTAIN_ERROR_CODES.E_TOML_INVALID, `failed to parse ${path}: ${error instanceof Error ? error.message : String(error)}`, error);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
function mergeMappings(base, override) {
|
|
65
|
+
const merged = new Map();
|
|
66
|
+
for (const mapping of base)
|
|
67
|
+
merged.set(mapping.captain_id, mapping);
|
|
68
|
+
for (const mapping of override)
|
|
69
|
+
merged.set(mapping.captain_id, mapping);
|
|
70
|
+
return [...merged.values()];
|
|
71
|
+
}
|
|
72
|
+
export function loadCaptainConfig(opts = {}) {
|
|
73
|
+
const { repoJsonPath, repoTomlPath, localJsonPath } = resolveCaptainMappingPaths(opts);
|
|
74
|
+
const repoExists = existsSync(repoJsonPath);
|
|
75
|
+
const repoTomlExists = existsSync(repoTomlPath);
|
|
76
|
+
const localExists = existsSync(localJsonPath);
|
|
77
|
+
if (!repoExists && !repoTomlExists && !localExists) {
|
|
78
|
+
throw new CaptainError(CAPTAIN_ERROR_CODES.E_TOML_MISSING, 'captain.json is missing in repo root and ~/.weaverbird');
|
|
79
|
+
}
|
|
80
|
+
const repoConfig = repoExists ? parseJsonConfig(repoJsonPath) : repoTomlExists ? parseTomlConfig(repoTomlPath) : { version: 1, mapping: [] };
|
|
81
|
+
const localConfig = localExists ? parseJsonConfig(localJsonPath) : { version: 1, mapping: [] };
|
|
82
|
+
return CaptainTomlSchema.parse({
|
|
83
|
+
version: Math.max(repoConfig.version, localConfig.version),
|
|
84
|
+
mapping: mergeMappings(repoConfig.mapping, localConfig.mapping),
|
|
85
|
+
});
|
|
86
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export const CODES = {
|
|
2
|
+
E_CONFIG_MISSING: 'config.missing',
|
|
3
|
+
E_CONFIG_PARSE: 'config.parse_error',
|
|
4
|
+
E_CAPTAIN_QUEUE_PARSE: 'captain.queue_parse_error',
|
|
5
|
+
};
|
|
6
|
+
export class ConfigError extends Error {
|
|
7
|
+
code;
|
|
8
|
+
cause;
|
|
9
|
+
constructor(code, message, cause) {
|
|
10
|
+
super(`[${code}] ${message}`);
|
|
11
|
+
this.code = code;
|
|
12
|
+
this.cause = cause;
|
|
13
|
+
this.name = 'ConfigError';
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { configFile } from '../paths.js';
|
|
3
|
+
import { CODES, ConfigError } from './errors.js';
|
|
4
|
+
function isErrnoException(error) {
|
|
5
|
+
return typeof error === 'object' && error !== null && 'code' in error;
|
|
6
|
+
}
|
|
7
|
+
export function loadConfig(dataDir, domain, schema, defaults) {
|
|
8
|
+
const path = configFile(dataDir, domain);
|
|
9
|
+
let raw;
|
|
10
|
+
try {
|
|
11
|
+
raw = readFileSync(path, 'utf8');
|
|
12
|
+
}
|
|
13
|
+
catch (error) {
|
|
14
|
+
if (isErrnoException(error) && error.code === 'ENOENT') {
|
|
15
|
+
if (defaults !== undefined)
|
|
16
|
+
return defaults;
|
|
17
|
+
throw new ConfigError(CODES.E_CONFIG_MISSING, `missing config for ${domain}`, error);
|
|
18
|
+
}
|
|
19
|
+
throw new ConfigError(CODES.E_CONFIG_PARSE, `failed to read config for ${domain}`, error);
|
|
20
|
+
}
|
|
21
|
+
let parsed;
|
|
22
|
+
try {
|
|
23
|
+
parsed = JSON.parse(raw);
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
throw new ConfigError(CODES.E_CONFIG_PARSE, `failed to parse config for ${domain}`, error);
|
|
27
|
+
}
|
|
28
|
+
try {
|
|
29
|
+
return schema.parse(parsed);
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
throw new ConfigError(CODES.E_CONFIG_PARSE, `invalid config for ${domain}`, error);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
export const ERROR_CODES = {
|
|
2
|
+
config: {
|
|
3
|
+
E_CONFIG_MISSING: 'config.missing',
|
|
4
|
+
E_CONFIG_PARSE: 'config.parse_error',
|
|
5
|
+
},
|
|
6
|
+
captain: {
|
|
7
|
+
E_CAPTAIN_QUEUE_PARSE: 'captain.queue_parse_error',
|
|
8
|
+
E_TOML_MISSING: 'captain.toml.missing',
|
|
9
|
+
E_TOML_INVALID: 'captain.toml.invalid',
|
|
10
|
+
E_INFERENCE_MISS: 'captain.cwd.inference_miss',
|
|
11
|
+
E_SESSION_NOT_FOUND: 'captain.session.not_found',
|
|
12
|
+
E_STORE_WRITE: 'captain.store.write_failed',
|
|
13
|
+
E_STORE_RETRY_EXHAUSTED: 'captain.store.retry_exhausted',
|
|
14
|
+
E_CATALOG_INCOMPLETE: 'captain.catalog.incomplete',
|
|
15
|
+
E_CONFIG_MISSING: 'captain.config.missing',
|
|
16
|
+
E_CONFIG_INCOMPLETE: 'captain.config.incomplete',
|
|
17
|
+
},
|
|
18
|
+
'run-observability': {
|
|
19
|
+
E_STORE_WRITE: 'run-observability.store.write_failed',
|
|
20
|
+
E_STORE_TRUNCATED: 'run-observability.store.truncated',
|
|
21
|
+
E_IM_SEND_FAILED: 'run-observability.im.send_failed',
|
|
22
|
+
E_IM_PATCH_FAILED: 'run-observability.im.patch_failed',
|
|
23
|
+
E_RUN_STALE_NOOP: 'run-observability.alert.stale_noop',
|
|
24
|
+
E_NO_ACTIVE_SESSION: 'run-observability.session.not_found',
|
|
25
|
+
},
|
|
26
|
+
'run-registry': {
|
|
27
|
+
E_CFG_MISSING: 'registry.config.missing',
|
|
28
|
+
E_CFG_INVALID: 'registry.config.invalid',
|
|
29
|
+
E_SCHEMA_MISMATCH: 'registry.schema.mismatch',
|
|
30
|
+
E_BITABLE_WRITE: 'registry.bitable.write_failed',
|
|
31
|
+
E_BITABLE_RETRY_EXHAUSTED: 'registry.bitable.retry_exhausted',
|
|
32
|
+
E_WAL_WRITE: 'registry.wal.write_failed',
|
|
33
|
+
E_TAILER_READ: 'registry.tailer.read_error',
|
|
34
|
+
E_INHERIT_NOT_FOUND: 'registry.inherit.run_not_found',
|
|
35
|
+
E_QUERY_TIMEOUT: 'registry.query.timeout',
|
|
36
|
+
E_DOC_SINK_WRITE: 'registry.doc_sink.write_failed',
|
|
37
|
+
},
|
|
38
|
+
audit: {
|
|
39
|
+
E_CFG_MISSING_FILE: 'audit.config.missing_file',
|
|
40
|
+
E_CFG_INVALID_JSON: 'audit.config.invalid_json',
|
|
41
|
+
E_CFG_MISSING_ENV: 'audit.config.missing_env',
|
|
42
|
+
E_CFG_PLACEHOLDER: 'audit.config.placeholder',
|
|
43
|
+
E_CFG_BAD_SOURCE_TYPE: 'audit.config.bad_source_type',
|
|
44
|
+
E_CFG_PERM_TOO_OPEN: 'audit.config.perm_too_open',
|
|
45
|
+
E_PARSE_BAD_LINE: 'audit.parse.bad_line',
|
|
46
|
+
E_NORM_MISSING_SPEC: 'audit.normalizer.missing_spec',
|
|
47
|
+
E_NORM_INVALID_ENTRY_FORM: 'audit.normalizer.invalid_entry_form',
|
|
48
|
+
E_MIRROR_WRITE_FATAL: 'audit.mirror.write_fatal',
|
|
49
|
+
E_WAL_WRITE: 'audit.wal.write',
|
|
50
|
+
E_BITABLE_HTTP_4XX: 'audit.bitable.http_4xx',
|
|
51
|
+
E_BITABLE_HTTP_5XX: 'audit.bitable.http_5xx',
|
|
52
|
+
E_BITABLE_LARK_CODE: 'audit.bitable.lark_code_nonzero',
|
|
53
|
+
E_BITABLE_RETRY_EXHAUSTED: 'audit.bitable.retry_exhausted',
|
|
54
|
+
},
|
|
55
|
+
reverse: {
|
|
56
|
+
E_ATTACH_TIMEOUT: 'reverse.attach.timeout',
|
|
57
|
+
E_ATTACH_NOT_FOUND: 'reverse.attach.not_found',
|
|
58
|
+
E_ATTACH_MUTEX: 'reverse.attach.mutex_conflict',
|
|
59
|
+
E_ATTACH_FLUSH_FAILED: 'reverse.attach.flush_failed',
|
|
60
|
+
E_IPC_CONNECT_FAILED: 'reverse.ipc.connect_failed',
|
|
61
|
+
E_IPC_SEND_TIMEOUT: 'reverse.ipc.send_timeout',
|
|
62
|
+
E_IPC_PARSE: 'reverse.ipc.parse_error',
|
|
63
|
+
E_ECHO_SEND_FAILED: 'reverse.echo.send_failed',
|
|
64
|
+
E_REVERSE_AT_PARSE: 'reverse.at.parse_error',
|
|
65
|
+
E_REVERSE_AT_RUN_GONE: 'reverse.at.run_not_found',
|
|
66
|
+
E_SIGNAL_FAILED: 'reverse.signal.send_failed',
|
|
67
|
+
E_CAPTAIN_HANDED_OVER: 'reverse.attach.handed_over',
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
export const ERROR_CODE_ALLOWED_DOMAINS = {
|
|
71
|
+
config: ['config'],
|
|
72
|
+
captain: ['captain'],
|
|
73
|
+
'run-observability': ['run-observability'],
|
|
74
|
+
'run-registry': ['registry'],
|
|
75
|
+
audit: ['audit'],
|
|
76
|
+
reverse: ['reverse'],
|
|
77
|
+
};
|
|
78
|
+
export function flattenErrorCodes() {
|
|
79
|
+
return Object.values(ERROR_CODES).flatMap((group) => Object.values(group));
|
|
80
|
+
}
|
|
81
|
+
export function getErrorCodeEntries() {
|
|
82
|
+
return Object.entries(ERROR_CODES).flatMap(([registryKey, group]) => Object.entries(group).map(([symbol, value]) => ({
|
|
83
|
+
registryKey: registryKey,
|
|
84
|
+
symbol,
|
|
85
|
+
value,
|
|
86
|
+
})));
|
|
87
|
+
}
|
|
88
|
+
export function extractErrorCodeDomain(code) {
|
|
89
|
+
const [domain = ''] = code.split('.');
|
|
90
|
+
return domain;
|
|
91
|
+
}
|
|
92
|
+
export function matchesAllowedErrorCodeDomain(registryKey, code) {
|
|
93
|
+
const allowedDomains = ERROR_CODE_ALLOWED_DOMAINS[registryKey];
|
|
94
|
+
return allowedDomains.includes(extractErrorCodeDomain(code));
|
|
95
|
+
}
|
|
96
|
+
export const ERROR_CODE_VALUES = flattenErrorCodes();
|
|
97
|
+
export const ERROR_CODE_ENTRIES = getErrorCodeEntries();
|
|
98
|
+
export const ERROR_CODE_INDEX = Object.fromEntries(ERROR_CODE_ENTRIES.map((entry) => [entry.value, entry]));
|