@taptap/cli 2026.8.27

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 (64) hide show
  1. package/.claude-plugin/marketplace.json +20 -0
  2. package/.claude-plugin/plugin.json +16 -0
  3. package/CHANGELOG.md +308 -0
  4. package/LICENSE +21 -0
  5. package/README.md +301 -0
  6. package/README.zh.md +295 -0
  7. package/affordance/README.md +32 -0
  8. package/affordance/app.md +140 -0
  9. package/bin/taptap-cli-darwin-amd64 +0 -0
  10. package/bin/taptap-cli-darwin-arm64 +0 -0
  11. package/bin/taptap-cli-linux-amd64 +0 -0
  12. package/bin/taptap-cli-linux-arm64 +0 -0
  13. package/bin/taptap-cli-linux-riscv64 +0 -0
  14. package/bin/taptap-cli-windows-amd64.exe +0 -0
  15. package/bin/taptap-cli-windows-arm64.exe +0 -0
  16. package/checksums.txt +7 -0
  17. package/hooks/hooks.json +53 -0
  18. package/package.json +50 -0
  19. package/scripts/claude-hooks/dispatch.mjs +563 -0
  20. package/scripts/claude-hooks/dispatch.test.mjs +362 -0
  21. package/scripts/install-wizard.js +338 -0
  22. package/scripts/run.js +121 -0
  23. package/scripts/skills-source.js +17 -0
  24. package/skills/index.json +14 -0
  25. package/skills/taptap-app-edit/SKILL.md +125 -0
  26. package/skills/taptap-app-edit/references/app-edit-analysis.md +80 -0
  27. package/skills/taptap-app-edit/references/app-edit-audit-and-history.md +274 -0
  28. package/skills/taptap-app-edit/references/app-edit-field-map.md +131 -0
  29. package/skills/taptap-app-edit/references/app-edit-fields-and-packages.md +109 -0
  30. package/skills/taptap-app-edit/references/app-edit-version-lifecycle.md +72 -0
  31. package/skills/taptap-app-edit/references/review-risk-checklist.md +128 -0
  32. package/skills/taptap-asset-library/SKILL.md +117 -0
  33. package/skills/taptap-asset-library/references/asset-library-ingest.md +99 -0
  34. package/skills/taptap-asset-library/references/asset-library-search.md +72 -0
  35. package/skills/taptap-cli/SKILL.md +82 -0
  36. package/skills/taptap-cli/references/business-routing.md +55 -0
  37. package/skills/taptap-cli/references/cli-command-patterns.md +166 -0
  38. package/skills/taptap-cli/references/material-requirements.md +107 -0
  39. package/skills/taptap-cli/references/official-review-rules-v4.md +287 -0
  40. package/skills/taptap-cli/references/operation-handbooks.md +35 -0
  41. package/skills/taptap-cli/references/shared-execution.md +126 -0
  42. package/skills/taptap-cli/references/sources/operation-handbooks/manifest.json +57 -0
  43. package/skills/taptap-cli/references/sources/v4/agree.md +408 -0
  44. package/skills/taptap-cli/references/sources/v4/manifest.json +25 -0
  45. package/skills/taptap-cli/references/sources/v4/material.md +217 -0
  46. package/skills/taptap-dashboard-stats/SKILL.md +71 -0
  47. package/skills/taptap-dashboard-stats/references/dashboard-metrics-cheatsheet.md +79 -0
  48. package/skills/taptap-identity/SKILL.md +98 -0
  49. package/skills/taptap-identity/references/identity-behavior-rules.md +115 -0
  50. package/skills/taptap-materials/SKILL.md +102 -0
  51. package/skills/taptap-package-management/SKILL.md +120 -0
  52. package/skills/taptap-package-management/references/package-management-diagnostics.md +65 -0
  53. package/skills/taptap-package-management/references/package-management-page-paths.md +11 -0
  54. package/skills/taptap-publish-game/SKILL.md +77 -0
  55. package/skills/taptap-publish-game/references/publish-game-creation.md +308 -0
  56. package/skills/taptap-qualification/SKILL.md +85 -0
  57. package/skills/taptap-qualification/references/qualification-analysis.md +96 -0
  58. package/skills/taptap-qualification/references/qualification-draft.md +70 -0
  59. package/skills/taptap-qualification/references/qualification-lifecycle.md +55 -0
  60. package/skills/taptap-qualification/references/qualification-materials.md +143 -0
  61. package/skills/taptap-test-plan/SKILL.md +125 -0
  62. package/skills/taptap-test-plan/references/test-plan-creation.md +103 -0
  63. package/skills/taptap-test-plan/references/test-plan-faq.md +71 -0
  64. package/skills/taptap-test-plan/references/test-plan-operations.md +57 -0
