skillar 0.0.0 → 0.2.1

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.
Files changed (114) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +250 -2
  3. package/dist/analysis/finding.js +190 -0
  4. package/dist/analysis/tree.js +157 -0
  5. package/dist/analysis/usage.js +394 -0
  6. package/dist/api/flows.js +285 -0
  7. package/dist/api/routes.js +192 -0
  8. package/dist/api/security.js +86 -0
  9. package/dist/api/sse.js +55 -0
  10. package/dist/api/static.js +33 -0
  11. package/dist/catalog/fields.js +159 -0
  12. package/dist/catalog/index.js +133 -0
  13. package/dist/catalog/scanner.js +204 -0
  14. package/dist/catalog/uri.js +43 -0
  15. package/dist/catalog/watcher.js +59 -0
  16. package/dist/cli/config-writer.js +255 -0
  17. package/dist/cli/doctor.js +268 -0
  18. package/dist/cli/eval.js +64 -0
  19. package/dist/cli/export-import.js +68 -0
  20. package/dist/cli/init.js +272 -0
  21. package/dist/cli/main.js +165 -0
  22. package/dist/cli/open.js +24 -0
  23. package/dist/cli/serve.js +147 -0
  24. package/dist/config.js +92 -0
  25. package/dist/dashboard/assets/app.js +354 -0
  26. package/dist/dashboard/assets/chunk-5DFWNJC2.js +1 -0
  27. package/dist/dashboard/assets/chunk-S6B2HJQA.js +17 -0
  28. package/dist/dashboard/assets/styles.css +542 -0
  29. package/dist/dashboard/index.html +15 -0
  30. package/dist/fs-watchdog.js +35 -0
  31. package/dist/herdr/client.js +205 -0
  32. package/dist/herdr/sync.js +342 -0
  33. package/dist/ingest/attribution.js +80 -0
  34. package/dist/ingest/hooks.js +168 -0
  35. package/dist/ingest/identity.js +4 -0
  36. package/dist/ingest/mcp-recorder.js +41 -0
  37. package/dist/ingest/otlp-traces.js +106 -0
  38. package/dist/ingest/otlp.js +314 -0
  39. package/dist/ingest/pipeline.js +119 -0
  40. package/dist/ingest/redact.js +36 -0
  41. package/dist/ingest/runtimes.js +25 -0
  42. package/dist/mcp/dispatch.js +54 -0
  43. package/dist/mcp/http.js +112 -0
  44. package/dist/mcp/legacy.js +61 -0
  45. package/dist/mcp/pagination.js +17 -0
  46. package/dist/mcp/protocol.js +121 -0
  47. package/dist/mcp/skills-extension.js +77 -0
  48. package/dist/mcp/stdio-proxy.js +108 -0
  49. package/dist/mcp/tools.js +59 -0
  50. package/dist/packs/claude-code.js +176 -0
  51. package/dist/packs/codex.js +207 -0
  52. package/dist/packs/cursor.js +97 -0
  53. package/dist/packs/gajae.js +7 -0
  54. package/dist/packs/gemini.js +90 -0
  55. package/dist/packs/json-config.js +55 -0
  56. package/dist/packs/omo.js +154 -0
  57. package/dist/packs/openclaw.js +132 -0
  58. package/dist/packs/registry.js +13 -0
  59. package/dist/search/fts.js +61 -0
  60. package/dist/search/fusion.js +50 -0
  61. package/dist/search/guidance.js +7 -0
  62. package/dist/search/index.js +74 -0
  63. package/dist/search/lexical.js +69 -0
  64. package/dist/server.js +267 -0
  65. package/dist/store/automation.js +18 -0
  66. package/dist/store/db.js +134 -0
  67. package/dist/store/execution.js +157 -0
  68. package/dist/store/export.js +269 -0
  69. package/dist/store/index.js +14 -0
  70. package/dist/store/migrations/002_tracing.sql +94 -0
  71. package/dist/store/migrations/003_tracing_indexes.sql +11 -0
  72. package/dist/store/migrations/004_load_reconciliation.sql +50 -0
  73. package/dist/store/migrations/005_execution_boundaries.sql +6 -0
  74. package/dist/store/migrations/006_recording_order.sql +72 -0
  75. package/dist/store/queries.js +643 -0
  76. package/dist/store/schema.sql +96 -0
  77. package/dist/store/workflow.js +250 -0
  78. package/dist/store/writes.js +315 -0
  79. package/dist/types.js +1 -0
  80. package/dist/version.js +19 -0
  81. package/dist/workflow/compare.js +68 -0
  82. package/dist/workflow/routes.js +100 -0
  83. package/dist/workflow/spec.js +40 -0
  84. package/docs/execution-ownership.md +98 -0
  85. package/docs/mcp-conformance.md +156 -0
  86. package/docs/skill-tracing.md +294 -0
  87. package/package.json +46 -3
  88. package/packs/claude-code/README.md +5 -0
  89. package/packs/claude-code/settings.template.json +34 -0
  90. package/packs/codex/README.md +8 -0
  91. package/packs/codex/config.template.toml +12 -0
  92. package/packs/cursor/hooks.example.json +8 -0
  93. package/packs/cursor/mcp.example.json +8 -0
  94. package/packs/gajae/extension/discovery.md +5 -0
  95. package/packs/gajae/extension/index.js +52 -0
  96. package/packs/gemini/settings.example.json +16 -0
  97. package/packs/hook-post.mjs +37 -0
  98. package/packs/omo/extension/discovery.md +5 -0
  99. package/packs/omo/extension/index.js +52 -0
  100. package/packs/openclaw/.codex-plugin/plugin.json +11 -0
  101. package/packs/openclaw/.mcp.json +12 -0
  102. package/packs/openclaw/hooks/skillar-discovery/HOOK.md +8 -0
  103. package/packs/openclaw/hooks/skillar-discovery/handler.js +30 -0
  104. package/packs/openclaw/index.mjs +55 -0
  105. package/packs/openclaw/openclaw.plugin.json +22 -0
  106. package/packs/openclaw/package.json +11 -0
  107. package/packs/openclaw/skillar.json +1 -0
  108. package/src/store/migrations/002_tracing.sql +94 -0
  109. package/src/store/migrations/003_tracing_indexes.sql +11 -0
  110. package/src/store/migrations/004_load_reconciliation.sql +50 -0
  111. package/src/store/migrations/005_execution_boundaries.sql +6 -0
  112. package/src/store/migrations/006_recording_order.sql +72 -0
  113. package/src/store/schema.sql +96 -0
  114. package/src/store/task-types.json +15 -0
