huaweicloud-devkit 2.0.0-next.3 → 2.0.0-next.4

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 (161) hide show
  1. package/README.md +3 -1
  2. package/package.json +3 -1
  3. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +16 -3
  4. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +16 -3
  5. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +16 -3
  6. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +16 -3
  7. package/plugins/huaweicloud-core/.mcp.json +55 -1
  8. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +16 -3
  9. package/plugins/huaweicloud-core/dist/agents/codex-config.js +374 -0
  10. package/plugins/huaweicloud-core/dist/agents/codex-desktop.js +8 -1
  11. package/plugins/huaweicloud-core/dist/agents/codex.js +9 -0
  12. package/plugins/huaweicloud-core/dist/agents/opencode-config.js +141 -86
  13. package/plugins/huaweicloud-core/dist/agents/opencode.js +106 -39
  14. package/plugins/huaweicloud-core/dist/approval-gate.js +1185 -0
  15. package/plugins/huaweicloud-core/dist/approval-ledger.js +2331 -0
  16. package/plugins/huaweicloud-core/dist/approval-roster.js +89 -0
  17. package/plugins/huaweicloud-core/dist/approval-types.js +1 -0
  18. package/plugins/huaweicloud-core/dist/approvals-cli.js +4 -4
  19. package/plugins/huaweicloud-core/dist/data/icons-manifest.v1.json +23 -5
  20. package/plugins/huaweicloud-core/dist/dep/receipts.js +65 -5
  21. package/plugins/huaweicloud-core/dist/hcloud-cli.js +1 -1
  22. package/plugins/huaweicloud-core/dist/hcloud-plan.js +62 -61
  23. package/plugins/huaweicloud-core/dist/lib/approval-mode.js +7 -5
  24. package/plugins/huaweicloud-core/dist/lib/approval-tokens.js +18 -4
  25. package/plugins/huaweicloud-core/dist/lib/call-trace.js +7 -14
  26. package/plugins/huaweicloud-core/dist/lib/confirm-language.js +50 -0
  27. package/plugins/huaweicloud-core/dist/lib/credentials.js +9 -9
  28. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkit-gate.js +1398 -0
  29. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +362 -32
  30. package/plugins/huaweicloud-core/dist/lib/hdkit/sandbox-pool.js +6 -16
  31. package/plugins/huaweicloud-core/dist/lib/opencode-ask-rule.js +224 -78
  32. package/plugins/huaweicloud-core/dist/lib/opencode-saved-perms.js +282 -0
  33. package/plugins/huaweicloud-core/dist/lib/supplemental-redaction.js +116 -0
  34. package/plugins/huaweicloud-core/dist/lib/tool-schema-parts.js +31 -0
  35. package/plugins/huaweicloud-core/dist/lib/workspace-glob.js +442 -0
  36. package/plugins/huaweicloud-core/dist/mcp-config-io.js +28 -1
  37. package/plugins/huaweicloud-core/dist/mcp-protocol.js +68 -16
  38. package/plugins/huaweicloud-core/dist/mcp-server.js +6506 -912
  39. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  40. package/plugins/huaweicloud-core/dist/mcp-stdio-transport.js +14 -4
  41. package/plugins/huaweicloud-core/dist/packs/auth/approval.js +249 -0
  42. package/plugins/huaweicloud-core/dist/packs/auth/tools.js +44 -44
  43. package/plugins/huaweicloud-core/dist/packs/huaweicloud-cli/tools.js +85 -130
  44. package/plugins/huaweicloud-core/dist/packs/obs/approval.js +110 -0
  45. package/plugins/huaweicloud-core/dist/packs/obs/tools.js +7 -2
  46. package/plugins/huaweicloud-core/dist/packs/registry.js +19 -1
  47. package/plugins/huaweicloud-core/dist/packs/sandbox/approval.js +245 -0
  48. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +156 -23
  49. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-credentials.js +13 -1
  50. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-hwexec.js +136 -0
  51. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-session.js +11 -1
  52. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +1 -0
  53. package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +79 -9
  54. package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +28 -9
  55. package/plugins/huaweicloud-core/dist/packs/secrets/approval.js +46 -0
  56. package/plugins/huaweicloud-core/dist/packs/secrets/tools.js +4 -1
  57. package/plugins/huaweicloud-core/dist/packs/update/approval.js +79 -0
  58. package/plugins/huaweicloud-core/dist/packs/update/tools.js +8 -1
  59. package/plugins/huaweicloud-core/dist/packs/voucher/tools.js +1 -1
  60. package/plugins/huaweicloud-core/dist/packs-configure.js +74 -0
  61. package/plugins/huaweicloud-core/dist/safety/classify-text.js +36 -0
  62. package/plugins/huaweicloud-core/dist/safety/policy.js +2 -0
  63. package/plugins/huaweicloud-core/dist/sandbox/deploy-check.js +1 -1
  64. package/plugins/huaweicloud-core/dist/sandbox/devbridge-auth.js +65 -14
  65. package/plugins/huaweicloud-core/dist/sandbox/devbridge-cleanup.js +422 -0
  66. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose-flow.js +66 -16
  67. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose.js +13 -10
  68. package/plugins/huaweicloud-core/dist/sandbox/devbridge-keepalive.js +42 -2
  69. package/plugins/huaweicloud-core/dist/sandbox/devbridge-key.js +11 -3
  70. package/plugins/huaweicloud-core/dist/sandbox/devbridge-tunnel.js +6 -0
  71. package/plugins/huaweicloud-core/dist/sandbox/devbridge-validation.js +10 -1
  72. package/plugins/huaweicloud-core/dist/sandbox/hwexec-task.js +244 -0
  73. package/plugins/huaweicloud-core/dist/setup-cli.js +36 -1
  74. package/plugins/huaweicloud-core/dist/tool-definitions.js +9 -1
  75. package/plugins/huaweicloud-core/dist/tool-schemas.js +32 -6
  76. package/plugins/huaweicloud-core/dist/tools.js +76 -9
  77. package/plugins/huaweicloud-core/dist/update-registry.js +358 -5
  78. package/plugins/huaweicloud-core/dist/update-upgrade.js +1083 -14
  79. package/plugins/huaweicloud-core/dist/vendor-gate.js +2 -2
  80. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.mjs +150 -1
  81. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +53 -3
  82. package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
  83. package/plugins/huaweicloud-core/safety/policy.json +18 -11
  84. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +114 -10
  85. package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +190 -138
  86. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/resource-pool.md +36 -12
  87. package/plugins/huaweicloud-core/skills/huawei-voucher/SKILL.md +2 -0
  88. package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/SKILL.md +2 -2
  89. package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +11 -7
  90. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +74 -29
  91. package/plugins/huaweicloud-core/skills/huaweicloud-troubleshooting/SKILL.md +21 -19
  92. package/plugins/huaweicloud-core/src/agents/codex-config.ts +432 -0
  93. package/plugins/huaweicloud-core/src/agents/codex-desktop.ts +8 -1
  94. package/plugins/huaweicloud-core/src/agents/codex.ts +10 -0
  95. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +176 -88
  96. package/plugins/huaweicloud-core/src/agents/opencode.ts +125 -54
  97. package/plugins/huaweicloud-core/src/approval-gate.ts +1306 -0
  98. package/plugins/huaweicloud-core/src/approval-ledger.ts +2446 -0
  99. package/plugins/huaweicloud-core/src/approval-roster.ts +127 -0
  100. package/plugins/huaweicloud-core/src/approval-types.ts +237 -0
  101. package/plugins/huaweicloud-core/src/approvals-cli.ts +4 -4
  102. package/plugins/huaweicloud-core/src/data/icons-manifest.v1.json +23 -5
  103. package/plugins/huaweicloud-core/src/dep/receipts.ts +84 -5
  104. package/plugins/huaweicloud-core/src/hcloud-cli.ts +3 -0
  105. package/plugins/huaweicloud-core/src/hcloud-plan.ts +68 -70
  106. package/plugins/huaweicloud-core/src/lib/approval-mode.ts +7 -5
  107. package/plugins/huaweicloud-core/src/lib/approval-tokens.ts +19 -4
  108. package/plugins/huaweicloud-core/src/lib/call-trace.ts +7 -17
  109. package/plugins/huaweicloud-core/src/lib/confirm-language.ts +51 -0
  110. package/plugins/huaweicloud-core/src/lib/credentials.ts +9 -8
  111. package/plugins/huaweicloud-core/src/lib/hdkit/hdkit-gate.ts +1428 -0
  112. package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +377 -30
  113. package/plugins/huaweicloud-core/src/lib/hdkit/sandbox-pool.ts +8 -15
  114. package/plugins/huaweicloud-core/src/lib/opencode-ask-rule.ts +302 -83
  115. package/plugins/huaweicloud-core/src/lib/opencode-saved-perms.ts +354 -0
  116. package/plugins/huaweicloud-core/src/lib/supplemental-redaction.ts +129 -0
  117. package/plugins/huaweicloud-core/src/lib/tool-schema-parts.ts +40 -0
  118. package/plugins/huaweicloud-core/src/lib/workspace-glob.ts +414 -0
  119. package/plugins/huaweicloud-core/src/mcp-config-io.ts +27 -1
  120. package/plugins/huaweicloud-core/src/mcp-protocol.ts +81 -17
  121. package/plugins/huaweicloud-core/src/mcp-server.ts +7 -7
  122. package/plugins/huaweicloud-core/src/mcp-stdio-transport.ts +14 -4
  123. package/plugins/huaweicloud-core/src/packs/auth/approval.ts +302 -0
  124. package/plugins/huaweicloud-core/src/packs/auth/tools.ts +54 -45
  125. package/plugins/huaweicloud-core/src/packs/huaweicloud-cli/tools.ts +99 -137
  126. package/plugins/huaweicloud-core/src/packs/obs/approval.ts +122 -0
  127. package/plugins/huaweicloud-core/src/packs/obs/tools.ts +7 -2
  128. package/plugins/huaweicloud-core/src/packs/registry.ts +42 -1
  129. package/plugins/huaweicloud-core/src/packs/sandbox/approval.ts +296 -0
  130. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +168 -23
  131. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-credentials.ts +11 -1
  132. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-hwexec.ts +228 -0
  133. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-session.ts +11 -1
  134. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +1 -0
  135. package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +100 -8
  136. package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +31 -8
  137. package/plugins/huaweicloud-core/src/packs/secrets/approval.ts +50 -0
  138. package/plugins/huaweicloud-core/src/packs/secrets/tools.ts +4 -1
  139. package/plugins/huaweicloud-core/src/packs/update/approval.ts +87 -0
  140. package/plugins/huaweicloud-core/src/packs/update/tools.ts +8 -1
  141. package/plugins/huaweicloud-core/src/packs/voucher/tools.ts +1 -1
  142. package/plugins/huaweicloud-core/src/packs-configure.ts +75 -0
  143. package/plugins/huaweicloud-core/src/safety/classify-text.ts +40 -0
  144. package/plugins/huaweicloud-core/src/safety/policy.ts +7 -0
  145. package/plugins/huaweicloud-core/src/sandbox/deploy-check.ts +1 -1
  146. package/plugins/huaweicloud-core/src/sandbox/devbridge-auth.ts +74 -14
  147. package/plugins/huaweicloud-core/src/sandbox/devbridge-cleanup.ts +509 -0
  148. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose-flow.ts +70 -18
  149. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose.ts +26 -10
  150. package/plugins/huaweicloud-core/src/sandbox/devbridge-keepalive.ts +41 -2
  151. package/plugins/huaweicloud-core/src/sandbox/devbridge-key.ts +9 -3
  152. package/plugins/huaweicloud-core/src/sandbox/devbridge-tunnel.ts +24 -0
  153. package/plugins/huaweicloud-core/src/sandbox/devbridge-validation.ts +11 -1
  154. package/plugins/huaweicloud-core/src/sandbox/hwexec-task.ts +304 -0
  155. package/plugins/huaweicloud-core/src/setup-cli.ts +39 -1
  156. package/plugins/huaweicloud-core/src/tool-definitions.ts +9 -1
  157. package/plugins/huaweicloud-core/src/tool-schemas.ts +39 -6
  158. package/plugins/huaweicloud-core/src/tools.ts +124 -10
  159. package/plugins/huaweicloud-core/src/update-registry.ts +340 -5
  160. package/plugins/huaweicloud-core/src/update-upgrade.ts +1130 -14
  161. package/plugins/huaweicloud-core/src/vendor-gate.ts +2 -2
