@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,38 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { parseArgs } from 'node:util';
|
|
3
|
+
import { startAuditPipe } from './index.js';
|
|
4
|
+
import { isEntryModule } from '../util/entry-module.js';
|
|
5
|
+
export function resolveAuditPipeCommand(argv) {
|
|
6
|
+
const parsed = parseArgs({
|
|
7
|
+
args: argv,
|
|
8
|
+
allowPositionals: false,
|
|
9
|
+
options: {
|
|
10
|
+
once: { type: 'boolean', default: false },
|
|
11
|
+
interval: { type: 'string' },
|
|
12
|
+
},
|
|
13
|
+
});
|
|
14
|
+
const intervalRaw = parsed.values.interval;
|
|
15
|
+
return { once: parsed.values.once, intervalMs: intervalRaw ? Number.parseInt(intervalRaw, 10) : undefined };
|
|
16
|
+
}
|
|
17
|
+
async function main() {
|
|
18
|
+
const command = resolveAuditPipeCommand(process.argv.slice(2));
|
|
19
|
+
const controller = await startAuditPipe();
|
|
20
|
+
if (command.once) {
|
|
21
|
+
const waitMs = command.intervalMs && command.intervalMs > 0 ? Math.min(command.intervalMs, 1_000) : 1_000;
|
|
22
|
+
await new Promise((resolve) => setTimeout(resolve, waitMs));
|
|
23
|
+
await controller.stop();
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
await new Promise((resolve) => {
|
|
27
|
+
const shutdown = () => { void controller.stop().finally(resolve); };
|
|
28
|
+
process.once('SIGINT', shutdown);
|
|
29
|
+
process.once('SIGTERM', shutdown);
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
const isEntry = isEntryModule(import.meta.url);
|
|
33
|
+
if (isEntry) {
|
|
34
|
+
void main().catch((error) => {
|
|
35
|
+
process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
|
|
36
|
+
process.exit(1);
|
|
37
|
+
});
|
|
38
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import * as Lark from '@larksuiteoapi/node-sdk';
|
|
2
|
+
import { AUDIT_PIPE_ERROR_CODES } from './contracts.js';
|
|
3
|
+
function isRecord(value) {
|
|
4
|
+
return typeof value === 'object' && value !== null;
|
|
5
|
+
}
|
|
6
|
+
function sleep(ms) {
|
|
7
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
8
|
+
}
|
|
9
|
+
function formatSDKLogArg(value) {
|
|
10
|
+
if (typeof value === 'string')
|
|
11
|
+
return value;
|
|
12
|
+
if (value instanceof Error)
|
|
13
|
+
return value.message;
|
|
14
|
+
try {
|
|
15
|
+
return JSON.stringify(value);
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return String(value);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function flattenSDKLogArgs(values) {
|
|
22
|
+
if (values.length === 1 && Array.isArray(values[0])) {
|
|
23
|
+
return flattenSDKLogArgs(values[0]);
|
|
24
|
+
}
|
|
25
|
+
return values.map(formatSDKLogArg);
|
|
26
|
+
}
|
|
27
|
+
function writeSDKLog(level, values) {
|
|
28
|
+
const body = flattenSDKLogArgs(values).join(' ');
|
|
29
|
+
const tokenLike = /request token|use cache token|get tenant access token|tenant_access_token/i.test(body);
|
|
30
|
+
const prefix = tokenLike ? `[lark-sdk:tenant_access_token:${level}]` : `[lark-sdk:${level}]`;
|
|
31
|
+
const safeBody = tokenLike ? '<redacted>' : body;
|
|
32
|
+
const message = `${prefix} ${safeBody}`;
|
|
33
|
+
if (level === 'error') {
|
|
34
|
+
console.error(message);
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
if (level === 'warn') {
|
|
38
|
+
console.warn(message);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
if (level === 'trace') {
|
|
42
|
+
console.trace(message);
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
console.log(message);
|
|
46
|
+
}
|
|
47
|
+
const SDK_LOGGER = {
|
|
48
|
+
error: (...msg) => writeSDKLog('error', msg),
|
|
49
|
+
warn: (...msg) => writeSDKLog('warn', msg),
|
|
50
|
+
info: (...msg) => writeSDKLog('info', msg),
|
|
51
|
+
debug: (...msg) => writeSDKLog('debug', msg),
|
|
52
|
+
trace: (...msg) => writeSDKLog('trace', msg),
|
|
53
|
+
};
|
|
54
|
+
function createClient({ appId, appSecret, larkDomain }) {
|
|
55
|
+
// Domain comes from config audit.lark_domain, e.g. https://open.larkoffice.com.
|
|
56
|
+
return new Lark.Client({
|
|
57
|
+
appId,
|
|
58
|
+
appSecret,
|
|
59
|
+
domain: larkDomain,
|
|
60
|
+
loggerLevel: Lark.LoggerLevel.debug,
|
|
61
|
+
logger: SDK_LOGGER,
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
function formatFields(record) {
|
|
65
|
+
return {
|
|
66
|
+
audit_record_id: record.audit_record_id,
|
|
67
|
+
session_id: record.session_id,
|
|
68
|
+
run_id: record.run_id,
|
|
69
|
+
revision: record.revision,
|
|
70
|
+
actor: record.actor,
|
|
71
|
+
action: record.action,
|
|
72
|
+
resource: record.resource.slice(0, 500),
|
|
73
|
+
ts: Date.parse(record.ts),
|
|
74
|
+
entry_form: record.entry_form,
|
|
75
|
+
entry_detail: JSON.stringify(record.entry_detail),
|
|
76
|
+
agent_id: record.agent_id,
|
|
77
|
+
raw_tool_use_id: record.raw_tool_use_id,
|
|
78
|
+
raw_tool_name: record.raw_tool_name,
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
function isRetryableCode(code) {
|
|
82
|
+
return code === 99991663 || code === 99991661 || code >= 99990000;
|
|
83
|
+
}
|
|
84
|
+
function httpStatusFromError(error) {
|
|
85
|
+
if (!isRecord(error) || !isRecord(error['response']))
|
|
86
|
+
return undefined;
|
|
87
|
+
const status = error['response']['status'];
|
|
88
|
+
return typeof status === 'number' ? status : undefined;
|
|
89
|
+
}
|
|
90
|
+
function nextDelay(retry, attempt) {
|
|
91
|
+
const base = Math.min(retry.baseMs * retry.factor ** (attempt - 1), retry.capMs);
|
|
92
|
+
const spread = base * retry.jitterRatio;
|
|
93
|
+
return Math.max(0, Math.round(base + (Math.random() * 2 - 1) * spread));
|
|
94
|
+
}
|
|
95
|
+
export function createBitableSink(options) {
|
|
96
|
+
const client = options._client ?? createClient(options);
|
|
97
|
+
return {
|
|
98
|
+
async flush() {
|
|
99
|
+
const recordIds = [];
|
|
100
|
+
let last = { ok: true, record_ids: recordIds, attempt: 0 };
|
|
101
|
+
for await (const entry of options.wal.replay()) {
|
|
102
|
+
const payload = {
|
|
103
|
+
path: { app_token: options.baseId, table_id: options.tableId },
|
|
104
|
+
params: { client_token: entry.record.audit_record_id },
|
|
105
|
+
data: { records: [{ fields: formatFields(entry.record) }] },
|
|
106
|
+
};
|
|
107
|
+
let delivered = false;
|
|
108
|
+
for (let attempt = 1; attempt <= options.retry.maxAttempts; attempt += 1) {
|
|
109
|
+
last = { ok: false, record_ids: recordIds, attempt };
|
|
110
|
+
try {
|
|
111
|
+
const response = await client.bitable.appTableRecord.batchCreate(payload);
|
|
112
|
+
const code = typeof response.code === 'number' ? response.code : 0;
|
|
113
|
+
const msg = typeof response.msg === 'string' ? response.msg : undefined;
|
|
114
|
+
if (code === 0) {
|
|
115
|
+
options.wal.ack(entry.seq);
|
|
116
|
+
delivered = true;
|
|
117
|
+
const ids = response.data?.records?.flatMap((item) => item.record_id ? [item.record_id] : []) ?? [];
|
|
118
|
+
recordIds.push(...ids);
|
|
119
|
+
last = { ok: true, record_ids: recordIds, lark_code: code, lark_msg: msg, attempt };
|
|
120
|
+
break;
|
|
121
|
+
}
|
|
122
|
+
if (isRetryableCode(code)) {
|
|
123
|
+
options.wal.bumpAttempts(entry.seq);
|
|
124
|
+
last = { ok: false, record_ids: recordIds, lark_code: code, lark_msg: msg, attempt };
|
|
125
|
+
if (attempt < options.retry.maxAttempts)
|
|
126
|
+
await sleep(nextDelay(options.retry, attempt));
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
options.wal.markPendingSync(entry.seq);
|
|
130
|
+
last = { ok: false, record_ids: recordIds, lark_code: code, lark_msg: msg, attempt };
|
|
131
|
+
delivered = true;
|
|
132
|
+
break;
|
|
133
|
+
}
|
|
134
|
+
catch (error) {
|
|
135
|
+
const status = httpStatusFromError(error);
|
|
136
|
+
if (typeof status === 'number' && status >= 400 && status < 500) {
|
|
137
|
+
options.wal.markPendingSync(entry.seq);
|
|
138
|
+
last = { ok: false, record_ids: recordIds, http_status: status, lark_msg: AUDIT_PIPE_ERROR_CODES.E_BITABLE_HTTP_4XX, attempt };
|
|
139
|
+
delivered = true;
|
|
140
|
+
break;
|
|
141
|
+
}
|
|
142
|
+
options.wal.bumpAttempts(entry.seq);
|
|
143
|
+
last = { ok: false, record_ids: recordIds, http_status: status, lark_msg: AUDIT_PIPE_ERROR_CODES.E_BITABLE_HTTP_5XX, attempt };
|
|
144
|
+
if (attempt < options.retry.maxAttempts)
|
|
145
|
+
await sleep(nextDelay(options.retry, attempt));
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
if (!delivered) {
|
|
149
|
+
options.wal.markPendingSync(entry.seq);
|
|
150
|
+
last = { ok: false, record_ids: recordIds, lark_msg: AUDIT_PIPE_ERROR_CODES.E_BITABLE_RETRY_EXHAUSTED, attempt: options.retry.maxAttempts };
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return last;
|
|
154
|
+
},
|
|
155
|
+
};
|
|
156
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { existsSync, readFileSync, statSync } from 'node:fs';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { configFile, legacyConfigJsonPath, resolveDataDir } from '../paths.js';
|
|
4
|
+
import { AUDIT_PIPE_ERROR_CODES, AuditPipeConfigSchema, AuditPipeError } from './contracts.js';
|
|
5
|
+
function isRecord(value) {
|
|
6
|
+
return typeof value === 'object' && value !== null;
|
|
7
|
+
}
|
|
8
|
+
function asConfigSource(value) {
|
|
9
|
+
if (!isRecord(value) || typeof value['type'] !== 'string') {
|
|
10
|
+
throw new AuditPipeError(AUDIT_PIPE_ERROR_CODES.E_CFG_BAD_SOURCE_TYPE, 'config source type is missing');
|
|
11
|
+
}
|
|
12
|
+
if (value['type'] === 'literal' && typeof value['value'] === 'string') {
|
|
13
|
+
return { type: 'literal', value: value['value'] };
|
|
14
|
+
}
|
|
15
|
+
if (value['type'] === 'env' && typeof value['name'] === 'string') {
|
|
16
|
+
return { type: 'env', name: value['name'] };
|
|
17
|
+
}
|
|
18
|
+
throw new AuditPipeError(AUDIT_PIPE_ERROR_CODES.E_CFG_BAD_SOURCE_TYPE, `unknown source type: ${String(value['type'])}`);
|
|
19
|
+
}
|
|
20
|
+
export function resolveAuditDataDir(env = process.env) {
|
|
21
|
+
return resolveDataDir({ dataDir: env['WB_DATA_DIR'] });
|
|
22
|
+
}
|
|
23
|
+
export function resolveAuditPipeConfigPath(env = process.env) {
|
|
24
|
+
return resolve(configFile(resolveAuditDataDir(env), 'audit-pipe'));
|
|
25
|
+
}
|
|
26
|
+
export function resolveSource(src, env) {
|
|
27
|
+
if (src.type === 'literal') {
|
|
28
|
+
if (!src.value || src.value.startsWith('<')) {
|
|
29
|
+
throw new AuditPipeError(AUDIT_PIPE_ERROR_CODES.E_CFG_PLACEHOLDER, 'config value is still a placeholder');
|
|
30
|
+
}
|
|
31
|
+
return src.value;
|
|
32
|
+
}
|
|
33
|
+
if (src.type === 'env') {
|
|
34
|
+
const value = env[src.name];
|
|
35
|
+
if (!value) {
|
|
36
|
+
throw new AuditPipeError(AUDIT_PIPE_ERROR_CODES.E_CFG_MISSING_ENV, `env ${src.name} is missing`);
|
|
37
|
+
}
|
|
38
|
+
return value;
|
|
39
|
+
}
|
|
40
|
+
throw new AuditPipeError(AUDIT_PIPE_ERROR_CODES.E_CFG_BAD_SOURCE_TYPE, 'unknown config source type');
|
|
41
|
+
}
|
|
42
|
+
function validateMode(path) {
|
|
43
|
+
const stat = statSync(path);
|
|
44
|
+
if ((stat.mode & 0o077) !== 0) {
|
|
45
|
+
throw new AuditPipeError(AUDIT_PIPE_ERROR_CODES.E_CFG_PERM_TOO_OPEN, `${path} permissions are too open (${(stat.mode & 0o777).toString(8)}), expected 600`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function parseDomainConfig(raw, env) {
|
|
49
|
+
if (!isRecord(raw)) {
|
|
50
|
+
throw new AuditPipeError(AUDIT_PIPE_ERROR_CODES.E_CFG_INVALID_JSON, 'audit-pipe config must be an object');
|
|
51
|
+
}
|
|
52
|
+
if (raw['enabled'] === false) {
|
|
53
|
+
return AuditPipeConfigSchema.parse({ audit: { enabled: false } });
|
|
54
|
+
}
|
|
55
|
+
if (raw['enabled'] !== true) {
|
|
56
|
+
throw new AuditPipeError(AUDIT_PIPE_ERROR_CODES.E_CFG_INVALID_JSON, 'enabled must be a boolean');
|
|
57
|
+
}
|
|
58
|
+
return AuditPipeConfigSchema.parse({
|
|
59
|
+
audit: {
|
|
60
|
+
enabled: true,
|
|
61
|
+
bitable_base_id: resolveSource(asConfigSource(raw['bitable_base_id']), env),
|
|
62
|
+
bitable_table_id: resolveSource(asConfigSource(raw['bitable_table_id']), env),
|
|
63
|
+
app_id: resolveSource(asConfigSource(raw['app_id']), env),
|
|
64
|
+
app_secret: resolveSource(asConfigSource(raw['app_secret']), env),
|
|
65
|
+
lark_domain: typeof raw['lark_domain'] === 'string' && raw['lark_domain'].trim().length > 0 ? raw['lark_domain'].trim() : 'https://open.larkoffice.com',
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
function parseLegacyConfig(raw, env) {
|
|
70
|
+
if (!isRecord(raw) || !isRecord(raw['audit'])) {
|
|
71
|
+
return AuditPipeConfigSchema.parse({ audit: { enabled: false } });
|
|
72
|
+
}
|
|
73
|
+
return parseDomainConfig(raw['audit'], env);
|
|
74
|
+
}
|
|
75
|
+
function readJson(path) {
|
|
76
|
+
try {
|
|
77
|
+
return JSON.parse(readFileSync(path, 'utf8'));
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
throw new AuditPipeError(AUDIT_PIPE_ERROR_CODES.E_CFG_INVALID_JSON, `failed to parse ${path}: ${error instanceof Error ? error.message : String(error)}`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
export function loadAuditPipeConfig(options = {}) {
|
|
84
|
+
const env = options.env ?? process.env;
|
|
85
|
+
const dataDir = resolveAuditDataDir(env);
|
|
86
|
+
const configPath = resolve(options.configPath ?? resolveAuditPipeConfigPath(env));
|
|
87
|
+
const legacyPath = resolve(legacyConfigJsonPath(dataDir));
|
|
88
|
+
if (existsSync(configPath)) {
|
|
89
|
+
validateMode(configPath);
|
|
90
|
+
const parsed = readJson(configPath);
|
|
91
|
+
if (configPath.endsWith('config.json'))
|
|
92
|
+
return parseLegacyConfig(parsed, env);
|
|
93
|
+
return parseDomainConfig(parsed, env);
|
|
94
|
+
}
|
|
95
|
+
if (options.configPath) {
|
|
96
|
+
return AuditPipeConfigSchema.parse({ audit: { enabled: false } });
|
|
97
|
+
}
|
|
98
|
+
if (existsSync(legacyPath)) {
|
|
99
|
+
validateMode(legacyPath);
|
|
100
|
+
console.warn('[audit-pipe] deprecated legacy config.json path in use; migrate to config/audit-pipe.json');
|
|
101
|
+
const parsed = readJson(legacyPath);
|
|
102
|
+
return parseLegacyConfig(parsed, env);
|
|
103
|
+
}
|
|
104
|
+
return AuditPipeConfigSchema.parse({ audit: { enabled: false } });
|
|
105
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export const EVENT_TYPES = ['file_read', 'file_write', 'shell_exec', 'network_call', 'env_access', 'git_op', 'other'];
|
|
3
|
+
export const ENTRY_FORMS = ['im', 'cli'];
|
|
4
|
+
export const RetryPolicySchema = z.object({ maxAttempts: z.literal(5), baseMs: z.number().int().positive(), factor: z.number().positive(), capMs: z.number().int().positive(), jitterRatio: z.number().min(0).max(1) });
|
|
5
|
+
export const DEFAULT_RETRY_POLICY = { maxAttempts: 5, baseMs: 1000, factor: 2, capMs: 30_000, jitterRatio: 0.2 };
|
|
6
|
+
const EnabledAuditConfigSchema = z.object({ audit: z.object({ enabled: z.literal(true), bitable_base_id: z.string().min(1), bitable_table_id: z.string().min(1), app_id: z.string().min(1), app_secret: z.string().min(1), lark_domain: z.string().url() }) });
|
|
7
|
+
const DisabledAuditConfigSchema = z.object({ audit: z.object({ enabled: z.literal(false) }) });
|
|
8
|
+
export const AuditPipeConfigSchema = z.union([EnabledAuditConfigSchema, DisabledAuditConfigSchema]);
|
|
9
|
+
export const AUDIT_PIPE_ERROR_CODES = {
|
|
10
|
+
E_CFG_MISSING_FILE: 'audit.config.missing_file',
|
|
11
|
+
E_CFG_INVALID_JSON: 'audit.config.invalid_json',
|
|
12
|
+
E_CFG_MISSING_ENV: 'audit.config.missing_env',
|
|
13
|
+
E_CFG_PLACEHOLDER: 'audit.config.placeholder',
|
|
14
|
+
E_CFG_BAD_SOURCE_TYPE: 'audit.config.bad_source_type',
|
|
15
|
+
E_CFG_PERM_TOO_OPEN: 'audit.config.perm_too_open',
|
|
16
|
+
E_PARSE_BAD_LINE: 'audit.parse.bad_line',
|
|
17
|
+
E_NORM_MISSING_SPEC: 'audit.normalizer.missing_spec',
|
|
18
|
+
E_NORM_INVALID_ENTRY_FORM: 'audit.normalizer.invalid_entry_form',
|
|
19
|
+
E_MIRROR_WRITE_FATAL: 'audit.mirror.write_fatal',
|
|
20
|
+
E_WAL_WRITE: 'audit.wal.write',
|
|
21
|
+
E_BITABLE_HTTP_4XX: 'audit.bitable.http_4xx',
|
|
22
|
+
E_BITABLE_HTTP_5XX: 'audit.bitable.http_5xx',
|
|
23
|
+
E_BITABLE_LARK_CODE: 'audit.bitable.lark_code_nonzero',
|
|
24
|
+
E_BITABLE_RETRY_EXHAUSTED: 'audit.bitable.retry_exhausted',
|
|
25
|
+
};
|
|
26
|
+
export class AuditPipeError extends Error {
|
|
27
|
+
code;
|
|
28
|
+
constructor(code, message) {
|
|
29
|
+
super(`[${code}] ${message}`);
|
|
30
|
+
this.code = code;
|
|
31
|
+
this.name = 'AuditPipeError';
|
|
32
|
+
}
|
|
33
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { mkdirSync } from 'node:fs';
|
|
2
|
+
import { auditMirrorPath } from '../paths.js';
|
|
3
|
+
import { appendNdjsonLine } from '../util/ndjson-rotation.js';
|
|
4
|
+
import { AUDIT_PIPE_ERROR_CODES } from './contracts.js';
|
|
5
|
+
export function createMirrorSink({ dataDir }) {
|
|
6
|
+
mkdirSync(dataDir, { recursive: true });
|
|
7
|
+
const path = auditMirrorPath(dataDir);
|
|
8
|
+
return {
|
|
9
|
+
path,
|
|
10
|
+
write(record) {
|
|
11
|
+
try {
|
|
12
|
+
appendNdjsonLine(path, JSON.stringify(record), { fsync: true });
|
|
13
|
+
}
|
|
14
|
+
catch (error) {
|
|
15
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
16
|
+
console.error(`FATAL ${AUDIT_PIPE_ERROR_CODES.E_MIRROR_WRITE_FATAL}: ${message}`);
|
|
17
|
+
process.exit(2);
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
}
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
const revisionByKey = new Map();
|
|
3
|
+
const recordIdByKey = new Map();
|
|
4
|
+
let nextRevision = 1;
|
|
5
|
+
function cacheKey(runId, toolUseId) {
|
|
6
|
+
return `${runId}:${toolUseId}`;
|
|
7
|
+
}
|
|
8
|
+
function isRecord(value) {
|
|
9
|
+
return typeof value === 'object' && value !== null;
|
|
10
|
+
}
|
|
11
|
+
function readString(value) {
|
|
12
|
+
return typeof value === 'string' ? value : null;
|
|
13
|
+
}
|
|
14
|
+
function classifyBash(command) {
|
|
15
|
+
if (/\$\{?[A-Z][A-Z0-9_]*\}?/.test(command))
|
|
16
|
+
return 'env_access';
|
|
17
|
+
if (/\bgit\b/.test(command))
|
|
18
|
+
return 'git_op';
|
|
19
|
+
return 'shell_exec';
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Check whether a tool_use input references a (potentially sensitive) env var.
|
|
23
|
+
* Catches `$NAME`, `${NAME}` inside `command`, plus `env.NAME` / `process.env.NAME`.
|
|
24
|
+
* Returns the matched names so callers can emit an independent env_filter_hit flag.
|
|
25
|
+
*/
|
|
26
|
+
export function detectEnvVarReferences(input) {
|
|
27
|
+
const found = new Set();
|
|
28
|
+
if (!input || typeof input !== 'object')
|
|
29
|
+
return [];
|
|
30
|
+
const command = input.command;
|
|
31
|
+
if (typeof command === 'string' && command) {
|
|
32
|
+
for (const match of command.matchAll(/\$\{?([A-Z][A-Z0-9_]*)\}?/g)) {
|
|
33
|
+
if (match[1])
|
|
34
|
+
found.add(match[1]);
|
|
35
|
+
}
|
|
36
|
+
for (const match of command.matchAll(/process\.env\.([A-Z][A-Z0-9_]*)/g)) {
|
|
37
|
+
if (match[1])
|
|
38
|
+
found.add(match[1]);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return [...found].sort();
|
|
42
|
+
}
|
|
43
|
+
function deriveAction(event) {
|
|
44
|
+
if (event.name === 'Read' || event.name === 'Glob' || event.name === 'Grep')
|
|
45
|
+
return 'file_read';
|
|
46
|
+
if (event.name === 'Write' || event.name === 'Edit')
|
|
47
|
+
return 'file_write';
|
|
48
|
+
if (event.name === 'WebSearch' || event.name === 'WebFetch')
|
|
49
|
+
return 'network_call';
|
|
50
|
+
if (event.name === 'Bash') {
|
|
51
|
+
const command = isRecord(event.input) ? readString(event.input['command']) : null;
|
|
52
|
+
return classifyBash(command ?? '');
|
|
53
|
+
}
|
|
54
|
+
return 'other';
|
|
55
|
+
}
|
|
56
|
+
function deriveResource(action, input) {
|
|
57
|
+
const record = isRecord(input) ? input : {};
|
|
58
|
+
if (action === 'file_read' || action === 'file_write') {
|
|
59
|
+
return readString(record['file_path']) ?? readString(record['pattern']) ?? 'unknown';
|
|
60
|
+
}
|
|
61
|
+
if (action === 'shell_exec' || action === 'env_access' || action === 'git_op') {
|
|
62
|
+
return (readString(record['command']) ?? 'unknown').slice(0, 500);
|
|
63
|
+
}
|
|
64
|
+
if (action === 'network_call') {
|
|
65
|
+
return readString(record['url']) ?? readString(record['query']) ?? 'unknown';
|
|
66
|
+
}
|
|
67
|
+
return JSON.stringify(input).slice(0, 500);
|
|
68
|
+
}
|
|
69
|
+
function deriveEntry(spec) {
|
|
70
|
+
if (typeof spec.sourceMessageId !== 'string' || typeof spec.userOpenId !== 'string' || typeof spec.threadId !== 'string' || typeof spec.host !== 'string') {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
if (spec.sourceMessageId.length > 0) {
|
|
74
|
+
return { entryForm: 'im', entryDetail: { source_message_id: spec.sourceMessageId, user_open_id: spec.userOpenId, thread_id: spec.threadId } };
|
|
75
|
+
}
|
|
76
|
+
return { entryForm: 'cli', entryDetail: { user_open_id: spec.userOpenId, host: spec.host } };
|
|
77
|
+
}
|
|
78
|
+
function createRejected(reason, runId, rawLine, now) {
|
|
79
|
+
return { audit_record_id: randomUUID(), status: 'rejected', reason, raw_line: rawLine.slice(0, 2048), ts: now, run_id: runId };
|
|
80
|
+
}
|
|
81
|
+
export function resetNormalizerState() {
|
|
82
|
+
revisionByKey.clear();
|
|
83
|
+
recordIdByKey.clear();
|
|
84
|
+
nextRevision = 1;
|
|
85
|
+
}
|
|
86
|
+
export function hydrateNormalizer(records) {
|
|
87
|
+
let maxRevision = nextRevision - 1;
|
|
88
|
+
for (const record of records) {
|
|
89
|
+
const key = cacheKey(record.run_id, record.raw_tool_use_id);
|
|
90
|
+
revisionByKey.set(key, record.revision);
|
|
91
|
+
recordIdByKey.set(key, record.audit_record_id);
|
|
92
|
+
if (record.revision > maxRevision)
|
|
93
|
+
maxRevision = record.revision;
|
|
94
|
+
}
|
|
95
|
+
nextRevision = Math.max(nextRevision, maxRevision + 1);
|
|
96
|
+
}
|
|
97
|
+
export function normalize(event, spec, now = new Date().toISOString(), rawLine = JSON.stringify(event)) {
|
|
98
|
+
if (!spec)
|
|
99
|
+
return { kind: 'rejected', record: createRejected('missing_spec', null, rawLine, now) };
|
|
100
|
+
const entry = deriveEntry(spec);
|
|
101
|
+
if (!entry)
|
|
102
|
+
return { kind: 'rejected', record: createRejected('invalid_entry_form', spec.runId, rawLine, now) };
|
|
103
|
+
const key = cacheKey(spec.runId, event.id);
|
|
104
|
+
const revision = revisionByKey.get(key) ?? nextRevision++;
|
|
105
|
+
revisionByKey.set(key, revision);
|
|
106
|
+
const auditRecordId = recordIdByKey.get(key) ?? randomUUID();
|
|
107
|
+
recordIdByKey.set(key, auditRecordId);
|
|
108
|
+
const action = deriveAction(event);
|
|
109
|
+
const envHits = detectEnvVarReferences(event.input);
|
|
110
|
+
return {
|
|
111
|
+
kind: 'audit',
|
|
112
|
+
record: {
|
|
113
|
+
audit_record_id: auditRecordId,
|
|
114
|
+
session_id: spec.threadId,
|
|
115
|
+
run_id: spec.runId,
|
|
116
|
+
revision,
|
|
117
|
+
actor: spec.userOpenId,
|
|
118
|
+
action,
|
|
119
|
+
resource: deriveResource(action, event.input),
|
|
120
|
+
ts: now,
|
|
121
|
+
entry_form: entry.entryForm,
|
|
122
|
+
entry_detail: entry.entryDetail,
|
|
123
|
+
agent_id: 'claude-code',
|
|
124
|
+
raw_tool_use_id: event.id,
|
|
125
|
+
raw_tool_name: event.name,
|
|
126
|
+
...(envHits.length > 0 ? { env_filter_hit: true } : {}),
|
|
127
|
+
},
|
|
128
|
+
};
|
|
129
|
+
}
|