@librechat/agents 4.0.5 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (191) hide show
  1. package/dist/cjs/agents/AgentContext.cjs +6 -4
  2. package/dist/cjs/agents/AgentContext.cjs.map +1 -1
  3. package/dist/cjs/decisions/breaker.cjs +59 -0
  4. package/dist/cjs/decisions/breaker.cjs.map +1 -0
  5. package/dist/cjs/decisions/core.cjs +44 -0
  6. package/dist/cjs/decisions/dialect.cjs +65 -12
  7. package/dist/cjs/decisions/dialect.cjs.map +1 -1
  8. package/dist/cjs/decisions/hook.cjs +19 -0
  9. package/dist/cjs/decisions/hook.cjs.map +1 -0
  10. package/dist/cjs/decisions/http.cjs +2 -1
  11. package/dist/cjs/decisions/http.cjs.map +1 -1
  12. package/dist/cjs/decisions/index.cjs +6 -0
  13. package/dist/cjs/decisions/node.cjs +315 -0
  14. package/dist/cjs/decisions/node.cjs.map +1 -0
  15. package/dist/cjs/decisions/probe.cjs +56 -0
  16. package/dist/cjs/decisions/probe.cjs.map +1 -0
  17. package/dist/cjs/decisions/redact.cjs +109 -0
  18. package/dist/cjs/decisions/redact.cjs.map +1 -0
  19. package/dist/cjs/decisions/structuredChat.cjs +2 -3
  20. package/dist/cjs/decisions/structuredChat.cjs.map +1 -1
  21. package/dist/cjs/decisions/transport.cjs +56 -23
  22. package/dist/cjs/decisions/transport.cjs.map +1 -1
  23. package/dist/cjs/decisions/types.cjs +2 -0
  24. package/dist/cjs/decisions/types.cjs.map +1 -1
  25. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs +7 -6
  26. package/dist/cjs/llm/anthropic/utils/message_inputs.cjs.map +1 -1
  27. package/dist/cjs/llm/bedrock/cachePoints.cjs +20 -0
  28. package/dist/cjs/llm/bedrock/cachePoints.cjs.map +1 -1
  29. package/dist/cjs/llm/bedrock/index.cjs +8 -5
  30. package/dist/cjs/llm/bedrock/index.cjs.map +1 -1
  31. package/dist/cjs/llm/google/index.cjs +1 -1
  32. package/dist/cjs/llm/google/index.cjs.map +1 -1
  33. package/dist/cjs/llm/google/utils/common.cjs +8 -2
  34. package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
  35. package/dist/cjs/main.cjs +45 -0
  36. package/dist/cjs/rerank/bm25.cjs +110 -0
  37. package/dist/cjs/rerank/bm25.cjs.map +1 -0
  38. package/dist/cjs/rerank/cache.cjs +50 -0
  39. package/dist/cjs/rerank/cache.cjs.map +1 -0
  40. package/dist/cjs/rerank/core.cjs +29 -0
  41. package/dist/cjs/rerank/crossEncoder.cjs +172 -0
  42. package/dist/cjs/rerank/crossEncoder.cjs.map +1 -0
  43. package/dist/cjs/rerank/fallback.cjs +280 -0
  44. package/dist/cjs/rerank/fallback.cjs.map +1 -0
  45. package/dist/cjs/rerank/index.cjs +8 -0
  46. package/dist/cjs/rerank/outcome.cjs +382 -0
  47. package/dist/cjs/rerank/outcome.cjs.map +1 -0
  48. package/dist/cjs/rerank/pin.cjs +74 -0
  49. package/dist/cjs/rerank/pin.cjs.map +1 -0
  50. package/dist/cjs/rerank/semaphore.cjs +38 -0
  51. package/dist/cjs/rerank/semaphore.cjs.map +1 -0
  52. package/dist/cjs/rerank/systemone.cjs +476 -50
  53. package/dist/cjs/rerank/systemone.cjs.map +1 -1
  54. package/dist/cjs/session/AgentSession.cjs +1 -1
  55. package/dist/cjs/session/AgentSession.cjs.map +1 -1
  56. package/dist/cjs/tools/local/LocalCodingTools.cjs +67 -19
  57. package/dist/cjs/tools/local/LocalCodingTools.cjs.map +1 -1
  58. package/dist/cjs/tools/local/LocalExecutionTools.cjs +12 -1
  59. package/dist/cjs/tools/local/LocalExecutionTools.cjs.map +1 -1
  60. package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs +63 -16
  61. package/dist/cjs/tools/local/resolveLocalExecutionTools.cjs.map +1 -1
  62. package/dist/cjs/tools/local/toolResultCaps.cjs +32 -0
  63. package/dist/cjs/tools/local/toolResultCaps.cjs.map +1 -0
  64. package/dist/esm/agents/AgentContext.mjs +7 -5
  65. package/dist/esm/agents/AgentContext.mjs.map +1 -1
  66. package/dist/esm/decisions/breaker.mjs +56 -0
  67. package/dist/esm/decisions/breaker.mjs.map +1 -0
  68. package/dist/esm/decisions/core.mjs +11 -0
  69. package/dist/esm/decisions/dialect.mjs +65 -12
  70. package/dist/esm/decisions/dialect.mjs.map +1 -1
  71. package/dist/esm/decisions/hook.mjs +19 -0
  72. package/dist/esm/decisions/hook.mjs.map +1 -0
  73. package/dist/esm/decisions/http.mjs +2 -1
  74. package/dist/esm/decisions/http.mjs.map +1 -1
  75. package/dist/esm/decisions/index.mjs +6 -0
  76. package/dist/esm/decisions/node.mjs +313 -0
  77. package/dist/esm/decisions/node.mjs.map +1 -0
  78. package/dist/esm/decisions/probe.mjs +54 -0
  79. package/dist/esm/decisions/probe.mjs.map +1 -0
  80. package/dist/esm/decisions/redact.mjs +108 -0
  81. package/dist/esm/decisions/redact.mjs.map +1 -0
  82. package/dist/esm/decisions/structuredChat.mjs +2 -3
  83. package/dist/esm/decisions/structuredChat.mjs.map +1 -1
  84. package/dist/esm/decisions/transport.mjs +56 -23
  85. package/dist/esm/decisions/transport.mjs.map +1 -1
  86. package/dist/esm/decisions/types.mjs +2 -0
  87. package/dist/esm/decisions/types.mjs.map +1 -1
  88. package/dist/esm/llm/anthropic/utils/message_inputs.mjs +7 -7
  89. package/dist/esm/llm/anthropic/utils/message_inputs.mjs.map +1 -1
  90. package/dist/esm/llm/bedrock/cachePoints.mjs +20 -1
  91. package/dist/esm/llm/bedrock/cachePoints.mjs.map +1 -1
  92. package/dist/esm/llm/bedrock/index.mjs +7 -4
  93. package/dist/esm/llm/bedrock/index.mjs.map +1 -1
  94. package/dist/esm/llm/google/index.mjs +2 -2
  95. package/dist/esm/llm/google/index.mjs.map +1 -1
  96. package/dist/esm/llm/google/utils/common.mjs +8 -3
  97. package/dist/esm/llm/google/utils/common.mjs.map +1 -1
  98. package/dist/esm/main.mjs +15 -3
  99. package/dist/esm/rerank/bm25.mjs +108 -0
  100. package/dist/esm/rerank/bm25.mjs.map +1 -0
  101. package/dist/esm/rerank/cache.mjs +50 -0
  102. package/dist/esm/rerank/cache.mjs.map +1 -0
  103. package/dist/esm/rerank/core.mjs +9 -0
  104. package/dist/esm/rerank/crossEncoder.mjs +172 -0
  105. package/dist/esm/rerank/crossEncoder.mjs.map +1 -0
  106. package/dist/esm/rerank/fallback.mjs +278 -0
  107. package/dist/esm/rerank/fallback.mjs.map +1 -0
  108. package/dist/esm/rerank/index.mjs +8 -0
  109. package/dist/esm/rerank/outcome.mjs +360 -0
  110. package/dist/esm/rerank/outcome.mjs.map +1 -0
  111. package/dist/esm/rerank/pin.mjs +73 -0
  112. package/dist/esm/rerank/pin.mjs.map +1 -0
  113. package/dist/esm/rerank/semaphore.mjs +38 -0
  114. package/dist/esm/rerank/semaphore.mjs.map +1 -0
  115. package/dist/esm/rerank/systemone.mjs +476 -50
  116. package/dist/esm/rerank/systemone.mjs.map +1 -1
  117. package/dist/esm/session/AgentSession.mjs +1 -1
  118. package/dist/esm/session/AgentSession.mjs.map +1 -1
  119. package/dist/esm/tools/local/LocalCodingTools.mjs +67 -19
  120. package/dist/esm/tools/local/LocalCodingTools.mjs.map +1 -1
  121. package/dist/esm/tools/local/LocalExecutionTools.mjs +12 -1
  122. package/dist/esm/tools/local/LocalExecutionTools.mjs.map +1 -1
  123. package/dist/esm/tools/local/resolveLocalExecutionTools.mjs +63 -17
  124. package/dist/esm/tools/local/resolveLocalExecutionTools.mjs.map +1 -1
  125. package/dist/esm/tools/local/toolResultCaps.mjs +31 -0
  126. package/dist/esm/tools/local/toolResultCaps.mjs.map +1 -0
  127. package/dist/types/decisions/breaker.d.ts +37 -0
  128. package/dist/types/decisions/core.d.ts +19 -0
  129. package/dist/types/decisions/hook.d.ts +9 -0
  130. package/dist/types/decisions/index.d.ts +3 -8
  131. package/dist/types/decisions/node.d.ts +90 -0
  132. package/dist/types/decisions/probe.d.ts +37 -0
  133. package/dist/types/decisions/redact.d.ts +22 -0
  134. package/dist/types/decisions/structuredChat.d.ts +1 -0
  135. package/dist/types/decisions/transport.d.ts +16 -3
  136. package/dist/types/decisions/types.d.ts +43 -4
  137. package/dist/types/llm/anthropic/utils/message_inputs.d.ts +1 -0
  138. package/dist/types/llm/bedrock/cachePoints.d.ts +7 -0
  139. package/dist/types/llm/bedrock/index.d.ts +2 -1
  140. package/dist/types/llm/google/index.d.ts +1 -0
  141. package/dist/types/llm/google/utils/common.d.ts +2 -0
  142. package/dist/types/rerank/bm25.d.ts +46 -0
  143. package/dist/types/rerank/cache.d.ts +40 -0
  144. package/dist/types/rerank/core.d.ts +24 -0
  145. package/dist/types/rerank/crossEncoder.d.ts +48 -0
  146. package/dist/types/rerank/fallback.d.ts +67 -0
  147. package/dist/types/rerank/index.d.ts +1 -3
  148. package/dist/types/rerank/outcome.d.ts +144 -0
  149. package/dist/types/rerank/pin.d.ts +48 -0
  150. package/dist/types/rerank/semaphore.d.ts +9 -0
  151. package/dist/types/rerank/systemone.d.ts +51 -5
  152. package/dist/types/rerank/types.d.ts +116 -1
  153. package/dist/types/tools/local/resolveLocalExecutionTools.d.ts +6 -0
  154. package/dist/types/tools/local/toolResultCaps.d.ts +16 -0
  155. package/dist/types/types/tools.d.ts +16 -0
  156. package/package.json +26 -1
  157. package/src/agents/AgentContext.ts +33 -4
  158. package/src/decisions/breaker.ts +110 -0
  159. package/src/decisions/core.ts +23 -0
  160. package/src/decisions/dialect.ts +134 -20
  161. package/src/decisions/hook.ts +32 -0
  162. package/src/decisions/http.ts +4 -1
  163. package/src/decisions/index.ts +3 -12
  164. package/src/decisions/node.ts +671 -0
  165. package/src/decisions/probe.ts +114 -0
  166. package/src/decisions/redact.ts +222 -0
  167. package/src/decisions/structuredChat.ts +6 -8
  168. package/src/decisions/transport.ts +104 -22
  169. package/src/decisions/types.ts +46 -5
  170. package/src/llm/anthropic/utils/message_inputs.ts +16 -16
  171. package/src/llm/bedrock/cachePoints.ts +47 -0
  172. package/src/llm/bedrock/index.ts +35 -13
  173. package/src/llm/google/index.ts +5 -3
  174. package/src/llm/google/utils/common.ts +19 -5
  175. package/src/rerank/bm25.ts +190 -0
  176. package/src/rerank/cache.ts +103 -0
  177. package/src/rerank/core.ts +47 -0
  178. package/src/rerank/crossEncoder.ts +289 -0
  179. package/src/rerank/fallback.ts +625 -0
  180. package/src/rerank/index.ts +1 -3
  181. package/src/rerank/outcome.ts +767 -0
  182. package/src/rerank/pin.ts +157 -0
  183. package/src/rerank/semaphore.ts +47 -0
  184. package/src/rerank/systemone.ts +914 -88
  185. package/src/rerank/types.ts +143 -1
  186. package/src/session/AgentSession.ts +3 -1
  187. package/src/tools/local/LocalCodingTools.ts +139 -19
  188. package/src/tools/local/LocalExecutionTools.ts +21 -1
  189. package/src/tools/local/resolveLocalExecutionTools.ts +116 -11
  190. package/src/tools/local/toolResultCaps.ts +60 -0
  191. package/src/types/tools.ts +16 -0
