@scrylog/cli 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.md +836 -0
- package/package.json +75 -0
- package/src/api/docs/sessions.keys.ts +6 -0
- package/src/api/docs/sessions.ts +81 -0
- package/src/api/docs/system.keys.ts +5 -0
- package/src/api/docs/system.ts +66 -0
- package/src/api/docs/usage.keys.ts +3 -0
- package/src/api/docs/usage.ts +24 -0
- package/src/api/docs/webhooks.keys.ts +5 -0
- package/src/api/docs/webhooks.ts +78 -0
- package/src/api/index.ts +18 -0
- package/src/api/lib/auth.ts +43 -0
- package/src/api/lib/errors.ts +28 -0
- package/src/api/lib/route.ts +18 -0
- package/src/api/models/claude.ts +4 -0
- package/src/api/models/codex.ts +4 -0
- package/src/api/models/opencode.ts +11 -0
- package/src/api/routes/sessions.ts +47 -0
- package/src/api/routes/system.ts +103 -0
- package/src/api/routes/usage.ts +15 -0
- package/src/api/routes/webhooks/claude.ts +161 -0
- package/src/api/routes/webhooks/codex.ts +175 -0
- package/src/api/routes/webhooks/opencode.ts +107 -0
- package/src/api/routes.ts +93 -0
- package/src/api/schemas/common.ts +21 -0
- package/src/api/schemas/sessions.ts +72 -0
- package/src/api/schemas/usage.ts +50 -0
- package/src/api/schemas/webhooks/claude.ts +32 -0
- package/src/api/schemas/webhooks/codex.ts +34 -0
- package/src/api/schemas/webhooks/opencode.ts +29 -0
- package/src/api/services/claude-session.ts +9 -0
- package/src/api/services/codex-session.ts +8 -0
- package/src/api/services/opencode-session.ts +73 -0
- package/src/classifier.ts +206 -0
- package/src/cli/commands.ts +498 -0
- package/src/cli/prompt.ts +44 -0
- package/src/daemon/cli.ts +27 -0
- package/src/daemon/collectors/claude/README.md +108 -0
- package/src/daemon/collectors/claude/collector.ts +413 -0
- package/src/daemon/collectors/claude/discovery.ts +148 -0
- package/src/daemon/collectors/claude/hooks.ts +181 -0
- package/src/daemon/collectors/claude/index.ts +8 -0
- package/src/daemon/collectors/claude/jsonl.ts +85 -0
- package/src/daemon/collectors/claude/transcript.ts +246 -0
- package/src/daemon/collectors/codex/README.md +147 -0
- package/src/daemon/collectors/codex/collector.ts +661 -0
- package/src/daemon/collectors/codex/discovery.ts +104 -0
- package/src/daemon/collectors/codex/hooks.ts +179 -0
- package/src/daemon/collectors/codex/index.ts +7 -0
- package/src/daemon/collectors/codex/jsonl.ts +108 -0
- package/src/daemon/collectors/codex/transcript.ts +299 -0
- package/src/daemon/collectors/git.ts +295 -0
- package/src/daemon/collectors/opencode/README.md +106 -0
- package/src/daemon/collectors/opencode/collector.ts +543 -0
- package/src/daemon/collectors/opencode/discovery.ts +257 -0
- package/src/daemon/collectors/opencode/index.ts +5 -0
- package/src/daemon/collectors/opencode/session-builder.ts +59 -0
- package/src/daemon/collectors/opencode-db.ts +282 -0
- package/src/daemon/collectors/process.ts +201 -0
- package/src/daemon/collectors/tmux/README.md +128 -0
- package/src/daemon/collectors/tmux/collector.ts +472 -0
- package/src/daemon/collectors/tmux/enrichment.ts +241 -0
- package/src/daemon/collectors/tmux/index.ts +4 -0
- package/src/daemon/collectors/tmux/parse.ts +128 -0
- package/src/daemon/collectors/usage.ts +193 -0
- package/src/daemon/index.ts +207 -0
- package/src/daemon/scheduler.ts +86 -0
- package/src/daemon/store.ts +535 -0
- package/src/detect.ts +143 -0
- package/src/hooks/claude.ts +596 -0
- package/src/hooks/codex.ts +517 -0
- package/src/legacy/classifier.ts +215 -0
- package/src/legacy/detect.ts +143 -0
- package/src/mcp/client-server.ts +21 -0
- package/src/mcp/http-handler.ts +126 -0
- package/src/mcp/index.ts +61 -0
- package/src/mcp/resources/config-current.ts +19 -0
- package/src/mcp/resources/index.ts +11 -0
- package/src/mcp/resources/sessions-active.ts +19 -0
- package/src/mcp/resources/sessions-all.ts +19 -0
- package/src/mcp/schemas/sessions.ts +3 -0
- package/src/mcp/server.ts +17 -0
- package/src/mcp/services/api-adapter.ts +48 -0
- package/src/mcp/services/data-source.ts +22 -0
- package/src/mcp/services/store-adapter.ts +40 -0
- package/src/mcp/tools/get-active-sessions.ts +16 -0
- package/src/mcp/tools/get-session-children.ts +24 -0
- package/src/mcp/tools/get-session-messages.ts +24 -0
- package/src/mcp/tools/get-session.ts +23 -0
- package/src/mcp/tools/index.ts +15 -0
- package/src/mcp/tools/list-sessions.ts +16 -0
- package/src/neo-blessed.d.ts +4 -0
- package/src/oc/index.ts +302 -0
- package/src/service/manager.ts +242 -0
- package/src/shared/config.ts +478 -0
- package/src/shared/ipc.ts +80 -0
- package/src/shared/logger.ts +248 -0
- package/src/shared/paths.ts +73 -0
- package/src/shared/platform.ts +110 -0
- package/src/shared/session-view.ts +241 -0
- package/src/shared/types.ts +299 -0
- package/src/shared/utils.ts +339 -0
- package/src/tui/app.ts +920 -0
- package/src/tui/client.ts +149 -0
- package/src/tui/index.ts +181 -0
- package/src/types.ts +113 -0
- package/src/usage/README.md +323 -0
- package/src/usage/api.ts +99 -0
- package/src/usage/client.ts +3 -0
- package/src/usage/clients/anthropic-oauth-usage.ts +178 -0
- package/src/usage/clients/anthropic-web-usage.ts +245 -0
- package/src/usage/clients/claude-cli-probe.ts +187 -0
- package/src/usage/clients/codex-oauth-usage.ts +113 -0
- package/src/usage/clients/opencode-go-usage.ts +441 -0
- package/src/usage/index.ts +19 -0
- package/src/usage/mappers.ts +273 -0
- package/src/usage/planner.ts +54 -0
- package/src/usage/providers/claude.ts +113 -0
- package/src/usage/providers/codex.ts +34 -0
- package/src/usage/providers/opencode-go.ts +37 -0
- package/src/usage/resolver.ts +4 -0
- package/src/usage/resolvers/browser-cookies.ts +198 -0
- package/src/usage/resolvers/claude-auth.ts +99 -0
- package/src/usage/resolvers/claude-cli.ts +24 -0
- package/src/usage/resolvers/claude-web.ts +16 -0
- package/src/usage/resolvers/codex-auth.ts +117 -0
- package/src/usage/resolvers/opencode-go-web.ts +14 -0
- package/src/usage/types.ts +190 -0
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { OpenAPIHono } from "@hono/zod-openapi";
|
|
2
|
+
import type { DaemonStore } from "../../../daemon/store";
|
|
3
|
+
import type { GitCollector } from "../../../daemon/collectors/git";
|
|
4
|
+
import type { Logger } from "../../../shared/logger";
|
|
5
|
+
import type { ClaudeWebhookPayload } from "../../models/claude";
|
|
6
|
+
import { isMetadataOnlyEvent } from "../../services/claude-session";
|
|
7
|
+
import { ValidationError } from "../../lib/errors";
|
|
8
|
+
import { WebhookRouteKey } from "../../docs/webhooks.keys";
|
|
9
|
+
import { defineRoute } from "../../lib/route";
|
|
10
|
+
|
|
11
|
+
export function createClaudeWebhookRouter(store: DaemonStore, logger: Logger, gitCollector?: GitCollector): OpenAPIHono {
|
|
12
|
+
const router = new OpenAPIHono();
|
|
13
|
+
|
|
14
|
+
router.openapi(defineRoute(WebhookRouteKey.WEBHOOK_CLAUDE), async (c) => {
|
|
15
|
+
const payload = c.req.valid("json") as ClaudeWebhookPayload;
|
|
16
|
+
|
|
17
|
+
const {
|
|
18
|
+
sessionId,
|
|
19
|
+
eventType,
|
|
20
|
+
eventTime,
|
|
21
|
+
hookSeq,
|
|
22
|
+
state,
|
|
23
|
+
hasAttention,
|
|
24
|
+
attentionKind,
|
|
25
|
+
summary,
|
|
26
|
+
activeTool,
|
|
27
|
+
toolName,
|
|
28
|
+
toolInputSummary,
|
|
29
|
+
toolResultStatus,
|
|
30
|
+
permissionMode,
|
|
31
|
+
startSource,
|
|
32
|
+
endReason,
|
|
33
|
+
errorType,
|
|
34
|
+
agentId,
|
|
35
|
+
agentType,
|
|
36
|
+
transcriptPath,
|
|
37
|
+
currentPath,
|
|
38
|
+
lastActivity,
|
|
39
|
+
parentSessionId,
|
|
40
|
+
} = payload;
|
|
41
|
+
|
|
42
|
+
if (!sessionId || typeof sessionId !== "string") {
|
|
43
|
+
throw new ValidationError("sessionId required");
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const storeId = `claude:${sessionId}`;
|
|
47
|
+
if (eventType === "SessionEnd") {
|
|
48
|
+
store.markLocalCommand(sessionId);
|
|
49
|
+
const existing = store.getSession(storeId);
|
|
50
|
+
if (existing) {
|
|
51
|
+
store.upsertSession({
|
|
52
|
+
...existing,
|
|
53
|
+
state: "idle",
|
|
54
|
+
hasAttention: false,
|
|
55
|
+
summary: summary ?? existing.summary ?? "Claude session ended",
|
|
56
|
+
lastActivity: lastActivity ?? Date.now(),
|
|
57
|
+
detectionSource: "claude-hook",
|
|
58
|
+
claude: {
|
|
59
|
+
sessionId,
|
|
60
|
+
transcriptPath: transcriptPath ?? existing.claude?.transcriptPath ?? "",
|
|
61
|
+
...(eventType !== undefined ? { hookEventType: eventType } : {}),
|
|
62
|
+
...(eventTime !== undefined ? { hookEventTime: eventTime } : {}),
|
|
63
|
+
...(hookSeq !== undefined ? { hookSeq } : {}),
|
|
64
|
+
...(endReason !== undefined ? { endReason } : {}),
|
|
65
|
+
...(errorType !== undefined ? { errorType } : {}),
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
logger.info("webhook", "claude session ended", { event: "session.ended", tool: "claude", sessionId, reason: endReason });
|
|
71
|
+
return c.json({ ok: true as const }, 200);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const existing = store.getSession(storeId);
|
|
75
|
+
|
|
76
|
+
if (existing) {
|
|
77
|
+
const existingSeq = existing.claude?.hookSeq;
|
|
78
|
+
if (typeof hookSeq === "number" && typeof existingSeq === "number" && hookSeq < existingSeq) {
|
|
79
|
+
logger.debug("webhook", "claude hook rejected — stale sequence", { sessionId, hookSeq, existingSeq });
|
|
80
|
+
return c.json({ ok: true as const, skipped: "stale-sequence" }, 200);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const isStateBearing = !isMetadataOnlyEvent(eventType ?? "");
|
|
85
|
+
|
|
86
|
+
logger.debug("webhook", "claude hook received", { sessionId, state, eventType });
|
|
87
|
+
|
|
88
|
+
if (existing) {
|
|
89
|
+
store.upsertSession({
|
|
90
|
+
...existing,
|
|
91
|
+
...(isStateBearing && state !== undefined ? { state } : {}),
|
|
92
|
+
...(isStateBearing && hasAttention !== undefined ? { hasAttention } : {}),
|
|
93
|
+
...(attentionKind !== undefined ? { attentionKind } : {}),
|
|
94
|
+
...(summary !== undefined ? { summary } : {}),
|
|
95
|
+
...(activeTool !== undefined ? { activeTool } : {}),
|
|
96
|
+
...(!isStateBearing && currentPath !== undefined ? { currentPath } : {}),
|
|
97
|
+
...(currentPath && !existing.project && gitCollector ? { project: gitCollector.resolve(currentPath) } : {}),
|
|
98
|
+
...(isStateBearing ? {} : existing.currentPath && !currentPath ? {} : {}),
|
|
99
|
+
lastActivity: lastActivity ?? Date.now(),
|
|
100
|
+
detectionSource: "claude-hook",
|
|
101
|
+
...(parentSessionId ? { parentSessionId } : {}),
|
|
102
|
+
claude: {
|
|
103
|
+
sessionId,
|
|
104
|
+
transcriptPath: transcriptPath ?? existing.claude?.transcriptPath ?? "",
|
|
105
|
+
...(eventType !== undefined ? { hookEventType: eventType } : {}),
|
|
106
|
+
...(eventTime !== undefined ? { hookEventTime: eventTime } : {}),
|
|
107
|
+
...(hookSeq !== undefined ? { hookSeq } : {}),
|
|
108
|
+
...(permissionMode !== undefined ? { permissionMode } : {}),
|
|
109
|
+
...(startSource !== undefined ? { startSource } : {}),
|
|
110
|
+
...(endReason !== undefined ? { endReason } : {}),
|
|
111
|
+
...(errorType !== undefined ? { errorType } : {}),
|
|
112
|
+
...(attentionKind !== undefined ? { attentionKind } : {}),
|
|
113
|
+
...(toolName !== undefined ? { toolName } : {}),
|
|
114
|
+
...(toolInputSummary !== undefined ? { toolInputSummary } : {}),
|
|
115
|
+
...(toolResultStatus !== undefined ? { toolResultStatus } : {}),
|
|
116
|
+
...(agentId !== undefined ? { agentId } : {}),
|
|
117
|
+
...(agentType !== undefined ? { agentType } : {}),
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
} else {
|
|
121
|
+
store.upsertSession({
|
|
122
|
+
id: storeId,
|
|
123
|
+
source: "standalone",
|
|
124
|
+
tool: "claude",
|
|
125
|
+
state: (isStateBearing ? state : undefined) ?? "idle",
|
|
126
|
+
summary: summary ?? "Claude session",
|
|
127
|
+
lastActivity: lastActivity ?? Date.now(),
|
|
128
|
+
detectionSource: "claude-hook",
|
|
129
|
+
hasAttention: isStateBearing ? (hasAttention ?? false) : false,
|
|
130
|
+
activeTool,
|
|
131
|
+
currentPath,
|
|
132
|
+
...(currentPath && gitCollector ? { project: gitCollector.resolve(currentPath) } : {}),
|
|
133
|
+
...(parentSessionId ? { parentSessionId } : {}),
|
|
134
|
+
claude: {
|
|
135
|
+
sessionId,
|
|
136
|
+
transcriptPath: transcriptPath ?? "",
|
|
137
|
+
...(eventType !== undefined ? { hookEventType: eventType } : {}),
|
|
138
|
+
...(eventTime !== undefined ? { hookEventTime: eventTime } : {}),
|
|
139
|
+
...(hookSeq !== undefined ? { hookSeq } : {}),
|
|
140
|
+
...(permissionMode !== undefined ? { permissionMode } : {}),
|
|
141
|
+
...(startSource !== undefined ? { startSource } : {}),
|
|
142
|
+
...(endReason !== undefined ? { endReason } : {}),
|
|
143
|
+
...(errorType !== undefined ? { errorType } : {}),
|
|
144
|
+
...(attentionKind !== undefined ? { attentionKind } : {}),
|
|
145
|
+
...(toolName !== undefined ? { toolName } : {}),
|
|
146
|
+
...(toolInputSummary !== undefined ? { toolInputSummary } : {}),
|
|
147
|
+
...(toolResultStatus !== undefined ? { toolResultStatus } : {}),
|
|
148
|
+
...(agentId !== undefined ? { agentId } : {}),
|
|
149
|
+
...(agentType !== undefined ? { agentType } : {}),
|
|
150
|
+
},
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
logger.debug("webhook", "claude stub session created from hook", { event: "session.upsert_from_webhook", tool: "claude", sessionId, state });
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
store.syncChildSessionIds();
|
|
157
|
+
return c.json({ ok: true as const }, 200);
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
return router;
|
|
161
|
+
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { OpenAPIHono } from "@hono/zod-openapi";
|
|
2
|
+
import type { DaemonStore } from "../../../daemon/store";
|
|
3
|
+
import type { GitCollector } from "../../../daemon/collectors/git";
|
|
4
|
+
import type { Logger } from "../../../shared/logger";
|
|
5
|
+
import type { SessionModel } from "../../../shared/types";
|
|
6
|
+
import type { CodexWebhookPayload } from "../../models/codex";
|
|
7
|
+
import { isMetadataOnlyEvent } from "../../services/codex-session";
|
|
8
|
+
import { ValidationError } from "../../lib/errors";
|
|
9
|
+
import { WebhookRouteKey } from "../../docs/webhooks.keys";
|
|
10
|
+
import { defineRoute } from "../../lib/route";
|
|
11
|
+
|
|
12
|
+
export function createCodexWebhookRouter(store: DaemonStore, logger: Logger, gitCollector?: GitCollector): OpenAPIHono {
|
|
13
|
+
const router = new OpenAPIHono();
|
|
14
|
+
|
|
15
|
+
router.openapi(defineRoute(WebhookRouteKey.WEBHOOK_CODEX), async (c) => {
|
|
16
|
+
const payload = c.req.valid("json") as CodexWebhookPayload;
|
|
17
|
+
|
|
18
|
+
const {
|
|
19
|
+
sessionId,
|
|
20
|
+
eventType,
|
|
21
|
+
eventTime,
|
|
22
|
+
hookSeq,
|
|
23
|
+
state,
|
|
24
|
+
hasAttention,
|
|
25
|
+
attentionKind,
|
|
26
|
+
summary,
|
|
27
|
+
activeTool,
|
|
28
|
+
model,
|
|
29
|
+
toolName,
|
|
30
|
+
toolInputSummary,
|
|
31
|
+
toolResultStatus,
|
|
32
|
+
permissionMode,
|
|
33
|
+
startSource,
|
|
34
|
+
endReason,
|
|
35
|
+
transcriptPath,
|
|
36
|
+
currentPath,
|
|
37
|
+
lastActivity,
|
|
38
|
+
parentSessionId,
|
|
39
|
+
forkedFromId,
|
|
40
|
+
turnId,
|
|
41
|
+
agentId,
|
|
42
|
+
agentType,
|
|
43
|
+
} = payload;
|
|
44
|
+
|
|
45
|
+
if (!sessionId || typeof sessionId !== "string") {
|
|
46
|
+
throw new ValidationError("sessionId required");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const storeId = `codex:${sessionId}`;
|
|
50
|
+
const hasActiveChildren = () => store.getSessions().some(
|
|
51
|
+
(s) => s.parentSessionId === storeId && (s.state === "working" || s.state === "waiting-input"),
|
|
52
|
+
);
|
|
53
|
+
|
|
54
|
+
// Stop with no continuation is the terminal event for Codex (no SessionEnd)
|
|
55
|
+
if (eventType === "Stop") {
|
|
56
|
+
const existing = store.getSession(storeId);
|
|
57
|
+
if (existing) {
|
|
58
|
+
const resolvedState: SessionModel["state"] =
|
|
59
|
+
(state === "waiting-input" || state === "error") ? state : "idle";
|
|
60
|
+
store.upsertSession({
|
|
61
|
+
...existing,
|
|
62
|
+
state: resolvedState,
|
|
63
|
+
hasAttention: resolvedState === "waiting-input" ? true : false,
|
|
64
|
+
summary: summary ?? existing.summary ?? "Codex session ended",
|
|
65
|
+
lastActivity: lastActivity ?? Date.now(),
|
|
66
|
+
detectionSource: "codex-hook",
|
|
67
|
+
codex: {
|
|
68
|
+
sessionId,
|
|
69
|
+
transcriptPath: transcriptPath ?? existing.codex?.transcriptPath ?? "",
|
|
70
|
+
...(eventType !== undefined ? { hookEventType: eventType } : {}),
|
|
71
|
+
...(eventTime !== undefined ? { hookEventTime: eventTime } : {}),
|
|
72
|
+
...(hookSeq !== undefined ? { hookSeq } : {}),
|
|
73
|
+
...(endReason !== undefined ? { endReason } : {}),
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
if (!hasActiveChildren()) {
|
|
79
|
+
store.markLocalCommand(sessionId);
|
|
80
|
+
}
|
|
81
|
+
logger.info("webhook", "codex session ended", { event: "session.ended", tool: "codex", sessionId, reason: endReason });
|
|
82
|
+
return c.json({ ok: true as const }, 200);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const existing = store.getSession(storeId);
|
|
86
|
+
|
|
87
|
+
if (existing) {
|
|
88
|
+
const existingSeq = existing.codex?.hookSeq;
|
|
89
|
+
if (typeof hookSeq === "number" && typeof existingSeq === "number" && hookSeq < existingSeq) {
|
|
90
|
+
logger.debug("webhook", "codex hook rejected — stale sequence", { sessionId, hookSeq, existingSeq });
|
|
91
|
+
return c.json({ ok: true as const, skipped: "stale-sequence" }, 200);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const isStateBearing = !isMetadataOnlyEvent(eventType ?? "");
|
|
96
|
+
|
|
97
|
+
logger.debug("webhook", "codex hook received", { sessionId, state, eventType });
|
|
98
|
+
|
|
99
|
+
if (existing) {
|
|
100
|
+
store.upsertSession({
|
|
101
|
+
...existing,
|
|
102
|
+
...(isStateBearing && state !== undefined ? { state } : {}),
|
|
103
|
+
...(isStateBearing && hasAttention !== undefined ? { hasAttention } : {}),
|
|
104
|
+
...(attentionKind !== undefined ? { attentionKind } : {}),
|
|
105
|
+
...(summary !== undefined ? { summary } : {}),
|
|
106
|
+
...(activeTool !== undefined ? { activeTool } : {}),
|
|
107
|
+
...(!isStateBearing && currentPath !== undefined ? { currentPath } : {}),
|
|
108
|
+
...(currentPath && !existing.project && gitCollector ? { project: gitCollector.resolve(currentPath) } : {}),
|
|
109
|
+
lastActivity: lastActivity ?? Date.now(),
|
|
110
|
+
detectionSource: "codex-hook",
|
|
111
|
+
...(parentSessionId ? { parentSessionId } : {}),
|
|
112
|
+
codex: {
|
|
113
|
+
sessionId,
|
|
114
|
+
transcriptPath: transcriptPath ?? existing.codex?.transcriptPath ?? "",
|
|
115
|
+
...(eventType !== undefined ? { hookEventType: eventType } : {}),
|
|
116
|
+
...(eventTime !== undefined ? { hookEventTime: eventTime } : {}),
|
|
117
|
+
...(hookSeq !== undefined ? { hookSeq } : {}),
|
|
118
|
+
...(permissionMode !== undefined ? { permissionMode } : {}),
|
|
119
|
+
...(startSource !== undefined ? { startSource } : {}),
|
|
120
|
+
...(endReason !== undefined ? { endReason } : {}),
|
|
121
|
+
...(model !== undefined ? { model } : {}),
|
|
122
|
+
...(toolName !== undefined ? { toolName } : {}),
|
|
123
|
+
...(toolInputSummary !== undefined ? { toolInputSummary } : {}),
|
|
124
|
+
...(toolResultStatus !== undefined ? { toolResultStatus } : {}),
|
|
125
|
+
...(attentionKind !== undefined ? { attentionKind } : {}),
|
|
126
|
+
...(turnId !== undefined ? { turnId } : {}),
|
|
127
|
+
...(agentId !== undefined ? { agentId } : {}),
|
|
128
|
+
...(agentType !== undefined ? { agentType } : {}),
|
|
129
|
+
...(forkedFromId !== undefined ? { forkedFromId } : {}),
|
|
130
|
+
},
|
|
131
|
+
});
|
|
132
|
+
} else {
|
|
133
|
+
store.upsertSession({
|
|
134
|
+
id: storeId,
|
|
135
|
+
source: "standalone",
|
|
136
|
+
tool: "codex",
|
|
137
|
+
state: (isStateBearing ? state : undefined) ?? "idle",
|
|
138
|
+
summary: summary ?? "Codex session",
|
|
139
|
+
lastActivity: lastActivity ?? Date.now(),
|
|
140
|
+
detectionSource: "codex-hook",
|
|
141
|
+
hasAttention: isStateBearing ? (hasAttention ?? false) : false,
|
|
142
|
+
activeTool,
|
|
143
|
+
currentPath,
|
|
144
|
+
...(currentPath && gitCollector ? { project: gitCollector.resolve(currentPath) } : {}),
|
|
145
|
+
...(parentSessionId ? { parentSessionId } : {}),
|
|
146
|
+
codex: {
|
|
147
|
+
sessionId,
|
|
148
|
+
transcriptPath: transcriptPath ?? "",
|
|
149
|
+
...(eventType !== undefined ? { hookEventType: eventType } : {}),
|
|
150
|
+
...(eventTime !== undefined ? { hookEventTime: eventTime } : {}),
|
|
151
|
+
...(hookSeq !== undefined ? { hookSeq } : {}),
|
|
152
|
+
...(permissionMode !== undefined ? { permissionMode } : {}),
|
|
153
|
+
...(startSource !== undefined ? { startSource } : {}),
|
|
154
|
+
...(endReason !== undefined ? { endReason } : {}),
|
|
155
|
+
...(model !== undefined ? { model } : {}),
|
|
156
|
+
...(toolName !== undefined ? { toolName } : {}),
|
|
157
|
+
...(toolInputSummary !== undefined ? { toolInputSummary } : {}),
|
|
158
|
+
...(toolResultStatus !== undefined ? { toolResultStatus } : {}),
|
|
159
|
+
...(attentionKind !== undefined ? { attentionKind } : {}),
|
|
160
|
+
...(turnId !== undefined ? { turnId } : {}),
|
|
161
|
+
...(agentId !== undefined ? { agentId } : {}),
|
|
162
|
+
...(agentType !== undefined ? { agentType } : {}),
|
|
163
|
+
...(forkedFromId !== undefined ? { forkedFromId } : {}),
|
|
164
|
+
},
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
logger.debug("webhook", "codex stub session created from hook", { event: "session.upsert_from_webhook", tool: "codex", sessionId, state });
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
store.syncChildSessionIds();
|
|
171
|
+
return c.json({ ok: true as const }, 200);
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
return router;
|
|
175
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { OpenAPIHono } from "@hono/zod-openapi";
|
|
2
|
+
import type { ScrylogConfig } from "../../../shared/config";
|
|
3
|
+
import type { DaemonStore } from "../../../daemon/store";
|
|
4
|
+
import type { Logger } from "../../../shared/logger";
|
|
5
|
+
import type { SessionModel } from "../../../shared/types";
|
|
6
|
+
import type { OpencodeWebhookPayload } from "../../models/opencode";
|
|
7
|
+
import { mapHookState, extractSessionParentId } from "../../services/opencode-session";
|
|
8
|
+
import { WebhookRouteKey } from "../../docs/webhooks.keys";
|
|
9
|
+
import { defineRoute } from "../../lib/route";
|
|
10
|
+
|
|
11
|
+
export function createOpencodeWebhookRouter(store: DaemonStore, config: ScrylogConfig, logger: Logger): OpenAPIHono {
|
|
12
|
+
const router = new OpenAPIHono();
|
|
13
|
+
|
|
14
|
+
router.openapi(defineRoute(WebhookRouteKey.WEBHOOK_OPENCODE), async (c) => {
|
|
15
|
+
const payload = c.req.valid("json") as OpencodeWebhookPayload;
|
|
16
|
+
const { event } = payload;
|
|
17
|
+
|
|
18
|
+
logger.debug("webhook", "received", {
|
|
19
|
+
event: "integration.event_received",
|
|
20
|
+
webhookEvent: event,
|
|
21
|
+
sessionID: payload.sessionID ?? payload.info?.id,
|
|
22
|
+
directory: payload.info?.directory ?? payload.directory,
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
if (config.opencode.mode === "sse") {
|
|
26
|
+
logger.debug("webhook", "skipped: opencode-mode-sse", { event: "integration.event_skipped", webhookEvent: event, reason: "opencode-mode-sse" });
|
|
27
|
+
return c.json({ ok: true as const, skipped: "opencode-mode-sse" }, 200);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const rawId = payload.sessionID ?? payload.info?.id;
|
|
31
|
+
if (!rawId && event !== "session.created") {
|
|
32
|
+
logger.debug("webhook", "skipped: no sessionID", { event: "integration.event_skipped", webhookEvent: event, reason: "no-session-id" });
|
|
33
|
+
return c.json({ ok: true as const, skipped: "no sessionID" }, 200);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (event === "session.deleted" && rawId) {
|
|
37
|
+
logger.debug("webhook", "session.deleted", { event: "integration.event_received", tool: "opencode", sessionId: rawId });
|
|
38
|
+
store.removeSession(`opencode:${rawId}`);
|
|
39
|
+
return c.json({ ok: true as const }, 200);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
if (rawId) {
|
|
43
|
+
const storeId = `opencode:${rawId}`;
|
|
44
|
+
const existing = store.getSession(storeId);
|
|
45
|
+
const { state, hasAttention, pendingAttentionCount } = mapHookState(event, payload, existing);
|
|
46
|
+
|
|
47
|
+
const title = payload.info?.title ?? payload.title ?? existing?.summary ?? "OpenCode session";
|
|
48
|
+
const directory = payload.info?.directory ?? payload.directory ?? existing?.currentPath;
|
|
49
|
+
const parentSessionId = extractSessionParentId(event, payload, existing);
|
|
50
|
+
const timeUpdated = payload.info?.time?.updated ?? Date.now();
|
|
51
|
+
|
|
52
|
+
if (payload.info?.parentID && payload.info.parentID !== parentSessionId?.replace(/^opencode:/, "")) {
|
|
53
|
+
logger.debug("webhook", "ignoring non-session parentID", {
|
|
54
|
+
event: "integration.event_skipped",
|
|
55
|
+
webhookEvent: event,
|
|
56
|
+
sessionId: rawId,
|
|
57
|
+
parentID: payload.info.parentID,
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (existing) {
|
|
62
|
+
const stateChanged = state !== existing.state;
|
|
63
|
+
const merged: SessionModel = {
|
|
64
|
+
...existing,
|
|
65
|
+
state,
|
|
66
|
+
hasAttention,
|
|
67
|
+
summary: title,
|
|
68
|
+
currentPath: directory ?? existing.currentPath,
|
|
69
|
+
parentSessionId,
|
|
70
|
+
lastActivity: stateChanged ? Date.now() : Math.max(existing.lastActivity, timeUpdated),
|
|
71
|
+
opencode: {
|
|
72
|
+
...existing.opencode,
|
|
73
|
+
sessionId: rawId,
|
|
74
|
+
instanceUrl: existing.opencode?.instanceUrl ?? "",
|
|
75
|
+
...(pendingAttentionCount !== undefined ? { pendingAttentionCount } : {}),
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
logger.debug("webhook", "upsert existing session", { event: "session.upsert_from_webhook", webhookEvent: event, sessionId: rawId, state: merged.state });
|
|
79
|
+
store.upsertSession(merged);
|
|
80
|
+
} else {
|
|
81
|
+
const newSession: SessionModel = {
|
|
82
|
+
id: storeId,
|
|
83
|
+
source: "standalone",
|
|
84
|
+
tool: "opencode",
|
|
85
|
+
state,
|
|
86
|
+
summary: title,
|
|
87
|
+
lastActivity: timeUpdated,
|
|
88
|
+
detectionSource: "opencode-hook",
|
|
89
|
+
hasAttention,
|
|
90
|
+
currentPath: directory,
|
|
91
|
+
parentSessionId,
|
|
92
|
+
opencode: {
|
|
93
|
+
sessionId: rawId,
|
|
94
|
+
instanceUrl: "",
|
|
95
|
+
...(pendingAttentionCount !== undefined ? { pendingAttentionCount } : {}),
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
logger.debug("webhook", "upsert new session", { event: "session.upsert_from_webhook", webhookEvent: event, sessionId: rawId, state, directory });
|
|
99
|
+
store.upsertSession(newSession);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return c.json({ ok: true as const }, 200);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
return router;
|
|
107
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { OpenAPIHono } from "@hono/zod-openapi";
|
|
2
|
+
import { Scalar } from "@scalar/hono-api-reference";
|
|
3
|
+
import { createMarkdownFromOpenApi } from "@scalar/openapi-to-markdown";
|
|
4
|
+
import { cors } from "hono/cors";
|
|
5
|
+
import type { ContentfulStatusCode } from "hono/utils/http-status";
|
|
6
|
+
import type { ScrylogConfig } from "../shared/config";
|
|
7
|
+
import type { DaemonStore } from "../daemon/store";
|
|
8
|
+
import type { GitCollector } from "../daemon/collectors/git";
|
|
9
|
+
import type { Logger } from "../shared/logger";
|
|
10
|
+
import { NOOP_LOGGER } from "../shared/logger";
|
|
11
|
+
import { ApiError } from "./lib/errors";
|
|
12
|
+
import { createSystemRouter } from "./routes/system";
|
|
13
|
+
import { createSessionsRouter } from "./routes/sessions";
|
|
14
|
+
import { createUsageRouter } from "./routes/usage";
|
|
15
|
+
import { createOpencodeWebhookRouter } from "./routes/webhooks/opencode";
|
|
16
|
+
import { createClaudeWebhookRouter } from "./routes/webhooks/claude";
|
|
17
|
+
import { createCodexWebhookRouter } from "./routes/webhooks/codex";
|
|
18
|
+
import { createBearerAuthMiddleware } from "./lib/auth";
|
|
19
|
+
|
|
20
|
+
export function createApiApp(
|
|
21
|
+
store: DaemonStore,
|
|
22
|
+
config: ScrylogConfig,
|
|
23
|
+
logger: Logger = NOOP_LOGGER,
|
|
24
|
+
gitCollector?: GitCollector,
|
|
25
|
+
): OpenAPIHono {
|
|
26
|
+
const app = new OpenAPIHono();
|
|
27
|
+
|
|
28
|
+
app.onError((err, c) => {
|
|
29
|
+
if (err instanceof ApiError) {
|
|
30
|
+
return c.json({ error: err.message, code: err.code }, err.status as ContentfulStatusCode);
|
|
31
|
+
}
|
|
32
|
+
logger.debug("api", "unhandled error", { message: err.message });
|
|
33
|
+
return c.json({ error: "Internal server error", code: "INTERNAL_ERROR" }, 500);
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
app.notFound((c) => c.json({ error: "Not found", code: "NOT_FOUND" }, 404));
|
|
37
|
+
|
|
38
|
+
if (config.cors.enabled) {
|
|
39
|
+
app.use("*", cors({
|
|
40
|
+
origin: config.cors.origins,
|
|
41
|
+
allowMethods: config.cors.methods,
|
|
42
|
+
allowHeaders: config.cors.allowedHeaders,
|
|
43
|
+
exposeHeaders: config.cors.exposedHeaders,
|
|
44
|
+
credentials: config.cors.credentials,
|
|
45
|
+
maxAge: config.cors.maxAge,
|
|
46
|
+
}));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
app.use(createBearerAuthMiddleware(config.api.bearerToken));
|
|
50
|
+
|
|
51
|
+
app.route("/api", createSystemRouter(store, config, logger));
|
|
52
|
+
app.route("/api", createSessionsRouter(store, config));
|
|
53
|
+
app.route("/api", createUsageRouter(store));
|
|
54
|
+
app.route("/api/webhook", createOpencodeWebhookRouter(store, config, logger));
|
|
55
|
+
app.route("/api/webhook", createClaudeWebhookRouter(store, logger, gitCollector));
|
|
56
|
+
app.route("/api/webhook", createCodexWebhookRouter(store, logger, gitCollector));
|
|
57
|
+
|
|
58
|
+
app.openAPIRegistry.registerComponent("securitySchemes", "BearerAuth", {
|
|
59
|
+
type: "http",
|
|
60
|
+
scheme: "bearer",
|
|
61
|
+
description: "Bearer token authentication (only enforced when api.bearerToken is configured)",
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
app.doc("/api/openapi.json", {
|
|
65
|
+
openapi: "3.0.0",
|
|
66
|
+
info: {
|
|
67
|
+
title: "scrylog API",
|
|
68
|
+
version: "1.0.0",
|
|
69
|
+
description: "scrylogd daemon HTTP API. Bearer auth is enforced on protected endpoints when api.bearerToken is configured.",
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
app.get("/api/docs", Scalar({ url: "/api/openapi.json" }));
|
|
74
|
+
|
|
75
|
+
app.get("/api/llms.txt", async (c) => {
|
|
76
|
+
const specUrl = new URL("/api/openapi.json", c.req.url);
|
|
77
|
+
const spec = await fetch(specUrl).then((r) => r.text());
|
|
78
|
+
const markdown = await createMarkdownFromOpenApi(spec);
|
|
79
|
+
return c.text(markdown);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
return app;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** @deprecated use createApiApp directly */
|
|
86
|
+
export function createRouteHandler(
|
|
87
|
+
store: DaemonStore,
|
|
88
|
+
config: ScrylogConfig,
|
|
89
|
+
logger: Logger = NOOP_LOGGER,
|
|
90
|
+
gitCollector?: GitCollector,
|
|
91
|
+
): (request: Request) => Response | Promise<Response> {
|
|
92
|
+
return createApiApp(store, config, logger, gitCollector).fetch;
|
|
93
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { z } from "@hono/zod-openapi";
|
|
2
|
+
|
|
3
|
+
export const ApiErrorSchema = z.object({
|
|
4
|
+
error: z.string().openapi({ example: "Session not found" }),
|
|
5
|
+
});
|
|
6
|
+
|
|
7
|
+
export const WebhookOkSchema = z.object({
|
|
8
|
+
ok: z.literal(true),
|
|
9
|
+
skipped: z.string().optional().openapi({ example: "stale-sequence" }),
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
// Session IDs follow prefix:suffix format (claude:uuid, opencode:ses_xxx, tmux:1:0.0).
|
|
13
|
+
// Rejects path traversal characters and shell metacharacters.
|
|
14
|
+
export const SessionIdParamSchema = z.object({
|
|
15
|
+
id: z
|
|
16
|
+
.string()
|
|
17
|
+
.min(1)
|
|
18
|
+
.max(200)
|
|
19
|
+
.regex(/^[a-zA-Z0-9:_\-.]+$/, "Invalid session ID")
|
|
20
|
+
.openapi({ param: { name: "id", in: "path" }, example: "claude:abc-123" }),
|
|
21
|
+
});
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { z } from "@hono/zod-openapi";
|
|
2
|
+
|
|
3
|
+
const SessionStateSchema = z.enum(["working", "idle", "waiting-input", "error", "shell", "unknown"]);
|
|
4
|
+
const SessionToolSchema = z.enum(["opencode", "claude", "codex", "copilotcli", "shell", "unknown"]);
|
|
5
|
+
|
|
6
|
+
const ProjectInfoSchema = z.object({
|
|
7
|
+
displayName: z.string(),
|
|
8
|
+
compactLabel: z.string(),
|
|
9
|
+
branch: z.string().optional(),
|
|
10
|
+
isGitRepository: z.boolean().optional(),
|
|
11
|
+
sourcePath: z.string().optional(),
|
|
12
|
+
gitRootPath: z.string().optional(),
|
|
13
|
+
repositoryIdentityPath: z.string().optional(),
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
const TmuxInfoSchema = z.object({
|
|
17
|
+
session: z.string(),
|
|
18
|
+
window: z.string(),
|
|
19
|
+
pane: z.string(),
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
export const SessionListItemSchema = z.object({
|
|
23
|
+
id: z.string(),
|
|
24
|
+
source: z.enum(["tmux", "standalone"]),
|
|
25
|
+
tool: SessionToolSchema,
|
|
26
|
+
state: SessionStateSchema,
|
|
27
|
+
summary: z.string(),
|
|
28
|
+
lastActivity: z.number(),
|
|
29
|
+
stableForMs: z.number().optional(),
|
|
30
|
+
hasAttention: z.boolean().optional(),
|
|
31
|
+
detectionSource: z.string().optional(),
|
|
32
|
+
parentSessionId: z.string().optional(),
|
|
33
|
+
project: ProjectInfoSchema.optional(),
|
|
34
|
+
tmux: TmuxInfoSchema.optional(),
|
|
35
|
+
currentPath: z.string().optional(),
|
|
36
|
+
activeTool: z.string().optional(),
|
|
37
|
+
childCount: z.number().optional(),
|
|
38
|
+
activeChildCount: z.number().optional(),
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
export const SessionTreeItemSchema = SessionListItemSchema.extend({
|
|
42
|
+
children: z.array(SessionListItemSchema),
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
export const SessionViewCountsSchema = z.object({
|
|
46
|
+
total: z.number(),
|
|
47
|
+
visible: z.number(),
|
|
48
|
+
rootsVisible: z.number(),
|
|
49
|
+
childrenVisible: z.number(),
|
|
50
|
+
byState: z.record(z.string(), z.number()),
|
|
51
|
+
byTool: z.record(z.string(), z.number()),
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
export const SessionsResponseSchema = z.object({
|
|
55
|
+
sessions: z.array(SessionTreeItemSchema),
|
|
56
|
+
counts: SessionViewCountsSchema,
|
|
57
|
+
generatedAt: z.number(),
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
export const SessionDetailResponseSchema = z.object({
|
|
61
|
+
session: z.record(z.string(), z.unknown()).openapi({ description: "Full SessionModel" }),
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
export const SessionChildrenResponseSchema = z.object({
|
|
65
|
+
sessionId: z.string(),
|
|
66
|
+
children: z.array(SessionListItemSchema),
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
export const SessionMessagesResponseSchema = z.object({
|
|
70
|
+
sessionId: z.string(),
|
|
71
|
+
messages: z.array(z.unknown()),
|
|
72
|
+
});
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { z } from "@hono/zod-openapi";
|
|
2
|
+
|
|
3
|
+
export const UsageWindowSchema = z.object({
|
|
4
|
+
id: z.string(),
|
|
5
|
+
title: z.string(),
|
|
6
|
+
usedPercent: z.number().min(0).max(100),
|
|
7
|
+
used: z.number().optional(),
|
|
8
|
+
limit: z.number().optional(),
|
|
9
|
+
windowMinutes: z.number().optional(),
|
|
10
|
+
resetsAt: z.string().datetime().nullable().optional(),
|
|
11
|
+
resetInSec: z.number().optional(),
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
export const ProviderCostSnapshotSchema = z.object({
|
|
15
|
+
used: z.number(),
|
|
16
|
+
limit: z.number(),
|
|
17
|
+
currency: z.string(),
|
|
18
|
+
period: z.string(),
|
|
19
|
+
resetsAt: z.string().datetime().nullable().optional(),
|
|
20
|
+
updatedAt: z.string().datetime(),
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
export const UsageProviderEntrySchema = z.object({
|
|
24
|
+
provider: z.string(),
|
|
25
|
+
accountId: z.string().nullable(),
|
|
26
|
+
available: z.boolean(),
|
|
27
|
+
status: z.enum(["ok", "error", "unavailable", "pending"]),
|
|
28
|
+
metadata: z
|
|
29
|
+
.object({
|
|
30
|
+
dataSource: z.string().optional(),
|
|
31
|
+
accountEmail: z.string().nullable().optional(),
|
|
32
|
+
accountOrganization: z.string().nullable().optional(),
|
|
33
|
+
subscriptionType: z.string().nullable().optional(),
|
|
34
|
+
rateLimitTier: z.string().nullable().optional(),
|
|
35
|
+
workspaceId: z.string().nullable().optional(),
|
|
36
|
+
workspaceName: z.string().nullable().optional(),
|
|
37
|
+
})
|
|
38
|
+
.optional(),
|
|
39
|
+
errors: z.array(z.string()).optional(),
|
|
40
|
+
windows: z.array(UsageWindowSchema).optional(),
|
|
41
|
+
cost: ProviderCostSnapshotSchema.nullable().optional(),
|
|
42
|
+
updatedAt: z.string().datetime().optional(),
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
export const UsageStateSchema = z.object({
|
|
46
|
+
providers: z.array(UsageProviderEntrySchema),
|
|
47
|
+
lastRefreshedAt: z.number(),
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
export const UsageResponseSchema = UsageStateSchema;
|