@@ -0,0 +1,563 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { execFileSync } from "node:child_process";
4
+ import { readFileSync } from "node:fs";
5
+ import { homedir } from "node:os";
6
+ import { resolve } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ const EVENT_SESSION_START = "SessionStart";
10
+ const EVENT_PRE_TOOL_USE = "PreToolUse";
11
+ const EVENT_POST_TOOL_USE = "PostToolUse";
12
+ const EVENT_POST_TOOL_USE_FAILURE = "PostToolUseFailure";
13
+ const SHELL_TOOLS = new Set(["Bash", "PowerShell"]);
14
+ const WRITE_RISKS = new Set(["write", "high-risk-write"]);
15
+ const MAX_STDIN_BYTES = 1024 * 1024;
16
+ const MAX_CONTEXT_CHARS = 800;
17
+
18
+ function truncate(value, max = MAX_CONTEXT_CHARS) {
19
+ const text = String(value ?? "");
20
+ return text.length <= max ? text : `${text.slice(0, max)}...`;
21
+ }
22
+
23
+ export function redactText(value) {
24
+ let text = String(value ?? "");
25
+ const home = homedir();
26
+ if (home) {
27
+ text = text.split(home).join("~");
28
+ }
29
+ text = text
30
+ .replace(
31
+ /(\bAuthorization\b\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\r\n]+)/gi,
32
+ "$1[REDACTED]",
33
+ )
34
+ .replace(/\bBearer\s+[^\s"',]+/gi, "Bearer [REDACTED]")
35
+ .replace(
36
+ /(\b(?:access[_-]?token|refresh[_-]?token|password|secret|ticket)\b\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi,
37
+ "$1[REDACTED]",
38
+ )
39
+ .replace(
40
+ /(--(?:access[_-]?token|refresh[_-]?token|authorization|password|secret|ticket))(?:=|\s+)([^\s]+)/gi,
41
+ "$1=[REDACTED]",
42
+ )
43
+ .replace(
44
+ /([?&](?:access[_-]?token|token|signature|x-amz-(?:signature|credential|security-token)|x-goog-(?:signature|credential))=)[^&\s]+/gi,
45
+ "$1[REDACTED]",
46
+ );
47
+ return truncate(text.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, ""));
48
+ }
49
+
50
+ function defaultLog(message) {
51
+ process.stderr.write(`[taptap-cli hook] ${redactText(message)}\n`);
52
+ }
53
+
54
+ function finishToken(tokens, current, started) {
55
+ if (started) {
56
+ tokens.push(current);
57
+ }
58
+ return { current: "", started: false };
59
+ }
60
+
61
+ function tokenizeSimpleCommand(command, shellTool) {
62
+ const tokens = [];
63
+ let current = "";
64
+ let started = false;
65
+ let quote = "";
66
+
67
+ for (let i = 0; i < command.length; i += 1) {
68
+ const ch = command[i];
69
+
70
+ if (ch === "`" || ch === "\r" || ch === "\n") {
71
+ return null;
72
+ }
73
+ if (shellTool === "PowerShell" && ch === "$") {
74
+ return null;
75
+ }
76
+
77
+ if (quote) {
78
+ if (ch === quote) {
79
+ quote = "";
80
+ started = true;
81
+ continue;
82
+ }
83
+ if (quote === "\"" && ch === "$") {
84
+ return null;
85
+ }
86
+ if (quote === "\"" && ch === "\\" && i + 1 < command.length) {
87
+ i += 1;
88
+ current += command[i];
89
+ started = true;
90
+ continue;
91
+ }
92
+ current += ch;
93
+ started = true;
94
+ continue;
95
+ }
96
+
97
+ if (ch === "'" || ch === "\"") {
98
+ quote = ch;
99
+ started = true;
100
+ continue;
101
+ }
102
+ if (/\s/.test(ch)) {
103
+ ({ current, started } = finishToken(tokens, current, started));
104
+ continue;
105
+ }
106
+ if ("|;&<>".includes(ch) || "$*?[](){}".includes(ch)) {
107
+ return null;
108
+ }
109
+ if (shellTool === "PowerShell" && "@,%".includes(ch)) {
110
+ return null;
111
+ }
112
+ if (shellTool === "Bash" && ch === "~") {
113
+ return null;
114
+ }
115
+ if (ch === "\\" && shellTool === "Bash" && i + 1 < command.length) {
116
+ i += 1;
117
+ current += command[i];
118
+ started = true;
119
+ continue;
120
+ }
121
+ current += ch;
122
+ started = true;
123
+ }
124
+
125
+ if (quote) {
126
+ return null;
127
+ }
128
+ finishToken(tokens, current, started);
129
+ return tokens;
130
+ }
131
+
132
+ function isBareTapTapExecutable(token) {
133
+ const lower = token.toLowerCase();
134
+ return lower === "taptap-cli" || lower === "taptap-cli.exe";
135
+ }
136
+
137
+ function looksLikeTapTap(command) {
138
+ return /\btaptap-cli(?:\.exe)?\b/i.test(command);
139
+ }
140
+
141
+ export function classifyShellCommand(command, shellTool) {
142
+ if (typeof command !== "string" || command.trim() === "") {
143
+ return { kind: "none" };
144
+ }
145
+ if (!looksLikeTapTap(command)) {
146
+ return { kind: "none" };
147
+ }
148
+
149
+ const tokens = tokenizeSimpleCommand(command.trim(), shellTool);
150
+ if (!tokens || tokens.length === 0 || !isBareTapTapExecutable(tokens[0])) {
151
+ return { kind: "unknown" };
152
+ }
153
+
154
+ return {
155
+ kind: "direct",
156
+ executable: tokens[0],
157
+ argv: tokens.slice(1),
158
+ };
159
+ }
160
+
161
+ function hasSensitiveOrLocalInput(argv) {
162
+ const sensitiveFlag = /^--(?:access[_-]?token|refresh[_-]?token|authorization|password|secret|ticket)(?:=|$)/i;
163
+ const signedURL = /[?&](?:access[_-]?token|token|signature|x-amz-(?:signature|credential|security-token)|x-goog-(?:signature|credential))=/i;
164
+ const localPathFlag = /^--(?:[a-z0-9]+-)*(?:data|dest|destination|dir|directory|file|input|out|output|path)(?:=|$)/i;
165
+ const localPath = /^(?:\.{1,2}[\\/]|~[\\/]|[\\/]|[A-Za-z]:[\\/]|file:)/i;
166
+
167
+ for (let i = 0; i < argv.length; i += 1) {
168
+ const arg = argv[i];
169
+ const flagValue = arg.includes("=") ? arg.slice(arg.indexOf("=") + 1) : "";
170
+ if (
171
+ sensitiveFlag.test(arg) ||
172
+ signedURL.test(arg) ||
173
+ arg.startsWith("@") ||
174
+ arg === "-" ||
175
+ localPathFlag.test(arg) ||
176
+ localPath.test(arg) ||
177
+ (flagValue && localPath.test(flagValue))
178
+ ) {
179
+ return true;
180
+ }
181
+ }
182
+ return false;
183
+ }
184
+
185
+ function parseJSONOutput(raw) {
186
+ const text = String(raw ?? "").trim();
187
+ if (!text) {
188
+ return null;
189
+ }
190
+ try {
191
+ return JSON.parse(text);
192
+ } catch {
193
+ return null;
194
+ }
195
+ }
196
+
197
+ function parseCLIEnvelope(raw) {
198
+ const text = String(raw ?? "").trim();
199
+ const direct = parseJSONOutput(text);
200
+ if (direct && typeof direct.ok === "boolean") {
201
+ return direct;
202
+ }
203
+ const exitPrefixed = /^Exit code \d+\s*\r?\n([\s\S]+)$/i.exec(text);
204
+ if (!exitPrefixed) {
205
+ return null;
206
+ }
207
+ const parsed = parseJSONOutput(exitPrefixed[1]);
208
+ return parsed && typeof parsed.ok === "boolean" ? parsed : null;
209
+ }
210
+
211
+ function unwrapData(value) {
212
+ if (value && typeof value === "object" && value.ok === true && value.data && typeof value.data === "object") {
213
+ return value.data;
214
+ }
215
+ return value;
216
+ }
217
+
218
+ function defaultInspectCommand(argv) {
219
+ const stdout = execFileSync(
220
+ "taptap-cli",
221
+ ["config", "command", "inspect", "--argv-json", JSON.stringify(argv)],
222
+ {
223
+ encoding: "utf8",
224
+ timeout: 900,
225
+ stdio: ["ignore", "pipe", "ignore"],
226
+ env: {
227
+ ...process.env,
228
+ TAPTAP_CLI_NO_UPDATE_NOTIFIER: "1",
229
+ TAPTAP_CLI_NO_SKILLS_NOTIFIER: "1",
230
+ TAPTAP_CLI_REMOTE_META: "off",
231
+ },
232
+ },
233
+ );
234
+ const parsed = unwrapData(parseJSONOutput(stdout));
235
+ if (!parsed || typeof parsed !== "object") {
236
+ throw new Error("command inspection returned invalid JSON");
237
+ }
238
+ return parsed;
239
+ }
240
+
241
+ function pluginVersion() {
242
+ try {
243
+ const manifestURL = new URL("../../.claude-plugin/plugin.json", import.meta.url);
244
+ const manifest = JSON.parse(readFileSync(manifestURL, "utf8"));
245
+ return typeof manifest.version === "string" ? manifest.version : "unknown";
246
+ } catch {
247
+ return "unknown";
248
+ }
249
+ }
250
+
251
+ function runLocalJSON(args, timeout) {
252
+ const stdout = execFileSync("taptap-cli", args, {
253
+ encoding: "utf8",
254
+ timeout,
255
+ stdio: ["ignore", "pipe", "ignore"],
256
+ env: {
257
+ ...process.env,
258
+ TAPTAP_CLI_NO_UPDATE_NOTIFIER: "1",
259
+ TAPTAP_CLI_NO_SKILLS_NOTIFIER: "1",
260
+ TAPTAP_CLI_REMOTE_META: "off",
261
+ },
262
+ });
263
+ const parsed = unwrapData(parseJSONOutput(stdout));
264
+ if (!parsed || typeof parsed !== "object") {
265
+ throw new Error(`${args.join(" ")} returned invalid JSON`);
266
+ }
267
+ return parsed;
268
+ }
269
+
270
+ export function probeSession(runJSON = runLocalJSON) {
271
+ try {
272
+ const version = runJSON(["version", "--format", "json"], 1000);
273
+ let auth = null;
274
+ let skills = null;
275
+ try {
276
+ auth = runJSON(["auth", "status", "--offline", "--json"], 1200);
277
+ } catch {
278
+ auth = { status: "unavailable" };
279
+ }
280
+ try {
281
+ skills = runJSON(["skills", "status", "--json"], 1200);
282
+ } catch {
283
+ skills = { status: "unavailable" };
284
+ }
285
+ return { available: true, version: version.version || "unknown", auth, skills };
286
+ } catch {
287
+ return { available: false, version: "", auth: null, skills: null };
288
+ }
289
+ }
290
+
291
+ function hookContext(event, additionalContext) {
292
+ return {
293
+ hookSpecificOutput: {
294
+ hookEventName: event,
295
+ additionalContext: redactText(additionalContext),
296
+ },
297
+ };
298
+ }
299
+
300
+ function permission(decision, reason) {
301
+ return {
302
+ hookSpecificOutput: {
303
+ hookEventName: EVENT_PRE_TOOL_USE,
304
+ permissionDecision: decision,
305
+ permissionDecisionReason: redactText(reason),
306
+ },
307
+ };
308
+ }
309
+
310
+ function directCommand(input) {
311
+ if (!SHELL_TOOLS.has(input?.tool_name)) {
312
+ return { kind: "none" };
313
+ }
314
+ return classifyShellCommand(input?.tool_input?.command, input.tool_name);
315
+ }
316
+
317
+ function inspectBestEffort(call, deps) {
318
+ try {
319
+ return deps.inspectCommand(call.argv);
320
+ } catch (error) {
321
+ deps.log(`command inspection unavailable: ${error instanceof Error ? error.message : error}`);
322
+ return null;
323
+ }
324
+ }
325
+
326
+ function commandLabel(inspection) {
327
+ if (typeof inspection?.canonical_path === "string" && inspection.canonical_path) {
328
+ return inspection.canonical_path;
329
+ }
330
+ return "direct TapTap CLI command";
331
+ }
332
+
333
+ function handleSessionStart(input, deps) {
334
+ const source = typeof input.source === "string" ? input.source : "startup";
335
+ if (source === "clear" || source === "compact") {
336
+ return hookContext(
337
+ EVENT_SESSION_START,
338
+ "TapTap CLI hooks remain active. CLI policy, risk metadata, and confirmation gates are authoritative.",
339
+ );
340
+ }
341
+
342
+ const probe = deps.probeSession();
343
+ const version = pluginVersion();
344
+ const versionMatches = probe.available && probe.version === version;
345
+ const cliStatus = probe.available
346
+ ? `taptap-cli is available (${probe.version || "version unknown"}; plugin version ${versionMatches ? "matches" : "does not match"}).`
347
+ : "taptap-cli was not found on PATH; TapTap commands will require environment repair.";
348
+ const authStatus = probe.auth && probe.auth.status !== "unavailable"
349
+ ? `Offline auth: profile ${probe.auth.profile || "default"}, credential ${probe.auth.credentialSource || "none"}, token ${probe.auth.hasAccessToken ? (probe.auth.accessTokenExpired ? "expired" : "present") : "absent"}.`
350
+ : "Offline auth status unavailable.";
351
+ const embedded = probe.skills?.embedded;
352
+ const globalSkills = probe.skills?.global_agent_skills;
353
+ const projectSkills = probe.skills?.project_agent_skills;
354
+ const projectPlugin = probe.skills?.project_plugin;
355
+ const skillsStatus = embedded
356
+ ? `Skills: embedded ${embedded.count ?? 0} (${embedded.content_hash || "hash unavailable"}); global ${globalSkills?.status || "unknown"}; project ${projectSkills?.status || "unknown"}; project plugin ${projectPlugin?.status || "unknown"}.`
357
+ : "Skills status unavailable.";
358
+ return hookContext(
359
+ EVENT_SESSION_START,
360
+ `TapTap Claude plugin ${version} loaded. ${cliStatus} ${authStatus} ${skillsStatus} No login, update, Skill installation, or project mutation was performed.`,
361
+ );
362
+ }
363
+
364
+ function handlePreToolUse(input, deps) {
365
+ const call = directCommand(input);
366
+ if (call.kind === "none") {
367
+ return {};
368
+ }
369
+ if (call.kind === "unknown") {
370
+ return permission("ask", "Command may invoke taptap-cli but is not a supported single direct call.");
371
+ }
372
+
373
+ const inspection = inspectBestEffort(call, deps);
374
+ if (!inspection || inspection.recognized !== true || inspection.invocation_valid !== true) {
375
+ return permission("ask", "TapTap command could not be inspected by the installed CLI.");
376
+ }
377
+
378
+ const label = commandLabel(inspection);
379
+ if (inspection.policy_decision === "deny") {
380
+ return permission(
381
+ "deny",
382
+ `TapTap policy denies ${label}${inspection.reason_code ? ` (${inspection.reason_code})` : ""}.`,
383
+ );
384
+ }
385
+ if (
386
+ WRITE_RISKS.has(inspection.risk) ||
387
+ inspection.requires_confirmation === true ||
388
+ hasSensitiveOrLocalInput(call.argv)
389
+ ) {
390
+ return permission("ask", `TapTap command requires review before execution: ${label}.`);
391
+ }
392
+ if (inspection.risk === "read" && inspection.policy_decision === "allow") {
393
+ return permission("allow", `TapTap read command allowed by CLI policy: ${label}.`);
394
+ }
395
+ return permission("ask", `TapTap command inspection was not sufficient to auto-allow: ${label}.`);
396
+ }
397
+
398
+ function envelopeFrom(value) {
399
+ if (!value) {
400
+ return null;
401
+ }
402
+ if (typeof value === "string") {
403
+ return parseCLIEnvelope(value);
404
+ }
405
+ if (typeof value !== "object") {
406
+ return null;
407
+ }
408
+ if (typeof value.ok === "boolean") {
409
+ return value;
410
+ }
411
+ for (const key of ["stdout", "output", "content", "stderr"]) {
412
+ if (key in value) {
413
+ const nested = envelopeFrom(value[key]);
414
+ if (nested) {
415
+ return nested;
416
+ }
417
+ }
418
+ }
419
+ return null;
420
+ }
421
+
422
+ function durationSuffix(input) {
423
+ const duration = Number(input?.duration_ms ?? input?.tool_response?.duration_ms);
424
+ return Number.isFinite(duration) && duration >= 0 ? ` Duration: ${Math.round(duration)}ms.` : "";
425
+ }
426
+
427
+ function handlePostToolUse(input, deps) {
428
+ const call = directCommand(input);
429
+ if (call.kind !== "direct") {
430
+ return {};
431
+ }
432
+ const inspection = inspectBestEffort(call, deps);
433
+ const envelope = envelopeFrom(input.tool_response);
434
+ const verified = envelope?.ok === true
435
+ ? " The complete CLI envelope reports ok:true."
436
+ : " No complete CLI success envelope was available; do not infer additional remote state.";
437
+ return hookContext(
438
+ EVENT_POST_TOOL_USE,
439
+ `TapTap command completed: ${commandLabel(inspection)}.${durationSuffix(input)}${verified}`,
440
+ );
441
+ }
442
+
443
+ function errorDetail(envelope) {
444
+ const error = envelope?.ok === false && envelope.error && typeof envelope.error === "object"
445
+ ? envelope.error
446
+ : null;
447
+ if (!error) {
448
+ return null;
449
+ }
450
+ return {
451
+ type: typeof error.type === "string" ? error.type : "",
452
+ subtype: typeof error.subtype === "string" ? error.subtype : "",
453
+ reasonCode: typeof error.reason_code === "string"
454
+ ? error.reason_code
455
+ : typeof error.detail?.reason_code === "string"
456
+ ? error.detail.reason_code
457
+ : "",
458
+ hint: typeof error.hint === "string" ? error.hint : "",
459
+ };
460
+ }
461
+
462
+ function failureGuidance(input, inspection) {
463
+ const envelope = envelopeFrom(input.error) ?? envelopeFrom(input.tool_response);
464
+ const detail = errorDetail(envelope);
465
+ const rawError = redactText(typeof input.error === "string" ? input.error : "");
466
+ const uncertain = /timeout|timed out|invalid_response|outcome unknown|unknown outcome/i.test(
467
+ `${detail?.type ?? ""} ${detail?.subtype ?? ""} ${rawError}`,
468
+ );
469
+ const writeLike =
470
+ WRITE_RISKS.has(inspection?.risk) ||
471
+ input?.tool_input?.command?.includes("--yes") ||
472
+ input?.tool_input?.command?.includes("--idempotency-key");
473
+
474
+ const parts = [`TapTap command failed: ${commandLabel(inspection)}.`];
475
+ if (detail) {
476
+ const classification = [detail.type, detail.subtype, detail.reasonCode].filter(Boolean).join("/");
477
+ if (classification) {
478
+ parts.push(`CLI classification: ${classification}.`);
479
+ }
480
+ if (detail.hint) {
481
+ parts.push(`CLI recovery hint: ${redactText(detail.hint)}.`);
482
+ }
483
+ if (detail.type === "auth" || /auth|credential|token/i.test(detail.subtype)) {
484
+ parts.push("Re-establish authentication before retrying.");
485
+ } else if (
486
+ detail.type === "validation" ||
487
+ /policy|denied|forbidden|failed_precondition/i.test(`${detail.type} ${detail.subtype}`)
488
+ ) {
489
+ parts.push("Do not bypass the validation or policy denial; correct the inputs or policy.");
490
+ } else if (/network|timeout|unavailable|server/i.test(`${detail.type} ${detail.subtype}`)) {
491
+ parts.push("Use a bounded retry only when the operation outcome is known.");
492
+ }
493
+ }
494
+ if (uncertain && writeLike) {
495
+ parts.push(
496
+ "The write outcome may be unknown. Read back by resource identity or idempotency key before retrying, and retry only after confirming it did not take effect.",
497
+ );
498
+ } else if (!detail) {
499
+ parts.push("No complete CLI error envelope was available; inspect the original tool error without guessing its category.");
500
+ }
501
+ return parts.join(" ");
502
+ }
503
+
504
+ function handlePostToolUseFailure(input, deps) {
505
+ const call = directCommand(input);
506
+ if (call.kind !== "direct") {
507
+ return {};
508
+ }
509
+ const inspection = inspectBestEffort(call, deps);
510
+ return hookContext(EVENT_POST_TOOL_USE_FAILURE, failureGuidance(input, inspection));
511
+ }
512
+
513
+ export function dispatchHook(input, overrides = {}) {
514
+ const deps = {
515
+ inspectCommand: defaultInspectCommand,
516
+ probeSession,
517
+ log: defaultLog,
518
+ ...overrides,
519
+ };
520
+
521
+ switch (input?.hook_event_name) {
522
+ case EVENT_SESSION_START:
523
+ return handleSessionStart(input, deps);
524
+ case EVENT_PRE_TOOL_USE:
525
+ return handlePreToolUse(input, deps);
526
+ case EVENT_POST_TOOL_USE:
527
+ return handlePostToolUse(input, deps);
528
+ case EVENT_POST_TOOL_USE_FAILURE:
529
+ return handlePostToolUseFailure(input, deps);
530
+ default:
531
+ return {};
532
+ }
533
+ }
534
+
535
+ async function readStdin() {
536
+ const chunks = [];
537
+ let size = 0;
538
+ for await (const chunk of process.stdin) {
539
+ size += chunk.length;
540
+ if (size > MAX_STDIN_BYTES) {
541
+ throw new Error("hook input exceeds 1 MiB");
542
+ }
543
+ chunks.push(chunk);
544
+ }
545
+ return Buffer.concat(chunks).toString("utf8");
546
+ }
547
+
548
+ async function main() {
549
+ let output = {};
550
+ try {
551
+ const raw = await readStdin();
552
+ output = dispatchHook(JSON.parse(raw));
553
+ } catch (error) {
554
+ defaultLog(`hook degraded safely: ${error instanceof Error ? error.message : error}`);
555
+ }
556
+ process.stdout.write(`${JSON.stringify(output)}\n`);
557
+ process.exitCode = 0;
558
+ }
559
+
560
+ const invokedPath = process.argv[1] ? resolve(process.argv[1]) : "";
561
+ if (invokedPath && invokedPath === fileURLToPath(import.meta.url)) {
562
+ await main();
563
+ }