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

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