@@ -0,0 +1,35 @@
1
+ // A long-running daemon was seen with every async fs request pending forever while the event loop stayed alive:
2
+ // /healthz kept answering but the dashboard, assets, and resource reads hung. The watchdog probes the filesystem on a
3
+ // timer; a probe still pending after timeoutMs means fs is stalled, and onStall runs once so the service manager
4
+ // can restart the process.
5
+ export function createFsWatchdog(opts) {
6
+ const now = opts.now ?? Date.now;
7
+ let inFlightSince;
8
+ let lastOkAt;
9
+ let stalled = false;
10
+ const tick = () => {
11
+ if (inFlightSince !== undefined) {
12
+ const waited = now() - inFlightSince;
13
+ if (!stalled && waited >= opts.timeoutMs) {
14
+ stalled = true;
15
+ opts.onStall(waited);
16
+ }
17
+ return;
18
+ }
19
+ const started = now();
20
+ inFlightSince = started;
21
+ opts.probe().then(() => { lastOkAt = now(); }, () => { lastOkAt = now(); }).finally(() => { if (inFlightSince === started)
22
+ inFlightSince = undefined; });
23
+ };
24
+ const timer = setInterval(tick, opts.intervalMs);
25
+ timer.unref();
26
+ tick();
27
+ return {
28
+ health() {
29
+ const pendingMs = inFlightSince === undefined ? 0 : now() - inFlightSince;
30
+ const ok = !stalled && pendingMs < opts.timeoutMs;
31
+ return { ok, ...(lastOkAt !== undefined ? { lastOkAt } : {}), ...(ok ? {} : { stalledMs: pendingMs }) };
32
+ },
33
+ stop() { clearInterval(timer); },
34
+ };
35
+ }
@@ -0,0 +1,205 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createConnection } from "node:net";
3
+ import { z } from "zod";
4
+ const messageSchema = z.object({
5
+ id: z.string().optional(),
6
+ result: z.unknown().optional(),
7
+ error: z.unknown().optional(),
8
+ event: z.string().optional(),
9
+ data: z.unknown().optional(),
10
+ });
11
+ /** Every connection attempt discovers the current socket with a bounded command. */
12
+ export function resolveHerdrSocket(env = process.env, signal) {
13
+ const configured = env.SKILLAR_HERDR_SOCKET ?? env.GISOOL_HERDR_SOCKET;
14
+ if (configured)
15
+ return Promise.resolve(configured);
16
+ return new Promise((resolve, reject) => {
17
+ execFile("herdr", ["status", "server"], { env, timeout: 5_000, signal }, (error, stdout) => {
18
+ if (error)
19
+ return reject(error);
20
+ const path = /^socket:\s*(\S.*)$/m.exec(stdout)?.[1]?.trim();
21
+ if (!path)
22
+ return reject(new Error("herdr status server returned no socket: line"));
23
+ resolve(path);
24
+ });
25
+ });
26
+ }
27
+ export function createHerdrClient(opts) {
28
+ const abort = new AbortController();
29
+ let socket;
30
+ let socketPath;
31
+ const sockets = new Set();
32
+ const paneStreams = new Set();
33
+ let stopped = false;
34
+ let retry;
35
+ let backoff = 1_000;
36
+ let state;
37
+ let seq = 0;
38
+ const causes = new Set();
39
+ const logCause = (error) => {
40
+ if (stopped)
41
+ return;
42
+ const cause = error instanceof Error ? error.message : String(error);
43
+ if (causes.has(cause))
44
+ return;
45
+ causes.add(cause);
46
+ opts.log(`herdr failure: ${cause}`);
47
+ };
48
+ const pending = new Map();
49
+ const transition = (next) => {
50
+ if (state === next)
51
+ return;
52
+ state = next;
53
+ opts.log(`herdr ${next}`);
54
+ };
55
+ const scheduleReconnect = () => {
56
+ if (stopped)
57
+ return;
58
+ transition("unreachable");
59
+ retry = setTimeout(connect, backoff);
60
+ retry.unref();
61
+ backoff = Math.min(backoff * 2, 30_000);
62
+ };
63
+ const requestOn = (active, method, params) => new Promise((resolve, reject) => {
64
+ const id = String(++seq);
65
+ const timer = setTimeout(() => active.destroy(new Error(`herdr ${method} timed out`)), 5_000);
66
+ timer.unref();
67
+ pending.set(id, { socket: active, resolve, reject, timer });
68
+ active.write(`${JSON.stringify({ id, method, params })}\n`);
69
+ });
70
+ const client = {
71
+ request(method, params = {}) {
72
+ if (stopped || !socketPath || !socket || socket.destroyed)
73
+ return Promise.reject(new Error("herdr disconnected"));
74
+ // herdr closes one-shot RPC sockets after their reply. Only subscriptions persist.
75
+ const active = method === "events.subscribe" ? socket : createConnection(socketPath);
76
+ if (active !== socket)
77
+ attach(active);
78
+ return requestOn(active, method, params);
79
+ },
80
+ async subscribePane(paneId) {
81
+ if (stopped || !socketPath || !socket || socket.destroyed)
82
+ throw new Error("herdr disconnected");
83
+ const active = createConnection(socketPath);
84
+ paneStreams.add(active);
85
+ attach(active);
86
+ try {
87
+ z.object({ type: z.literal("subscription_started") }).parse(await requestOn(active, "events.subscribe", {
88
+ subscriptions: [{ type: "pane.agent_status_changed", pane_id: paneId }],
89
+ }));
90
+ }
91
+ catch (error) {
92
+ paneStreams.delete(active);
93
+ active.destroy();
94
+ throw error;
95
+ }
96
+ // Herdr subscriptions belong to their socket; closing it is the unsubscribe operation.
97
+ return () => { paneStreams.delete(active); active.destroy(); };
98
+ },
99
+ close() {
100
+ stopped = true;
101
+ abort.abort();
102
+ if (retry)
103
+ clearTimeout(retry);
104
+ for (const active of sockets)
105
+ active.destroy();
106
+ for (const p of pending.values()) {
107
+ clearTimeout(p.timer);
108
+ p.reject(new Error("herdr client closed"));
109
+ }
110
+ pending.clear();
111
+ },
112
+ };
113
+ const attach = (active) => {
114
+ sockets.add(active);
115
+ let buffer = "";
116
+ active.setEncoding("utf8");
117
+ active.on("error", (error) => {
118
+ logCause(error);
119
+ if (!stopped && active !== socket)
120
+ socket?.destroy(error);
121
+ });
122
+ active.on("close", () => {
123
+ sockets.delete(active);
124
+ const paneStream = paneStreams.delete(active);
125
+ for (const [id, p] of pending) {
126
+ if (p.socket !== active)
127
+ continue;
128
+ clearTimeout(p.timer);
129
+ p.reject(new Error("herdr disconnected"));
130
+ pending.delete(id);
131
+ }
132
+ if (!stopped && paneStream)
133
+ socket?.destroy(new Error("herdr pane subscription disconnected"));
134
+ if (stopped || active !== socket)
135
+ return;
136
+ for (const other of sockets)
137
+ other.destroy();
138
+ opts.onDisconnect();
139
+ scheduleReconnect();
140
+ });
141
+ active.on("data", (chunk) => {
142
+ buffer += chunk;
143
+ let newline;
144
+ while ((newline = buffer.indexOf("\n")) !== -1) {
145
+ const line = buffer.slice(0, newline);
146
+ buffer = buffer.slice(newline + 1);
147
+ let raw;
148
+ try {
149
+ raw = JSON.parse(line);
150
+ }
151
+ catch (error) {
152
+ if (error instanceof SyntaxError)
153
+ continue;
154
+ throw error;
155
+ }
156
+ const parsed = messageSchema.safeParse(raw);
157
+ if (!parsed.success)
158
+ continue;
159
+ const message = parsed.data;
160
+ if (message.id) {
161
+ const p = pending.get(message.id);
162
+ if (!p || p.socket !== active)
163
+ continue;
164
+ pending.delete(message.id);
165
+ clearTimeout(p.timer);
166
+ if (message.error !== undefined)
167
+ p.reject(new Error(`herdr error: ${JSON.stringify(message.error)}`));
168
+ else
169
+ p.resolve(message.result);
170
+ if (active !== socket && !paneStreams.has(active))
171
+ active.destroy();
172
+ }
173
+ else if (message.event && (active === socket || paneStreams.has(active)))
174
+ opts.onEvent(message.event, message.data);
175
+ }
176
+ if (buffer.length > 8 * 1024 * 1024)
177
+ active.destroy(new Error("herdr line exceeds 8 MB"));
178
+ });
179
+ };
180
+ const connect = () => {
181
+ if (stopped)
182
+ return;
183
+ void resolveHerdrSocket(opts.env, abort.signal).then((path) => {
184
+ if (stopped)
185
+ return;
186
+ socketPath = path;
187
+ const active = createConnection(path);
188
+ socket = active;
189
+ attach(active);
190
+ active.once("connect", () => {
191
+ void opts.onConnect(client).then(() => {
192
+ if (stopped || active.destroyed)
193
+ return;
194
+ backoff = 1_000;
195
+ transition("connected");
196
+ }, (error) => active.destroy(error instanceof Error ? error : new Error(String(error))));
197
+ });
198
+ }, (error) => {
199
+ logCause(error);
200
+ scheduleReconnect();
201
+ });
202
+ };
203
+ connect();
204
+ return client;
205
+ }
@@ -0,0 +1,342 @@
1
+ import { z } from "zod";
2
+ import { createHerdrClient } from "./client.js";
3
+ const subscriptions = [
4
+ "workspace.created", "workspace.renamed", "workspace.closed",
5
+ "tab.created", "tab.renamed", "tab.closed",
6
+ "pane.created", "pane.updated", "pane.moved", "pane.closed", "pane.exited", "pane.agent_detected",
7
+ ];
8
+ const workspaceSchema = z.object({ workspace_id: z.string(), label: z.string().nullish(), created_ms: z.number().nullish() });
9
+ const tabSchema = z.object({ tab_id: z.string(), workspace_id: z.string(), label: z.string().nullish(), created_ms: z.number().nullish() });
10
+ const paneSchema = z.object({
11
+ pane_id: z.string(), workspace_id: z.string(), tab_id: z.string(),
12
+ label: z.string().nullish(), title: z.string().nullish(), cwd: z.string().nullish(),
13
+ created_ms: z.number().nullish(), agent: z.string().nullish(),
14
+ agent_status: z.string().nullish(),
15
+ agent_session: z.object({ agent: z.string(), source: z.string(), value: z.string(), kind: z.string() }).nullish().catch(null),
16
+ });
17
+ const snapshotSchema = z.object({
18
+ type: z.literal("session_snapshot"),
19
+ snapshot: z.object({ workspaces: z.array(workspaceSchema), tabs: z.array(tabSchema), panes: z.array(paneSchema) }),
20
+ });
21
+ const closedSchema = z.object({ workspace_id: z.string().optional(), tab_id: z.string().optional(), pane_id: z.string().optional(),
22
+ agent_status: z.string().optional(), agent: z.string().nullish() });
23
+ const RECENT_PANE_MS = 24 * 60 * 60 * 1000;
24
+ const runtimeOf = (agent) => agent === "claude" ? "claude-code" : agent;
25
+ export function startHerdrSync(db, opts) {
26
+ let stopped = false;
27
+ let revision = 0;
28
+ let connection = 0;
29
+ let ready = false;
30
+ let running;
31
+ let again = false;
32
+ const changedCwds = new Set();
33
+ const paneSubscriptions = new Map();
34
+ const unsubscribePane = (paneId) => {
35
+ paneSubscriptions.get(paneId)?.stop();
36
+ paneSubscriptions.delete(paneId);
37
+ };
38
+ const upsertWorkspace = db.prepare(`INSERT INTO herdr_workspaces (id, label, created_ms) VALUES (?, ?, ?)
39
+ ON CONFLICT(id) DO UPDATE SET label = excluded.label, closed_ms = NULL`);
40
+ const upsertTab = db.prepare(`INSERT INTO herdr_tabs (id, workspace_id, label, created_ms) VALUES (?, ?, ?, ?)
41
+ ON CONFLICT(id) DO UPDATE SET workspace_id = excluded.workspace_id, label = excluded.label, closed_ms = NULL`);
42
+ const upsertPane = db.prepare(`INSERT INTO herdr_panes (id, workspace_id, tab_id, label, cwd, created_ms, agent, last_seen_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
43
+ ON CONFLICT(id) DO UPDATE SET workspace_id = excluded.workspace_id, tab_id = excluded.tab_id,
44
+ label = excluded.label, cwd = excluded.cwd, agent = excluded.agent, last_seen_ms = excluded.last_seen_ms, closed_ms = NULL`);
45
+ const upsertReported = db.prepare(`INSERT INTO pane_sessions
46
+ (pane_id, agent, source, agent_session_value, first_seen_ms, last_seen_ms) VALUES (?, ?, ?, ?, ?, ?)
47
+ ON CONFLICT(pane_id, agent_session_value) DO UPDATE SET agent = excluded.agent, source = excluded.source, last_seen_ms = excluded.last_seen_ms`);
48
+ const linkPending = db.prepare(`UPDATE pane_sessions SET session_id = (
49
+ SELECT id FROM (
50
+ SELECT id, started_at FROM sessions
51
+ WHERE runtime = CASE pane_sessions.agent WHEN 'claude' THEN 'claude-code' ELSE pane_sessions.agent END
52
+ AND runtime_session_id = pane_sessions.agent_session_value
53
+ UNION
54
+ SELECT id, started_at FROM sessions
55
+ WHERE runtime = CASE pane_sessions.agent WHEN 'claude' THEN 'claude-code' ELSE pane_sessions.agent END
56
+ AND conversation_id = pane_sessions.agent_session_value
57
+ UNION
58
+ SELECT id, started_at FROM sessions
59
+ WHERE pane_sessions.source = 'inferred:cwd_time' AND id = pane_sessions.agent_session_value)
60
+ ORDER BY started_at, id LIMIT 1)
61
+ WHERE session_id IS NULL RETURNING pane_id, session_id, source`);
62
+ const clearPane = db.prepare(`DELETE FROM pane_sessions WHERE pane_id = ? AND source = 'inferred:cwd_time'
63
+ AND session_id IN (SELECT id FROM sessions WHERE ended_at IS NULL)`);
64
+ const clearSession = db.prepare("DELETE FROM pane_sessions WHERE session_id = ? AND source = 'inferred:cwd_time'");
65
+ const previousLinks = db.prepare("SELECT pane_id, agent, first_seen_ms FROM pane_sessions WHERE session_id = ? AND source = 'inferred:cwd_time'");
66
+ const endPaneSessions = db.prepare(`UPDATE sessions SET ended_at = MAX(started_at, ?) WHERE ended_at IS NULL
67
+ AND id IN (SELECT session_id FROM pane_sessions WHERE pane_id = ?)`);
68
+ const endPrevious = db.prepare(`UPDATE sessions SET ended_at = ? WHERE id <> ? AND started_at < ?
69
+ AND (ended_at IS NULL OR ended_at > ?) AND id IN (SELECT session_id FROM pane_sessions WHERE pane_id = ?)`);
70
+ const infer = db.prepare(`INSERT INTO pane_sessions
71
+ (pane_id, agent, source, agent_session_value, session_id, first_seen_ms, last_seen_ms)
72
+ VALUES (?, ?, 'inferred:cwd_time', ?, ?, ?, ?)`);
73
+ const inferSessions = db.prepare(`SELECT DISTINCT s.id, s.started_at FROM herdr_panes p CROSS JOIN sessions s
74
+ WHERE (p.closed_ms IS NULL OR p.last_seen_ms >= ?) AND p.cwd IS NOT NULL AND p.cwd <> ''
75
+ AND s.cwd = p.cwd AND s.started_at >= p.created_ms AND s.started_at <= COALESCE(p.closed_ms, ?)
76
+ AND NOT EXISTS (SELECT 1 FROM pane_sessions ps WHERE ps.session_id = s.id)`);
77
+ const revisitSessions = db.prepare(`SELECT DISTINCT s.id, s.started_at FROM herdr_panes p CROSS JOIN sessions s
78
+ WHERE p.cwd = ? AND (p.closed_ms IS NULL OR p.last_seen_ms >= ?)
79
+ AND s.cwd = p.cwd AND s.ended_at IS NULL AND s.started_at >= p.created_ms AND s.started_at <= COALESCE(p.closed_ms, ?)`);
80
+ const touchedSession = db.prepare("SELECT id, started_at, ended_at FROM sessions WHERE id = ?");
81
+ const hasLink = db.prepare("SELECT 1 FROM pane_sessions WHERE session_id = ? LIMIT 1");
82
+ const candidates = db.prepare(`SELECT p.id, p.agent, s.runtime,
83
+ NOT EXISTS (SELECT 1 FROM pane_sessions ps LEFT JOIN sessions reported ON reported.id = ps.session_id
84
+ WHERE ps.pane_id = p.id AND ps.source <> 'inferred:cwd_time'
85
+ AND (ps.session_id IS NULL OR (reported.started_at <= s.started_at
86
+ AND COALESCE(reported.ended_at, 9223372036854775807) > s.started_at
87
+ AND NOT (reported.started_at < s.started_at AND reported.runtime = s.runtime
88
+ AND EXISTS (SELECT 1 FROM events e WHERE e.session_id = s.id AND e.kind = 'session_start')))))
89
+ AND NOT EXISTS (SELECT 1 FROM pane_sessions ps JOIN sessions other ON other.id = ps.session_id
90
+ WHERE ps.pane_id = p.id AND other.started_at < COALESCE(s.ended_at, 9223372036854775807)
91
+ AND s.started_at < COALESCE(other.ended_at, 9223372036854775807)
92
+ AND NOT (other.started_at < s.started_at AND other.runtime = s.runtime
93
+ AND EXISTS (SELECT 1 FROM events e WHERE e.session_id = s.id AND e.kind = 'session_start'))) AS available
94
+ FROM herdr_panes p JOIN sessions s ON s.cwd = p.cwd
95
+ WHERE s.id = ? AND s.started_at >= p.created_ms AND s.started_at <= COALESCE(p.closed_ms, ?)
96
+ ORDER BY p.id`);
97
+ const usable = (pane) => pane.agent_session?.kind === "id" && pane.agent_session.value.trim() !== "";
98
+ const linkSessions = (touched = []) => {
99
+ if (stopped)
100
+ return;
101
+ const now = Date.now();
102
+ db.exec("SAVEPOINT herdr_links");
103
+ try {
104
+ for (const row of linkPending.all()) {
105
+ if (row.session_id === null || row.source === "inferred:cwd_time")
106
+ continue;
107
+ const session = touchedSession.get(row.session_id);
108
+ if (session)
109
+ endPrevious.run(session.started_at, session.id, session.started_at, session.started_at, row.pane_id);
110
+ clearPane.run(row.pane_id);
111
+ clearSession.run(row.session_id);
112
+ }
113
+ // Only revisit sessions inside recent/open pane lifetimes or this ingest batch.
114
+ // Historical inferred links outside that set are never rewritten.
115
+ const batch = new Map(inferSessions.all(now - RECENT_PANE_MS, now).map((s) => [s.id, s]));
116
+ for (const cwd of changedCwds) {
117
+ for (const session of revisitSessions.all(cwd, now - RECENT_PANE_MS, now))
118
+ batch.set(session.id, session);
119
+ }
120
+ for (const id of touched) {
121
+ const session = touchedSession.get(id);
122
+ if (session && (session.ended_at === null || !hasLink.get(session.id)))
123
+ batch.set(session.id, session);
124
+ }
125
+ const sessions = [...batch.values()].sort((a, b) => Number(a.started_at) - Number(b.started_at) || String(a.id).localeCompare(String(b.id)));
126
+ const previous = new Map(sessions.map((s) => [s.id, previousLinks.all(s.id)]));
127
+ for (const session of sessions)
128
+ clearSession.run(session.id);
129
+ for (const session of sessions) {
130
+ if (hasLink.get(session.id))
131
+ continue;
132
+ let eligible = candidates.all(session.id, now);
133
+ const matching = eligible.filter((p) => p.agent && runtimeOf(p.agent) === p.runtime);
134
+ // Rank evidence before availability: an occupied matching agent must never redirect work to a shell.
135
+ if (matching.length)
136
+ eligible = matching.filter((p) => p.available === 1);
137
+ else if (eligible.some((p) => p.agent))
138
+ eligible = [];
139
+ else
140
+ eligible = eligible.filter((p) => !p.agent && p.available === 1);
141
+ if (eligible.length !== 1)
142
+ continue;
143
+ const first = eligible[0];
144
+ if (!first)
145
+ continue;
146
+ const old = previous.get(session.id)?.find((row) => row.pane_id === first.id);
147
+ infer.run(first.id, first.agent, session.id, session.id, old?.first_seen_ms ?? now, now);
148
+ if (db.prepare("SELECT 1 FROM events WHERE session_id = ? AND kind = 'session_start' LIMIT 1").get(session.id)) {
149
+ endPrevious.run(session.started_at, session.id, session.started_at, session.started_at, first.id);
150
+ }
151
+ }
152
+ db.exec("RELEASE herdr_links");
153
+ changedCwds.clear();
154
+ }
155
+ catch (error) {
156
+ db.exec("ROLLBACK TO herdr_links; RELEASE herdr_links");
157
+ throw error;
158
+ }
159
+ };
160
+ const applySnapshot = (snapshot) => {
161
+ const now = Date.now();
162
+ db.exec("BEGIN IMMEDIATE");
163
+ try {
164
+ for (const w of snapshot.workspaces)
165
+ upsertWorkspace.run(w.workspace_id, w.label ?? null, w.created_ms ?? now);
166
+ for (const t of snapshot.tabs)
167
+ upsertTab.run(t.tab_id, t.workspace_id, t.label ?? null, t.created_ms ?? now);
168
+ for (const p of snapshot.panes) {
169
+ const previousPane = db.prepare("SELECT agent, cwd, created_ms, closed_ms FROM herdr_panes WHERE id = ?").get(p.pane_id);
170
+ const agent = p.agent_session?.agent ?? p.agent ?? null;
171
+ if (!previousPane || previousPane.agent !== agent || previousPane.cwd !== (p.cwd ?? null) || previousPane.closed_ms !== null) {
172
+ if (typeof previousPane?.cwd === "string" && previousPane.cwd !== "")
173
+ changedCwds.add(previousPane.cwd);
174
+ if (p.cwd)
175
+ changedCwds.add(p.cwd);
176
+ }
177
+ // A complete snapshot omits these fields for a shell after agent exit. Partial events below do not.
178
+ if (p.agent_status === "exited" || (previousPane?.agent && p.agent == null && !p.agent_session)) {
179
+ endPaneSessions.run(now, p.pane_id);
180
+ }
181
+ upsertPane.run(p.pane_id, p.workspace_id, p.tab_id, p.label ?? p.title ?? null, p.cwd ?? null, p.created_ms ?? now, p.agent_session?.agent ?? p.agent ?? null, now);
182
+ if (usable(p) && p.agent_session) {
183
+ const source = p.agent_session.source.startsWith("herdr:") ? p.agent_session.source : `herdr:${p.agent_session.source}`;
184
+ upsertReported.run(p.pane_id, p.agent_session.agent, source, p.agent_session.value, now, now);
185
+ // Keep inferred history; reported identity replaces only the same session during linking.
186
+ }
187
+ }
188
+ // A full snapshot is authoritative: recover closes lost during an outage.
189
+ for (const [table, ids] of [
190
+ ["herdr_workspaces", snapshot.workspaces.map((w) => w.workspace_id)],
191
+ ["herdr_tabs", snapshot.tabs.map((t) => t.tab_id)],
192
+ ["herdr_panes", snapshot.panes.map((p) => p.pane_id)],
193
+ ]) {
194
+ const live = new Set(ids);
195
+ const close = db.prepare(`UPDATE ${table} SET closed_ms = ? WHERE id = ? AND closed_ms IS NULL`);
196
+ for (const row of db.prepare(`SELECT id FROM ${table} WHERE closed_ms IS NULL`).all()) {
197
+ if (typeof row.id === "string" && !live.has(row.id))
198
+ close.run(now, row.id);
199
+ }
200
+ }
201
+ linkSessions();
202
+ db.exec("COMMIT");
203
+ }
204
+ catch (error) {
205
+ db.exec("ROLLBACK");
206
+ throw error;
207
+ }
208
+ };
209
+ const reconcile = () => {
210
+ if (stopped || !ready)
211
+ return Promise.resolve();
212
+ if (running) {
213
+ again = true;
214
+ return running;
215
+ }
216
+ const generation = connection;
217
+ running = (async () => {
218
+ do {
219
+ again = false;
220
+ const before = revision;
221
+ const snapshot = snapshotSchema.parse(await client.request("session.snapshot"));
222
+ if (stopped || generation !== connection)
223
+ return;
224
+ // Do not resurrect a pane from a response overtaken by a close/update event.
225
+ if (before !== revision)
226
+ again = true;
227
+ else {
228
+ applySnapshot(snapshot.snapshot);
229
+ const panes = new Map(snapshot.snapshot.panes
230
+ .filter((pane) => snapshot.snapshot.workspaces.some((workspace) => workspace.workspace_id === pane.workspace_id))
231
+ .map((pane) => [pane.pane_id, pane]));
232
+ for (const [paneId, subscription] of paneSubscriptions) {
233
+ if (panes.get(paneId)?.workspace_id !== subscription.workspaceId)
234
+ unsubscribePane(paneId);
235
+ }
236
+ for (const [paneId, pane] of panes) {
237
+ if (paneSubscriptions.has(paneId))
238
+ continue;
239
+ const stop = await client.subscribePane(paneId);
240
+ if (stopped || generation !== connection) {
241
+ stop();
242
+ again = true;
243
+ break;
244
+ }
245
+ paneSubscriptions.set(paneId, { workspaceId: pane.workspace_id, stop });
246
+ if (before !== revision) {
247
+ again = true;
248
+ break;
249
+ }
250
+ }
251
+ }
252
+ } while (again && !stopped);
253
+ })().finally(() => { running = undefined; });
254
+ return running;
255
+ };
256
+ const refresh = () => {
257
+ void reconcile().catch((error) => {
258
+ if (!stopped)
259
+ opts.log(`herdr reconcile failed: ${error instanceof Error ? error.message : String(error)}`);
260
+ });
261
+ };
262
+ const client = createHerdrClient({
263
+ ...opts,
264
+ onDisconnect() {
265
+ ready = false;
266
+ connection += 1;
267
+ for (const paneId of paneSubscriptions.keys())
268
+ unsubscribePane(paneId);
269
+ },
270
+ async onConnect(active) {
271
+ ready = false;
272
+ connection += 1;
273
+ if (running)
274
+ await running.catch(() => undefined);
275
+ z.object({ type: z.literal("pong") }).parse(await active.request("ping"));
276
+ z.object({ type: z.literal("subscription_started") }).parse(await active.request("events.subscribe", {
277
+ subscriptions: subscriptions.map((type) => ({ type })),
278
+ }));
279
+ ready = true;
280
+ await reconcile();
281
+ },
282
+ onEvent(event, data) {
283
+ if (stopped)
284
+ return;
285
+ revision += 1;
286
+ const parsed = closedSchema.safeParse(data);
287
+ if (parsed.success) {
288
+ const { workspace_id: workspace, tab_id: tab, pane_id: pane } = parsed.data;
289
+ const now = Date.now();
290
+ switch (event) {
291
+ case "workspace_closed":
292
+ if (workspace) {
293
+ for (const row of db.prepare("SELECT id FROM herdr_panes WHERE workspace_id = ?").all(workspace)) {
294
+ if (typeof row.id === "string")
295
+ unsubscribePane(row.id);
296
+ }
297
+ db.prepare("UPDATE herdr_workspaces SET closed_ms = ? WHERE id = ?").run(now, workspace);
298
+ db.prepare("UPDATE herdr_tabs SET closed_ms = ? WHERE workspace_id = ?").run(now, workspace);
299
+ db.prepare("UPDATE herdr_panes SET closed_ms = ? WHERE workspace_id = ?").run(now, workspace);
300
+ }
301
+ break;
302
+ case "tab_closed":
303
+ if (tab) {
304
+ for (const row of db.prepare("SELECT id FROM herdr_panes WHERE tab_id = ?").all(tab)) {
305
+ if (typeof row.id === "string")
306
+ unsubscribePane(row.id);
307
+ }
308
+ db.prepare("UPDATE herdr_tabs SET closed_ms = ? WHERE id = ?").run(now, tab);
309
+ db.prepare("UPDATE herdr_panes SET closed_ms = ? WHERE tab_id = ?").run(now, tab);
310
+ }
311
+ break;
312
+ case "pane_closed":
313
+ case "pane_exited":
314
+ if (pane) {
315
+ unsubscribePane(pane);
316
+ endPaneSessions.run(now, pane);
317
+ db.prepare("UPDATE herdr_panes SET closed_ms = ? WHERE id = ?").run(now, pane);
318
+ }
319
+ break;
320
+ case "pane.agent_status_changed":
321
+ if (pane && parsed.data.agent === null)
322
+ endPaneSessions.run(now, pane);
323
+ break;
324
+ }
325
+ }
326
+ refresh();
327
+ },
328
+ });
329
+ const interval = setInterval(refresh, 30_000);
330
+ interval.unref();
331
+ return {
332
+ reconcile,
333
+ linkSessions,
334
+ close() {
335
+ stopped = true;
336
+ clearInterval(interval);
337
+ for (const paneId of paneSubscriptions.keys())
338
+ unsubscribePane(paneId);
339
+ client.close();
340
+ },
341
+ };
342
+ }
@@ -0,0 +1,80 @@
1
+ export const WINDOW_MS = 120_000;
2
+ export const URI_WINDOW_MS = 10_000;
3
+ const MAX_TRACKED = 10_000;
4
+ export function createAttributionState() {
5
+ return { toolUseSessions: new Map(), loadSessions: new Map() };
6
+ }
7
+ export function remember(map, key, value) {
8
+ map.delete(key);
9
+ map.set(key, value);
10
+ if (map.size > MAX_TRACKED) {
11
+ const oldest = map.keys().next().value;
12
+ if (oldest !== undefined)
13
+ map.delete(oldest);
14
+ }
15
+ }
16
+ function attributed(sessionId) {
17
+ return sessionId !== undefined && sessionId !== "unattributed";
18
+ }
19
+ /** Exact JSON string values only: a URI mentioned in shell/exec source is not a resource-read argument. */
20
+ export function toolCallReferencesUri(text, uri, skillarMcp) {
21
+ if (text === null)
22
+ return false;
23
+ let args;
24
+ try {
25
+ args = JSON.parse(text);
26
+ }
27
+ catch {
28
+ return false; // Truncated or non-JSON arguments cannot prove a URI match.
29
+ }
30
+ // Historical OTLP resource calls predate skillarMcp; their explicit server argument is equally strong evidence.
31
+ const server = args !== null && typeof args === "object" && "server" in args ? args.server : undefined;
32
+ if (!skillarMcp && !(typeof server === "string" && ["skillar", "gisool"].includes(server.toLowerCase())))
33
+ return false;
34
+ const references = (value) => {
35
+ if (typeof value === "string")
36
+ return value === uri;
37
+ if (Array.isArray(value))
38
+ return value.some(references);
39
+ return value !== null && typeof value === "object" && Object.values(value).some(references);
40
+ };
41
+ return references(args);
42
+ }
43
+ export function attribute(event, store, now, state = createAttributionState()) {
44
+ const { ref } = event;
45
+ const hasRuntimeKey = Boolean(ref.runtimeSessionId || ref.conversationId);
46
+ // (1) hook / OTel events carry the runtime's own session id.
47
+ if (event.source !== "mcp" && hasRuntimeKey) {
48
+ return { sessionId: store.upsertSession(ref, event.ts), method: "runtime_id" };
49
+ }
50
+ // (2) MCP events: vendor _meta session ids, or a Claude tool_use_id already bound by a PostToolUse hook.
51
+ if (event.source === "mcp") {
52
+ if (hasRuntimeKey)
53
+ return { sessionId: store.upsertSession(ref, event.ts), method: "vendor_meta" };
54
+ const bound = event.toolUseId ? state.toolUseSessions.get(event.toolUseId) : undefined;
55
+ if (bound)
56
+ return { sessionId: bound, method: "vendor_meta" };
57
+ }
58
+ // (3) load / read_file joined to an attributed search (traceId) or load (loadId).
59
+ if (event.kind === "load" || event.kind === "read_file") {
60
+ const viaTrace = event.traceId ? store.traceSession(event.traceId) : undefined;
61
+ if (attributed(viaTrace))
62
+ return { sessionId: viaTrace, method: "trace_handle" };
63
+ const viaLoad = event.loadId ? state.loadSessions.get(event.loadId) : undefined;
64
+ if (attributed(viaLoad))
65
+ return { sessionId: viaLoad, method: "trace_handle" };
66
+ }
67
+ // (4) exactly one open session of the same runtime active within the window; never across runtimes.
68
+ if (ref.runtime === "unknown")
69
+ return { sessionId: "unattributed", method: "none", reason: "no_session" };
70
+ const open = store.openSessions(ref.runtime, 0).filter((s) => s.ref.runtime === ref.runtime);
71
+ const fresh = open.filter((s) => now - s.lastActivityAt <= WINDOW_MS);
72
+ if (fresh.length === 1)
73
+ return { sessionId: fresh[0].id, method: "window" };
74
+ // (5) unattributed with the reason the window could not decide.
75
+ if (fresh.length > 1)
76
+ return { sessionId: "unattributed", method: "none", reason: "ambiguous" };
77
+ if (open.length > 0)
78
+ return { sessionId: "unattributed", method: "none", reason: "stale" };
79
+ return { sessionId: "unattributed", method: "none", reason: "no_session" };
80
+ }