@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,308 @@
|
|
|
1
|
+
import * as Lark from '@larksuiteoapi/node-sdk';
|
|
2
|
+
import { runRegistryWalDir } from '../paths.js';
|
|
3
|
+
import { DEFAULT_RETRY_POLICY, RUN_REGISTRY_ERROR_CODES, RunQuerySchema, RunRecordSchema, RunRegistryError, } from './contracts.js';
|
|
4
|
+
import { loadRunRegistryConfig, resolveRunRegistryDataDir } from './config.js';
|
|
5
|
+
import { createRunRegistryWal } from './wal.js';
|
|
6
|
+
function sleep(ms) {
|
|
7
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
8
|
+
}
|
|
9
|
+
function createClient(config) {
|
|
10
|
+
const domain = config.lark_domain.includes('larkoffice') ? Lark.Domain.Lark : config.lark_domain;
|
|
11
|
+
return new Lark.Client({
|
|
12
|
+
appId: config.app_id,
|
|
13
|
+
appSecret: config.app_secret,
|
|
14
|
+
domain,
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
function nextDelay(retry, attempt) {
|
|
18
|
+
const base = Math.min(retry.baseMs * retry.factor ** (attempt - 1), retry.capMs);
|
|
19
|
+
const spread = base * retry.jitterRatio;
|
|
20
|
+
return Math.max(0, Math.round(base + (Math.random() * 2 - 1) * spread));
|
|
21
|
+
}
|
|
22
|
+
function isRetryableCode(code) {
|
|
23
|
+
return code === 99991663 || code === 99991661 || code >= 99990000;
|
|
24
|
+
}
|
|
25
|
+
function httpStatusFromError(error) {
|
|
26
|
+
if (typeof error !== 'object' || error === null)
|
|
27
|
+
return undefined;
|
|
28
|
+
const response = error.response;
|
|
29
|
+
return typeof response?.status === 'number' ? response.status : undefined;
|
|
30
|
+
}
|
|
31
|
+
function asString(value) {
|
|
32
|
+
return typeof value === 'string' ? value : null;
|
|
33
|
+
}
|
|
34
|
+
function asStringArray(value) {
|
|
35
|
+
if (Array.isArray(value))
|
|
36
|
+
return value.filter((item) => typeof item === 'string');
|
|
37
|
+
if (typeof value === 'string' && value.trim())
|
|
38
|
+
return value.split(/\n+/).map((item) => item.trim()).filter(Boolean);
|
|
39
|
+
return [];
|
|
40
|
+
}
|
|
41
|
+
function asNullableNumber(value) {
|
|
42
|
+
return typeof value === 'number' ? value : null;
|
|
43
|
+
}
|
|
44
|
+
function asStrictBoolean(value) {
|
|
45
|
+
if (value === true || value === 1)
|
|
46
|
+
return true;
|
|
47
|
+
if (value === false || value === 0 || value === null || value === undefined)
|
|
48
|
+
return false;
|
|
49
|
+
if (typeof value === 'string') {
|
|
50
|
+
const normalized = value.trim().toLowerCase();
|
|
51
|
+
if (normalized === 'true' || normalized === '1' || normalized === 'yes' || normalized === 'checked')
|
|
52
|
+
return true;
|
|
53
|
+
if (normalized === '' || normalized === 'false' || normalized === '0' || normalized === 'no' || normalized === 'unchecked')
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
function formatFields(record) {
|
|
59
|
+
return {
|
|
60
|
+
run_id: record.run_id,
|
|
61
|
+
created_at: Date.parse(record.created_at),
|
|
62
|
+
operator: record.operator,
|
|
63
|
+
project: record.project,
|
|
64
|
+
cwd: record.cwd,
|
|
65
|
+
scope: record.scope,
|
|
66
|
+
agent: record.agent,
|
|
67
|
+
cmd: record.cmd,
|
|
68
|
+
status: record.status,
|
|
69
|
+
cost_tokens: record.cost_tokens,
|
|
70
|
+
cost_minutes: record.cost_minutes,
|
|
71
|
+
produced_doc_urls: record.produced_doc_urls,
|
|
72
|
+
commit_shas: record.commit_shas,
|
|
73
|
+
doc_sink_failed: record.doc_sink_failed,
|
|
74
|
+
calendar_block_id: record.calendar_block_id,
|
|
75
|
+
calendar_hook_failed: record.calendar_hook_failed,
|
|
76
|
+
risk_level: record.risk_level,
|
|
77
|
+
home_group_id: record.home_group_id,
|
|
78
|
+
entry_form: record.entry_form,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
function parseRunRecord(fields) {
|
|
82
|
+
return RunRecordSchema.parse({
|
|
83
|
+
run_id: asString(fields['run_id']) ?? '',
|
|
84
|
+
created_at: typeof fields['created_at'] === 'number'
|
|
85
|
+
? new Date(fields['created_at']).toISOString()
|
|
86
|
+
: asString(fields['created_at']) ?? '',
|
|
87
|
+
operator: asString(fields['operator']) ?? '',
|
|
88
|
+
project: asString(fields['project']),
|
|
89
|
+
cwd: asString(fields['cwd']) ?? '',
|
|
90
|
+
scope: asString(fields['scope']) ?? '',
|
|
91
|
+
agent: asString(fields['agent']) ?? '',
|
|
92
|
+
cmd: asString(fields['cmd']) ?? '',
|
|
93
|
+
status: asString(fields['status']) ?? '',
|
|
94
|
+
cost_tokens: asNullableNumber(fields['cost_tokens']),
|
|
95
|
+
cost_minutes: asNullableNumber(fields['cost_minutes']),
|
|
96
|
+
produced_doc_urls: asStringArray(fields['produced_doc_urls']),
|
|
97
|
+
commit_shas: asStringArray(fields['commit_shas']),
|
|
98
|
+
doc_sink_failed: asStrictBoolean(fields['doc_sink_failed']),
|
|
99
|
+
calendar_block_id: asString(fields['calendar_block_id']),
|
|
100
|
+
calendar_hook_failed: asStrictBoolean(fields['calendar_hook_failed']),
|
|
101
|
+
risk_level: asString(fields['risk_level']) ?? 'unknown',
|
|
102
|
+
home_group_id: asString(fields['home_group_id']),
|
|
103
|
+
entry_form: asString(fields['entry_form']) ?? 'cli',
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
function buildQueryConditions(query) {
|
|
107
|
+
const conditions = [];
|
|
108
|
+
if (query.operator)
|
|
109
|
+
conditions.push({ field_name: 'operator', operator: 'is', value: [query.operator] });
|
|
110
|
+
if (query.project)
|
|
111
|
+
conditions.push({ field_name: 'project', operator: 'is', value: [query.project] });
|
|
112
|
+
if (query.agent)
|
|
113
|
+
conditions.push({ field_name: 'agent', operator: 'is', value: [query.agent] });
|
|
114
|
+
if (query.entry_form)
|
|
115
|
+
conditions.push({ field_name: 'entry_form', operator: 'is', value: [query.entry_form] });
|
|
116
|
+
if (query.status)
|
|
117
|
+
conditions.push({ field_name: 'status', operator: 'is', value: [query.status] });
|
|
118
|
+
if (query.after)
|
|
119
|
+
conditions.push({ field_name: 'created_at', operator: 'isGreaterEqual', value: [String(Date.parse(query.after))] });
|
|
120
|
+
if (query.before)
|
|
121
|
+
conditions.push({ field_name: 'created_at', operator: 'isLessEqual', value: [String(Date.parse(query.before))] });
|
|
122
|
+
return conditions;
|
|
123
|
+
}
|
|
124
|
+
function buildQueryChildren(query) {
|
|
125
|
+
if (!query.keyword)
|
|
126
|
+
return [];
|
|
127
|
+
return [{
|
|
128
|
+
conjunction: 'or',
|
|
129
|
+
conditions: [
|
|
130
|
+
{ field_name: 'cwd', operator: 'contains', value: [query.keyword] },
|
|
131
|
+
{ field_name: 'cmd', operator: 'contains', value: [query.keyword] },
|
|
132
|
+
{ field_name: 'project', operator: 'contains', value: [query.keyword] },
|
|
133
|
+
],
|
|
134
|
+
}];
|
|
135
|
+
}
|
|
136
|
+
function buildSearchPayload(config, query) {
|
|
137
|
+
const conditions = buildQueryConditions(query);
|
|
138
|
+
const children = buildQueryChildren(query);
|
|
139
|
+
return {
|
|
140
|
+
path: { app_token: config.bitable_base_id, table_id: config.bitable_table_id },
|
|
141
|
+
params: { page_size: query.limit, page_token: query.cursor },
|
|
142
|
+
data: {
|
|
143
|
+
field_names: Object.keys(RunRecordSchema.shape),
|
|
144
|
+
sort: [{ field_name: 'created_at', desc: true }],
|
|
145
|
+
filter: conditions.length || children.length
|
|
146
|
+
? { conjunction: 'and', conditions, children }
|
|
147
|
+
: undefined,
|
|
148
|
+
},
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
async function searchByRunId(client, config, runId) {
|
|
152
|
+
const response = await client.bitable.appTableRecord.search({
|
|
153
|
+
path: { app_token: config.bitable_base_id, table_id: config.bitable_table_id },
|
|
154
|
+
params: { page_size: 1 },
|
|
155
|
+
data: {
|
|
156
|
+
field_names: Object.keys(RunRecordSchema.shape),
|
|
157
|
+
filter: { conjunction: 'and', conditions: [{ field_name: 'run_id', operator: 'is', value: [runId] }] },
|
|
158
|
+
},
|
|
159
|
+
});
|
|
160
|
+
const item = response.data?.items?.[0];
|
|
161
|
+
if (!item?.record_id || !item.fields)
|
|
162
|
+
return null;
|
|
163
|
+
return { recordId: item.record_id, record: parseRunRecord(item.fields) };
|
|
164
|
+
}
|
|
165
|
+
export function createRunRegistryWriter(options = {}) {
|
|
166
|
+
const dataDir = resolveRunRegistryDataDir(options.env);
|
|
167
|
+
const config = loadRunRegistryConfig({ configPath: options.configPath, env: options.env });
|
|
168
|
+
const wal = createRunRegistryWal({ dataDir, walPath: options.walPath ?? runRegistryWalDir(dataDir) });
|
|
169
|
+
const retry = options._retryOverride ?? DEFAULT_RETRY_POLICY;
|
|
170
|
+
const client = options._client ?? createClient(config);
|
|
171
|
+
let syncTimer = null;
|
|
172
|
+
async function validateSchema() {
|
|
173
|
+
const response = await client.bitable.appTableField.list({
|
|
174
|
+
path: { app_token: config.bitable_base_id, table_id: config.bitable_table_id },
|
|
175
|
+
params: { page_size: 100 },
|
|
176
|
+
});
|
|
177
|
+
if ((response.code ?? 0) !== 0) {
|
|
178
|
+
throw new RunRegistryError(RUN_REGISTRY_ERROR_CODES.E_SCHEMA_MISMATCH, response.msg ?? 'failed to list bitable fields');
|
|
179
|
+
}
|
|
180
|
+
const fields = new Set((response.data?.items ?? []).map((item) => item.field_name).filter((name) => Boolean(name)));
|
|
181
|
+
const missing = Object.keys(RunRecordSchema.shape).filter((name) => !fields.has(name));
|
|
182
|
+
if (missing.length > 0) {
|
|
183
|
+
throw new RunRegistryError(RUN_REGISTRY_ERROR_CODES.E_SCHEMA_MISMATCH, `missing fields: ${missing.join(', ')}`);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
async function upsert(record) {
|
|
187
|
+
let seq = null;
|
|
188
|
+
let last = { ok: false, attempt: 0 };
|
|
189
|
+
for (let attempt = 1; attempt <= retry.maxAttempts; attempt += 1) {
|
|
190
|
+
try {
|
|
191
|
+
const existing = await searchByRunId(client, config, record.run_id);
|
|
192
|
+
if (existing) {
|
|
193
|
+
const response = await client.bitable.appTableRecord.batchUpdate({
|
|
194
|
+
path: { app_token: config.bitable_base_id, table_id: config.bitable_table_id },
|
|
195
|
+
data: { records: [{ record_id: existing.recordId, fields: formatFields(record) }] },
|
|
196
|
+
});
|
|
197
|
+
const code = response.code ?? 0;
|
|
198
|
+
if (code === 0) {
|
|
199
|
+
if (seq !== null)
|
|
200
|
+
wal.ack(seq);
|
|
201
|
+
return { ok: true, attempt, record_id: existing.recordId, lark_code: code, lark_msg: response.msg };
|
|
202
|
+
}
|
|
203
|
+
if (seq === null)
|
|
204
|
+
seq = wal.append(record.run_id, record);
|
|
205
|
+
if (isRetryableCode(code)) {
|
|
206
|
+
wal.bumpAttempts(seq);
|
|
207
|
+
last = { ok: false, attempt, lark_code: code, lark_msg: response.msg };
|
|
208
|
+
if (attempt < retry.maxAttempts)
|
|
209
|
+
await sleep(nextDelay(retry, attempt));
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
wal.markPendingSync(seq);
|
|
213
|
+
return { ok: false, attempt, lark_code: code, lark_msg: response.msg };
|
|
214
|
+
}
|
|
215
|
+
const response = await client.bitable.appTableRecord.batchCreate({
|
|
216
|
+
path: { app_token: config.bitable_base_id, table_id: config.bitable_table_id },
|
|
217
|
+
params: { client_token: record.run_id },
|
|
218
|
+
data: { records: [{ fields: formatFields(record) }] },
|
|
219
|
+
});
|
|
220
|
+
const code = response.code ?? 0;
|
|
221
|
+
if (code === 0) {
|
|
222
|
+
if (seq !== null)
|
|
223
|
+
wal.ack(seq);
|
|
224
|
+
return { ok: true, attempt, record_id: response.data?.records?.[0]?.record_id, lark_code: code, lark_msg: response.msg };
|
|
225
|
+
}
|
|
226
|
+
if (seq === null)
|
|
227
|
+
seq = wal.append(record.run_id, record);
|
|
228
|
+
if (isRetryableCode(code)) {
|
|
229
|
+
wal.bumpAttempts(seq);
|
|
230
|
+
last = { ok: false, attempt, lark_code: code, lark_msg: response.msg };
|
|
231
|
+
if (attempt < retry.maxAttempts)
|
|
232
|
+
await sleep(nextDelay(retry, attempt));
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
wal.markPendingSync(seq);
|
|
236
|
+
return { ok: false, attempt, lark_code: code, lark_msg: response.msg };
|
|
237
|
+
}
|
|
238
|
+
catch (error) {
|
|
239
|
+
if (seq === null)
|
|
240
|
+
seq = wal.append(record.run_id, record);
|
|
241
|
+
const status = httpStatusFromError(error);
|
|
242
|
+
if (typeof status === 'number' && status >= 400 && status < 500) {
|
|
243
|
+
wal.markPendingSync(seq);
|
|
244
|
+
return { ok: false, attempt, http_status: status, lark_msg: RUN_REGISTRY_ERROR_CODES.E_BITABLE_WRITE };
|
|
245
|
+
}
|
|
246
|
+
wal.bumpAttempts(seq);
|
|
247
|
+
last = { ok: false, attempt, http_status: status, lark_msg: RUN_REGISTRY_ERROR_CODES.E_BITABLE_WRITE };
|
|
248
|
+
if (attempt < retry.maxAttempts)
|
|
249
|
+
await sleep(nextDelay(retry, attempt));
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
if (seq !== null)
|
|
253
|
+
wal.markPendingSync(seq);
|
|
254
|
+
return { ...last, lark_msg: RUN_REGISTRY_ERROR_CODES.E_BITABLE_RETRY_EXHAUSTED };
|
|
255
|
+
}
|
|
256
|
+
async function findByRunId(runId) {
|
|
257
|
+
return (await searchByRunId(client, config, runId))?.record ?? null;
|
|
258
|
+
}
|
|
259
|
+
async function queryRuns(query) {
|
|
260
|
+
const parsed = RunQuerySchema.parse(query);
|
|
261
|
+
const response = await client.bitable.appTableRecord.search(buildSearchPayload(config, parsed));
|
|
262
|
+
return {
|
|
263
|
+
runs: (response.data?.items ?? [])
|
|
264
|
+
.filter((item) => Boolean(item.fields))
|
|
265
|
+
.map((item) => parseRunRecord(item.fields)),
|
|
266
|
+
next_cursor: response.data?.has_more ? (response.data?.page_token ?? null) : null,
|
|
267
|
+
total_hint: response.data?.total ?? null,
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
async function syncOnce() {
|
|
271
|
+
let drained = 0;
|
|
272
|
+
for await (const entry of wal.replay()) {
|
|
273
|
+
const result = await upsert(entry.record);
|
|
274
|
+
if (result.ok) {
|
|
275
|
+
wal.ack(entry.seq);
|
|
276
|
+
drained += 1;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
return drained;
|
|
280
|
+
}
|
|
281
|
+
function startSyncWorker() {
|
|
282
|
+
if (syncTimer)
|
|
283
|
+
return syncTimer;
|
|
284
|
+
syncTimer = setInterval(() => {
|
|
285
|
+
if (!wal.listFiles().length)
|
|
286
|
+
return;
|
|
287
|
+
void syncOnce();
|
|
288
|
+
}, options._syncIntervalMs ?? 60_000);
|
|
289
|
+
return syncTimer;
|
|
290
|
+
}
|
|
291
|
+
function stopSyncWorker() {
|
|
292
|
+
if (!syncTimer)
|
|
293
|
+
return;
|
|
294
|
+
clearInterval(syncTimer);
|
|
295
|
+
syncTimer = null;
|
|
296
|
+
}
|
|
297
|
+
return {
|
|
298
|
+
config,
|
|
299
|
+
wal,
|
|
300
|
+
validateSchema,
|
|
301
|
+
upsert,
|
|
302
|
+
findByRunId,
|
|
303
|
+
queryRuns,
|
|
304
|
+
syncOnce,
|
|
305
|
+
startSyncWorker,
|
|
306
|
+
stopSyncWorker,
|
|
307
|
+
};
|
|
308
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { loadConfig } from '../config/registry.js';
|
|
4
|
+
import { configFile, legacyConfigJsonPath, resolveDataDir } from '../paths.js';
|
|
5
|
+
import { RUN_REGISTRY_ERROR_CODES, RunRegistryConfigSchema, RunRegistryError, } from './contracts.js';
|
|
6
|
+
function isRecord(value) {
|
|
7
|
+
return typeof value === 'object' && value !== null;
|
|
8
|
+
}
|
|
9
|
+
function validateMode(path) {
|
|
10
|
+
const stat = statSync(path);
|
|
11
|
+
if ((stat.mode & 0o077) !== 0) {
|
|
12
|
+
throw new RunRegistryError(RUN_REGISTRY_ERROR_CODES.E_CFG_INVALID, `${path} permissions are too open (${(stat.mode & 0o777).toString(8)}), expected 600`);
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function readJson(path) {
|
|
16
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
17
|
+
}
|
|
18
|
+
function parseLegacyConfig(path) {
|
|
19
|
+
let parsed;
|
|
20
|
+
try {
|
|
21
|
+
parsed = readJson(path);
|
|
22
|
+
}
|
|
23
|
+
catch (error) {
|
|
24
|
+
throw new RunRegistryError(RUN_REGISTRY_ERROR_CODES.E_CFG_INVALID, `failed to parse ${path}: ${error instanceof Error ? error.message : String(error)}`, error);
|
|
25
|
+
}
|
|
26
|
+
if (!isRecord(parsed) || !isRecord(parsed['run_registry'])) {
|
|
27
|
+
throw new RunRegistryError(RUN_REGISTRY_ERROR_CODES.E_CFG_MISSING, 'config.json must contain a run_registry object');
|
|
28
|
+
}
|
|
29
|
+
try {
|
|
30
|
+
return RunRegistryConfigSchema.parse(parsed['run_registry']);
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
throw new RunRegistryError(RUN_REGISTRY_ERROR_CODES.E_CFG_INVALID, 'run-registry config is invalid', error);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
export function resolveRunRegistryDataDir(env = process.env) {
|
|
37
|
+
return resolveDataDir({ dataDir: env['WB_DATA_DIR'] });
|
|
38
|
+
}
|
|
39
|
+
export function resolveRunRegistryConfigPath(env = process.env) {
|
|
40
|
+
return resolve(configFile(resolveRunRegistryDataDir(env), 'run-registry'));
|
|
41
|
+
}
|
|
42
|
+
export function loadRunRegistryConfig(options = {}) {
|
|
43
|
+
const env = options.env ?? process.env;
|
|
44
|
+
const dataDir = resolveRunRegistryDataDir(env);
|
|
45
|
+
const configPath = resolve(options.configPath ?? resolveRunRegistryConfigPath(env));
|
|
46
|
+
const legacyPath = resolve(legacyConfigJsonPath(dataDir));
|
|
47
|
+
if (existsSync(configPath)) {
|
|
48
|
+
validateMode(configPath);
|
|
49
|
+
try {
|
|
50
|
+
return loadConfig(dataDir, 'run-registry', RunRegistryConfigSchema);
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
throw new RunRegistryError(RUN_REGISTRY_ERROR_CODES.E_CFG_INVALID, 'run-registry config is invalid', error);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
if (options.configPath && existsSync(configPath)) {
|
|
57
|
+
validateMode(configPath);
|
|
58
|
+
try {
|
|
59
|
+
const parsed = readJson(configPath);
|
|
60
|
+
return RunRegistryConfigSchema.parse(parsed);
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
throw new RunRegistryError(RUN_REGISTRY_ERROR_CODES.E_CFG_INVALID, `failed to parse ${configPath}: ${error instanceof Error ? error.message : String(error)}`, error);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if (existsSync(legacyPath)) {
|
|
67
|
+
validateMode(legacyPath);
|
|
68
|
+
console.warn('[run-registry] deprecated legacy config.json path in use; migrate to config/run-registry.json');
|
|
69
|
+
return parseLegacyConfig(legacyPath);
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
return loadConfig(dataDir, 'run-registry', RunRegistryConfigSchema);
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
throw new RunRegistryError(RUN_REGISTRY_ERROR_CODES.E_CFG_MISSING, 'run-registry config is missing', error);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* W3.2 F15 Run Registry — SPEC contracts
|
|
3
|
+
* ≤200 lines · zod schemas + derived TS types · no runtime imports
|
|
4
|
+
*
|
|
5
|
+
* Import-only from W3.1 runtime (do NOT modify):
|
|
6
|
+
* EVENT_TYPES, ENTRY_FORMS, DEFAULT_RETRY_POLICY, AuditRecord, RunSpec
|
|
7
|
+
*/
|
|
8
|
+
import { z } from 'zod';
|
|
9
|
+
import { ENTRY_FORMS, DEFAULT_RETRY_POLICY } from '../audit-pipe/contracts.js';
|
|
10
|
+
export { ENTRY_FORMS, DEFAULT_RETRY_POLICY };
|
|
11
|
+
export const RUN_STATUS = {
|
|
12
|
+
PENDING: 'pending',
|
|
13
|
+
ACTIVE: 'active',
|
|
14
|
+
FINALIZING: 'finalizing',
|
|
15
|
+
SUCCEEDED: 'succeeded',
|
|
16
|
+
FAILED: 'failed',
|
|
17
|
+
CANCELLED: 'cancelled',
|
|
18
|
+
};
|
|
19
|
+
const RunStatusSchema = z.enum([
|
|
20
|
+
'pending', 'active', 'finalizing', 'succeeded', 'failed', 'cancelled',
|
|
21
|
+
]);
|
|
22
|
+
export const RunRecordSchema = z.object({
|
|
23
|
+
run_id: z.string().min(1),
|
|
24
|
+
created_at: z.string().datetime(),
|
|
25
|
+
operator: z.string(),
|
|
26
|
+
project: z.string().nullable(),
|
|
27
|
+
cwd: z.string(),
|
|
28
|
+
scope: z.string(),
|
|
29
|
+
agent: z.string(),
|
|
30
|
+
cmd: z.string(),
|
|
31
|
+
status: RunStatusSchema,
|
|
32
|
+
cost_tokens: z.number().int().nullable(),
|
|
33
|
+
cost_minutes: z.number().nullable(),
|
|
34
|
+
produced_doc_urls: z.array(z.string().url()),
|
|
35
|
+
commit_shas: z.array(z.string()),
|
|
36
|
+
doc_sink_failed: z.boolean(),
|
|
37
|
+
calendar_block_id: z.string().nullable(),
|
|
38
|
+
calendar_hook_failed: z.boolean(),
|
|
39
|
+
risk_level: z.enum(['unknown', 'low', 'medium', 'high']),
|
|
40
|
+
home_group_id: z.string().nullable(),
|
|
41
|
+
entry_form: z.enum(ENTRY_FORMS),
|
|
42
|
+
});
|
|
43
|
+
export const RunUpsertedSchema = z.object({
|
|
44
|
+
event: z.literal('RunUpserted'),
|
|
45
|
+
run_id: z.string().min(1),
|
|
46
|
+
session_id: z.string(),
|
|
47
|
+
revision: z.number().int().min(0),
|
|
48
|
+
status: RunStatusSchema,
|
|
49
|
+
cost_tokens: z.number().int().nullable(),
|
|
50
|
+
cost_minutes: z.number().nullable(),
|
|
51
|
+
produced_doc_urls: z.array(z.string().url()),
|
|
52
|
+
commit_shas: z.array(z.string()),
|
|
53
|
+
doc_sink_failed: z.boolean(),
|
|
54
|
+
calendar_block_id: z.string().nullable(),
|
|
55
|
+
calendar_hook_failed: z.boolean(),
|
|
56
|
+
updated_at: z.string().datetime(),
|
|
57
|
+
});
|
|
58
|
+
export const RunQuerySchema = z.object({
|
|
59
|
+
keyword: z.string().optional(),
|
|
60
|
+
operator: z.string().optional(),
|
|
61
|
+
project: z.string().optional(),
|
|
62
|
+
agent: z.string().optional(),
|
|
63
|
+
entry_form: z.enum(ENTRY_FORMS).optional(),
|
|
64
|
+
status: RunStatusSchema.optional(),
|
|
65
|
+
after: z.string().datetime().optional(),
|
|
66
|
+
before: z.string().datetime().optional(),
|
|
67
|
+
limit: z.number().int().min(1).max(50).default(20),
|
|
68
|
+
cursor: z.string().optional(),
|
|
69
|
+
});
|
|
70
|
+
export const RunQueryResultSchema = z.object({
|
|
71
|
+
runs: z.array(RunRecordSchema),
|
|
72
|
+
next_cursor: z.string().nullable(),
|
|
73
|
+
total_hint: z.number().int().nullable(),
|
|
74
|
+
});
|
|
75
|
+
export const RunInheritSpecSchema = z.object({
|
|
76
|
+
from_run_id: z.string().min(1),
|
|
77
|
+
inherit_fields: z.array(z.enum([
|
|
78
|
+
'project', 'cwd', 'scope', 'agent', 'home_group_id', 'entry_form',
|
|
79
|
+
])),
|
|
80
|
+
new_run_id: z.string().min(1),
|
|
81
|
+
});
|
|
82
|
+
export const RunRegistryConfigSchema = z.object({
|
|
83
|
+
bitable_base_id: z.string().min(1),
|
|
84
|
+
bitable_table_id: z.string().min(1),
|
|
85
|
+
app_id: z.string().min(1),
|
|
86
|
+
app_secret: z.string().min(1),
|
|
87
|
+
lark_domain: z.string().url(),
|
|
88
|
+
run_finalize_grace_ms: z.number().int().positive().default(30_000),
|
|
89
|
+
doc_url_allowlist: z.array(z.string()).default([
|
|
90
|
+
'*.larkoffice.com', '*.feishu.cn', 'github.com',
|
|
91
|
+
]),
|
|
92
|
+
});
|
|
93
|
+
export const RUN_REGISTRY_ERROR_CODES = {
|
|
94
|
+
E_CFG_MISSING: 'registry.config.missing',
|
|
95
|
+
E_CFG_INVALID: 'registry.config.invalid',
|
|
96
|
+
E_SCHEMA_MISMATCH: 'registry.schema.mismatch',
|
|
97
|
+
E_BITABLE_WRITE: 'registry.bitable.write_failed',
|
|
98
|
+
E_BITABLE_RETRY_EXHAUSTED: 'registry.bitable.retry_exhausted',
|
|
99
|
+
E_WAL_WRITE: 'registry.wal.write_failed',
|
|
100
|
+
E_TAILER_READ: 'registry.tailer.read_error',
|
|
101
|
+
E_INHERIT_NOT_FOUND: 'registry.inherit.run_not_found',
|
|
102
|
+
E_QUERY_TIMEOUT: 'registry.query.timeout',
|
|
103
|
+
E_DOC_SINK_WRITE: 'registry.doc_sink.write_failed',
|
|
104
|
+
};
|
|
105
|
+
export class RunRegistryError extends Error {
|
|
106
|
+
code;
|
|
107
|
+
cause;
|
|
108
|
+
constructor(code, message, cause) {
|
|
109
|
+
super(`[${code}] ${message}`);
|
|
110
|
+
this.code = code;
|
|
111
|
+
this.cause = cause;
|
|
112
|
+
this.name = 'RunRegistryError';
|
|
113
|
+
}
|
|
114
|
+
}
|
|
Binary file
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { resolve } from 'node:path';
|
|
4
|
+
import { RUN_REGISTRY_ERROR_CODES, RunRegistryError } from './contracts.js';
|
|
5
|
+
const DEFAULT_TIMEOUT_MS = 15_000;
|
|
6
|
+
const URL_PATTERN = /https:\/\/[^\s"']+/g;
|
|
7
|
+
const DOC_URL_PATTERN = /^https:\/\/[\w.-]+\/.+\/(?:docx|docs)\//i;
|
|
8
|
+
function resolveCommand(command) {
|
|
9
|
+
if (command.includes('/'))
|
|
10
|
+
return resolve(command);
|
|
11
|
+
return command;
|
|
12
|
+
}
|
|
13
|
+
function findDocUrl(output) {
|
|
14
|
+
const urls = output.match(URL_PATTERN) ?? [];
|
|
15
|
+
return urls.find((url) => DOC_URL_PATTERN.test(url)) ?? null;
|
|
16
|
+
}
|
|
17
|
+
export function createLarkDocTransport(options = {}) {
|
|
18
|
+
const baseArgs = options.args ?? ['docs', '+create', '--doc-format', 'markdown'];
|
|
19
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
20
|
+
return {
|
|
21
|
+
async create(input) {
|
|
22
|
+
const command = resolveCommand(options.command ?? 'lark-cli');
|
|
23
|
+
if (command.includes('/') && !existsSync(command)) {
|
|
24
|
+
throw new RunRegistryError(RUN_REGISTRY_ERROR_CODES.E_DOC_SINK_WRITE, `doc sink command not found: ${command}`);
|
|
25
|
+
}
|
|
26
|
+
const args = [...baseArgs, '--title', input.title, '--content', input.body];
|
|
27
|
+
const child = spawn(command, args, {
|
|
28
|
+
cwd: input.cwd,
|
|
29
|
+
env: input.env,
|
|
30
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
31
|
+
});
|
|
32
|
+
const stdout = [];
|
|
33
|
+
const stderr = [];
|
|
34
|
+
child.stdout?.on('data', (chunk) => stdout.push(Buffer.from(chunk)));
|
|
35
|
+
child.stderr?.on('data', (chunk) => stderr.push(Buffer.from(chunk)));
|
|
36
|
+
const result = await new Promise((resolvePromise, reject) => {
|
|
37
|
+
const timer = setTimeout(() => {
|
|
38
|
+
child.kill('SIGTERM');
|
|
39
|
+
reject(new RunRegistryError(RUN_REGISTRY_ERROR_CODES.E_DOC_SINK_WRITE, `doc sink timed out after ${timeoutMs}ms`));
|
|
40
|
+
}, timeoutMs);
|
|
41
|
+
child.once('error', (error) => {
|
|
42
|
+
clearTimeout(timer);
|
|
43
|
+
reject(new RunRegistryError(RUN_REGISTRY_ERROR_CODES.E_DOC_SINK_WRITE, 'doc sink spawn failed', error));
|
|
44
|
+
});
|
|
45
|
+
child.once('close', (code) => {
|
|
46
|
+
clearTimeout(timer);
|
|
47
|
+
const output = Buffer.concat([...stdout, ...stderr]).toString('utf8').trim();
|
|
48
|
+
if (code !== 0) {
|
|
49
|
+
reject(new RunRegistryError(RUN_REGISTRY_ERROR_CODES.E_DOC_SINK_WRITE, output || `doc sink exited with code ${code ?? -1}`));
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
const url = findDocUrl(output);
|
|
53
|
+
if (!url) {
|
|
54
|
+
reject(new RunRegistryError(RUN_REGISTRY_ERROR_CODES.E_DOC_SINK_WRITE, `doc sink did not return a doc url: ${output || '<empty>'}`));
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
resolvePromise({ url, rawOutput: output });
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
return result;
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
}
|