@@ -0,0 +1,671 @@
1
+ /**
2
+ * Node-only `@librechat/agents/decisions/node` entry: credential helpers that
3
+ * need `node:child_process`. The `./decisions` entry stays platform-neutral.
4
+ */
5
+ import { spawn } from 'node:child_process';
6
+ import type { ChildProcess } from 'node:child_process';
7
+ import type { Readable } from 'node:stream';
8
+ import type { DecisionFailure, DecisionTokenMinter } from './types';
9
+ import type { DecisionBreaker } from './breaker';
10
+ import { redactExcerpt } from './redact';
11
+ import { DecisionError } from './types';
12
+
13
+ /** Fifty minutes: under the ClickHouse gateway's hourly token. */
14
+ const DEFAULT_TTL_MS = 50 * 60_000;
15
+ const DEFAULT_TIMEOUT_MS = 60_000;
16
+ const DEFAULT_KILL_GRACE_MS = 2_000;
17
+ const MAX_OUTPUT_BYTES = 1024 * 1024;
18
+ const STDERR_LIMIT = 200;
19
+ /** Off Windows a shell reports a command killed by signal N as exit status 128 + N; Linux numbers signals up to 64. */
20
+ const SIGNAL_EXIT_MIN = 129;
21
+ const SIGNAL_EXIT_MAX = 128 + 64;
22
+ /** How long a run whose shell has exited waits for a process it left holding stdout or stderr to let go. */
23
+ const DRAIN_MS = 100;
24
+ /** How often a killed run checks whether its process group has emptied, so the `SIGKILL` escalation stops waiting. */
25
+ const REAP_POLL_MS = 25;
26
+ const MAX_EXIT_CODE = 255;
27
+ /** How many recent tokens, cached or not, a failed run's stderr is redacted against. */
28
+ const KNOWN_TOKENS = 8;
29
+ const KILL_SIGNAL = 'SIGTERM';
30
+ const FORCE_SIGNAL = 'SIGKILL';
31
+ const GROUP_KILL = process.platform !== 'win32';
32
+
33
+ export const COMMAND_TOKEN_PROVIDER = 'command';
34
+
35
+ export interface CommandTokenOptions {
36
+ /**
37
+ * How long a minted token is reused without running the command again,
38
+ * counted from when the command finished; `0` mints on every call. Leave
39
+ * headroom under the issuer's lifetime for the command's own runtime.
40
+ */
41
+ ttlMs?: number;
42
+ /** Bounds one run of the command. */
43
+ timeoutMs?: number;
44
+ /**
45
+ * How long a killed run gets to exit on `SIGTERM` before it is sent
46
+ * `SIGKILL`, so a command that traps or ignores `SIGTERM` cannot outlive
47
+ * its run; `0` escalates at once. Defaults to two seconds.
48
+ */
49
+ killGraceMs?: number;
50
+ /**
51
+ * The exit statuses that mean the credential was refused. A run that exits
52
+ * with any other non-zero status is a `network` failure, which the
53
+ * transport retries and which never trips a breaker, so a token CLI that
54
+ * exits 7 when its auth server is unreachable cannot open the breaker until
55
+ * a manual reset. By default every non-zero status outside 129–192 is a
56
+ * refusal.
57
+ */
58
+ refusalExitCodes?: ReadonlyArray<number>;
59
+ /**
60
+ * The breaker this credential's model is fused with. Neither a run that
61
+ * started before `breaker.reset()` nor a token it minted, cached or still in
62
+ * flight, serves callers that arrive after it, so the operator's fix is
63
+ * tested by a fresh run instead of failing on stale evidence and reopening
64
+ * the breaker.
65
+ */
66
+ breaker?: Pick<DecisionBreaker, 'generation'>;
67
+ }
68
+
69
+ interface SharedRun {
70
+ token: Promise<string>;
71
+ /** Callers still awaiting `token`; the run is killed when the last one aborts. */
72
+ waiters: number;
73
+ abandon: AbortController;
74
+ /** The breaker generation the run started under; `undefined` without a breaker. */
75
+ generation: number | undefined;
76
+ /** Set once a breaker reset stops the run serving new callers; its token is then not cached. */
77
+ detached: boolean;
78
+ }
79
+
80
+ /** Runs that may still have a live process group; the host's `exit` kills each, since the command's own process group does not receive the host's signals. */
81
+ const live = new Set<ChildProcess>();
82
+
83
+ function killLive(): void {
84
+ for (const child of live) {
85
+ killRun(child, FORCE_SIGNAL);
86
+ }
87
+ }
88
+
89
+ function track(child: ChildProcess): void {
90
+ if (child.pid === undefined) {
91
+ return;
92
+ }
93
+ if (live.size === 0) {
94
+ process.on('exit', killLive);
95
+ }
96
+ live.add(child);
97
+ }
98
+
99
+ function untrack(child: ChildProcess): void {
100
+ if (live.delete(child) && live.size === 0) {
101
+ process.off('exit', killLive);
102
+ }
103
+ }
104
+
105
+ function abandonedError(): DecisionError {
106
+ return new DecisionError('aborted', 'token command was abandoned', {
107
+ provider: COMMAND_TOKEN_PROVIDER,
108
+ });
109
+ }
110
+
111
+ function validMs(value: number, allowZero: boolean): boolean {
112
+ return (
113
+ Number.isSafeInteger(value) &&
114
+ (allowZero ? value >= 0 : value > 0) &&
115
+ value <= 24 * 3_600_000
116
+ );
117
+ }
118
+
119
+ function lastLine(text: string): string {
120
+ const lines = text
121
+ .split(/\r?\n/)
122
+ .map((line) => line.trim())
123
+ .filter((line) => line !== '');
124
+ return lines.length > 0 ? lines[lines.length - 1] : '';
125
+ }
126
+
127
+ /** Why a run ended without a token. */
128
+ type RunEnd =
129
+ | { kind: 'exit'; code: number }
130
+ | { kind: 'signal'; signal: string }
131
+ | { kind: 'shellSignal'; code: number }
132
+ | { kind: 'timeout' | 'overflow' | 'spawn' | 'abandoned' };
133
+
134
+ /**
135
+ * Only a run that finished and exited non-zero, with a status in `refusals`
136
+ * when that list is given, is a refusal. A run killed at
137
+ * `timeoutMs` is a `timeout`; a spawn error, an output overflow, or a signal
138
+ * from outside is `network`, including one that killed a command the shell
139
+ * forked, which the surviving shell reports as exit status 129–192. None of
140
+ * these says anything about the credential, so none may trip a breaker.
141
+ */
142
+ function classify(
143
+ end: RunEnd,
144
+ refusals: ReadonlySet<number> | undefined
145
+ ): { failure: DecisionFailure; reason: string } {
146
+ if (end.kind === 'exit') {
147
+ return {
148
+ failure:
149
+ refusals === undefined || refusals.has(end.code)
150
+ ? 'unauthorized'
151
+ : 'network',
152
+ reason: `token command exited with code ${end.code}`,
153
+ };
154
+ }
155
+ if (end.kind === 'timeout') {
156
+ return {
157
+ failure: 'timeout',
158
+ reason: `token command timed out (${KILL_SIGNAL})`,
159
+ };
160
+ }
161
+ if (end.kind === 'shellSignal') {
162
+ return {
163
+ failure: 'network',
164
+ reason: `token command exited with code ${end.code} (killed by signal ${end.code - 128})`,
165
+ };
166
+ }
167
+ if (end.kind === 'signal') {
168
+ return {
169
+ failure: 'network',
170
+ reason: `token command was killed (${end.signal})`,
171
+ };
172
+ }
173
+ if (end.kind === 'abandoned') {
174
+ return { failure: 'aborted', reason: 'token command was abandoned' };
175
+ }
176
+ return { failure: 'network', reason: 'token command failed' };
177
+ }
178
+
179
+ /**
180
+ * Off Windows the shell leads its own process group, so a kill reaches the
181
+ * command it forked (dash does not `exec` it) and anything that command
182
+ * started, not only the shell. On Windows it reaches only the shell.
183
+ */
184
+ function killRun(child: ChildProcess, signal: NodeJS.Signals): void {
185
+ if (child.pid === undefined) {
186
+ return;
187
+ }
188
+ try {
189
+ if (GROUP_KILL) {
190
+ process.kill(-child.pid, signal);
191
+ } else {
192
+ child.kill(signal);
193
+ }
194
+ } catch {
195
+ // Already gone.
196
+ }
197
+ }
198
+
199
+ /** Whether anything a kill would reach is still running: off Windows, any member of the run's process group. */
200
+ function runAlive(child: ChildProcess): boolean {
201
+ if (child.pid === undefined) {
202
+ return false;
203
+ }
204
+ if (!GROUP_KILL) {
205
+ return child.exitCode === null && child.signalCode === null;
206
+ }
207
+ try {
208
+ process.kill(-child.pid, 0);
209
+ return true;
210
+ } catch (error) {
211
+ /** Not `instanceof Error`: a host that runs this module in a `vm` context (Jest does) gets the error from another realm. */
212
+ return !(
213
+ typeof error === 'object' &&
214
+ error !== null &&
215
+ 'code' in error &&
216
+ error.code === 'ESRCH'
217
+ );
218
+ }
219
+ }
220
+
221
+ /** Collects a stream up to the output limit; `onOverflow` fires once past it. */
222
+ function collect(
223
+ stream: Readable | null,
224
+ onOverflow: () => void
225
+ ): () => string {
226
+ const chunks: Buffer[] = [];
227
+ let bytes = 0;
228
+ stream?.on('data', (chunk: Buffer) => {
229
+ if (bytes > MAX_OUTPUT_BYTES) {
230
+ return;
231
+ }
232
+ bytes += chunk.length;
233
+ chunks.push(chunk);
234
+ if (bytes > MAX_OUTPUT_BYTES) {
235
+ onOverflow();
236
+ }
237
+ });
238
+ stream?.on('error', () => {});
239
+ return () => Buffer.concat(chunks).toString('utf8');
240
+ }
241
+
242
+ /**
243
+ * The command text and every word of it whatever its length, so neither a
244
+ * shell that echoes the line nor a program that quotes an argument back can
245
+ * leak an inline secret; a short word may garble the excerpt instead. Words
246
+ * split at quotes, which the shell removes; at braces and commas, which
247
+ * bash's brace expansion splits a word at; and at `;`, `&`, `|`, `(`, `)`,
248
+ * `<`, and `>`, which end an unquoted word without whitespace in a POSIX
249
+ * shell and in cmd.exe alike. Splitting quoted text there too is harmless,
250
+ * since every piece is still redacted.
251
+ */
252
+ function commandSecrets(command: string): string[] {
253
+ return [command, ...command.split(/[\s'"`=,{};&|()<>]+/)].filter(
254
+ (word) => word.trim() !== ''
255
+ );
256
+ }
257
+
258
+ /** A double-quoted, single-quoted, or unquoted stretch of a POSIX command; a stray quote reads as unquoted. */
259
+ const SHELL_SEGMENT = /"[^"]*"|'[^']*'|[^"']+|["']/g;
260
+ const SINGLE_QUOTED = /^'[^']*'$/;
261
+
262
+ /**
263
+ * Whether the shell may hand the program an argument built from text the
264
+ * command does not show (a variable, command output, or a decoded escape),
265
+ * which no word of the text can redact: off Windows, a backslash escape or a
266
+ * `$` or backtick expansion outside single quotes; on Windows, cmd.exe's `%`
267
+ * expansion and `^` escape, or a `\"` a program's argument parser decodes.
268
+ * Pathname and tilde expansion are left alone: they substitute paths that
269
+ * already exist on disk, not text the command carried.
270
+ */
271
+ function rewritesWords(command: string): boolean {
272
+ if (!GROUP_KILL) {
273
+ return /[%^]|\\"/.test(command);
274
+ }
275
+ for (const [segment] of command.matchAll(SHELL_SEGMENT)) {
276
+ if (!SINGLE_QUOTED.test(segment) && /[\\$`]/.test(segment)) {
277
+ return true;
278
+ }
279
+ }
280
+ return false;
281
+ }
282
+
283
+ /** How a run that closed with `code` and `signal` ended; off Windows, an exit status in the shell's signal range is a kill, not a refusal. */
284
+ function closedEnd(code: number | null, signal: string | null): RunEnd {
285
+ if (code === null) {
286
+ return { kind: 'signal', signal: signal ?? 'unknown' };
287
+ }
288
+ if (GROUP_KILL && code >= SIGNAL_EXIT_MIN && code <= SIGNAL_EXIT_MAX) {
289
+ return { kind: 'shellSignal', code };
290
+ }
291
+ return { kind: 'exit', code };
292
+ }
293
+
294
+ /**
295
+ * Names how the command failed; never its text, stdout, or `error.message`,
296
+ * which echoes both. Stderr that is not `scrubbable` is withheld.
297
+ */
298
+ function describeFailure(
299
+ reason: string,
300
+ stderr: string,
301
+ secrets: ReadonlyArray<string | null>,
302
+ scrubbable: boolean
303
+ ): string {
304
+ if (stderr.trim() === '') {
305
+ return reason;
306
+ }
307
+ if (!scrubbable) {
308
+ return `${reason} (stderr withheld: the command uses shell escapes or expansion)`;
309
+ }
310
+ const detail = redactExcerpt(stderr, secrets, STDERR_LIMIT);
311
+ return detail === '' ? reason : `${reason}: ${detail}`;
312
+ }
313
+
314
+ function validExitCodes(codes: ReadonlyArray<number> | undefined): boolean {
315
+ return (
316
+ codes === undefined ||
317
+ (Array.isArray(codes) &&
318
+ codes.every(
319
+ (code) =>
320
+ Number.isSafeInteger(code) && code > 0 && code <= MAX_EXIT_CODE
321
+ ))
322
+ );
323
+ }
324
+
325
+ /**
326
+ * A credential minted by a shell command that prints a short-lived bearer
327
+ * token (for example `dataplanectl chai auth token`); the last non-empty line
328
+ * of stdout is the token, and the command reads no stdin. The token is reused
329
+ * for `ttlMs` (default 50 minutes) after the run that minted it finishes,
330
+ * concurrent calls share one run of the command, and a `refresh` (the
331
+ * transport asks after a 401) runs it again unless the token it `refused` has
332
+ * already been replaced, in which case the newer token (or the run minting
333
+ * it) is shared instead. Given the model's `breaker`, a call made after
334
+ * `breaker.reset()` never joins a run that started before it.
335
+ *
336
+ * A run ends when its shell exits: a process the command leaves behind
337
+ * holding stdout or stderr gets 100 ms to let go, then the run settles from
338
+ * what it printed and that process is left running, unkilled.
339
+ *
340
+ * A caller whose `signal` aborts rejects at once with `aborted`; the run is
341
+ * killed when every caller sharing it has aborted, and the next call starts a
342
+ * fresh one. A run that exits non-zero or prints nothing rejects with an
343
+ * `unauthorized` `DecisionError`, unless `refusalExitCodes` is given and does
344
+ * not list its status, which makes it `network`; a run killed at `timeoutMs`
345
+ * rejects with `timeout`, and a spawn failure, output overflow, or kill from
346
+ * outside with `network`, so a slow command or one that cannot start never
347
+ * trips a breaker. Off Windows an exit status of 129–192 is how a shell
348
+ * reports a command it forked being killed by a signal (137 for `SIGKILL`),
349
+ * so it is a kill, not a refusal; a pipeline such as `cmd | tail -1` hides a
350
+ * killed `cmd` behind a clean exit with no output, which reads as
351
+ * `unauthorized`, so keep the token command last in a pipeline. A kill sends
352
+ * `SIGTERM`, then `SIGKILL` once `killGraceMs` passes with the run still
353
+ * alive, so a killed run overlaps the next one for at most that grace; the
354
+ * escalation is dropped as soon as nothing it would reach is left. Off
355
+ * Windows a kill reaches the command's whole process group; on Windows it
356
+ * ends only the shell, not the command the shell launched.
357
+ *
358
+ * Off Windows the command runs in its own session, with no controlling
359
+ * terminal, so a signal sent to the host's process group (a terminal's
360
+ * Ctrl-C) does not reach it. When the host process exits, each run still
361
+ * going is sent `SIGKILL`; a host killed by a signal it does not handle never
362
+ * reaches its `exit` event, so it leaves such a run going.
363
+ *
364
+ * The message carries the exit status and a redacted stderr excerpt, never
365
+ * a line of stdout, the command or any word of it (split at whitespace,
366
+ * quotes, `=`, braces, commas, and the shell operators `;`, `&`, `|`, `(`,
367
+ * `)`, `<`, and `>`), or any of the last eight tokens it minted
368
+ * or was told were refused, cached or not, whatever their length, including a
369
+ * refused token whose refresh failed. The excerpt reads only the start of
370
+ * stderr, so formatting it stays cheap whatever the command printed. When the
371
+ * shell may pass the program an argument built from text the command does
372
+ * not show, such as a variable, command output, or a decoded escape (off
373
+ * Windows, a backslash escape or a `$` or backtick expansion outside single
374
+ * quotes; on Windows, `%`, `^`, or `\"`), stderr is withheld instead.
375
+ * Pathname (`*`, `?`, `[`) and tilde expansion do not withhold it: they
376
+ * substitute existing paths, which can reach the excerpt.
377
+ */
378
+ export function commandToken(
379
+ command: string,
380
+ options: CommandTokenOptions = {}
381
+ ): DecisionTokenMinter {
382
+ const ttlMs = options.ttlMs ?? DEFAULT_TTL_MS;
383
+ const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
384
+ const killGraceMs = options.killGraceMs ?? DEFAULT_KILL_GRACE_MS;
385
+ const { breaker } = options;
386
+ if (typeof command !== 'string' || command.trim() === '') {
387
+ throw new DecisionError('bad_request', 'token command is empty', {
388
+ provider: COMMAND_TOKEN_PROVIDER,
389
+ });
390
+ }
391
+ if (
392
+ !validMs(ttlMs, true) ||
393
+ !validMs(timeoutMs, false) ||
394
+ !validMs(killGraceMs, true)
395
+ ) {
396
+ throw new DecisionError('bad_request', 'invalid token command timing', {
397
+ provider: COMMAND_TOKEN_PROVIDER,
398
+ });
399
+ }
400
+ if (!validExitCodes(options.refusalExitCodes)) {
401
+ throw new DecisionError(
402
+ 'bad_request',
403
+ 'invalid token command refusal exit codes',
404
+ { provider: COMMAND_TOKEN_PROVIDER }
405
+ );
406
+ }
407
+ const refusals =
408
+ options.refusalExitCodes === undefined
409
+ ? undefined
410
+ : new Set(options.refusalExitCodes);
411
+
412
+ /** The last minted token; kept after a refusal so a failed refresh still redacts it. */
413
+ let cached: string | null = null;
414
+ let expiresAt = 0;
415
+ /** The breaker generation the run that minted `cached` started under; a reset since then bypasses it. */
416
+ let cachedGeneration: number | undefined;
417
+ let pending: SharedRun | null = null;
418
+ const echoed = commandSecrets(command);
419
+ /** Stderr may quote an argument the shell decoded or expanded, which no word of the text matches. */
420
+ const scrubbable = !rewritesWords(command);
421
+ /**
422
+ * The last tokens minted or refused, cached or not: a run detached by a
423
+ * breaker reset hands out a token it never caches, and the command's own
424
+ * store may still hold it or an older one when a later run fails.
425
+ */
426
+ const known: string[] = [];
427
+ const remember = (token: string): void => {
428
+ if (known.includes(token)) {
429
+ return;
430
+ }
431
+ known.push(token);
432
+ if (known.length > KNOWN_TOKENS) {
433
+ known.shift();
434
+ }
435
+ };
436
+
437
+ /**
438
+ * `feedsCache` says whether a token this run mints may still be cached when
439
+ * it lands; `generation` is the breaker generation the run started under.
440
+ */
441
+ const run = (
442
+ abandoned: AbortSignal,
443
+ generation: number | undefined,
444
+ feedsCache: () => boolean
445
+ ): Promise<string> =>
446
+ new Promise<string>((resolve, reject) => {
447
+ let child: ChildProcess;
448
+ try {
449
+ child = spawn(command, {
450
+ shell: true,
451
+ detached: GROUP_KILL,
452
+ windowsHide: true,
453
+ stdio: ['ignore', 'pipe', 'pipe'],
454
+ });
455
+ } catch {
456
+ /** Node's synchronous spawn errors quote the command, so none of the message survives. */
457
+ reject(
458
+ new DecisionError('network', 'token command failed', {
459
+ provider: COMMAND_TOKEN_PROVIDER,
460
+ })
461
+ );
462
+ return;
463
+ }
464
+ track(child);
465
+ let settled = false;
466
+ let killed = false;
467
+ /** Armed by the first kill; outlives the shell, since a forked command may ignore the `SIGTERM` that ended it. */
468
+ let escalation: NodeJS.Timeout | undefined;
469
+ /** Polls the killed group, so the escalation holds the host only while something it would reach is alive. */
470
+ let reaping: NodeJS.Timeout | undefined;
471
+ /** After the shell exits, bounds the wait for a process it left holding stdout or stderr. */
472
+ let draining: NodeJS.Timeout | undefined;
473
+ const release = (): void => {
474
+ clearTimeout(escalation);
475
+ clearInterval(reaping);
476
+ untrack(child);
477
+ };
478
+ const reap = (): void => {
479
+ if (!runAlive(child)) {
480
+ release();
481
+ }
482
+ };
483
+ const stop = (end: RunEnd): void => {
484
+ if (!killed) {
485
+ killed = true;
486
+ killRun(child, KILL_SIGNAL);
487
+ escalation = setTimeout(() => {
488
+ killRun(child, FORCE_SIGNAL);
489
+ release();
490
+ }, killGraceMs);
491
+ reaping = setInterval(reap, REAP_POLL_MS);
492
+ reaping.unref();
493
+ }
494
+ child.stdout?.destroy();
495
+ child.stderr?.destroy();
496
+ fail(end);
497
+ };
498
+ const stdout = collect(child.stdout, () => stop({ kind: 'overflow' }));
499
+ const stderr = collect(child.stderr, () => stop({ kind: 'overflow' }));
500
+ const onAbandon = (): void => stop({ kind: 'abandoned' });
501
+ const timer = setTimeout(() => stop({ kind: 'timeout' }), timeoutMs);
502
+ abandoned.addEventListener('abort', onAbandon, { once: true });
503
+
504
+ const finish = (): boolean => {
505
+ if (settled) {
506
+ return false;
507
+ }
508
+ settled = true;
509
+ clearTimeout(timer);
510
+ clearTimeout(draining);
511
+ abandoned.removeEventListener('abort', onAbandon);
512
+ return true;
513
+ };
514
+ function fail(end: RunEnd): void {
515
+ if (!finish()) {
516
+ return;
517
+ }
518
+ /**
519
+ * Any stdout line may be the token, since a successful run accepts
520
+ * one of any length, and the cached and recent tokens are known
521
+ * credentials; all are listed whatever their length, at the cost of a
522
+ * garbled excerpt.
523
+ */
524
+ const secrets = [
525
+ ...echoed,
526
+ ...stdout().split(/\r?\n/),
527
+ cached,
528
+ ...known,
529
+ ];
530
+ const { failure, reason } = classify(end, refusals);
531
+ reject(
532
+ new DecisionError(
533
+ failure,
534
+ describeFailure(reason, stderr(), secrets, scrubbable),
535
+ { provider: COMMAND_TOKEN_PROVIDER }
536
+ )
537
+ );
538
+ }
539
+ /** Settles a run that ended on its own, from what it printed. */
540
+ const ended = (code: number | null, signal: string | null): void => {
541
+ if (!killed) {
542
+ untrack(child);
543
+ }
544
+ if (code !== 0) {
545
+ fail(closedEnd(code, signal));
546
+ return;
547
+ }
548
+ if (!finish()) {
549
+ return;
550
+ }
551
+ const token = lastLine(stdout());
552
+ if (token === '') {
553
+ reject(
554
+ new DecisionError(
555
+ 'unauthorized',
556
+ 'token command printed no token',
557
+ {
558
+ provider: COMMAND_TOKEN_PROVIDER,
559
+ }
560
+ )
561
+ );
562
+ return;
563
+ }
564
+ remember(token);
565
+ if (!abandoned.aborted && feedsCache()) {
566
+ cached = token;
567
+ cachedGeneration = generation;
568
+ /** From completion, so a slow command cannot hand out a token that is already expired. */
569
+ expiresAt = Date.now() + ttlMs;
570
+ }
571
+ resolve(token);
572
+ };
573
+
574
+ child.once('error', () => fail({ kind: 'spawn' }));
575
+ child.once('exit', (code: number | null, signal: string | null) => {
576
+ clearTimeout(timer);
577
+ if (killed) {
578
+ reap();
579
+ return;
580
+ }
581
+ draining = setTimeout(() => {
582
+ child.stdout?.destroy();
583
+ child.stderr?.destroy();
584
+ ended(code, signal);
585
+ }, DRAIN_MS);
586
+ });
587
+ child.once('close', (code: number | null, signal: string | null) => {
588
+ if (killed) {
589
+ reap();
590
+ return;
591
+ }
592
+ ended(code, signal);
593
+ });
594
+ });
595
+
596
+ const start = (): SharedRun => {
597
+ const abandon = new AbortController();
598
+ const generation = breaker?.generation;
599
+ const shared: SharedRun = {
600
+ token: run(abandon.signal, generation, () => !shared.detached),
601
+ waiters: 0,
602
+ abandon,
603
+ generation,
604
+ detached: false,
605
+ };
606
+ const settle = (): void => {
607
+ if (pending === shared) {
608
+ pending = null;
609
+ }
610
+ };
611
+ shared.token.then(settle, settle);
612
+ return shared;
613
+ };
614
+
615
+ /** One caller's view of a shared run; the run is killed only when its last caller leaves. */
616
+ const join = (shared: SharedRun, signal?: AbortSignal): Promise<string> =>
617
+ new Promise<string>((resolve, reject) => {
618
+ shared.waiters += 1;
619
+ const onAbort = (): void => {
620
+ shared.waiters -= 1;
621
+ if (shared.waiters === 0) {
622
+ if (pending === shared) {
623
+ pending = null;
624
+ }
625
+ shared.abandon.abort();
626
+ }
627
+ reject(abandonedError());
628
+ };
629
+ signal?.addEventListener('abort', onAbort, { once: true });
630
+ shared.token.then(
631
+ (token) => {
632
+ signal?.removeEventListener('abort', onAbort);
633
+ resolve(token);
634
+ },
635
+ (error: unknown) => {
636
+ signal?.removeEventListener('abort', onAbort);
637
+ reject(error);
638
+ }
639
+ );
640
+ });
641
+
642
+ return ({ refresh, refused, signal }): Promise<string> => {
643
+ if (signal?.aborted === true) {
644
+ return Promise.reject(abandonedError());
645
+ }
646
+ if (refused !== undefined) {
647
+ remember(refused);
648
+ }
649
+ /** A run from before a breaker reset carries the credential state the reset was meant to clear; its callers keep it, new ones start fresh. */
650
+ if (pending !== null && pending.generation !== breaker?.generation) {
651
+ pending.detached = true;
652
+ pending = null;
653
+ }
654
+ /** A refusal of an older token says nothing about the one cached since. */
655
+ if (refresh && (refused === undefined || refused === cached)) {
656
+ /** The cached token was refused; never hand it out again. */
657
+ expiresAt = 0;
658
+ }
659
+ /** A token minted before a reset is stale evidence too, even when its run settled before anyone arrived to detach it. */
660
+ if (
661
+ pending === null &&
662
+ cached !== null &&
663
+ cachedGeneration === breaker?.generation &&
664
+ Date.now() < expiresAt
665
+ ) {
666
+ return Promise.resolve(cached);
667
+ }
668
+ pending ??= start();
669
+ return join(pending, signal);
670
+ };
671
+ }