@@ -0,0 +1,1306 @@
1
+ // The dispatch-layer approval gate. Every roster tool's call flows through
2
+ // here AFTER the vendor gate and BEFORE pack dispatch (tools.ts), with the
3
+ // tool's ApprovalSpec resolved from the registry merge (packs/registry.ts
4
+ // APPROVAL_SPECS). The hcloud path migrated in with zero behavior change:
5
+ // its spec registers normalizeArgs (stripLeadingHcloudBinArgs) so the gate
6
+ // binds the plan's effective args exactly as the pack handler did, and
7
+ // tokenSource 'plan-face' keeps the trunk contract — the plan face is the
8
+ // only minter, so a no-token call returns CONFIRM_TOKEN_NOT_FOUND and the
9
+ // gate mints nothing (ApprovalCoreMint: GateNeverMintsForPlanFace,
10
+ // PlanFaceMintsOnlyItsOwn).
11
+ //
12
+ // A 'gate' tool (PR-3 registrations) mints on the first no-token call and
13
+ // returns USER_CONFIRMATION_REQUIRED with the fresh approvalToken and the
14
+ // redacted summarize view, executing nothing. Ask mode routes straight to
15
+ // the registered handler with no token and records the consent event in
16
+ // the ledger. requiresSessionSeam tools (packs_configure) check
17
+ // opts.onPacksChanged BEFORE engaging, mirroring the handler's own
18
+ // stdio-only refusal, so no-seam calls refuse with nothing minted and no
19
+ // ledger entry. With a token the gate runs the existing consume flow —
20
+ // single-use claim, grant verification, hash and pin-view binding — and
21
+ // the registered handler keeps only the pure execution it owns, so the
22
+ // one-snapshot TOCTOU contract stays inside consumeApprovalToken.
23
+ import { realpathSync } from 'node:fs';
24
+ import { homedir } from 'node:os';
25
+ import { join, resolve } from 'node:path';
26
+
27
+ import type { ToolName } from './tool-definitions.ts';
28
+ import type { ToolArgs, CallToolOptions } from './tools.ts';
29
+ import { approvalModeFromEnv } from './lib/approval-mode.ts';
30
+ import { createApprovalToken, consumeApprovalToken, hashArgs, inspectApprovalToken } from './lib/approval-tokens.ts';
31
+ import { huaweiConfigBase } from './lib/state-dir.ts';
32
+ import { annotateDispatchOutcome, recordAskModeConsent } from './approval-ledger.ts';
33
+ import type {
34
+ ApprovalSpec,
35
+ ConsentDeliveryOutcome,
36
+ ElicitFormRequest,
37
+ ElicitFormSchema,
38
+ ElicitOutcome,
39
+ } from './approval-types.ts';
40
+ import { resolveConfirmLanguage, type ConfirmLanguage } from './lib/confirm-language.ts';
41
+
42
+ // The gate result: a structured pass carries the arrival's identity (the
43
+ // consent stamp AND the seq the ask branch just wrote — round 15, finding
44
+ // 2) to the dispatch layer, which hands it to the delivery recorder — the
45
+ // ownership-by-identity requirement (never by position or absence) — and,
46
+ // from PR-3a, the REUSE attribution: 'retry-uncertain' when a
47
+ // byte-identical repeat rode the S1 retry memo, 'standing-session' when an
48
+ // identical call rode the S3 standing grant the user ticked. The dispatch
49
+ // layer attaches the carrier to the handler's result so the response names
50
+ // what authorized it. The pass ALSO carries the APPROVED BINDING (the
51
+ // spec's normalizeArgs value for this call, the resolved snapshot a
52
+ // credential-consuming handler must execute — never a post-consent re-read
53
+ // of its backing stores; PR-3b's TOCTOU finding); an envelope
54
+ // object is returned to the caller INSTEAD of the handler's value.
55
+ // Approval-shaped refusals are results, not throws, so callTool's caller
56
+ // (and the trace seam) see the same JSON shapes the pack handler returns
57
+ // for them.
58
+ export type ApprovalReuseVia = 'retry-uncertain' | 'standing-session';
59
+
60
+ // The consent row's scope for the arrival the pass represents, threaded to
61
+ // the dispatch recorder: 'once' for fresh confirmations and memo reuses
62
+ // (the memo keys on these arrivals' delivery outcome), 'session' for the
63
+ // standing-consent tick (a scope-'session' grant must never arm the retry
64
+ // memo), absent for standing rides (no row was written).
65
+ export type ApprovalConsentScope = 'once' | 'session';
66
+
67
+ export type ApprovalGateOutcome =
68
+ | {
69
+ pass: {
70
+ arrivalStamp?: number;
71
+ arrivalSeq?: number;
72
+ approvedVia?: ApprovalReuseVia;
73
+ consentScope?: ApprovalConsentScope;
74
+ };
75
+ // The APPROVED BINDING (the spec's normalizeArgs value for this call,
76
+ // the resolved snapshot a credential-consuming handler must execute —
77
+ // never a post-consent re-read of its backing stores; PR-3b's TOCTOU
78
+ // finding). Undefined only for an envelope path, which never passes.
79
+ binding: unknown;
80
+ }
81
+ | { envelope: Record<string, unknown> };
82
+
83
+ export const NO_SESSION_SEAM_ERROR =
84
+ 'Runtime pack configuration is available in stdio agent sessions only; this surface carries no session state.';
85
+
86
+ const GRANT_REQUIRED_NEXT_STEP =
87
+ 'Ask the user to run "npx huaweicloud-devkit approve <this approvalToken>" in their own terminal, then retry this exact call.';
88
+
89
+ // The command-forward anchor (the operator-approved display field): a call
90
+ // that carries the tool's `command` string must spell the exact line its args
91
+ // execute, so the harness popup's first line is the command the user is
92
+ // approving rather than a JSON args blob with self-attestation fields beside
93
+ // it. The check runs in BOTH modes, before any mint, consent record, or
94
+ // execution: a line that disagrees with the args is never what the user saw,
95
+ // so nothing may run. The legacy args-only shape carries no field and is
96
+ // untouched (the trunk battery drives exactly that shape), and a tool with no
97
+ // executable line ignores the field.
98
+ export const COMMAND_ARGS_MISMATCH = 'COMMAND_ARGS_MISMATCH';
99
+ export const COMMAND_REQUIRES_ARGS = 'COMMAND_REQUIRES_ARGS';
100
+
101
+ function commandAnchorRefusal(spec: ApprovalSpec, value: unknown, provided: unknown): Record<string, unknown> | null {
102
+ if (provided === undefined) return null; // the legacy args-only shape
103
+ // The refusal envelope's shared content: the REAL summarize view, so the
104
+ // confirmation surface can only ever carry real content (interrogate
105
+ // round 2, fix-in-pass iv) — never a fabricated display line.
106
+ const noAnchorRefusal = (reason: string): Record<string, unknown> => {
107
+ const view = spec.summarize(value);
108
+ return {
109
+ status: 'rejected',
110
+ code: COMMAND_ARGS_MISMATCH,
111
+ reason,
112
+ summary: view.summary,
113
+ nextStep: 'Remove the command field. This tool\u2019s confirmation view is its summarized request.',
114
+ };
115
+ };
116
+ // A tool that declares no anchorable line refuses a `command` field
117
+ // outright (the serial landing's no-anchor refusal): the field exists to
118
+ // carry the line the user reads, and on a no-anchor tool it is a stuffed
119
+ // display field — the exec faces, which DO anchor their own command, and
120
+ // the structured faces behave as their registrations say.
121
+ if (spec.commandAnchor === undefined) {
122
+ return noAnchorRefusal(
123
+ 'this tool declares no displayable command line, so a command field is not accepted for it.',
124
+ );
125
+ }
126
+ const expected = spec.commandAnchor(value);
127
+ if (expected.length === 0) {
128
+ // This call declares no executable line even though the spec anchors:
129
+ // a provided one is a fabricated display line the user would read as
130
+ // "the approved command" while the real request executes underneath.
131
+ return noAnchorRefusal(
132
+ 'this tool takes no command field for this call: it has no executable line to anchor, and a fabricated line must never display as the approved content.',
133
+ );
134
+ }
135
+ if (typeof provided !== 'string' || provided.trim() === '') {
136
+ return {
137
+ status: 'rejected',
138
+ code: COMMAND_ARGS_MISMATCH,
139
+ reason: 'the command field must be the full command line, as a non-empty string.',
140
+ nextStep: 'Send command as the exact line the args execute, or omit it for the legacy args-only shape.',
141
+ };
142
+ }
143
+ // The args-display shape (the run face): the command field anchors an
144
+ // ARGS call, so an EMPTY args array cannot carry it. Self-anchored
145
+ // registrations (the sandbox exec faces, whose binding is the object
146
+ // carrying the command content itself) never take this check — their
147
+ // anchor derives from the binding, not from an argv beside it, and their
148
+ // object binding is not the args-array display shape at all.
149
+ if (Array.isArray(value) && value.length === 0) {
150
+ return {
151
+ status: 'rejected',
152
+ code: COMMAND_REQUIRES_ARGS,
153
+ reason: `the command field is the display anchor for an args call and cannot stand alone (got "${provided.slice(0, 200)}").`,
154
+ nextStep: 'Send the args array together with the matching command line, or omit command entirely.',
155
+ };
156
+ }
157
+ if (!expected.includes(provided)) {
158
+ return {
159
+ status: 'rejected',
160
+ code: COMMAND_ARGS_MISMATCH,
161
+ reason:
162
+ `the command field does not match the requested args (got "${provided.slice(0, 200)}"). ` +
163
+ 'The line the user reads in the popup must be the line that executes.',
164
+ expected,
165
+ nextStep:
166
+ "Send the exact command line: the plan result's command field, or the args array spelled out. " +
167
+ 'Substitute real values where the plan shows <redacted>.',
168
+ };
169
+ }
170
+ return null;
171
+ }
172
+
173
+ function bindingValue(spec: ApprovalSpec, args: ToolArgs): unknown {
174
+ return spec.normalizeArgs ? spec.normalizeArgs(args) : args;
175
+ }
176
+
177
+ // The credential-file hard floor (interrogate rounds 1-3): the hook
178
+ // exemption bets "the server gate is strictly stronger" for the classes it
179
+ // skips, and for the write class that bet holds (token + grant + pin-view
180
+ // binding). It did NOT hold for credential-file reads: the argv classifier
181
+ // never consults credentialFilePatterns, so an approved OBS cp of the vault
182
+ // master key or /proc/self/environ executed where the hook used to deny.
183
+ // The floor walks the binding value's string leaves, in BOTH modes, before
184
+ // any mint, consume, or consent record — so the refusal burns nothing and
185
+ // the exfil refuses even where no hook exists at all (the remote face,
186
+ // hook-less harnesses, direct callTool). Credential denies are never
187
+ // unlockable by any confirmation, the same doctrine the strict plan applies
188
+ // to secret and invalid denies.
189
+ //
190
+ // Round 2 added alias resolution; round 3 reworked both halves for trunk
191
+ // parity on benign operations:
192
+ //
193
+ // (a) RESOLUTION, child-faithful. Every leaf that can name a local file —
194
+ // absolute, relative, or BARE (the child resolves a bare name against
195
+ // its cwd; skipping bare names let an innocuous symlink named 'blob'
196
+ // ship the master key) — is resolved through realpathSync against
197
+ // only the bases the spawned child can actually apply: the call's
198
+ // own cwd, else the server process's cwd (spawn's default). The
199
+ // round-2 extra bases (user home, config home) manufactured refusals
200
+ // for files the child never sees and are gone. Tilde and $HOME
201
+ // spellings are expanded against the real and devkit home roots
202
+ // before resolution — expanding a path's own spelling is not a base.
203
+ //
204
+ // (a2) SCHEME-SPELLING, precise (interrogate round 4). obs:// is the one
205
+ // documented cloud-object key an hcloud operand carries — those stay
206
+ // skipped. Every OTHER scheme-shaped leaf is ALSO resolved as a
207
+ // potential local path: obsutil treats any non-obs:// operand as a
208
+ // LOCAL file, and POSIX collapses the double slash, so s3://x IS the
209
+ // relative path ./s3:/x — the real KooCLI normalized s3://k to
210
+ // childdir/s3:/k and read the credential file (round 4's live
211
+ // dry-run). A scheme spelling that resolves to an existing local
212
+ // file is a local operand and hits the floor; one that resolves to
213
+ // nothing stays clean.
214
+ //
215
+ // (a3) '='-EMBEDDED VALUES (interrogate round 4). The child dereferences
216
+ // the VALUE half of an =-shaped leaf — KooCLI's own --param=value
217
+ // syntax; -config=<alias> and --cli-jsonInput=<relative path> read
218
+ // the file the bare spelling of the same value refuses. Every
219
+ // =-shaped leaf contributes its post-'=' value as a second spelling,
220
+ // resolved with the same rules; a value that resolves to no existing
221
+ // file stays clean (--server.id=i-123 keeps executing).
222
+ //
223
+ // (b) MATCHING, path-semantic. Patterns apply to RESOLVED PATHS only,
224
+ // segment-anchored — the policy regexes are substring-shaped for the
225
+ // hook's text posture, and raw-substring matching denied a plain
226
+ // note file (notes.huaweicloud.md), an obs:// key containing
227
+ // huaweicloud/secrets, and a project's deploy/huaweicloud/config.yaml.
228
+ // The segment rules below operationalize each credentialFilePattern
229
+ // as a path reading; the hook keeps its own layer unchanged.
230
+ //
231
+ // A refusal requires a resolved path that EXISTS and hits a segment rule,
232
+ // so speculative names cannot false-deny. Honest residual, recorded: a
233
+ // target that does not exist yet at call time, or a path only reachable
234
+ // from a child cwd the gate cannot know (args.cwd unset and a wrapper
235
+ // changing the child's directory), stays uncovered.
236
+ // obs:// — lowercase exactly — is the documented cloud-object key scheme
237
+ // (interrogate round 5, both seats: the real KooCLI's own scheme match is
238
+ // case-sensitive; Obs:// and OBS:// operands are LOCAL paths it lstats and
239
+ // reads, measured live — `Error: lstat …/Obs:/no-such-twin` for the case
240
+ // variants against a cloud-style error for lowercase). Case-variant
241
+ // scheme spellings flow into local-path resolution like s3:// does.
242
+ const OBS_URI_RE = /^obs:\/\//;
243
+
244
+ // Segment rules, one per policy credentialFilePattern (each rule's comment
245
+ // names the pattern it operationalizes):
246
+ // \.hcloud, \.huaweicloud → a path segment STARTING with the
247
+ // dot-directory spelling (.hcloud,
248
+ // .huaweicloud, .hcloud-backup)
249
+ // \.master-key → the vault key file itself
250
+ // creds-import\.json → the import file, exact name
251
+ // /proc/(self|[0-9]+)/environ → three consecutive segments
252
+ // huaweicloud[/\]secrets → a 'huaweicloud' segment directly
253
+ // above a 'secrets' segment
254
+ // hcloud[/\](config|credentials), → a 'hcloud' or 'huaweicloud' segment
255
+ // huaweicloud[/\](config| directly above the config/credentials
256
+ // credentials|creds-import) file names — suffixed names like
257
+ // config.yaml are NOT the config file,
258
+ // so deploy/huaweicloud/config.yaml
259
+ // executes as trunk did
260
+ const CREDS_FILE_NAMES = new Set(['config', 'credentials', 'config.json', 'credentials.json', 'creds-import.json']);
261
+
262
+ export function isCredentialResolvedPath(resolvedPath: string): boolean {
263
+ // Compare in the filesystem's own case and split on BOTH separators.
264
+ //
265
+ // The split: win32 realpathSync returns backslash-separated paths, so a
266
+ // '/'-only split matched no segment rule there and the floor never
267
+ // refused on Windows (the PR-2.5 CI finding, fixed here). The resolution
268
+ // half above already speaks both spellings — its absolute candidate test
269
+ // accepts drive-letter forms with either separator on every platform —
270
+ // and this split reuses the same [\\/] vocabulary, one seam rather than
271
+ // a second win32 spelling of the rule.
272
+ //
273
+ // The lowercasing (the root-reproduced finding this round): NTFS is
274
+ // case-insensitive, so an attacker's upper-case spelling
275
+ // (.CONFIG\HUAWEICLOUD\SECRETS\.MASTER-KEY) resolves to the real
276
+ // credential file, while Node's non-native realpathSync preserves the
277
+ // caller's spelling instead of the on-disk one — a case-sensitive
278
+ // comparison then reads the attacker's spelling as a clean path and the
279
+ // floor refuses nothing. Lowercasing closes exactly that case-variant
280
+ // alias class and aligns the floor with the hook face's case-insensitive
281
+ // regex doctrine (policy patterns match with the 'i' flag). Trailing-dot
282
+ // and 8.3 short-name aliases ride the same spelling-preservation
283
+ // mechanism but are NOT normalized here — recorded residuals: they
284
+ // defeat the exact-name segment rules where one is the sole coverage,
285
+ // while the prefix rules (startsWith) and the vault tree's
286
+ // huaweicloud/secrets pair still cover the practical vault-key
287
+ // spellings. Pinned as non-matches in the driver battery.
288
+ //
289
+ // Drift direction, both changes: the floor only ever ADDS matches. On
290
+ // win32 a filename can contain neither a backslash nor (post-lowercase)
291
+ // a case distinction against the canonical tree, so every added match is
292
+ // a real credential path the floor was missing; on POSIX a distinct file
293
+ // whose name lowercases or backslash-splits onto a rule shape
294
+ // ('hcloud\credentials' as one name, a real 'HCloud/config' directory)
295
+ // picks up one extra refusal — the documented safe direction for a
296
+ // security floor, and the exhaustive direction probe over the alias
297
+ // enumeration confirms zero matches lost.
298
+ const segments = resolvedPath
299
+ .toLowerCase()
300
+ .split(/[\\/]/)
301
+ .filter((segment) => segment.length > 0);
302
+ for (let i = 0; i < segments.length; i += 1) {
303
+ const segment = segments[i]!;
304
+ if (segment.startsWith('.hcloud') || segment.startsWith('.huaweicloud')) return true;
305
+ if (segment === '.master-key' || segment === 'creds-import.json') return true;
306
+ if (segment === 'proc' && i + 2 < segments.length) {
307
+ const owner = segments[i + 1]!;
308
+ const file = segments[i + 2]!;
309
+ if ((owner === 'self' || /^\d+$/.test(owner)) && file === 'environ') return true;
310
+ }
311
+ const next = i + 1 < segments.length ? segments[i + 1]! : null;
312
+ if (
313
+ next &&
314
+ (segment === 'huaweicloud' || segment === 'hcloud') &&
315
+ (CREDS_FILE_NAMES.has(next) || (segment === 'huaweicloud' && next === 'secrets'))
316
+ ) {
317
+ return true;
318
+ }
319
+ }
320
+ return false;
321
+ }
322
+
323
+ // The home roots a tilde or $HOME spelling can mean: the real home, the
324
+ // process's HOME if set, and the devkit's home root (HUAWEICLOUD_HOME —
325
+ // the config tree, and therefore the credential files, relocate with it).
326
+ function homeRootsForSpelling(): ReadonlyArray<string> {
327
+ const configBase = huaweiConfigBase();
328
+ const roots = [homedir(), resolve(configBase, '..', '..')];
329
+ const envHome = process.env.HOME;
330
+ if (typeof envHome === 'string' && envHome !== '') roots.push(envHome);
331
+ return [...new Set(roots)];
332
+ }
333
+
334
+ // schemeSkip marks a WHOLE leaf: an obs:// operand on the OBS commands is
335
+ // a cloud object key, never a local file. An =-value spelling is NEVER
336
+ // scheme-skipped (interrogate round 5, shape 2): the child dereferences
337
+ // that channel as a file path regardless of the value's scheme spelling —
338
+ // --cli-jsonInput=obs://probe.json opens cwd/obs:/probe.json, measured
339
+ // live — so the value always resolves and refuses only when it resolves
340
+ // to an existing credential file.
341
+ function resolvedLeafCandidates(leaf: string, cwdBases: ReadonlyArray<string>, schemeSkip: boolean): string[] {
342
+ if (schemeSkip && OBS_URI_RE.test(leaf)) return []; // a cloud object key, never a local path
343
+ if (leaf === '') return []; // an empty spelling names no file the child can dereference
344
+ // Any other scheme-shaped leaf still resolves below as a potential LOCAL
345
+ // relative path: POSIX collapses the double slash, so join(base, 's3://k')
346
+ // is base/s3:/k — exactly the local file the child opens.
347
+ // Edge-quote strip: the child's shell would have removed them; the round-1
348
+ // vectors carry them.
349
+ const stripped = leaf.replace(/^['"]|['"]$/g, '');
350
+ const expanded: string[] = [stripped];
351
+ if (stripped.startsWith('~')) {
352
+ const tail = stripped.slice(1);
353
+ for (const root of homeRootsForSpelling()) expanded.push(join(root, tail));
354
+ } else if (/^\$\{?HOME\}?([/\\].*)?$/.test(stripped)) {
355
+ const tail = stripped.replace(/^\$\{?HOME\}?[/\\]?/, '');
356
+ for (const root of homeRootsForSpelling()) expanded.push(join(root, tail));
357
+ }
358
+ const candidates: string[] = [];
359
+ const tryResolve = (candidate: string): void => {
360
+ try {
361
+ candidates.push(realpathSync(candidate));
362
+ } catch {
363
+ // not an existing path from this base — the next candidate speaks
364
+ }
365
+ };
366
+ // Absolute spellings resolve on their own; relative and bare spellings
367
+ // against the child's bases only.
368
+ for (const candidate of expanded) {
369
+ if (candidate.startsWith('/') || /^[A-Za-z]:[\\/]/.test(candidate)) tryResolve(candidate);
370
+ }
371
+ for (const base of cwdBases) {
372
+ for (const candidate of expanded) {
373
+ if (!candidate.startsWith('/') && !/^[A-Za-z]:[\\/]/.test(candidate)) tryResolve(join(base, candidate));
374
+ }
375
+ }
376
+ return candidates;
377
+ }
378
+
379
+ function firstCredentialPathIn(value: unknown, cwdBases: ReadonlyArray<string>): string | null {
380
+ if (typeof value === 'string') {
381
+ if (value === '') return null; // a bare empty leaf dereferences nothing
382
+ // The whole leaf (scheme-skippable as a cloud operand), plus the VALUE
383
+ // half of an =-shaped leaf (rule a3) — the child splits on the first
384
+ // '=' and dereferences the value as a file path, so the value spelling
385
+ // is never scheme-skipped and never empty: an empty value is rejected
386
+ // by the child at parse level ([USE_ERROR] must be --param=value), it
387
+ // cannot name a file, and resolving it to the base directory would
388
+ // manufacture refusals (interrogate round 5, finding 3).
389
+ const eq = value.indexOf('=');
390
+ const valuePart = eq >= 0 ? value.slice(eq + 1) : null;
391
+ const spellings: Array<[string, boolean]> = [[value, true]];
392
+ if (valuePart !== null && valuePart !== '') spellings.push([valuePart, false]);
393
+ for (const [spelling, schemeSkip] of spellings) {
394
+ for (const resolved of resolvedLeafCandidates(spelling, cwdBases, schemeSkip)) {
395
+ if (isCredentialResolvedPath(resolved)) return resolved;
396
+ }
397
+ }
398
+ return null;
399
+ }
400
+ if (Array.isArray(value)) {
401
+ for (const item of value) {
402
+ const hit = firstCredentialPathIn(item, cwdBases);
403
+ if (hit !== null) return hit;
404
+ }
405
+ return null;
406
+ }
407
+ if (value !== null && typeof value === 'object') {
408
+ for (const leaf of Object.values(value)) {
409
+ const hit = firstCredentialPathIn(leaf, cwdBases);
410
+ if (hit !== null) return hit;
411
+ }
412
+ }
413
+ return null;
414
+ }
415
+
416
+ // The child's working directories, in spawn order: the call's own cwd when
417
+ // set, else the server process's cwd (spawn's default) — nothing else. Any
418
+ // wider base manufactured refusals for files the child cannot see.
419
+ function credentialBases(args: ToolArgs): ReadonlyArray<string> {
420
+ const bases = [typeof args.cwd === 'string' ? args.cwd : '', process.cwd()];
421
+ return [...new Set(bases.filter((base): base is string => base !== ''))];
422
+ }
423
+
424
+ function assertNoCredentialPath(value: unknown, args: ToolArgs): void {
425
+ const hit = firstCredentialPathIn(value, credentialBases(args));
426
+ if (hit !== null) {
427
+ throw new Error(
428
+ `Reading Huawei Cloud credential or profile files is blocked (argument "${hit.slice(0, 120)}"). ` +
429
+ 'Use redacted profile inspection tools instead.',
430
+ );
431
+ }
432
+ }
433
+
434
+ // A spec-provided classify is the grant requirement: the plan-face hcloud
435
+ // tool keeps the trunk's content-dependent gate (a read-classified command
436
+ // executes on an unconfirmed token). A registered tool with no classify
437
+ // always rides a human's grant.
438
+ function grantRequired(spec: ApprovalSpec, value: unknown, opts: CallToolOptions): boolean {
439
+ return spec.classify ? spec.classify(value, opts) === 'required' : true;
440
+ }
441
+
442
+ // The T3 envelope binding (interrogate round 2, finding 4): the chat
443
+ // round-trip is the only tier where the line the user reads and the line the
444
+ // gate executes are two messages, so the envelope's argsHash must be the
445
+ // binding, not a decoration. Every envelope emission records
446
+ // (session, tool, argsHash -> shownAt); an attested ask arrival executes only
447
+ // when its OWN argsHash has a live record. A drifted retry (different args)
448
+ // and a pre-attested first call (no record at all) both get the envelope for
449
+ // the line they are asking about, so the ritual always precedes the
450
+ // execution. TTL-bounded rather than single-use: the binding fact is "this
451
+ // exact line was shown", which stays true for the same command, and a lost
452
+ // record only costs one extra round-trip. Session-scoped through
453
+ // opts.sessionId, exactly like the token custody store is state-scoped.
454
+ export const ASK_ENVELOPE_TTL_MS = 30 * 60_000;
455
+ const shownAskEnvelopes = new Map<string, Map<string, number>>();
456
+
457
+ function askEnvelopeScope(sessionId: string, tool: string): string {
458
+ return `${sessionId}\u0000${tool}`;
459
+ }
460
+
461
+ /** Record that the T3 envelope for this exact line was shown in this session. */
462
+ export function noteAskEnvelopeShown(sessionId: string, tool: string, argsHash: string, at: number = Date.now()): void {
463
+ const scope = askEnvelopeScope(sessionId, tool);
464
+ const live = shownAskEnvelopes.get(scope) ?? new Map<string, number>();
465
+ live.set(argsHash, at);
466
+ shownAskEnvelopes.set(scope, live);
467
+ }
468
+
469
+ /** True when this exact line's envelope was shown in this session and is live. */
470
+ export function askEnvelopeLive(sessionId: string, tool: string, argsHash: string, at: number = Date.now()): boolean {
471
+ const scope = askEnvelopeScope(sessionId, tool);
472
+ const live = shownAskEnvelopes.get(scope);
473
+ if (!live) return false;
474
+ // Lazy prune: a session's expired records never accumulate (the map is the
475
+ // only growth surface of this mechanism).
476
+ for (const [hash, shownAt] of live) {
477
+ if (at - shownAt > ASK_ENVELOPE_TTL_MS) live.delete(hash);
478
+ }
479
+ if (live.size === 0) {
480
+ shownAskEnvelopes.delete(scope);
481
+ return false;
482
+ }
483
+ return live.has(argsHash);
484
+ }
485
+
486
+ // ── The S1 retry memo (PR-3a, interrogate round 2: in-memory) ─────────────
487
+ //
488
+ // A byte-identical repeat after a NON-DELIVERED outcome reuses the prior
489
+ // consent. The memo's state is the IN-MEMORY record of what the last
490
+ // 'once'-scoped consent's dispatch did — armed by the dispatch recorder
491
+ // from the COMPUTED outcome (uncertain/failed arm it, delivered clears it),
492
+ // never read back from the ledger. Three properties fall out, each pinned:
493
+ // the annotate is best-effort and may fail to write its outcome line, but
494
+ // the memo keys on the computed truth, so an unannotated delivered row
495
+ // never arms a reuse (round-2 F5); the state dies with the process like
496
+ // the T3 binding and the standing map, so a consent whose session ended
497
+ // can never arm a cross-process execution (DECISION 3, seat B's F6); and
498
+ // only 'once'-scoped arrivals feed it — a standing-consent tick's failed
499
+ // dispatch is the grant's own lifecycle, not memo fuel (F4).
500
+ const retryMemos = new Map<string, Map<string, boolean>>();
501
+
502
+ function memoScope(sessionId: string, tool: string): string {
503
+ return `${sessionId}\u0000${tool}`;
504
+ }
505
+
506
+ /** The dispatch recorder's arm/clear seam: one 'once' consent's outcome. */
507
+ export function noteRetryMemo(sessionId: string, tool: string, argsHash: string, covering: boolean): void {
508
+ const scope = memoScope(sessionId, tool);
509
+ const live = retryMemos.get(scope) ?? new Map<string, boolean>();
510
+ live.set(argsHash, covering);
511
+ retryMemos.set(scope, live);
512
+ }
513
+
514
+ /** True when the last 'once' consent on this exact key did not deliver. */
515
+ export function retryMemoArmed(sessionId: string, tool: string, argsHash: string): boolean {
516
+ const scope = memoScope(sessionId, tool);
517
+ return retryMemos.get(scope)?.get(argsHash) === true;
518
+ }
519
+
520
+ // ── S3 session standing consent (PR-3a) ────────────────────────────────────
521
+ //
522
+ // The elicitation form's "Remember for this session" tick grants standing
523
+ // consent for the exact (session, tool, argsHash) key: identical later
524
+ // executions ride the grant with no form, no envelope, and no new consent
525
+ // row. The grant PERSISTS for the session — it is never consumed by a ride
526
+ // (the first-use disappearance bug the ApprovalCoreConsent spec caught:
527
+ // ElicitAllowStanding's later executions must keep riding), and it dies
528
+ // only with the process, exactly like the T3 binding map above: a server
529
+ // restart forgets it fail-closed, and the retry asks again. The durable
530
+ // record is the scope:'session' consent row the tick writes through the
531
+ // ledger's tier-safe scoped writer (the row the doctor lists); this map is
532
+ // the ride check and the in-memory lifetime.
533
+ const standingGrants = new Map<string, Map<string, number>>();
534
+
535
+ function standingScope(sessionId: string, tool: string): string {
536
+ return `${sessionId}\u0000${tool}`;
537
+ }
538
+
539
+ /** Record the session standing-consent grant the form's tick just created. */
540
+ export function noteStandingGrant(sessionId: string, tool: string, argsHash: string, at: number = Date.now()): void {
541
+ const scope = standingScope(sessionId, tool);
542
+ const live = standingGrants.get(scope) ?? new Map<string, number>();
543
+ live.set(argsHash, at);
544
+ standingGrants.set(scope, live);
545
+ }
546
+
547
+ /** True when the session's standing-consent grant covers this exact key. */
548
+ export function standingGrantLive(sessionId: string, tool: string, argsHash: string): boolean {
549
+ const scope = standingScope(sessionId, tool);
550
+ const live = standingGrants.get(scope);
551
+ return live !== undefined && live.has(argsHash);
552
+ }
553
+
554
+ // ── The server-run confirmation ladder (PR-1.5) ───────────────────────────
555
+ //
556
+ // Ask mode no longer trusts a client popup. On a client that declared the
557
+ // elicitation form capability in its initialize params, the gate raises the
558
+ // form itself (T1): the form body carries the command line and the redacted
559
+ // summarize view, and one boolean field is the approval. On a client that
560
+ // declared nothing, the gate refuses with a chat round-trip envelope (T3):
561
+ // the model must show the command to the user and retry with the attestation,
562
+ // which is model-relayed posture trust and every surface labels it so.
563
+ // Token mode (T4) is untouched.
564
+ export const ELICITATION_DECLINED = 'ELICITATION_DECLINED';
565
+ export const ELICITATION_CANCELLED = 'ELICITATION_CANCELLED';
566
+ export const ELICITATION_TIMEOUT = 'ELICITATION_TIMEOUT';
567
+ export const ELICITATION_FAILED = 'ELICITATION_FAILED';
568
+ export const ELICITATION_INVALID_CONTENT = 'ELICITATION_INVALID_CONTENT';
569
+ export const ASK_CONFIRMATION_REQUIRED = 'ASK_CONFIRMATION_REQUIRED';
570
+
571
+ // The explicit abstention bound. The SDK's 60 s default is the no-answer
572
+ // bound the probe measured (-32001), and it is shorter than a human reading
573
+ // a command line; five minutes leaves room to read and answer without
574
+ // leaving an unresponsive client able to stall a call indefinitely.
575
+ export const ELICITATION_TIMEOUT_MS = 300_000;
576
+
577
+ // The enum's VALUES are wire vocabulary and never localize: the gate
578
+ // matches them, the ledger and the tests pin them, and a client that
579
+ // ignores enumNames (codex renders raw values) still shows the English
580
+ // spelling the description teaches. The pre-enum shape was two booleans
581
+ // (confirm + rememberForSession), and three measured facts forced the
582
+ // merge: codex renders one field per screen, so two booleans were two
583
+ // interactions for one decision; the boolean pair admitted a meaningless
584
+ // confirm:false + remember:true submission the gate had to silently
585
+ // ignore; and opencode's Submit always answers accept, so with a boolean
586
+ // the refusal only existed as the unticked default — the #58184 wire
587
+ // measurement. The enum makes the refusal an explicit choice, keeps the
588
+ // once/session grant one click away, and stays inside the restricted flat
589
+ // schema the form mode accepts (string + enum). 'decline' is listed FIRST
590
+ // so a client that preselects the first option defaults to the refusal.
591
+ const ELICITATION_DECISIONS = ['decline', 'approve-once', 'approve-session'] as const;
592
+
593
+ // The form is the one surface the HUMAN reads, so its display language
594
+ // follows the resolved tier ladder (lib/confirm-language.ts): the
595
+ // operator's DEVKIT_CONFIRM_LANG pin, the model's per-call
596
+ // confirmLanguage relay of the conversation's language, or the machine
597
+ // locale as the floor. A zh resolution renders the form in Simplified
598
+ // Chinese; the refusal envelopes and the T3 instruction stay English,
599
+ // being model- and log-facing wire vocabulary. enumNames is a
600
+ // first-class SDK 1.32.1 keyword (LegacyTitledEnumSchemaSchema carries it,
601
+ // probe-verified to round-trip intact) that opencode renders as the
602
+ // choice labels (source-verified in toElicitationField); a client that
603
+ // ignores the extension falls back to the English enum value.
604
+ function elicitSchema(language: ConfirmLanguage): ElicitFormSchema {
605
+ const decision: Record<string, unknown> = {
606
+ type: 'string',
607
+ enum: [...ELICITATION_DECISIONS],
608
+ };
609
+ if (language === 'zh') {
610
+ decision['enumNames'] = ['拒绝', '批准本次', '批准并记住本次会话'];
611
+ decision['title'] = '运行此命令?';
612
+ decision['description'] =
613
+ 'approve-once:仅运行这一次。approve-session:同一会话内后续相同调用不再询问(授权持续到 devkit 服务器重启)。decline:拒绝,不执行任何操作。';
614
+ } else {
615
+ decision['title'] = 'Run this command?';
616
+ decision['description'] =
617
+ 'approve-once runs it exactly once. approve-session also covers identical later calls in this session (the grant lasts until the devkit server restarts). decline cancels it.';
618
+ }
619
+ return { type: 'object', properties: { decision }, required: ['decision'] };
620
+ }
621
+
622
+ function elicitationRequest(commandLine: string, summary: string, language: ConfirmLanguage): ElicitFormRequest {
623
+ // A tool with an executable line shows it first (the command-forward
624
+ // doctrine); a tool without one (the sandbox lifecycle faces, the auth
625
+ // pair, PR-3c's registrations) centers the redacted summary instead —
626
+ // never a blank command slot under a command heading (interrogate
627
+ // round 2, fix-in-pass ii, adopted by the serial landing). The display
628
+ // strings follow the resolved language (see lib/confirm-language.ts);
629
+ // the brand and the decision vocabulary stay English.
630
+ const zh = language === 'zh';
631
+ const head =
632
+ commandLine !== ''
633
+ ? zh
634
+ ? `HuaweiCloud DevKit 请求你确认运行此命令:\n\n${commandLine}\n\n`
635
+ : `HuaweiCloud DevKit is requesting your confirmation to run this command:\n\n${commandLine}\n\n`
636
+ : zh
637
+ ? 'HuaweiCloud DevKit 请求你确认此操作:\n\n'
638
+ : 'HuaweiCloud DevKit is requesting your confirmation for this request:\n\n';
639
+ const tail = zh
640
+ ? '选择 approve-once 仅运行这一次;选择 approve-session 同时覆盖本会话内后续相同调用(授权持续到 devkit 服务器重启);拒绝或关闭表单则不执行任何操作。'
641
+ : 'Choose approve-once to run it exactly once, or approve-session to also cover identical later calls in this session (the grant lasts until the devkit server restarts). Decline or dismiss cancels without running anything.';
642
+ return {
643
+ message: head + `${summary}\n\n` + tail,
644
+ schema: elicitSchema(language),
645
+ timeoutMs: ELICITATION_TIMEOUT_MS,
646
+ };
647
+ }
648
+
649
+ function elicitRefusal(outcome: ElicitOutcome, displayLine: string): Record<string, unknown> {
650
+ const nextStep = 'Nothing ran and nothing was approved. Retry the call when the user is ready to answer the form.';
651
+ if (outcome.decision === 'timeout') {
652
+ return {
653
+ status: 'rejected',
654
+ code: ELICITATION_TIMEOUT,
655
+ reason: `the confirmation form was not answered within ${Math.round(ELICITATION_TIMEOUT_MS / 1000)} s.`,
656
+ command: displayLine,
657
+ nextStep,
658
+ };
659
+ }
660
+ if (outcome.decision === 'error') {
661
+ return {
662
+ status: 'rejected',
663
+ code: ELICITATION_FAILED,
664
+ reason: `the client could not deliver the confirmation form (${outcome.detail ?? 'transport failure'}).`,
665
+ command: displayLine,
666
+ nextStep,
667
+ };
668
+ }
669
+ const cancelled = outcome.decision === 'cancel';
670
+ return {
671
+ status: 'rejected',
672
+ code: cancelled ? ELICITATION_CANCELLED : ELICITATION_DECLINED,
673
+ reason: cancelled
674
+ ? 'the user dismissed the confirmation form without approving.'
675
+ : 'the user declined the confirmation form.',
676
+ command: displayLine,
677
+ nextStep: 'Nothing ran. Do not retry the same call without a fresh approval from the user.',
678
+ };
679
+ }
680
+
681
+ // T3: the client cannot render a form, so the model is the relay. The
682
+ // envelope names the line it must show — the executable command when the
683
+ // tool carries one, else the redacted summary (the commandless faces have
684
+ // no command string) — and the exact retry that continues; the refusals
685
+ // below and the ledger tier keep the posture labelled where a later
686
+ // reader meets it.
687
+ function askConfirmationEnvelope(
688
+ commandLine: string,
689
+ summary: string,
690
+ view: { argsHash: string },
691
+ ): Record<string, unknown> {
692
+ const askLine =
693
+ commandLine !== '' ? 'Show this exact command to the user in chat' : 'Show this exact request to the user in chat';
694
+ return {
695
+ status: 'rejected',
696
+ code: ASK_CONFIRMATION_REQUIRED,
697
+ userConfirmation: {
698
+ needed: true,
699
+ mode: 'chat',
700
+ command: commandLine !== '' ? commandLine : undefined,
701
+ summary,
702
+ instruction:
703
+ `${askLine} and wait for their answer. If they approve, retry the same call ` +
704
+ "with approvedByUser: true. That retry is model-relayed posture trust: it is the user's word as you report it, " +
705
+ 'not a mechanically verified answer.',
706
+ },
707
+ argsHash: view.argsHash,
708
+ nextStep: 'Retry with approvedByUser: true only after the user explicitly approves the request above.',
709
+ };
710
+ }
711
+
712
+ export async function runApprovalGate(
713
+ name: ToolName,
714
+ spec: ApprovalSpec,
715
+ args: ToolArgs,
716
+ opts: CallToolOptions,
717
+ ): Promise<ApprovalGateOutcome> {
718
+ // Seam precheck first: packs_configure's own refusal lives inside its
719
+ // handler, downstream of this gate, so the gate is the only place the
720
+ // ordering rule (refuse with no token minted, no ledger entry) can be
721
+ // enforced (ApprovalCoreMint GateMintSeam's disabled-guard posture).
722
+ if (spec.requiresSessionSeam && !opts.onPacksChanged) {
723
+ return { envelope: { ok: false, error: NO_SESSION_SEAM_ERROR } };
724
+ }
725
+
726
+ // The approval posture resolves once, before any effect: a bogus
727
+ // DEVKIT_APPROVAL_MODE is boot fail-fast, never a silent fallback.
728
+ const approvalMode = approvalModeFromEnv(process.env);
729
+
730
+ const token = typeof args.approvalToken === 'string' ? args.approvalToken : '';
731
+
732
+ // The attestation's scope (PR-3b's adopted line, landed here so the
733
+ // registrations' teaching is true at landing): the plan-face tool always
734
+ // demands it (the trunk contract the hcloud battery pins), and EVERY
735
+ // tool demands it once a token rides the call — the token's spend is the
736
+ // confirmed execution, so the agent's statement is part of that
737
+ // contract. Ask mode demands nothing: EVERY arrival there is server-run
738
+ // confirmed — the form on a capable client, the chat envelope on the
739
+ // rest — and the human's answer is the confirmation the attestation only
740
+ // claims, so the bare pass-through that once let a commandless attested
741
+ // arrival execute with no confirmation surface at all is closed (the
742
+ // live incident: run rows with posture evidence, zero forms, zero
743
+ // envelopes). The throw below is therefore token-mode-only.
744
+ const attestationRequired = spec.tokenSource === 'plan-face' || token !== '';
745
+ if (args.approvedByUser !== true && attestationRequired && approvalMode !== 'ask') {
746
+ throw new Error('approvedByUser must be true after explicit user approval for this exact command.');
747
+ }
748
+
749
+ const value = bindingValue(spec, args);
750
+
751
+ // The command-forward anchor precedes every mode effect (see the helper):
752
+ // a mismatched or malformed display line rejects with nothing minted,
753
+ // recorded, or executed.
754
+ const commandRefusal = commandAnchorRefusal(spec, value, args.command);
755
+ if (commandRefusal !== null) return { envelope: commandRefusal };
756
+
757
+ // Classified flavor engages on content: a classify that says 'none'
758
+ // needs no consent, so no mint, no ledger entry, no gate. The verdict is
759
+ // computed once here and consulted per-branch below, and the floors run
760
+ // BEFORE it (interrogate round 2, finding 5): a credential path in the
761
+ // binding refuses regardless of the flavor outcome — the pass-through
762
+ // skips consent machinery, never safety floors.
763
+ const classifiedPass = spec.flavor === 'classified' && spec.classify?.(value, opts) === 'none';
764
+
765
+ if (approvalMode === 'ask') {
766
+ // Floors first, so a refused call is not a consent arrival; a classified
767
+ // pass-through sits after the floors and skips only the consent record.
768
+ assertNoCredentialPath(value, args);
769
+ spec.assertArgsExecutable?.(value, 'ask');
770
+ if (classifiedPass) return { pass: {}, binding: value };
771
+
772
+ const view = spec.summarize(value);
773
+ // The display line every confirmation surface shows: the REDACTED
774
+ // view.command — the same redaction the pin view carries — never the
775
+ // raw args.command the anchor validated (interrogate F1: the form head
776
+ // and the T3 envelope echoed a plaintext secret from the raw field).
777
+ // The legacy args-only shape keeps its redacted echo; the no-command
778
+ // faces show the summary alone (never a blank command slot,
779
+ // interrogate round 2 fix-in-pass ii).
780
+ const commandLine = view.command ?? '';
781
+ const sessionId = opts.sessionId ?? 'default';
782
+ const consented = (evidence: 'elicitation' | 'posture'): ApprovalGateOutcome => {
783
+ const arrival = recordAskModeConsent({
784
+ sessionId,
785
+ tool: name,
786
+ argsHash: view.argsHash,
787
+ outcome: 'granted',
788
+ evidence,
789
+ evidenceFinal: true,
790
+ command: view.command,
791
+ });
792
+ // The arrival's IDENTITY (round 15, finding 2): the stamp AND the seq —
793
+ // the dispatch layer threads both to the delivery recorder so the
794
+ // annotate binds the outcome line to EXACTLY the row this arrival
795
+ // wrote, never to a positional candidate (a same-ms twin compacted in
796
+ // behind used to steal the line). The binding rides along: the value
797
+ // resolved BEFORE the confirmation surface was shown, so a credential-
798
+ // consuming handler executes the approved snapshot, never a
799
+ // post-consent re-read (PR-3b's TOCTOU finding — the shown account is
800
+ // the executed account).
801
+ return {
802
+ pass: { arrivalStamp: arrival.grantedAt, arrivalSeq: arrival.arrivalSeq, consentScope: 'once' },
803
+ binding: value,
804
+ };
805
+ };
806
+
807
+ // S3 standing consent: a grant the user ticked covers identical later
808
+ // executions for the session. The ride writes NO new consent row (the
809
+ // grant row is the durable record; the TLA+ StandingRun models the ride,
810
+ // not a new consent) and never consumes the grant — the first-use
811
+ // disappearance bug the spec caught.
812
+ if (standingGrantLive(sessionId, name, view.argsHash)) {
813
+ return { pass: { approvedVia: 'standing-session' }, binding: value };
814
+ }
815
+
816
+ // The S1 retry memo: a byte-identical repeat after a non-delivered
817
+ // outcome reuses the prior consent — no second form, no fresh envelope
818
+ // (the carve the T3 binding's arrival condition needed: an attested
819
+ // retry whose shown-envelope record expired rides the memo instead of
820
+ // silently degrading to a fresh chat round-trip). The reuse row
821
+ // inherits the original's evidence tier through the ledger's
822
+ // never-upgrade resolution (the caller's tier is only the no-original
823
+ // fallback, so the posture floor holds), the arrival identity rides
824
+ // the pass so this dispatch's own outcome re-arms or clears the memo
825
+ // for the next identical call, and the consent scope stays 'once'.
826
+ if (retryMemoArmed(sessionId, name, view.argsHash)) {
827
+ const arrival = recordAskModeConsent({
828
+ sessionId,
829
+ tool: name,
830
+ argsHash: view.argsHash,
831
+ outcome: 'granted',
832
+ evidence: 'posture',
833
+ command: view.command,
834
+ });
835
+ return {
836
+ pass: {
837
+ approvedVia: 'retry-uncertain',
838
+ arrivalStamp: arrival.grantedAt,
839
+ arrivalSeq: arrival.arrivalSeq,
840
+ consentScope: 'once',
841
+ },
842
+ binding: value,
843
+ };
844
+ }
845
+
846
+ // T1: the client declared elicitation.form, so the gate raises the form
847
+ // itself. The accept IS the confirmation (the attestation is not
848
+ // consulted: a human answered, which is strictly stronger). Any other
849
+ // answer — decline, dismiss, the explicit timeout, a transport failure,
850
+ // an accept that chose decline, or an accept whose content carries no
851
+ // valid decision value — refuses fail-closed: nothing executes, nothing
852
+ // mints, nothing is recorded.
853
+ // The form's display language resolves per arrival (the operator pin,
854
+ // the model's confirmLanguage relay, the machine locale — in that
855
+ // order; lib/confirm-language.ts owns the ladder).
856
+ const language: ConfirmLanguage = resolveConfirmLanguage(args, process.env);
857
+ const elicitation = opts.elicitation;
858
+ if (elicitation?.capable) {
859
+ const outcome = await elicitation.prompt(elicitationRequest(commandLine, view.summary, language));
860
+ // The enum's three values map the ladder: decline is the explicit
861
+ // refusal; approve-once is a fresh single consent; approve-session
862
+ // additionally arms the S3 standing grant. An accept with a MISSING or
863
+ // unknown decision value gets its own refusal code: hermes answers the
864
+ // form path with accept and empty content (measured in its source —
865
+ // its panel never synthesizes answers from the schema it was shown),
866
+ // and that shape must be diagnosable from the refusal alone instead
867
+ // of reading as a generic transport failure.
868
+ const decision = outcome.decision === 'accept' ? outcome.content?.['decision'] : undefined;
869
+ if (
870
+ decision === undefined ||
871
+ typeof decision !== 'string' ||
872
+ !(ELICITATION_DECISIONS as readonly string[]).includes(decision)
873
+ ) {
874
+ if (outcome.decision !== 'accept') return { envelope: elicitRefusal(outcome, commandLine) };
875
+ return {
876
+ envelope: {
877
+ status: 'rejected',
878
+ code: ELICITATION_INVALID_CONTENT,
879
+ reason:
880
+ 'the client answered accept but the submitted form content carries no valid decision value — the client did not answer the form schema it was shown.',
881
+ command: commandLine,
882
+ nextStep:
883
+ 'Nothing ran and nothing was approved. The client must submit one of: decline, approve-once, approve-session.',
884
+ },
885
+ };
886
+ }
887
+ if (decision === 'decline') {
888
+ // The explicit refusal choice maps to the same fail-closed envelope
889
+ // as the wire-level decline (the pre-enum shape reached this branch
890
+ // through the confirm:false rewrite; the enum makes it a first-class
891
+ // answer).
892
+ return {
893
+ envelope: {
894
+ status: 'rejected',
895
+ code: ELICITATION_DECLINED,
896
+ reason: 'the user declined the confirmation form.',
897
+ command: commandLine,
898
+ nextStep: 'Nothing ran. Do not retry the same call without a fresh approval from the user.',
899
+ },
900
+ };
901
+ }
902
+ // The standing-consent choice: this execution is a fresh consent (the
903
+ // row carries the elicitation evidence and the session scope — the
904
+ // durable grant record the doctor lists), and the in-memory grant
905
+ // covers identical later executions until the process dies. The
906
+ // scope-'session' pass is the recorder's memo-exclusion signal: the
907
+ // grant's own delivery outcome is the grant's lifecycle, never memo
908
+ // fuel (round-2 F4).
909
+ if (decision === 'approve-session') {
910
+ noteStandingGrant(sessionId, name, view.argsHash);
911
+ const arrival = recordAskModeConsent({
912
+ sessionId,
913
+ tool: name,
914
+ argsHash: view.argsHash,
915
+ outcome: 'granted',
916
+ evidence: 'elicitation',
917
+ evidenceFinal: true,
918
+ command: view.command,
919
+ scope: 'session',
920
+ });
921
+ return {
922
+ pass: { arrivalStamp: arrival.grantedAt, arrivalSeq: arrival.arrivalSeq, consentScope: 'session' },
923
+ binding: value,
924
+ };
925
+ }
926
+ return consented('elicitation');
927
+ }
928
+
929
+ // T3: no form capability. The attested path executes only when THIS
930
+ // line's envelope was shown in this session (see the binding state
931
+ // above): the args hash the envelope advertised is the binding, so a
932
+ // retry for different args — and a pre-attested first call — gets the
933
+ // envelope for the line they ask about instead of executing. The refusal
934
+ // teaches the ritual for the new line, so the proper envelope-then-retry
935
+ // still completes. The binding covers EVERY ask arrival — the
936
+ // commandless bare-attestation pass-through (once this block's skipped
937
+ // shape, executing with no confirmation surface at all) is the hole
938
+ // this doctrine closed.
939
+ const envelopeShown = askEnvelopeLive(sessionId, name, view.argsHash);
940
+ if (args.approvedByUser !== true || !envelopeShown) {
941
+ noteAskEnvelopeShown(sessionId, name, view.argsHash);
942
+ return { envelope: askConfirmationEnvelope(commandLine, view.summary, view) };
943
+ }
944
+ return consented('posture');
945
+ }
946
+
947
+ if (!token) {
948
+ // plan-face keeps the trunk contract: the plan face is the only
949
+ // minter, so a no-token run call is a not-found rejection and the
950
+ // gate mints nothing. The floors do not preempt this envelope — trunk
951
+ // classified nothing on a tokenless call, and the plan face's own hook
952
+ // deny already covers the credential class at plan time.
953
+ if (spec.tokenSource === 'plan-face') {
954
+ return { envelope: { status: 'rejected', code: 'CONFIRM_TOKEN_NOT_FOUND' } };
955
+ }
956
+ // Gate-source mint face (PR-3 registrations; ApprovalCoreMint's
957
+ // classify-before-mint). BOTH floors sit before the mint for the same
958
+ // reason classify does: never mint a token for a call the gate would
959
+ // refuse (NoDoomedToken's posture, one class wider) — the round-2
960
+ // token-mode branch ran only the credential floor, minting a token for
961
+ // content the spec's execution floor refuses. A classified
962
+ // pass-through skips the mint and the floors never.
963
+ assertNoCredentialPath(value, args);
964
+ spec.assertArgsExecutable?.(value, 'token');
965
+ if (classifiedPass) return { pass: {}, binding: value };
966
+ const view = spec.summarize(value);
967
+ const minted = createApprovalToken(value, { secretsSubstitutable: false, argsPinView: view.pinView });
968
+ return {
969
+ envelope: {
970
+ status: 'rejected',
971
+ code: 'USER_CONFIRMATION_REQUIRED',
972
+ approvalToken: minted,
973
+ userConfirmation: {
974
+ needed: true,
975
+ // Order matters: the summarize view carries its own `command`
976
+ // (the redacted executable line, PR-1.5), and spreading it after
977
+ // this line overwrote the approve command the user must run.
978
+ ...view,
979
+ command: `npx huaweicloud-devkit approve ${minted}`,
980
+ },
981
+ nextStep: GRANT_REQUIRED_NEXT_STEP,
982
+ },
983
+ };
984
+ }
985
+
986
+ // With a token, the gate runs the existing lifecycle classification
987
+ // (D4-24 precise JSON contract) on the same inspect the trunk handler
988
+ // used, then the consume flow.
989
+ const inspection = inspectApprovalToken(token);
990
+ if (inspection.state === 'already_consumed') {
991
+ return { envelope: { status: 'ok', outcome: 'already_processed' } };
992
+ }
993
+ if (inspection.state === 'expired') {
994
+ return { envelope: { status: 'rejected', code: 'CONFIRM_TOKEN_EXPIRED' } };
995
+ }
996
+ if (inspection.state === 'not_found') {
997
+ // A token that was never created (typo / unknown / pruned beyond the
998
+ // tombstone window) is still a rejection, but carries no expired or
999
+ // already semantics — a distinct code so clients can tell them apart.
1000
+ return { envelope: { status: 'rejected', code: 'CONFIRM_TOKEN_NOT_FOUND' } };
1001
+ }
1002
+
1003
+ // Credential floor before the consume, so the refusal burns nothing and
1004
+ // the guidance stays followable on the same token; the execution floor
1005
+ // (placeholder secrets) rides the same placement for the same reason.
1006
+ assertNoCredentialPath(value, args);
1007
+ spec.assertArgsExecutable?.(value, 'token');
1008
+
1009
+ // One snapshot: the confirmation gate, the args-hash binding, the pinView
1010
+ // fallback, and the single-use claim all read the SAME entry — the one
1011
+ // consumeApprovalToken returns (the TOCTOU contract).
1012
+ const consumed = consumeApprovalToken(token, { requireGrant: grantRequired(spec, value, opts) });
1013
+ if (consumed.status === 'grant_required') {
1014
+ return { envelope: { status: 'rejected', code: 'USER_CONFIRMATION_REQUIRED', nextStep: GRANT_REQUIRED_NEXT_STEP } };
1015
+ }
1016
+ if (consumed.status === 'gone') {
1017
+ // Defensive: inspectApprovalToken said 'valid' but consume returned
1018
+ // gone — the O_EXCL claim losing a race or a store swap between the
1019
+ // two reads. Classify via re-inspect, never a misleading success and
1020
+ // never a false not_found.
1021
+ const recheck = inspectApprovalToken(token);
1022
+ if (recheck.state === 'expired') return { envelope: { status: 'rejected', code: 'CONFIRM_TOKEN_EXPIRED' } };
1023
+ return { envelope: { status: 'ok', outcome: 'already_processed' } };
1024
+ }
1025
+
1026
+ const stored = consumed.entry;
1027
+ const view = spec.summarize(value);
1028
+ if (view.argsHash !== stored.argsHash) {
1029
+ // The pin view is the canonical fold for the substitution comparison:
1030
+ // pre-schema entries (no argsPinView) fall back to the redactor form.
1031
+ const storedView = JSON.stringify(stored.argsPinView ?? stored.argsRedacted);
1032
+ const providedView = JSON.stringify(view.pinView);
1033
+ if (storedView !== providedView) {
1034
+ throw new Error(
1035
+ 'Provided args do not match the approved confirmation. Use the exact args the confirmation shows. ' +
1036
+ 'If it shows <redacted> for passwords or secrets, replace <redacted> with the actual values.',
1037
+ );
1038
+ }
1039
+ // Views equal means ONLY secret values differ. The confirmed call carried real
1040
+ // (non-placeholder) secrets → they are pinned: a different real secret
1041
+ // rejects. A placeholder-bearing confirmation (secretsSubstitutable) keeps
1042
+ // the documented substitution flow.
1043
+ if (stored.secretsSubstitutable !== true) {
1044
+ throw new Error(
1045
+ 'Secret values are pinned to the approved confirmation: get a fresh confirmation for the final values and retry with it.',
1046
+ );
1047
+ }
1048
+ }
1049
+
1050
+ // The token spent and the binding verified: the registered handler runs
1051
+ // the pure execution it owns. The binding rides along: this call's
1052
+ // recomputed resolution, which the hash comparison just proved equal to
1053
+ // the minted one, so the handler executes exactly what was approved —
1054
+ // never a post-consent re-read (PR-3b's TOCTOU finding).
1055
+ return { pass: {}, binding: value };
1056
+ }
1057
+
1058
+ // The dispatch-result follow-up (round 10, finding 4, PR-3a's memo
1059
+ // datum): after the pack handler the gate's caller dispatched returns —
1060
+ // or throws — callTool hands the result here, and this records what
1061
+ // became of the call the gate approved, on the gate's behalf. The gate
1062
+ // itself returns a structured pass before dispatch (its ask branch carries
1063
+ // the arrival's stamp — the recorded PR-3a approvedVia precursor); the
1064
+ // dispatch layer is the only place that ever sees the handler's return or
1065
+ // throw, so it is the only place the delivery class can be observed.
1066
+ //
1067
+ // The classes, from the handler's return or throw: 'delivered' when the
1068
+ // returned result carries no failure marks, 'failed' when the child
1069
+ // ANSWERED with a failure, 'uncertain' when the handler threw and whether
1070
+ // the call completed is unknowable. PR-3a's S1 memo reuses a prior
1071
+ // consent exactly on 'uncertain' or 'failed' (ApprovalCoreConsent's
1072
+ // result-conditioned scope).
1073
+ //
1074
+ // Ownership by stamp (round 12, finding 2, both seats' shape): the
1075
+ // arrival stamp the gate returned MUST reach the annotate — no stamp
1076
+ // (a recorder call without one, token mode where no arrival was
1077
+ // recorded, any failure) means no annotate, ever, because absence never
1078
+ // proves which row this dispatch created. The annotate then requires a
1079
+ // row with EXACTLY that stamp in the main store, so a dropped or degraded
1080
+ // arrival's outcome lands nowhere at all.
1081
+ //
1082
+ // Best-effort in every direction: ask mode only (token mode records no
1083
+ // arrival, so there is no row to annotate — and the check keeps the
1084
+ // default-mode dispatch path free of any ledger work), no-ops without a
1085
+ // spec, and never throws — a recording failure must never fail the call
1086
+ // it is recording.
1087
+ export function recordApprovalDispatchOutcome(
1088
+ name: ToolName,
1089
+ spec: ApprovalSpec | undefined,
1090
+ args: ToolArgs,
1091
+ opts: CallToolOptions,
1092
+ handlerResult: unknown,
1093
+ handlerThrew?: unknown,
1094
+ arrivalStamp?: number,
1095
+ arrivalSeq?: number,
1096
+ consentScope?: ApprovalConsentScope,
1097
+ ): void {
1098
+ try {
1099
+ if (!spec) return;
1100
+ if (approvalModeFromEnv(process.env) !== 'ask') return; // no ask arrival was recorded
1101
+ const outcomeDetail: ConsentDeliveryOutcome =
1102
+ handlerThrew !== undefined ? 'uncertain' : handlerResultCarriesFailure(handlerResult) ? 'failed' : 'delivered';
1103
+ // The retry memo's state (interrogate round 2): armed from the COMPUTED
1104
+ // outcome, before the best-effort annotate and independent of its
1105
+ // success — a failed annotate may leave the ledger row without its
1106
+ // outcome line, but the memo never reads the ledger back, so an
1107
+ // unannotated delivered row can never arm a reuse (F5). Only
1108
+ // 'once'-scoped arrivals feed it; a standing tick's outcome is the
1109
+ // grant's own lifecycle, not memo fuel (F4).
1110
+ if (consentScope === 'once' && typeof arrivalStamp === 'number') {
1111
+ noteRetryMemo(
1112
+ opts.sessionId ?? 'default',
1113
+ name,
1114
+ hashArgs(bindingValue(spec, args)),
1115
+ outcomeDetail !== 'delivered',
1116
+ );
1117
+ }
1118
+ annotateDispatchOutcome({
1119
+ sessionId: opts.sessionId ?? 'default',
1120
+ tool: name,
1121
+ argsHash: hashArgs(bindingValue(spec, args)),
1122
+ arrivalStamp,
1123
+ arrivalSeq,
1124
+ outcomeDetail,
1125
+ });
1126
+ } catch {
1127
+ // best-effort by contract: the dispatch outcome is a convenience
1128
+ // datum; the consent (the safety-critical fact) is already recorded
1129
+ }
1130
+ }
1131
+
1132
+ // The failure-mark reader for the three-valued delivery classification
1133
+ // (rounds 11-12): a returned result is 'failed' when the child ANSWERED
1134
+ // with a failure — by any of the shapes the handler families report it
1135
+ // in. Round 12, finding 1 (both seats, complementary shapes) fixed the
1136
+ // reading ORDER: an EXPLICIT success signal wins before every failure
1137
+ // mark. The run engine's own ok gate returns ok:true with a NONZERO
1138
+ // exitCode for OBS success (obsutil exits nonzero on success text —
1139
+ // repo-pinned #921), so an unconditional exitCode mark recorded a
1140
+ // delivered OBS write as failed; the PR-3c handler successes carry
1141
+ // benign human-facing message fields, so an unconditional message mark
1142
+ // recorded every successful signed PUT and upgrade as failed. The
1143
+ // permissive direction makes it worse than cosmetic: PR-3a's memo
1144
+ // reuses prior consent exactly on failed/uncertain, so a delivered call
1145
+ // recorded failed grants the next identical call a popup-free reuse.
1146
+ //
1147
+ // The order: (1) explicit success — ok === true, success === true, or
1148
+ // status === 'ok' — short-circuits to delivered, whatever failure-shaped
1149
+ // fields ride along; (2) an ok field that is not success is the explicit
1150
+ // verdict (false or the loose string 'false' → failed); (3) exitCode
1151
+ // marks ONLY when the shape carries no ok field at all (the sandbox exec
1152
+ // faces' {stdout, exitCode} — the r11 shapes exitCode:1 stays failed,
1153
+ // exitCode:0 delivered); (4) a rejected/error status; (5) an
1154
+ // error-truthy error/errorMessage/message value. A RETURNED Error
1155
+ // instance is judged failed, recorded honestly: a returned error is an
1156
+ // ANSWER (the handler decided the call failed), not an uncertainty —
1157
+ // the thrown leg above stays the only 'uncertain'. Every other returned
1158
+ // shape — no success signal, no failure marks — is 'delivered' (the
1159
+ // void handler, the async-start receipt {started:'uncertain'}: an
1160
+ // accepted start is a delivered dispatch, and the async completion is
1161
+ // the poll call's own result).
1162
+ // The benign-message content test (round 14, finding 3; rounds 15-16,
1163
+ // findings 3/4 — both seats both rounds): the failure vocabulary the real
1164
+ // handlers' message channels use, both languages — small and honest, not
1165
+ // a heuristic. Round 15 added a 16-char negation proximity window; round
1166
+ // 16 falsified it in BOTH directions: a REAL failure behind a verb-
1167
+ // negation read delivered (无法确认,查询失败 / 无法完成提交,操作失败 —
1168
+ // 无法 and 未通过 negate the VERB, not the failure noun that follows, so
1169
+ // six genuine error reports recorded delivered), and genuinely benign
1170
+ // absence phrasings read failed (error-free / 0 errors / cannot be any
1171
+ // error / 错误未发生). Proximity cannot decide polarity in either
1172
+ // language, so the window is GONE: the test now runs on an explicit
1173
+ // absence vocabulary. A message whose failure markers are all covered by
1174
+ // an explicit absence phrase (the marker negated by construction: "no
1175
+ // error", "0 errors", "error-free", 未发生错误, 无 error, nothing to do,
1176
+ // 已是最新, 无需升级) is benign by CONTENT — the absence phrases are
1177
+ // stripped before the scan, so a failure marker OUTSIDE them always
1178
+ // wins, whatever negation characters surround it: 查询失败 and "failed to
1179
+ // write config" record failed regardless of the 无 in 无法 or a leading
1180
+ // "no error in cleanup" clause, and the real failure envelope
1181
+ // 无法确认最新版本(registry 查询失败) keeps its hit. The ZH markers get
1182
+ // NO character-level negation logic at all (round 16's explicit call):
1183
+ // 无/未/没有 are not negation morphemes for the failure nouns, only the
1184
+ // enumerated phrases are.
1185
+ const MESSAGE_FAILURE_MARKERS = [
1186
+ 'failed',
1187
+ 'error',
1188
+ 'exception',
1189
+ 'denied',
1190
+ 'rejected',
1191
+ 'is not',
1192
+ '失败',
1193
+ '错误',
1194
+ '未通过',
1195
+ ];
1196
+
1197
+ // The explicit absence/no-op vocabulary, both languages. Every phrase that
1198
+ // NEGATES a failure marker must cover the marker word itself (the phrase
1199
+ // is stripped from the message before the marker scan), so "no error"
1200
+ // strips the "error" it contains and "nothing was denied" strips the
1201
+ // "denied". A phrase that merely asserts success without covering a
1202
+ // marker (完成 alone — it sits inside 无法完成) stays OUT: the carve-out
1203
+ // keys on the marker's absence, not on a success word's presence.
1204
+ const BENIGN_ABSENCE_PHRASES = [
1205
+ // EN: the marker word explicitly negated, excluded, or counted at zero.
1206
+ 'no error',
1207
+ 'no errors',
1208
+ 'no failure',
1209
+ 'no failures',
1210
+ 'no exception',
1211
+ 'no exceptions',
1212
+ 'no denial',
1213
+ 'not denied',
1214
+ 'nothing was denied',
1215
+ '0 errors',
1216
+ 'zero errors',
1217
+ 'zero failures',
1218
+ 'error-free',
1219
+ 'failure-free',
1220
+ 'exception-free',
1221
+ 'without error',
1222
+ 'without errors',
1223
+ 'without failures',
1224
+ 'without any error',
1225
+ 'not any error',
1226
+ 'cannot be any error',
1227
+ 'error was not detected',
1228
+ 'errors were not detected',
1229
+ 'error did not occur',
1230
+ 'errors did not occur',
1231
+ // EN: the no-op/OK assertion vocabulary (the marker-free companions).
1232
+ 'nothing to do',
1233
+ 'no change',
1234
+ 'nothing failed',
1235
+ 'did not fail',
1236
+ 'unchanged',
1237
+ // ZH: the error word explicitly negated (the enumerated forms; 无/未/没有
1238
+ // by themselves are NOT negations of 错误/失败).
1239
+ '未发生错误',
1240
+ '错误未发生',
1241
+ '没有发生错误',
1242
+ '未出现错误',
1243
+ '错误未出现',
1244
+ '无错误',
1245
+ '没有错误',
1246
+ '无任何错误',
1247
+ '无 error',
1248
+ '没有 error',
1249
+ // ZH: the no-op/OK assertion vocabulary (the real up-to-date envelope).
1250
+ '已是最新',
1251
+ '无需升级',
1252
+ '无需操作',
1253
+ '无需',
1254
+ ];
1255
+
1256
+ function messageCarriesFailure(message: string): boolean {
1257
+ let rest = message.toLowerCase();
1258
+ // Strip every explicit absence phrase FIRST: a marker covered by an
1259
+ // absence phrase is benign by content; a marker outside them is a real
1260
+ // failure report and survives the strip with its polarity untouched.
1261
+ for (const phrase of BENIGN_ABSENCE_PHRASES) {
1262
+ if (!rest.includes(phrase)) continue;
1263
+ rest = rest.split(phrase).join('\u0000');
1264
+ }
1265
+ return MESSAGE_FAILURE_MARKERS.some((marker) => rest.includes(marker));
1266
+ }
1267
+
1268
+ function handlerResultCarriesFailure(handlerResult: unknown): boolean {
1269
+ if (handlerResult instanceof Error) return true; // returned, not thrown: an answer
1270
+ if (typeof handlerResult !== 'object' || handlerResult === null) return false;
1271
+ const record = handlerResult as Record<string, unknown>;
1272
+ // (1) An explicit success signal wins before every failure mark.
1273
+ if (record.ok === true || record.success === true || record.status === 'ok') return false;
1274
+ // (2) The upgrade family's benign no-op envelope (round 13, finding 3):
1275
+ // `success: false` plus the requiresRestart marker plus a BENIGN message,
1276
+ // with no error field — the REAL "already at the latest version" return
1277
+ // of upgradePackage/handleUpgrade ({success:false, message:'已是最新版本…',
1278
+ // requiresRestart:false}). Round 14, finding 3 (both seats): the message's
1279
+ // CONTENT must be benign — an error-ish message under the marker pair is
1280
+ // a real failure reported in the message channel ({success:false,
1281
+ // requiresRestart:true, message:'failed: network error'} recorded
1282
+ // delivered pre-fix — a suppressed failure, the permissive direction the
1283
+ // memo keys on), so the carve-out requires a message free of the failure
1284
+ // vocabulary below and an error-ish shape falls through to the failure
1285
+ // marks. A bare {success:false} (no marker pair) reads failed: the real
1286
+ // up-to-date envelope carries all three.
1287
+ if (
1288
+ record.success === false &&
1289
+ record.requiresRestart !== undefined &&
1290
+ typeof record.message === 'string' &&
1291
+ record.message.length > 0 &&
1292
+ !messageCarriesFailure(record.message) &&
1293
+ record.error === undefined &&
1294
+ record.errorMessage === undefined
1295
+ ) {
1296
+ return false; // an explicit benign "nothing to do" answer: delivered
1297
+ }
1298
+ if (record.success === false) return true; // not-ok with no benign carve-out: failed
1299
+ // (3) An ok field that is not success is the explicit verdict.
1300
+ if (record.ok === false || record.ok === 'false') return true;
1301
+ // (4) exitCode marks only shapes with no ok field (the exec faces).
1302
+ if (!('ok' in record) && typeof record.exitCode === 'number' && record.exitCode !== 0) return true;
1303
+ if (record.status === 'rejected' || record.status === 'error') return true;
1304
+ const failure = record.error ?? record.errorMessage ?? record.message;
1305
+ return failure !== undefined && failure !== null && failure !== '';
1306
+ }