@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,108 @@
|
|
|
1
|
+
import { ATTACH_TIMEOUT_MS, REVERSE_CHANNEL_ERROR_CODES, ReverseChannelError } from './contracts.js';
|
|
2
|
+
import { CaptainService, CAPTAIN_ERROR_CODES, CaptainError } from '../captain/index.js';
|
|
3
|
+
import { encodeAuditResource } from './audit-encoder.js';
|
|
4
|
+
export async function handleAttachRequest(captainService, request) {
|
|
5
|
+
const current = captainService.getSession(request.session_id);
|
|
6
|
+
if (!current) {
|
|
7
|
+
return { outcome: 'not_found', session_id: request.session_id, candidates: [] };
|
|
8
|
+
}
|
|
9
|
+
const timeout = new Promise((_, reject) => {
|
|
10
|
+
setTimeout(() => reject(new ReverseChannelError(REVERSE_CHANNEL_ERROR_CODES.E_ATTACH_TIMEOUT, 'attach timed out')), ATTACH_TIMEOUT_MS);
|
|
11
|
+
});
|
|
12
|
+
const existing = current.record;
|
|
13
|
+
const work = (async () => {
|
|
14
|
+
if (existing.captain_id !== request.requester_captain_id && !request.force) {
|
|
15
|
+
return {
|
|
16
|
+
outcome: 'mutex_conflict',
|
|
17
|
+
session_id: request.session_id,
|
|
18
|
+
current_captain_id: existing.captain_id,
|
|
19
|
+
conflict_since: existing.last_active_at,
|
|
20
|
+
suggestion: 'use --force to take over',
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
const patched = {
|
|
24
|
+
captain_id: request.requester_captain_id,
|
|
25
|
+
status: 'active',
|
|
26
|
+
last_active_at: request.requested_at,
|
|
27
|
+
};
|
|
28
|
+
captainService.updateSession(request.session_id, patched);
|
|
29
|
+
try {
|
|
30
|
+
await captainService.flush();
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
throw new ReverseChannelError(REVERSE_CHANNEL_ERROR_CODES.E_ATTACH_FLUSH_FAILED, `attach flush failed: ${error instanceof Error ? error.message : String(error)}`, error);
|
|
34
|
+
}
|
|
35
|
+
return {
|
|
36
|
+
outcome: 'attached',
|
|
37
|
+
session_id: request.session_id,
|
|
38
|
+
session: captainService.getSession(request.session_id)?.record,
|
|
39
|
+
run_ids: captainService.getSession(request.session_id)?.run_ids ?? [],
|
|
40
|
+
};
|
|
41
|
+
})();
|
|
42
|
+
return Promise.race([work, timeout]);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* M11-D D2 (2026-08-04 owner-authorized): 同样的 attach 语义,但把 updated 提交到
|
|
46
|
+
* `CaptainSessionStore.upsertWithRevision` 而不是普通 upsert。在远端 session-store 已经
|
|
47
|
+
* 把 revision 推过别的值时,会抛 `CaptainError(E_REVISION_MISMATCH)`, 这里转换成
|
|
48
|
+
* `mutex_conflict` 让调用方端到端处理 (建议先 reconcile 再 force attach)。
|
|
49
|
+
*
|
|
50
|
+
* 返回 `expected` / `actual` 供 CLI 端把冲突状态写化到日志;调用方拿到该结果后通常
|
|
51
|
+
* 要么 reconcile 要么 force,不需要再额外索 store。
|
|
52
|
+
*/
|
|
53
|
+
export async function handleAttachRequestWithRevision(captainService, request) {
|
|
54
|
+
const current = captainService.getSession(request.session_id);
|
|
55
|
+
if (!current) {
|
|
56
|
+
return { outcome: 'not_found', session_id: request.session_id, candidates: [] };
|
|
57
|
+
}
|
|
58
|
+
const existing = current.record;
|
|
59
|
+
if (existing.captain_id !== request.requester_captain_id && !request.force) {
|
|
60
|
+
return {
|
|
61
|
+
outcome: 'mutex_conflict',
|
|
62
|
+
session_id: request.session_id,
|
|
63
|
+
current_captain_id: existing.captain_id,
|
|
64
|
+
conflict_since: existing.last_active_at,
|
|
65
|
+
suggestion: 'use --force to take over',
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
const expectedRevision = request.expected_revision ?? existing.revision;
|
|
69
|
+
const patched = {
|
|
70
|
+
...existing,
|
|
71
|
+
captain_id: request.requester_captain_id,
|
|
72
|
+
status: 'active',
|
|
73
|
+
last_active_at: request.requested_at,
|
|
74
|
+
revision: expectedRevision,
|
|
75
|
+
};
|
|
76
|
+
try {
|
|
77
|
+
captainService.updateSession(request.session_id, patched);
|
|
78
|
+
await captainService.flush();
|
|
79
|
+
return {
|
|
80
|
+
outcome: 'attached',
|
|
81
|
+
session_id: request.session_id,
|
|
82
|
+
session: captainService.getSession(request.session_id)?.record,
|
|
83
|
+
run_ids: captainService.getSession(request.session_id)?.run_ids ?? [],
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
if (error instanceof CaptainError && error.code === CAPTAIN_ERROR_CODES.E_REVISION_MISMATCH) {
|
|
88
|
+
const match = /actual=(\d+)/.exec(error.message);
|
|
89
|
+
const actual = match ? Number.parseInt(match[1], 10) : existing.revision;
|
|
90
|
+
return {
|
|
91
|
+
outcome: 'revision_mismatch',
|
|
92
|
+
session_id: request.session_id,
|
|
93
|
+
expected_revision: expectedRevision,
|
|
94
|
+
actual_revision: actual,
|
|
95
|
+
suggestion: 'run reconcile or use --force',
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
throw error;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
export function attachAuditResource(sessionId, previousCaptainId) {
|
|
102
|
+
return encodeAuditResource({ verb: 'attach', targetId: sessionId, result: 'ok', fromCaptainId: previousCaptainId });
|
|
103
|
+
}
|
|
104
|
+
export function attachRevisionMismatchAuditResource(sessionId, expected, actual) {
|
|
105
|
+
// Salt the fromCaptainId slot with the revisions so the audit sink keeps
|
|
106
|
+
// the conflict evidence without inventing a new field on the encoder.
|
|
107
|
+
return encodeAuditResource({ verb: 'attach', targetId: sessionId, result: 'fail', fromCaptainId: `rev_${expected}_to_${actual}` });
|
|
108
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { REVERSE_CHANNEL_ERROR_CODES } from './contracts.js';
|
|
2
|
+
export const REVERSE_CHANNEL_AUDIT_RESOURCE_PREFIX = 'reverse-channel:';
|
|
3
|
+
function sanitize(value) {
|
|
4
|
+
return value.replace(/[:\s]/g, '_');
|
|
5
|
+
}
|
|
6
|
+
export function redactSenderOpenId(openId) {
|
|
7
|
+
return `${openId.slice(0, 8)}***`;
|
|
8
|
+
}
|
|
9
|
+
function buildAndTruncate(parts, maxLen = 256) {
|
|
10
|
+
let raw = parts.join(':');
|
|
11
|
+
if (raw.length <= maxLen)
|
|
12
|
+
return raw;
|
|
13
|
+
const dropOrder = [
|
|
14
|
+
(part) => part.startsWith('result=fail:reason='),
|
|
15
|
+
(part) => part === 'result=ok',
|
|
16
|
+
(part) => part.startsWith('sig='),
|
|
17
|
+
(part) => part.startsWith('sender='),
|
|
18
|
+
(part) => part.startsWith('from='),
|
|
19
|
+
];
|
|
20
|
+
let working = [...parts];
|
|
21
|
+
for (const matcher of dropOrder) {
|
|
22
|
+
working = working.filter((part) => !matcher(part));
|
|
23
|
+
raw = working.join(':');
|
|
24
|
+
if (raw.length <= maxLen)
|
|
25
|
+
return raw;
|
|
26
|
+
}
|
|
27
|
+
return `${raw.slice(0, maxLen - 3)}...`;
|
|
28
|
+
}
|
|
29
|
+
export function encodeAuditResource(input) {
|
|
30
|
+
const parts = [`${REVERSE_CHANNEL_AUDIT_RESOURCE_PREFIX}${input.verb}`, sanitize(input.targetId)];
|
|
31
|
+
if (input.verb === 'attach' && input.fromCaptainId) {
|
|
32
|
+
parts.push(`from=${sanitize(input.fromCaptainId)}`);
|
|
33
|
+
}
|
|
34
|
+
if (input.senderOpenId) {
|
|
35
|
+
parts.push(`sender=${sanitize(redactSenderOpenId(input.senderOpenId))}`);
|
|
36
|
+
}
|
|
37
|
+
if (input.signal) {
|
|
38
|
+
parts.push(`sig=${input.signal}`);
|
|
39
|
+
}
|
|
40
|
+
if (input.result === 'ok') {
|
|
41
|
+
parts.push('result=ok');
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
parts.push(`result=fail:reason=${sanitize(input.reasonCode ?? 'unknown')}`);
|
|
45
|
+
}
|
|
46
|
+
return buildAndTruncate(parts);
|
|
47
|
+
}
|
|
48
|
+
export function decodeAuditResource(resource) {
|
|
49
|
+
const [prefix, verb, targetId = '', ...rest] = resource.split(':');
|
|
50
|
+
const safeVerb = prefix === REVERSE_CHANNEL_AUDIT_RESOURCE_PREFIX.slice(0, -1) ? (verb ?? '') : `${prefix}:${verb ?? ''}`;
|
|
51
|
+
const decoded = { verb: safeVerb, targetId };
|
|
52
|
+
for (const item of rest) {
|
|
53
|
+
if (item.startsWith('sender='))
|
|
54
|
+
decoded.sender = item.slice('sender='.length);
|
|
55
|
+
if (item.startsWith('sig='))
|
|
56
|
+
decoded.sig = item.slice('sig='.length);
|
|
57
|
+
if (item.startsWith('result='))
|
|
58
|
+
decoded.result = item.slice('result='.length);
|
|
59
|
+
}
|
|
60
|
+
return decoded;
|
|
61
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* W3.3 wb-cli Console + 反向@ — SPEC contracts
|
|
3
|
+
* ≤200 lines · zod schemas + derived TS types · no runtime imports
|
|
4
|
+
*
|
|
5
|
+
* Import-only from W3.1/W3.2/W3.2.5 (do NOT modify):
|
|
6
|
+
* EVENT_TYPES, ENTRY_FORMS ← audit-pipe (W3.1)
|
|
7
|
+
* RUN_STATUS ← run-registry (W3.2)
|
|
8
|
+
* SESSION_STATUS, SessionRecord,
|
|
9
|
+
* CaptainConfig, CAPTAIN_ERROR_CODES ← captain (W3.2.5)
|
|
10
|
+
*/
|
|
11
|
+
import { z } from 'zod';
|
|
12
|
+
import { RUN_STATUS } from '../run-registry/contracts.js';
|
|
13
|
+
import { ENTRY_FORMS } from '../audit-pipe/contracts.js';
|
|
14
|
+
import { SESSION_STATUS, CAPTAIN_ERROR_CODES, } from '../captain/contracts.js';
|
|
15
|
+
const RUN_STATUS_VALUES = Object.values(RUN_STATUS);
|
|
16
|
+
export { RUN_STATUS, ENTRY_FORMS, SESSION_STATUS, CAPTAIN_ERROR_CODES };
|
|
17
|
+
// ── Reverse channel constants ─────────────────────────────────────────────────
|
|
18
|
+
export const IPC_SOCKET_PATH = '~/.weaverbird/captain.sock';
|
|
19
|
+
export const ECHO_DEDUP_WINDOW_MS = 30_000;
|
|
20
|
+
export const ATTACH_TIMEOUT_MS = 5_000;
|
|
21
|
+
export const HEARTBEAT_INTERVAL_MS = 30_000;
|
|
22
|
+
export const REVERSE_AT_PREFIX = '@wb';
|
|
23
|
+
export const REVERSE_AT_PATTERN = /^\s*(pause|resume|cancel)\s+([a-zA-Z0-9_-]{1,64})\s*$/i;
|
|
24
|
+
export const REVERSE_CHANNEL_AUDIT_RESOURCE_PREFIX = 'reverse-channel:';
|
|
25
|
+
export const ECHO_CMD_PREVIEW_MAX = 80;
|
|
26
|
+
export const ECHO_MAX_PER_RUN = 3;
|
|
27
|
+
export const REVERSE_COMMAND = ['pause', 'resume', 'cancel', 'attach', 'echo'];
|
|
28
|
+
// ── F18 Attach ────────────────────────────────────────────────────────────────
|
|
29
|
+
export const AttachRequestSchema = z.object({
|
|
30
|
+
session_id: z.string().min(1),
|
|
31
|
+
requester_captain_id: z.string().min(1),
|
|
32
|
+
requested_at: z.string().datetime(), // ISO8601
|
|
33
|
+
force: z.boolean().default(false), // force attach even if mutex conflict
|
|
34
|
+
});
|
|
35
|
+
export const AttachResultSchema = z.discriminatedUnion('outcome', [
|
|
36
|
+
z.object({
|
|
37
|
+
outcome: z.literal('attached'),
|
|
38
|
+
session_id: z.string(),
|
|
39
|
+
session: z.unknown(), // SessionRecord (avoid circular import)
|
|
40
|
+
run_ids: z.array(z.string()),
|
|
41
|
+
}),
|
|
42
|
+
z.object({
|
|
43
|
+
outcome: z.literal('mutex_conflict'),
|
|
44
|
+
session_id: z.string(),
|
|
45
|
+
current_captain_id: z.string(),
|
|
46
|
+
conflict_since: z.string().datetime(),
|
|
47
|
+
suggestion: z.string(), // "use --force to take over"
|
|
48
|
+
}),
|
|
49
|
+
z.object({
|
|
50
|
+
outcome: z.literal('not_found'),
|
|
51
|
+
session_id: z.string(),
|
|
52
|
+
candidates: z.array(z.string()), // recent session_ids from local mirror
|
|
53
|
+
}),
|
|
54
|
+
z.object({
|
|
55
|
+
outcome: z.literal('timed_out'),
|
|
56
|
+
session_id: z.string(),
|
|
57
|
+
elapsed_ms: z.number().int(),
|
|
58
|
+
}),
|
|
59
|
+
z.object({
|
|
60
|
+
outcome: z.literal('revision_mismatch'),
|
|
61
|
+
session_id: z.string(),
|
|
62
|
+
expected_revision: z.number().int().min(0),
|
|
63
|
+
actual_revision: z.number().int().min(0),
|
|
64
|
+
suggestion: z.string(),
|
|
65
|
+
}),
|
|
66
|
+
]);
|
|
67
|
+
// ── F19 Echo ──────────────────────────────────────────────────────────────────
|
|
68
|
+
export const EchoPayloadSchema = z.object({
|
|
69
|
+
run_id: z.string().min(1),
|
|
70
|
+
cmd_preview: z.string().max(ECHO_CMD_PREVIEW_MAX), // first 80 chars of prompt
|
|
71
|
+
cwd: z.string(),
|
|
72
|
+
created_at: z.string().datetime(),
|
|
73
|
+
status: z.enum(RUN_STATUS_VALUES),
|
|
74
|
+
session_id: z.string(),
|
|
75
|
+
home_group_id: z.string(),
|
|
76
|
+
operator_open_id: z.string(), // for @mention in IM message
|
|
77
|
+
});
|
|
78
|
+
// ── F21 Reverse @ ─────────────────────────────────────────────────────────────
|
|
79
|
+
const CONTROL_COMMANDS = ['pause', 'resume', 'cancel'];
|
|
80
|
+
export const ReverseAtCommandSchema = z.object({
|
|
81
|
+
command: z.enum(CONTROL_COMMANDS),
|
|
82
|
+
run_id: z.string().min(1),
|
|
83
|
+
requester_open_id: z.string(),
|
|
84
|
+
requested_at: z.string().datetime(),
|
|
85
|
+
message_id: z.string(), // Lark message_id for reply threading
|
|
86
|
+
});
|
|
87
|
+
// ── IPC message envelope ──────────────────────────────────────────────────────
|
|
88
|
+
export const AttachIpcMessageSchema = z.object({
|
|
89
|
+
kind: z.literal('attach'),
|
|
90
|
+
run_id: z.string().min(1),
|
|
91
|
+
session_id: z.string().min(1),
|
|
92
|
+
requester_captain_id: z.string().min(1),
|
|
93
|
+
force: z.boolean().optional(),
|
|
94
|
+
});
|
|
95
|
+
export const AckIpcMessageSchema = z.object({
|
|
96
|
+
kind: z.literal('ack'),
|
|
97
|
+
command: z.string(),
|
|
98
|
+
run_id: z.string(),
|
|
99
|
+
ok: z.boolean(),
|
|
100
|
+
reason: z.string().optional(),
|
|
101
|
+
payload: z.unknown().optional(),
|
|
102
|
+
});
|
|
103
|
+
export const IpcMessageSchema = z.discriminatedUnion('kind', [
|
|
104
|
+
z.object({ kind: z.literal('hello'), run_id: z.string(), pid: z.number().int() }),
|
|
105
|
+
z.object({ kind: z.literal('control'), command: z.enum(CONTROL_COMMANDS), run_id: z.string() }),
|
|
106
|
+
AttachIpcMessageSchema,
|
|
107
|
+
AckIpcMessageSchema,
|
|
108
|
+
z.object({ kind: z.literal('ping') }),
|
|
109
|
+
z.object({ kind: z.literal('pong') }),
|
|
110
|
+
z.object({ kind: z.literal('bye'), run_id: z.string(), exit_code: z.number().int().optional() }),
|
|
111
|
+
]);
|
|
112
|
+
// ── Error codes + Error class ─────────────────────────────────────────────────
|
|
113
|
+
export const REVERSE_CHANNEL_ERROR_CODES = {
|
|
114
|
+
E_ATTACH_TIMEOUT: 'reverse.attach.timeout',
|
|
115
|
+
E_ATTACH_NOT_FOUND: 'reverse.attach.not_found',
|
|
116
|
+
E_ATTACH_MUTEX: 'reverse.attach.mutex_conflict',
|
|
117
|
+
E_ATTACH_FLUSH_FAILED: 'reverse.attach.flush_failed',
|
|
118
|
+
E_IPC_CONNECT_FAILED: 'reverse.ipc.connect_failed',
|
|
119
|
+
E_IPC_SEND_TIMEOUT: 'reverse.ipc.send_timeout',
|
|
120
|
+
E_IPC_PARSE: 'reverse.ipc.parse_error',
|
|
121
|
+
E_ECHO_SEND_FAILED: 'reverse.echo.send_failed',
|
|
122
|
+
E_REVERSE_AT_PARSE: 'reverse.at.parse_error',
|
|
123
|
+
E_REVERSE_AT_RUN_GONE: 'reverse.at.run_not_found',
|
|
124
|
+
E_SIGNAL_FAILED: 'reverse.signal.send_failed',
|
|
125
|
+
E_CAPTAIN_HANDED_OVER: 'reverse.attach.handed_over',
|
|
126
|
+
};
|
|
127
|
+
export class ReverseChannelError extends Error {
|
|
128
|
+
code;
|
|
129
|
+
cause;
|
|
130
|
+
constructor(code, message, cause) {
|
|
131
|
+
super(`[${code}] ${message}`);
|
|
132
|
+
this.code = code;
|
|
133
|
+
this.cause = cause;
|
|
134
|
+
this.name = 'ReverseChannelError';
|
|
135
|
+
}
|
|
136
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { EchoPayloadSchema, ECHO_CMD_PREVIEW_MAX, ECHO_MAX_PER_RUN } from './contracts.js';
|
|
2
|
+
export class EchoTailer {
|
|
3
|
+
messageSink;
|
|
4
|
+
nowFn;
|
|
5
|
+
lastEchoMap = new Map();
|
|
6
|
+
sentPerRun = new Map();
|
|
7
|
+
constructor(messageSink, options = {}) {
|
|
8
|
+
this.messageSink = messageSink;
|
|
9
|
+
this.nowFn = options.nowFn ?? Date.now;
|
|
10
|
+
}
|
|
11
|
+
async onRunUpserted(input) {
|
|
12
|
+
if (!input.session?.home_group_id)
|
|
13
|
+
return false;
|
|
14
|
+
const dedupKey = `${input.run_id}:${input.status}`;
|
|
15
|
+
const last = this.lastEchoMap.get(dedupKey);
|
|
16
|
+
if (last !== undefined && this.nowFn() - last < 30_000)
|
|
17
|
+
return false;
|
|
18
|
+
const count = this.sentPerRun.get(input.run_id) ?? 0;
|
|
19
|
+
if (count >= ECHO_MAX_PER_RUN)
|
|
20
|
+
return false;
|
|
21
|
+
this.lastEchoMap.set(dedupKey, this.nowFn());
|
|
22
|
+
this.sentPerRun.set(input.run_id, count + 1);
|
|
23
|
+
const payload = EchoPayloadSchema.parse({
|
|
24
|
+
run_id: input.run_id,
|
|
25
|
+
cmd_preview: input.cmd.slice(0, ECHO_CMD_PREVIEW_MAX),
|
|
26
|
+
cwd: input.cwd,
|
|
27
|
+
created_at: input.created_at,
|
|
28
|
+
status: input.status,
|
|
29
|
+
session_id: input.session.session_id,
|
|
30
|
+
home_group_id: input.session.home_group_id,
|
|
31
|
+
operator_open_id: input.operator_open_id,
|
|
32
|
+
});
|
|
33
|
+
await this.messageSink(payload);
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
@@ -0,0 +1,238 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { ENTRY_FORMS, buildRunInheritanceSnapshot } from '../run-registry/index.js';
|
|
5
|
+
import { runDir } from '../paths.js';
|
|
6
|
+
import { appendNdjsonLine } from '../util/ndjson-rotation.js';
|
|
7
|
+
const ReverseHandoffInheritedSchema = z.object({
|
|
8
|
+
project: z.string().nullable(),
|
|
9
|
+
cwd: z.string().min(1),
|
|
10
|
+
scope: z.string().min(1),
|
|
11
|
+
agent: z.string().min(1),
|
|
12
|
+
home_group_id: z.string().nullable(),
|
|
13
|
+
entry_form: z.enum(ENTRY_FORMS),
|
|
14
|
+
});
|
|
15
|
+
export const ReverseHandoffInputSchema = ReverseHandoffInheritedSchema.extend({
|
|
16
|
+
session_id: z.string().min(1),
|
|
17
|
+
run_id: z.string().min(1),
|
|
18
|
+
revision: z.number().int().min(0),
|
|
19
|
+
changed_at: z.string().datetime(),
|
|
20
|
+
previous_captain_id: z.string().min(1),
|
|
21
|
+
next_captain_id: z.string().min(1),
|
|
22
|
+
previous_holder_open_id: z.string().nullable().default(null),
|
|
23
|
+
next_holder_open_id: z.string().min(1),
|
|
24
|
+
});
|
|
25
|
+
export const ReverseHandoffNotificationSchema = ReverseHandoffInheritedSchema.extend({
|
|
26
|
+
handoff_id: z.string().min(1),
|
|
27
|
+
session_id: z.string().min(1),
|
|
28
|
+
run_id: z.string().min(1),
|
|
29
|
+
revision: z.number().int().min(0),
|
|
30
|
+
created_at: z.string().datetime(),
|
|
31
|
+
previous_captain_id: z.string().min(1),
|
|
32
|
+
next_captain_id: z.string().min(1),
|
|
33
|
+
previous_holder_open_id: z.string().nullable(),
|
|
34
|
+
next_holder_open_id: z.string().min(1),
|
|
35
|
+
});
|
|
36
|
+
export const ReverseHandoffRecordSchema = ReverseHandoffNotificationSchema.extend({
|
|
37
|
+
notify_failed: z.boolean().default(false),
|
|
38
|
+
notified_at: z.string().datetime().nullable().default(null),
|
|
39
|
+
last_error: z.string().nullable().default(null),
|
|
40
|
+
});
|
|
41
|
+
export const ReverseHandoffStateSchema = z.object({
|
|
42
|
+
session_id: z.string().min(1),
|
|
43
|
+
run_id: z.string().min(1),
|
|
44
|
+
last_revision: z.number().int().min(0),
|
|
45
|
+
updated_at: z.string().datetime(),
|
|
46
|
+
handoffs: z.array(ReverseHandoffRecordSchema).default([]),
|
|
47
|
+
});
|
|
48
|
+
function atomicWrite(path, content) {
|
|
49
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
50
|
+
const temp = `${path}.tmp`;
|
|
51
|
+
writeFileSync(temp, content);
|
|
52
|
+
renameSync(temp, path);
|
|
53
|
+
}
|
|
54
|
+
function reverseChannelDir(dataDir) {
|
|
55
|
+
return join(dataDir, 'reverse-channel');
|
|
56
|
+
}
|
|
57
|
+
function runReverseHandoffStatePath(dataDir, runId, botId = 'default') {
|
|
58
|
+
return join(runDir(dataDir, runId, botId), 'reverse-handoff.json');
|
|
59
|
+
}
|
|
60
|
+
export function reverseHandoffMockLedgerPath(dataDir) {
|
|
61
|
+
return join(reverseChannelDir(dataDir), 'mock-handoffs.ndjson');
|
|
62
|
+
}
|
|
63
|
+
function readReverseHandoffState(path, input, nowIso) {
|
|
64
|
+
if (!existsSync(path)) {
|
|
65
|
+
return ReverseHandoffStateSchema.parse({
|
|
66
|
+
session_id: input.session_id,
|
|
67
|
+
run_id: input.run_id,
|
|
68
|
+
last_revision: input.revision,
|
|
69
|
+
updated_at: nowIso,
|
|
70
|
+
handoffs: [],
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
return ReverseHandoffStateSchema.parse(JSON.parse(readFileSync(path, 'utf8')));
|
|
74
|
+
}
|
|
75
|
+
function writeReverseHandoffState(path, state) {
|
|
76
|
+
atomicWrite(path, JSON.stringify(state, null, 2));
|
|
77
|
+
}
|
|
78
|
+
function sanitizeIdPart(value) {
|
|
79
|
+
const raw = value?.trim() ?? '';
|
|
80
|
+
if (raw.length === 0)
|
|
81
|
+
return 'none';
|
|
82
|
+
return raw.replace(/[^a-zA-Z0-9._-]+/g, '_');
|
|
83
|
+
}
|
|
84
|
+
function buildHandoffId(input) {
|
|
85
|
+
return [
|
|
86
|
+
'reverse-handoff',
|
|
87
|
+
sanitizeIdPart(input.session_id),
|
|
88
|
+
sanitizeIdPart(input.run_id),
|
|
89
|
+
sanitizeIdPart(String(input.revision)),
|
|
90
|
+
sanitizeIdPart(input.next_holder_open_id),
|
|
91
|
+
].join(':');
|
|
92
|
+
}
|
|
93
|
+
function mergeReverseHandoffState(state, record, nowIso) {
|
|
94
|
+
const handoffs = state.handoffs.filter((item) => item.handoff_id !== record.handoff_id);
|
|
95
|
+
handoffs.push(record);
|
|
96
|
+
handoffs.sort((left, right) => left.handoff_id.localeCompare(right.handoff_id));
|
|
97
|
+
return ReverseHandoffStateSchema.parse({
|
|
98
|
+
session_id: state.session_id,
|
|
99
|
+
run_id: state.run_id,
|
|
100
|
+
last_revision: Math.max(state.last_revision, record.revision),
|
|
101
|
+
updated_at: nowIso,
|
|
102
|
+
handoffs,
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
function buildInherited(input) {
|
|
106
|
+
return buildRunInheritanceSnapshot({
|
|
107
|
+
project: input.project,
|
|
108
|
+
cwd: input.cwd,
|
|
109
|
+
scope: input.scope,
|
|
110
|
+
agent: input.agent,
|
|
111
|
+
home_group_id: input.home_group_id,
|
|
112
|
+
entry_form: input.entry_form,
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
function toNotification(input, createdAt) {
|
|
116
|
+
const inherited = buildInherited(input);
|
|
117
|
+
return ReverseHandoffNotificationSchema.parse({
|
|
118
|
+
handoff_id: buildHandoffId(input),
|
|
119
|
+
session_id: input.session_id,
|
|
120
|
+
run_id: input.run_id,
|
|
121
|
+
revision: input.revision,
|
|
122
|
+
created_at: createdAt,
|
|
123
|
+
previous_captain_id: input.previous_captain_id,
|
|
124
|
+
next_captain_id: input.next_captain_id,
|
|
125
|
+
previous_holder_open_id: input.previous_holder_open_id,
|
|
126
|
+
next_holder_open_id: input.next_holder_open_id,
|
|
127
|
+
...inherited,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
function toRecord(notification, patch = {}) {
|
|
131
|
+
return ReverseHandoffRecordSchema.parse({
|
|
132
|
+
...notification,
|
|
133
|
+
notify_failed: patch.notify_failed ?? false,
|
|
134
|
+
notified_at: patch.notified_at !== undefined ? patch.notified_at : notification.created_at,
|
|
135
|
+
last_error: patch.last_error !== undefined ? patch.last_error : null,
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
export function createInlineReverseHandoffTransport(handler) {
|
|
139
|
+
return {
|
|
140
|
+
async notifyReverseAt(input) {
|
|
141
|
+
await handler(input);
|
|
142
|
+
},
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
export function createMockReverseHandoffTransport(dataDir) {
|
|
146
|
+
const ledgerPath = reverseHandoffMockLedgerPath(dataDir);
|
|
147
|
+
return {
|
|
148
|
+
async notifyReverseAt(input) {
|
|
149
|
+
mkdirSync(dirname(ledgerPath), { recursive: true });
|
|
150
|
+
appendNdjsonLine(ledgerPath, JSON.stringify(ReverseHandoffNotificationSchema.parse(input)));
|
|
151
|
+
},
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
export function createGuardedReverseHandoffTransport() {
|
|
155
|
+
return {
|
|
156
|
+
async notifyReverseAt() {
|
|
157
|
+
throw new Error('reverse handoff reverse-@ egress requires explicit real-device authorization');
|
|
158
|
+
},
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
export async function publishReverseHandoff(options) {
|
|
162
|
+
const input = ReverseHandoffInputSchema.parse(options.handoff);
|
|
163
|
+
const nowFn = options.nowFn ?? Date.now;
|
|
164
|
+
const nowIso = new Date(nowFn()).toISOString();
|
|
165
|
+
const statePath = runReverseHandoffStatePath(options.dataDir, input.run_id, options.botId ?? 'default');
|
|
166
|
+
const current = readReverseHandoffState(statePath, input, nowIso);
|
|
167
|
+
const handoffId = buildHandoffId(input);
|
|
168
|
+
const existing = current.handoffs.find((item) => item.handoff_id === handoffId);
|
|
169
|
+
if (existing) {
|
|
170
|
+
return {
|
|
171
|
+
notify_failed: existing.notify_failed,
|
|
172
|
+
record: existing,
|
|
173
|
+
state: current,
|
|
174
|
+
statePath,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
const notification = toNotification(input, nowIso);
|
|
178
|
+
try {
|
|
179
|
+
await options.transport.notifyReverseAt(notification);
|
|
180
|
+
const record = toRecord(notification, { notify_failed: false, notified_at: nowIso, last_error: null });
|
|
181
|
+
const nextState = mergeReverseHandoffState(current, record, nowIso);
|
|
182
|
+
writeReverseHandoffState(statePath, nextState);
|
|
183
|
+
return {
|
|
184
|
+
notify_failed: false,
|
|
185
|
+
record,
|
|
186
|
+
state: nextState,
|
|
187
|
+
statePath,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
catch (error) {
|
|
191
|
+
const record = toRecord(notification, {
|
|
192
|
+
notify_failed: true,
|
|
193
|
+
notified_at: null,
|
|
194
|
+
last_error: error instanceof Error ? error.message : String(error),
|
|
195
|
+
});
|
|
196
|
+
const nextState = mergeReverseHandoffState(current, record, nowIso);
|
|
197
|
+
writeReverseHandoffState(statePath, nextState);
|
|
198
|
+
return {
|
|
199
|
+
notify_failed: true,
|
|
200
|
+
record,
|
|
201
|
+
state: nextState,
|
|
202
|
+
statePath,
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
export async function recordReverseHandoffFromSession(options) {
|
|
207
|
+
const runId = options.runId ?? options.nextSession.latest_run_id;
|
|
208
|
+
if (!runId) {
|
|
209
|
+
return null;
|
|
210
|
+
}
|
|
211
|
+
if (options.previousSession.captain_id === options.nextSession.captain_id
|
|
212
|
+
&& options.previousSession.operator === options.nextSession.operator) {
|
|
213
|
+
return null;
|
|
214
|
+
}
|
|
215
|
+
const nowFn = options.nowFn ?? Date.now;
|
|
216
|
+
return publishReverseHandoff({
|
|
217
|
+
dataDir: options.dataDir,
|
|
218
|
+
botId: options.botId,
|
|
219
|
+
transport: options.transport,
|
|
220
|
+
nowFn,
|
|
221
|
+
handoff: {
|
|
222
|
+
session_id: options.nextSession.session_id,
|
|
223
|
+
run_id: runId,
|
|
224
|
+
revision: options.revision,
|
|
225
|
+
changed_at: new Date(nowFn()).toISOString(),
|
|
226
|
+
previous_captain_id: options.previousSession.captain_id,
|
|
227
|
+
next_captain_id: options.nextSession.captain_id,
|
|
228
|
+
previous_holder_open_id: options.previousSession.operator,
|
|
229
|
+
next_holder_open_id: options.nextSession.operator,
|
|
230
|
+
project: options.nextSession.project,
|
|
231
|
+
cwd: options.nextSession.cwd,
|
|
232
|
+
scope: options.nextSession.scope,
|
|
233
|
+
agent: options.nextSession.agent,
|
|
234
|
+
home_group_id: options.nextSession.home_group_id,
|
|
235
|
+
entry_form: options.nextSession.entry_form,
|
|
236
|
+
},
|
|
237
|
+
});
|
|
238
|
+
}
|