@mainwave/cli 0.8.0 → 0.10.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/README.md +169 -42
- package/dist/adapters/claude-code.js +23 -4
- package/dist/adapters/codex-cli.js +1 -1
- package/dist/adapters/cursor.js +4 -2
- package/dist/adapters/index.js +3 -0
- package/dist/adapters/kiro.js +361 -0
- package/dist/core/apply.js +161 -46
- package/dist/core/behaviour-hooks.js +7 -7
- package/dist/core/codecs/kiro-hooks-json.js +76 -0
- package/dist/core/doctor.js +27 -9
- package/dist/core/effective-settings.js +10 -0
- package/dist/core/entry-script.js +90 -0
- package/dist/core/git-bash.js +40 -0
- package/dist/core/install-hooks.js +126 -43
- package/dist/core/interview.js +114 -16
- package/dist/core/markers.js +678 -140
- package/dist/core/remove.js +67 -0
- package/dist/core/settings.js +32 -6
- package/dist/core/skills.js +47 -1
- package/dist/core/status.js +2 -1
- package/dist/core/wizard.js +64 -3
- package/dist/main.js +28 -9
- package/hooks/cursor-otlp.mjs +4 -27
- package/hooks/github-pr-marker.mjs +35 -22
- package/hooks/glab-mr-marker.mjs +795 -0
- package/hooks/jira-ticket-marker.mjs +27 -15
- package/hooks/kiro-otlp.mjs +570 -0
- package/hooks/linear-ticket-marker.mjs +27 -15
- package/hooks/mainwave-hook-node.mjs +42 -0
- package/hooks/mainwave-hook.mjs +301 -0
- package/hooks/marker-core.mjs +368 -41
- package/hooks/matchers.json +82 -6
- package/hooks/plan-snapshot.mjs +529 -0
- package/hooks/stop-failure.mjs +43 -0
- package/hooks/vocabulary.d.mts +49 -0
- package/hooks/vocabulary.mjs +188 -0
- package/package.json +5 -5
- package/skills/mainwave-instrument/SKILL.md +21 -7
- package/skills/mainwave-instrument/reference/api.md +29 -10
- package/skills/mainwave-instrument/reference/frameworks.md +3 -3
- package/skills/mainwave-instrument/reference/troubleshooting.md +12 -5
- package/skills/mainwave-setup/SKILL.md +47 -12
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
//
|
|
2
|
+
// The Jira ticket marker: a PostToolUse feature of the Mainwave hook
|
|
3
|
+
// dispatcher (mainwave-hook.mjs) for Jira issue creation/edits. It also still
|
|
4
|
+
// runs on its own (§ the main at the bottom), because hook settings pasted
|
|
5
|
+
// before the dispatcher name this file.
|
|
3
6
|
//
|
|
4
7
|
// The Jira analogue of the Linear ticket-marker. Claude Code's telemetry
|
|
5
8
|
// records only that an Atlassian tool *call* happened — the span carries the
|
|
@@ -58,7 +61,7 @@ import {
|
|
|
58
61
|
WORK_OP_UPDATED,
|
|
59
62
|
} from './vocabulary.mjs'
|
|
60
63
|
|
|
61
|
-
const
|
|
64
|
+
const LOG_NAME = 'jira-ticket-marker.log'
|
|
62
65
|
|
|
63
66
|
// The same non-coding source/service the Linear ticket hook stamps, so a Jira
|
|
64
67
|
// marker is classified identically to a Linear one: an ordinary ("other") span
|
|
@@ -194,15 +197,13 @@ export const buildTracePayload = ({
|
|
|
194
197
|
nowNs,
|
|
195
198
|
})
|
|
196
199
|
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
}
|
|
205
|
-
|
|
200
|
+
/**
|
|
201
|
+
* The feature: one marker span for the created or edited issue, or a logged
|
|
202
|
+
* skip when the output names none. `ctx.argv` carries the hook command's flags
|
|
203
|
+
* (and `--tool <host>` under the dispatcher); `ctx.emit` posts.
|
|
204
|
+
*/
|
|
205
|
+
export const handle = async (payload, { argv = process.argv, emit = emitMarker } = {}) => {
|
|
206
|
+
const log = markerLog(argv, LOG_NAME)
|
|
206
207
|
const output = toolOutput(payload)
|
|
207
208
|
const issueKey = extractIssueKey(output)
|
|
208
209
|
if (!issueKey) {
|
|
@@ -214,8 +215,8 @@ const main = async () => {
|
|
|
214
215
|
const op = detectOp(payload.tool_name)
|
|
215
216
|
|
|
216
217
|
const projectDir = markerProjectDir(payload)
|
|
217
|
-
const tool = markerTool(
|
|
218
|
-
const managedDir = markerManagedDir(
|
|
218
|
+
const tool = markerTool(argv)
|
|
219
|
+
const managedDir = markerManagedDir(argv)
|
|
219
220
|
const env = markerSessionEnv(tool, payload)
|
|
220
221
|
const { endpoint, bearer, resourceAttrs } = loadOtelConfig(projectDir, env, tool, managedDir)
|
|
221
222
|
log(
|
|
@@ -246,7 +247,18 @@ const main = async () => {
|
|
|
246
247
|
callContext: markerCallContext(tool, payload),
|
|
247
248
|
nowNs: BigInt(Date.now()) * 1_000_000n,
|
|
248
249
|
})
|
|
249
|
-
await
|
|
250
|
+
await emit({ endpoint, bearer, body, label: issueKey, log })
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
const main = async () => {
|
|
254
|
+
let payload
|
|
255
|
+
try {
|
|
256
|
+
payload = JSON.parse(await readStdin())
|
|
257
|
+
} catch {
|
|
258
|
+
markerLog(process.argv, LOG_NAME)('skip: no parseable hook payload')
|
|
259
|
+
return
|
|
260
|
+
}
|
|
261
|
+
await handle(payload)
|
|
250
262
|
}
|
|
251
263
|
|
|
252
264
|
// Run the IO path only when executed directly, so tests can import the pure fns.
|
|
@@ -254,6 +266,6 @@ const main = async () => {
|
|
|
254
266
|
// file URL (e.g. the space in the managed install dir "/Library/Application
|
|
255
267
|
// Support/…") still matches import.meta.url — a raw `file://${argv[1]}` template
|
|
256
268
|
// keeps the literal space, never matches, and silently skips main().
|
|
257
|
-
if (import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
269
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
258
270
|
await main()
|
|
259
271
|
}
|
|
@@ -0,0 +1,570 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Kiro hook → OTLP session telemetry.
|
|
3
|
+
//
|
|
4
|
+
// Kiro (IDE 1.0+, and Kiro CLI 2.13+ in V3 mode) runs the command hooks in
|
|
5
|
+
// `~/.kiro/hooks/*.json` for every session. mainwave-cli registers THIS script
|
|
6
|
+
// in one file there, `mainwave.json`, once per trigger: SessionStart,
|
|
7
|
+
// UserPromptSubmit, PostToolUse, PostFileCreate / PostFileSave /
|
|
8
|
+
// PostFileDelete, Stop and SessionEnd. Kiro invokes it with a JSON payload on
|
|
9
|
+
// stdin (`hook_event_name`, `cwd`, `session_id`, plus `tool_name` /
|
|
10
|
+
// `tool_input` on tool events and `prompt` on prompt submit); the script maps
|
|
11
|
+
// the event to one small OTLP span and posts it to the collector.
|
|
12
|
+
//
|
|
13
|
+
// Kiro runs command hooks synchronously and treats their output as input:
|
|
14
|
+
// on exit 0 the command's stdout is added to the agent's context, and any
|
|
15
|
+
// other exit code BLOCKS a UserPromptSubmit or PreToolUse. So this script
|
|
16
|
+
// writes nothing to stdout, always exits 0, bounds every wait, and fails open:
|
|
17
|
+
// a telemetry hiccup must never block or steer the developer's session. It
|
|
18
|
+
// never waits on the network either: it reads the event, builds the span,
|
|
19
|
+
// hands it to a detached copy of itself (`--send <spool file>`) that does the
|
|
20
|
+
// POST, and exits.
|
|
21
|
+
//
|
|
22
|
+
// Like the Cursor hook, Kiro exposes no config file we can read the collector
|
|
23
|
+
// endpoint and key back out of, so setup writes a managed env file
|
|
24
|
+
// (`~/.mainwave/kiro.env`, mode 0600) and this script reads its OTLP target,
|
|
25
|
+
// the developer's email and the prompt-capture choice from there — only from
|
|
26
|
+
// there, never from the workspace or the environment, so a repository can't
|
|
27
|
+
// choose where the developer's key is sent. The hook never sends a use-case
|
|
28
|
+
// id: the collector derives one at ingest from the email.
|
|
29
|
+
|
|
30
|
+
import { spawn } from 'node:child_process'
|
|
31
|
+
import { randomBytes } from 'node:crypto'
|
|
32
|
+
import {
|
|
33
|
+
chmodSync,
|
|
34
|
+
mkdirSync,
|
|
35
|
+
readdirSync,
|
|
36
|
+
readFileSync,
|
|
37
|
+
realpathSync,
|
|
38
|
+
statSync,
|
|
39
|
+
unlinkSync,
|
|
40
|
+
writeFileSync,
|
|
41
|
+
} from 'node:fs'
|
|
42
|
+
import { homedir } from 'node:os'
|
|
43
|
+
import { dirname, join, resolve } from 'node:path'
|
|
44
|
+
import { fileURLToPath, pathToFileURL } from 'node:url'
|
|
45
|
+
|
|
46
|
+
import {
|
|
47
|
+
bearerFromHeaders,
|
|
48
|
+
buildMarkerPayload,
|
|
49
|
+
emitMarker,
|
|
50
|
+
ensureLogDir,
|
|
51
|
+
hookFlag,
|
|
52
|
+
isOkStatus,
|
|
53
|
+
markerLog,
|
|
54
|
+
markerLogPath,
|
|
55
|
+
parseEnvFile,
|
|
56
|
+
parseKv,
|
|
57
|
+
} from './marker-core.mjs'
|
|
58
|
+
|
|
59
|
+
const LOG_NAME = 'kiro.log'
|
|
60
|
+
const log = markerLog(process.argv, LOG_NAME)
|
|
61
|
+
|
|
62
|
+
export const SOURCE_IDE = 'coding_agent.kiro_ide'
|
|
63
|
+
export const SOURCE_CLI = 'coding_agent.kiro_cli'
|
|
64
|
+
const SOURCES = { ide: SOURCE_IDE, cli: SOURCE_CLI }
|
|
65
|
+
// The resource `service.name` per surface; the collector routes on it when
|
|
66
|
+
// `mainwave.source` is missing.
|
|
67
|
+
const SERVICES = { ide: 'kiro-ide', cli: 'kiro-cli' }
|
|
68
|
+
const SCOPE_NAME = 'mainwave.kiro-hook'
|
|
69
|
+
|
|
70
|
+
// Bounds. The hook Kiro waits on reads stdin for at most STDIN_TIMEOUT_MS and
|
|
71
|
+
// exits by HARD_EXIT_MS whatever happens; the detached sender has its own.
|
|
72
|
+
const STDIN_MAX_BYTES = 1024 * 1024
|
|
73
|
+
// Kept from an oversized payload, to recover the event's ids (§ `partialPayload`).
|
|
74
|
+
const STDIN_HEAD_BYTES = 64 * 1024
|
|
75
|
+
const STDIN_TIMEOUT_MS = 1500
|
|
76
|
+
const HARD_EXIT_MS = 2500
|
|
77
|
+
const POST_TIMEOUT_MS = 3000
|
|
78
|
+
const SENDER_EXIT_MS = 5000
|
|
79
|
+
// Spool hygiene: a span its sender never picked up (a crash, a kill) is
|
|
80
|
+
// deleted after SPOOL_MAX_AGE_MS, and past SPOOL_MAX_FILES pending spans new
|
|
81
|
+
// events are dropped rather than piling up behind a collector that is down.
|
|
82
|
+
const SPOOL_MAX_AGE_MS = 10 * 60 * 1000
|
|
83
|
+
export const SPOOL_MAX_FILES = 500
|
|
84
|
+
|
|
85
|
+
// ---------------------------------------------------------------------------
|
|
86
|
+
// Config — the managed env file setup writes.
|
|
87
|
+
// ---------------------------------------------------------------------------
|
|
88
|
+
|
|
89
|
+
export const kiroEnvPath = () => join(homedir(), '.mainwave', 'kiro.env')
|
|
90
|
+
|
|
91
|
+
/** Where a hook leaves a built span for its detached sender: owner-only. */
|
|
92
|
+
export const spoolDir = () => join(homedir(), '.mainwave', 'spool')
|
|
93
|
+
|
|
94
|
+
const readFileSafe = (path) => {
|
|
95
|
+
try {
|
|
96
|
+
return readFileSync(path, 'utf8')
|
|
97
|
+
} catch {
|
|
98
|
+
return ''
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* OTLP config from `~/.mainwave/kiro.env`: endpoint, bearer, the developer's
|
|
104
|
+
* email, which Kiro surfaces are set up (`MAINWAVE_KIRO_IDE` /
|
|
105
|
+
* `MAINWAVE_KIRO_CLI` = 1; a file from before those marks names one surface
|
|
106
|
+
* in its `X-Mainwave-Source`), which were removed while the other stayed (the
|
|
107
|
+
* same keys = 0, written by `--remove`) and the prompt-capture choice
|
|
108
|
+
* (`OTEL_LOG_USER_PROMPTS=1`, the same switch Claude Code reads). A
|
|
109
|
+
* `X-Mainwave-UCID` in the file is ignored: this hook never sends a use-case
|
|
110
|
+
* id. Missing values are undefined and the emit is skipped.
|
|
111
|
+
*/
|
|
112
|
+
const markedSurfaces = (env, value) => [
|
|
113
|
+
...(env.MAINWAVE_KIRO_IDE === value ? ['ide'] : []),
|
|
114
|
+
...(env.MAINWAVE_KIRO_CLI === value ? ['cli'] : []),
|
|
115
|
+
]
|
|
116
|
+
|
|
117
|
+
const installedSurfaces = (env, source) => {
|
|
118
|
+
const marked = markedSurfaces(env, '1')
|
|
119
|
+
if (marked.length > 0) return marked
|
|
120
|
+
return source === SOURCE_IDE ? ['ide'] : source === SOURCE_CLI ? ['cli'] : []
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export const loadKiroConfig = (readFile = readFileSafe) => {
|
|
124
|
+
const env = parseEnvFile(readFile(kiroEnvPath()))
|
|
125
|
+
const headers = parseKv(env.OTEL_EXPORTER_OTLP_HEADERS)
|
|
126
|
+
const source = headers['X-Mainwave-Source']
|
|
127
|
+
return {
|
|
128
|
+
endpoint: env.OTEL_EXPORTER_OTLP_ENDPOINT || undefined,
|
|
129
|
+
bearer: bearerFromHeaders(env.OTEL_EXPORTER_OTLP_HEADERS),
|
|
130
|
+
userEmail: headers['X-Mainwave-User-Email'] || undefined,
|
|
131
|
+
surfaces: installedSurfaces(env, source),
|
|
132
|
+
removed: markedSurfaces(env, '0'),
|
|
133
|
+
capturePrompts: env.OTEL_LOG_USER_PROMPTS === '1',
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// ---------------------------------------------------------------------------
|
|
138
|
+
// Event mapping — Kiro payload → span name + attributes.
|
|
139
|
+
// ---------------------------------------------------------------------------
|
|
140
|
+
|
|
141
|
+
/** The registered trigger → span name. Setup registers exactly these. */
|
|
142
|
+
export const SPAN_NAME = {
|
|
143
|
+
SessionStart: 'kiro.session.start',
|
|
144
|
+
UserPromptSubmit: 'kiro.prompt.submit',
|
|
145
|
+
PostToolUse: 'kiro.tool.execution',
|
|
146
|
+
PostFileCreate: 'kiro.file.edit',
|
|
147
|
+
PostFileSave: 'kiro.file.edit',
|
|
148
|
+
PostFileDelete: 'kiro.file.edit',
|
|
149
|
+
Stop: 'kiro.turn.stop',
|
|
150
|
+
SessionEnd: 'kiro.session.end',
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const FILE_OP = { PostFileCreate: 'create', PostFileSave: 'save', PostFileDelete: 'delete' }
|
|
154
|
+
|
|
155
|
+
// `hook_event_name` spellings Kiro documents besides the PascalCase trigger
|
|
156
|
+
// names: CLI 2.x camelCase names, which its documented sample payloads still
|
|
157
|
+
// carry, and the IDE 0.x file-event names. Keys are lower-cased.
|
|
158
|
+
const EVENT_ALIASES = {
|
|
159
|
+
agentspawn: 'SessionStart',
|
|
160
|
+
sessionstart: 'SessionStart',
|
|
161
|
+
userpromptsubmit: 'UserPromptSubmit',
|
|
162
|
+
posttooluse: 'PostToolUse',
|
|
163
|
+
filecreated: 'PostFileCreate',
|
|
164
|
+
postfilecreate: 'PostFileCreate',
|
|
165
|
+
fileedited: 'PostFileSave',
|
|
166
|
+
postfilesave: 'PostFileSave',
|
|
167
|
+
filedeleted: 'PostFileDelete',
|
|
168
|
+
postfiledelete: 'PostFileDelete',
|
|
169
|
+
agentstop: 'Stop',
|
|
170
|
+
stop: 'Stop',
|
|
171
|
+
sessionend: 'SessionEnd',
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Which trigger fired. The `--trigger` flag setup bakes into each registered
|
|
176
|
+
* command wins: it names exactly the hook entry Kiro ran, whatever spelling
|
|
177
|
+
* the payload uses. Without it (a hand-run script), the payload's
|
|
178
|
+
* `hook_event_name` through the documented aliases. Undefined when neither
|
|
179
|
+
* names a trigger we map.
|
|
180
|
+
*/
|
|
181
|
+
export const resolveTrigger = (argv, payload) => {
|
|
182
|
+
const flagged = hookFlag(argv, '--trigger')
|
|
183
|
+
if (flagged && SPAN_NAME[flagged]) return flagged
|
|
184
|
+
const name = payload?.hook_event_name
|
|
185
|
+
if (typeof name !== 'string') return undefined
|
|
186
|
+
return EVENT_ALIASES[name.toLowerCase()]
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
const nonEmpty = (v) => (typeof v === 'string' && v.trim() !== '' ? v : undefined)
|
|
190
|
+
|
|
191
|
+
const SESSION_ID_RE = /^[A-Za-z0-9_.:-]{1,256}$/
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* The Kiro session id: the payload's `session_id`, else `KIRO_SESSION_ID` from
|
|
195
|
+
* the hook's environment (early IDE 1.0 builds omit it from some payloads),
|
|
196
|
+
* else undefined — and then the event is dropped. Never fabricated: a made-up
|
|
197
|
+
* id would split one session into many.
|
|
198
|
+
*/
|
|
199
|
+
export const resolveSessionId = (payload, env = process.env) => {
|
|
200
|
+
for (const v of [payload?.session_id, env.KIRO_SESSION_ID]) {
|
|
201
|
+
const s = nonEmpty(v)?.trim()
|
|
202
|
+
if (s !== undefined && SESSION_ID_RE.test(s)) return s
|
|
203
|
+
}
|
|
204
|
+
return undefined
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const has = (env, key) => typeof env[key] === 'string' && env[key] !== ''
|
|
208
|
+
|
|
209
|
+
// Set in processes an Electron / VS Code-based editor (Kiro IDE is one)
|
|
210
|
+
// starts, including its terminals and the hooks it runs.
|
|
211
|
+
const EDITOR_VARS = ['VSCODE_PID', 'VSCODE_IPC_HOOK', 'VSCODE_NLS_CONFIG', 'ELECTRON_RUN_AS_NODE']
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Which Kiro surface the hook's environment points at: 'ide', 'cli', or
|
|
215
|
+
* undefined when nothing here says. Only § `resolveSurface` acts on it.
|
|
216
|
+
*
|
|
217
|
+
* PROVISIONAL — inferred from documentation and from how VS Code-based editors
|
|
218
|
+
* launch child processes, not yet observed on a real Kiro install. Revisit
|
|
219
|
+
* once a capture of both surfaces' hook environments exists.
|
|
220
|
+
*
|
|
221
|
+
* - SessionEnd fires only in Kiro CLI V3: the CLI, for certain.
|
|
222
|
+
* - Editor variables point at the IDE, but only weakly: a Kiro CLI run in an
|
|
223
|
+
* editor's terminal (VS Code, Cursor, Kiro) inherits them too. They outrank
|
|
224
|
+
* terminal ones, since an IDE launched from a shell inherits TERM_PROGRAM.
|
|
225
|
+
* - Nothing else is CLI-specific in Kiro's documentation, so anything else is
|
|
226
|
+
* undetected.
|
|
227
|
+
*/
|
|
228
|
+
export const detectSurface = (trigger, env = process.env) => {
|
|
229
|
+
if (trigger === 'SessionEnd') return 'cli'
|
|
230
|
+
if (EDITOR_VARS.some((k) => has(env, k))) return 'ide'
|
|
231
|
+
return undefined
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* The surface to report for an event, or undefined to send nothing. Every
|
|
236
|
+
* event of a session must land on one source, or one session splits across
|
|
237
|
+
* two sources (and two ucids). Both surfaces run the one hooks file, so the
|
|
238
|
+
* hook can't refuse a surface that was never set up — it can't tell it apart
|
|
239
|
+
* — but it drops one that was removed.
|
|
240
|
+
*
|
|
241
|
+
* - Nothing recorded (a hand-written kiro.env): the detected surface, as
|
|
242
|
+
* before the surface marks existed.
|
|
243
|
+
* - One surface set up and the other never was: that surface, whatever the
|
|
244
|
+
* editor variables say, since a CLI in an editor's terminal carries them
|
|
245
|
+
* too. The other surface's sessions report under it. Only SessionEnd
|
|
246
|
+
* overrides it: an IDE-only setup drops it.
|
|
247
|
+
* - Both set up, or one removed while the other stayed: the environment tells
|
|
248
|
+
* them apart, and an event with no editor variables is the terminal's (so a
|
|
249
|
+
* CLI session's events and its SessionEnd share one source). A removed
|
|
250
|
+
* surface's events are dropped, at the cost of a CLI run in an editor's
|
|
251
|
+
* terminal after `--remove kiro-ide`, which reads as the IDE.
|
|
252
|
+
*/
|
|
253
|
+
export const resolveSurface = (trigger, env, { surfaces = [], removed = [] } = {}) => {
|
|
254
|
+
const detected = detectSurface(trigger, env)
|
|
255
|
+
if (surfaces.length === 0) return detected
|
|
256
|
+
const known = new Set([...surfaces, ...removed])
|
|
257
|
+
const surface =
|
|
258
|
+
known.size > 1 ? (detected ?? 'cli') : trigger === 'SessionEnd' ? 'cli' : surfaces[0]
|
|
259
|
+
return surfaces.includes(surface) ? surface : undefined
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** `hook_event_name` as sent when it looks like an event name, else the
|
|
263
|
+
* trigger: the attribute is an id, never free text. */
|
|
264
|
+
const eventName = (raw, trigger) =>
|
|
265
|
+
typeof raw === 'string' && /^[A-Za-z]{1,64}$/.test(raw) ? raw : trigger
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* The span for a Kiro hook payload, or undefined (with the reason) when it
|
|
269
|
+
* must not be sent: an unmapped trigger, no session id, or no surface set up
|
|
270
|
+
* for it (§ `resolveSurface`). `kiro.surface` is stamped only when the
|
|
271
|
+
* environment's surface is the one reported.
|
|
272
|
+
*/
|
|
273
|
+
export const spanForPayload = (payload, config, { argv = [], env = process.env } = {}) => {
|
|
274
|
+
const trigger = resolveTrigger(argv, payload)
|
|
275
|
+
if (!trigger) return { skip: `unmapped event ${String(payload?.hook_event_name)}` }
|
|
276
|
+
const sessionId = resolveSessionId(payload, env)
|
|
277
|
+
if (!sessionId) return { skip: `${trigger}: no session id` }
|
|
278
|
+
const detected = detectSurface(trigger, env)
|
|
279
|
+
const effective = resolveSurface(trigger, env, config)
|
|
280
|
+
const source = SOURCES[effective]
|
|
281
|
+
if (!source) {
|
|
282
|
+
return {
|
|
283
|
+
skip:
|
|
284
|
+
(config.surfaces ?? []).length === 0
|
|
285
|
+
? `${trigger}: surface unknown and none recorded in kiro.env`
|
|
286
|
+
: `${trigger}: from a Kiro surface not set up in kiro.env`,
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const attributes = {
|
|
291
|
+
'kiro.hook_event_name': eventName(payload?.hook_event_name, trigger),
|
|
292
|
+
'kiro.surface': detected === effective ? detected : undefined,
|
|
293
|
+
}
|
|
294
|
+
if (trigger === 'PostToolUse') {
|
|
295
|
+
const tool = nonEmpty(payload?.tool_name)
|
|
296
|
+
attributes['kiro.tool_name'] = tool && tool.length <= 256 ? tool : undefined
|
|
297
|
+
}
|
|
298
|
+
if (FILE_OP[trigger]) attributes['kiro.file.op'] = FILE_OP[trigger]
|
|
299
|
+
if (trigger === 'UserPromptSubmit' && config.capturePrompts) {
|
|
300
|
+
attributes.prompt = nonEmpty(payload?.prompt) ?? nonEmpty(env.USER_PROMPT)
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const resourceAttrs = {}
|
|
304
|
+
if (config.userEmail) resourceAttrs['mainwave.user_email'] = config.userEmail
|
|
305
|
+
|
|
306
|
+
return {
|
|
307
|
+
span: {
|
|
308
|
+
spanName: SPAN_NAME[trigger],
|
|
309
|
+
attributes,
|
|
310
|
+
resourceAttrs,
|
|
311
|
+
sessionId,
|
|
312
|
+
source,
|
|
313
|
+
service: SERVICES[effective],
|
|
314
|
+
},
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/** The sidecar whose mtime is the last delivered span — doctor reads it. */
|
|
319
|
+
export const activityPath = (argv) => `${markerLogPath(argv, LOG_NAME)}.ok`
|
|
320
|
+
|
|
321
|
+
const markDelivered = (argv) => {
|
|
322
|
+
try {
|
|
323
|
+
const p = activityPath(argv)
|
|
324
|
+
ensureLogDir(p)
|
|
325
|
+
writeFileSync(p, `${new Date().toISOString()}\n`, { mode: 0o600 })
|
|
326
|
+
} catch {
|
|
327
|
+
// best-effort, like every log write
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Read stdin up to `max` bytes, keeping the first `head` bytes of a payload
|
|
333
|
+
* that runs over: `{ text, truncated }`, or undefined on a read error or
|
|
334
|
+
* when stdin doesn't close within `timeoutMs`.
|
|
335
|
+
*/
|
|
336
|
+
export const readStdinBounded = (
|
|
337
|
+
{ max = STDIN_MAX_BYTES, head = STDIN_HEAD_BYTES, timeoutMs = STDIN_TIMEOUT_MS } = {},
|
|
338
|
+
stream = process.stdin,
|
|
339
|
+
) =>
|
|
340
|
+
new Promise((done) => {
|
|
341
|
+
const chunks = []
|
|
342
|
+
let size = 0
|
|
343
|
+
let settled = false
|
|
344
|
+
const settle = (v) => {
|
|
345
|
+
if (settled) return
|
|
346
|
+
settled = true
|
|
347
|
+
clearTimeout(timer)
|
|
348
|
+
done(v)
|
|
349
|
+
}
|
|
350
|
+
const timer = setTimeout(() => settle(undefined), timeoutMs)
|
|
351
|
+
timer.unref?.()
|
|
352
|
+
stream.on('data', (c) => {
|
|
353
|
+
if (settled) return
|
|
354
|
+
const buf = typeof c === 'string' ? Buffer.from(c) : c
|
|
355
|
+
size += buf.length
|
|
356
|
+
chunks.push(buf)
|
|
357
|
+
if (size > max) {
|
|
358
|
+
settle({ text: Buffer.concat(chunks).subarray(0, head).toString('utf8'), truncated: true })
|
|
359
|
+
stream.destroy?.()
|
|
360
|
+
}
|
|
361
|
+
})
|
|
362
|
+
stream.on('end', () =>
|
|
363
|
+
settle({ text: Buffer.concat(chunks).toString('utf8'), truncated: false }),
|
|
364
|
+
)
|
|
365
|
+
stream.on('error', () => settle(undefined))
|
|
366
|
+
})
|
|
367
|
+
|
|
368
|
+
const field = (text, key) => {
|
|
369
|
+
const m = new RegExp(`"${key}"\\s*:\\s*"((?:[^"\\\\]|\\\\.){1,256})"`).exec(text)
|
|
370
|
+
if (!m) return undefined
|
|
371
|
+
try {
|
|
372
|
+
return JSON.parse(`"${m[1]}"`)
|
|
373
|
+
} catch {
|
|
374
|
+
return undefined
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* The ids from the head of a payload too big to parse (a tool call with a
|
|
380
|
+
* huge response): `hook_event_name`, `session_id` and `tool_name`, so the
|
|
381
|
+
* event still counts. Kiro puts them before `tool_input` / `tool_response` in
|
|
382
|
+
* its documented payloads; a field found nowhere in the head is left out.
|
|
383
|
+
*/
|
|
384
|
+
export const partialPayload = (head) => {
|
|
385
|
+
const out = {}
|
|
386
|
+
for (const k of ['hook_event_name', 'session_id', 'tool_name']) {
|
|
387
|
+
const v = field(head, k)
|
|
388
|
+
if (v !== undefined) out[k] = v
|
|
389
|
+
}
|
|
390
|
+
return out
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* The OTLP body for this hook run, or undefined (logged) when there is
|
|
395
|
+
* nothing to send. Everything the hook does before handing off.
|
|
396
|
+
*/
|
|
397
|
+
export const buildBody = async (argv = process.argv, env = process.env, stream = process.stdin) => {
|
|
398
|
+
const read = await readStdinBounded({}, stream)
|
|
399
|
+
if (read === undefined) {
|
|
400
|
+
log('skip: stdin unreadable or not closed in time')
|
|
401
|
+
return undefined
|
|
402
|
+
}
|
|
403
|
+
let payload
|
|
404
|
+
if (read.truncated) {
|
|
405
|
+
payload = partialPayload(read.text)
|
|
406
|
+
log(`stdin over ${STDIN_MAX_BYTES} bytes: sending the ids from its head`)
|
|
407
|
+
} else {
|
|
408
|
+
try {
|
|
409
|
+
payload = JSON.parse(read.text)
|
|
410
|
+
} catch {
|
|
411
|
+
log(`skip: unparseable stdin (${read.text.length} bytes)`)
|
|
412
|
+
return undefined
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
const config = loadKiroConfig()
|
|
416
|
+
if (!config.endpoint || !config.bearer) {
|
|
417
|
+
log('skip: no endpoint/auth in ~/.mainwave/kiro.env')
|
|
418
|
+
return undefined
|
|
419
|
+
}
|
|
420
|
+
const result = spanForPayload(payload, config, { argv, env })
|
|
421
|
+
if (!result.span) {
|
|
422
|
+
log(`skip: ${result.skip}`)
|
|
423
|
+
return undefined
|
|
424
|
+
}
|
|
425
|
+
const { span } = result
|
|
426
|
+
return {
|
|
427
|
+
label: span.spanName,
|
|
428
|
+
body: buildMarkerPayload({
|
|
429
|
+
spanName: span.spanName,
|
|
430
|
+
scopeName: SCOPE_NAME,
|
|
431
|
+
attributes: span.attributes,
|
|
432
|
+
sessionId: span.sessionId,
|
|
433
|
+
resourceAttrs: span.resourceAttrs,
|
|
434
|
+
source: span.source,
|
|
435
|
+
service: span.service,
|
|
436
|
+
nowNs: Date.now() * 1_000_000,
|
|
437
|
+
}),
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* Leave the span in the spool and start a detached sender for it, so the
|
|
443
|
+
* hook Kiro waits on returns without touching the network. The sender gets
|
|
444
|
+
* only the spool file's path (and `--log-file`, if given): the key stays in
|
|
445
|
+
* kiro.env, never on a command line.
|
|
446
|
+
*/
|
|
447
|
+
/**
|
|
448
|
+
* Delete spooled spans older than SPOOL_MAX_AGE_MS; return how many remain.
|
|
449
|
+
* Only `kiro-*.json` files are considered, and every error is ignored.
|
|
450
|
+
*/
|
|
451
|
+
export const sweepSpool = (dir = spoolDir(), now = Date.now()) => {
|
|
452
|
+
let names
|
|
453
|
+
try {
|
|
454
|
+
names = readdirSync(dir).filter((n) => n.startsWith('kiro-') && n.endsWith('.json'))
|
|
455
|
+
} catch {
|
|
456
|
+
return 0
|
|
457
|
+
}
|
|
458
|
+
let left = 0
|
|
459
|
+
for (const name of names) {
|
|
460
|
+
const path = join(dir, name)
|
|
461
|
+
try {
|
|
462
|
+
if (now - statSync(path).mtimeMs > SPOOL_MAX_AGE_MS) unlinkSync(path)
|
|
463
|
+
else left++
|
|
464
|
+
} catch {
|
|
465
|
+
// gone already, or unreadable: not ours to count
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
return left
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/** Logged once while the spool stays full, not on every dropped event. */
|
|
472
|
+
const FULL_MARK = '.full'
|
|
473
|
+
|
|
474
|
+
/** Create the spool owner-only, tightening one an earlier run left looser. */
|
|
475
|
+
const ensureSpool = () => {
|
|
476
|
+
const dir = spoolDir()
|
|
477
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
478
|
+
chmodSync(dir, 0o700)
|
|
479
|
+
return dir
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
export const handOff = (
|
|
483
|
+
{ label, body },
|
|
484
|
+
argv = process.argv,
|
|
485
|
+
script = fileURLToPath(import.meta.url),
|
|
486
|
+
) => {
|
|
487
|
+
const dir = ensureSpool()
|
|
488
|
+
const full = join(dir, FULL_MARK)
|
|
489
|
+
if (sweepSpool(dir) >= SPOOL_MAX_FILES) {
|
|
490
|
+
try {
|
|
491
|
+
writeFileSync(full, '', { flag: 'wx', mode: 0o600 })
|
|
492
|
+
log(
|
|
493
|
+
`skip: ${SPOOL_MAX_FILES} spans already waiting in ${dir}; dropping events until it drains`,
|
|
494
|
+
)
|
|
495
|
+
} catch {
|
|
496
|
+
// already logged for this full spell
|
|
497
|
+
}
|
|
498
|
+
return false
|
|
499
|
+
}
|
|
500
|
+
try {
|
|
501
|
+
unlinkSync(full)
|
|
502
|
+
} catch {
|
|
503
|
+
// not full before
|
|
504
|
+
}
|
|
505
|
+
const file = join(dir, `kiro-${Date.now()}-${randomBytes(6).toString('hex')}.json`)
|
|
506
|
+
writeFileSync(file, JSON.stringify({ label, body }), { mode: 0o600, flag: 'wx' })
|
|
507
|
+
const logFile = hookFlag(argv, '--log-file')
|
|
508
|
+
const child = spawn(
|
|
509
|
+
process.execPath,
|
|
510
|
+
[script, '--send', file, ...(logFile ? ['--log-file', logFile] : [])],
|
|
511
|
+
{ detached: true, stdio: 'ignore', windowsHide: true },
|
|
512
|
+
)
|
|
513
|
+
child.on('error', () => {})
|
|
514
|
+
child.unref()
|
|
515
|
+
return true
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/** The detached sender: POST one spooled span, then delete it. Reads only a
|
|
519
|
+
* file inside the spool directory. */
|
|
520
|
+
export const send = async (argv = process.argv) => {
|
|
521
|
+
const file = hookFlag(argv, '--send')
|
|
522
|
+
if (!file) return
|
|
523
|
+
// The file's real directory must be the spool's real directory, so neither
|
|
524
|
+
// a relative path nor a symlink reaches anything else.
|
|
525
|
+
try {
|
|
526
|
+
if (dirname(realpathSync(resolve(file))) !== realpathSync(spoolDir())) return
|
|
527
|
+
} catch {
|
|
528
|
+
return
|
|
529
|
+
}
|
|
530
|
+
let spooled
|
|
531
|
+
try {
|
|
532
|
+
spooled = JSON.parse(readFileSync(file, 'utf8'))
|
|
533
|
+
} catch {
|
|
534
|
+
return
|
|
535
|
+
} finally {
|
|
536
|
+
try {
|
|
537
|
+
unlinkSync(file)
|
|
538
|
+
} catch {
|
|
539
|
+
// already gone
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
const config = loadKiroConfig()
|
|
543
|
+
if (!config.endpoint || !config.bearer) return
|
|
544
|
+
const status = await emitMarker({
|
|
545
|
+
endpoint: config.endpoint,
|
|
546
|
+
bearer: config.bearer,
|
|
547
|
+
body: spooled.body,
|
|
548
|
+
label: spooled.label,
|
|
549
|
+
log,
|
|
550
|
+
timeoutMs: POST_TIMEOUT_MS,
|
|
551
|
+
logOk: false,
|
|
552
|
+
})
|
|
553
|
+
if (isOkStatus(status)) markDelivered(argv)
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
// Run only as a script, not when imported by tests.
|
|
557
|
+
if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
|
|
558
|
+
const sender = hookFlag(process.argv, '--send') !== undefined
|
|
559
|
+
// Whatever happens, exit 0 in bounded time: for the hook, a non-zero exit
|
|
560
|
+
// would block the developer's prompt or tool call.
|
|
561
|
+
setTimeout(() => process.exit(0), sender ? SENDER_EXIT_MS : HARD_EXIT_MS).unref()
|
|
562
|
+
process.on('uncaughtException', () => process.exit(0))
|
|
563
|
+
process.on('unhandledRejection', () => process.exit(0))
|
|
564
|
+
const work = sender
|
|
565
|
+
? send()
|
|
566
|
+
: buildBody().then((built) => {
|
|
567
|
+
if (built) handOff(built)
|
|
568
|
+
})
|
|
569
|
+
work.catch(() => {}).finally(() => process.exit(0))
|
|
570
|
+
}
|