dsh-taskbridge 1.7.1 → 1.8.1

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 (84) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/LICENSE +21 -21
  3. package/README.md +733 -877
  4. package/THIRD_PARTY_NOTICES.txt +23 -23
  5. package/antigravity/agents/dsh-taskbridge.md +32 -0
  6. package/antigravity/skills/dsh-taskbridge/SKILL.md +51 -0
  7. package/codex/dsh-taskbridge.toml +181 -631
  8. package/cordis.patch.yml +6 -6
  9. package/docs/INTRODUCTION.md +122 -295
  10. package/docs/INTRODUCTION.zh.md +134 -279
  11. package/docs/antigravity-integration.md +42 -0
  12. package/docs/auth-contract.md +138 -138
  13. package/docs/claude-code.md +6 -11
  14. package/docs/codex-integration.md +2 -2
  15. package/docs/contracts-stage-b.md +443 -443
  16. package/docs/conversation-placement.md +7 -6
  17. package/docs/plugin-market.md +30 -30
  18. package/docs/redaction-contract.md +170 -170
  19. package/docs/releases/1.7.0.zh.md +11 -11
  20. package/docs/releases/1.8.0.zh.md +16 -0
  21. package/docs/releases/1.8.1.zh.md +24 -0
  22. package/docs/runtime-compatibility.md +1 -1
  23. package/docs/taskbridge-upgrade.md +28 -28
  24. package/docs/taskdispatch-upgrade.md +25 -25
  25. package/docs/workspace-contract.md +538 -538
  26. package/docs/workspace-grouping.md +126 -126
  27. package/icon.svg +1 -1
  28. package/lib/client.d.ts +804 -699
  29. package/lib/client.js +7 -7
  30. package/locale/en.json +1 -1
  31. package/locale/zh.json +1 -1
  32. package/package.json +150 -144
  33. package/src/antigravity/installer.js +1068 -0
  34. package/src/antigravity/seam.js +142 -0
  35. package/src/auth/fence.js +361 -361
  36. package/src/auth/grants.js +789 -789
  37. package/src/client/api.js +266 -3
  38. package/src/client/index.jsx +224 -11
  39. package/src/client/sidebar.jsx +862 -862
  40. package/src/client/styles.js +624 -624
  41. package/src/client/task-cleanup.js +429 -304
  42. package/src/client/task-records-table.jsx +217 -217
  43. package/src/client/task-view.js +307 -307
  44. package/src/client/workspace-groups.js +482 -482
  45. package/src/client/workspaces-browser.jsx +770 -770
  46. package/src/codex/agent-ownership.js +270 -270
  47. package/src/codex/installer.js +6 -0
  48. package/src/codex/toml.js +784 -784
  49. package/src/config/defaults.js +11 -15
  50. package/src/config/redact.js +245 -245
  51. package/src/config/store.js +186 -186
  52. package/src/credentials/seam.js +202 -202
  53. package/src/http/respond.js +6 -5
  54. package/src/http/user-plane.js +83 -1
  55. package/src/index.js +25 -0
  56. package/src/jobs/diagnostics.js +15 -15
  57. package/src/jobs/engine.js +1 -0
  58. package/src/jobs/history.js +1 -1
  59. package/src/jobs/plan-store.js +1103 -1020
  60. package/src/jobs/record-cleanup.js +452 -7
  61. package/src/jobs/review-note.js +63 -63
  62. package/src/jobs/task-descriptions.js +82 -82
  63. package/src/jobs/task-display.js +73 -73
  64. package/src/jobs/task-tree.js +786 -786
  65. package/src/jobs/title.js +134 -134
  66. package/src/mcp/continuation.js +317 -317
  67. package/src/mcp/server.js +34 -27
  68. package/src/mcp/wait.js +34 -15
  69. package/src/model/connectivity.js +371 -371
  70. package/src/model/discovery.js +582 -582
  71. package/src/model/native-catalog.js +68 -68
  72. package/src/model/openai-adapter.js +671 -671
  73. package/src/model/probe.js +264 -264
  74. package/src/model/providers.js +756 -756
  75. package/src/model/routing.js +321 -321
  76. package/src/runtime/agent-runner.js +1 -0
  77. package/src/runtime/permissions.js +1619 -1619
  78. package/src/runtime/question-call.js +162 -162
  79. package/src/runtime/questions.js +909 -909
  80. package/src/runtime/session-placement.js +36 -1
  81. package/src/runtime/worker-prompt.js +61 -55
  82. package/src/workspace/audit.js +775 -775
  83. package/src/workspace/preflight.js +424 -424
  84. package/src/workspace/worktrees.js +833 -679
@@ -102,27 +102,23 @@ export const LIMITS = Object.freeze({
102
102
  });
103
103
 
104
104
  /**
105
- * Default activity-monitoring thresholds, in seconds of *inactivity*.
105
+ * Default progress-and-monitoring thresholds, in seconds.
106
106
  *
107
- * There is exactly ONE time base: consecutive time without real progress. Real progress
108
- * — model output, a reasoning step, a tool call or a tool result — resets it; a
109
- * heartbeat, a result poll, the self-check itself and a plain state read do not.
107
+ * `selfCheckSeconds` measures elapsed time from run start for one read-only local
108
+ * inspection (default 10 minutes; does not require a host to be waiting).
110
109
  *
111
- * Two reminders are measured on that clock, and each can be switched off with `0`:
112
- *
113
- * * `selfCheckSeconds` — one read-only local inspection (default 10 minutes);
114
- * * `attentionSeconds` — one notification to the commander asking it to check the
115
- * run's progress (default 40 minutes).
116
- *
117
- * Neither depends on total runtime, so a task that keeps working for hours produces
118
- * neither. Nothing here ever ends, cancels or restarts a run: a reminder is a REPORT,
119
- * never a verdict.
110
+ * `attentionSeconds` measures how long nothing new has been RETURNED to the commander
111
+ * (default 40 minutes). Internal model/tool activity, heartbeats, permission/question
112
+ * waits, and local self-checks do NOT reset this delivery clock; only a real stage
113
+ * result or terminal delivery moves it. Neither threshold ever ends, cancels, or restarts
114
+ * a run: a reminder is a progress checkpoint, never a verdict.
120
115
  */
121
116
  export const MONITORING_DEFAULTS = Object.freeze({
122
- /** No-progress span after which one read-only local self-check is performed (0 = off). */
117
+ /** Elapsed seconds from run start after which one read-only local self-check runs (0 = off). */
123
118
  selfCheckSeconds: 10 * 60,
124
119
  /**
125
- * No-progress span after which the wait reports the run progress check (0 = off).
120
+ * Seconds without returning a new result to the commander before the wait reports a
121
+ * run progress check (0 = off).
126
122
  *
127
123
  * This is the ONE notification interval: it doubles as the point at which a host is
128
124
  * asked to confirm the goal, so there is no second duration to configure.
@@ -1,245 +1,245 @@
1
- // Secret masking and structural redaction.
2
- //
3
- // One rule governs every public surface: a stored secret value never leaves the
4
- // module that read it. Configuration surfaces, job history, MCP results and
5
- // logs carry a masked marker at most.
6
-
7
- /** Masked placeholder returned wherever a credential would otherwise appear. */
8
- export const MASK = '••••••••';
9
-
10
- const SECRET_KEY_PATTERN = /(api[_-]?key|apikey|secret|token|password|passwd|credential[_-]?value|authorization)/i;
11
- const BEARER_PATTERN = /\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi;
12
- const KEYLIKE_PATTERN = /\b(sk|pk|ak)-[A-Za-z0-9_-]{16,}\b/g;
13
- const ASSIGNMENT_PATTERN = /\b([A-Za-z0-9_]*(?:API_?KEY|SECRET|TOKEN|PASSWORD)[A-Za-z0-9_]*)\s*=\s*("[^"]*"|'[^']*'|\S+)/gi;
14
- /**
15
- * A per-user profile directory under the OPERATING SYSTEM'S temporary root.
16
- *
17
- * The observed shape is `%TEMP%\dsh-VG1MVl\dsh-delegate-test-…` (and on some hosts
18
- * `~/.cache/dsh-SoexNz/…`): the platform points `TEMP` at a per-profile directory
19
- * whose six-character suffix is the account key. That suffix is exactly what is
20
- * masked, and the marker is `dsh-`/`profile-` plus six characters plus digits —
21
- * nothing more.
22
- *
23
- * Two earlier versions were wrong in opposite directions, so the rule is stated
24
- * around what is PROVABLE instead of around what looks unusual:
25
- *
26
- * * the first masked every `dsh-`/`profile-` segment with six alphanumerics, so an
27
- * ordinary repository or package name — this product's own `dsh-delegate` and its
28
- * installed `dsh-taskbridge` — was rewritten in every published path;
29
- * * the second tried to tell a profile key from a word by case and digit shape. That
30
- * is a guess: a repository may be `v2-tools`, a package `dsh-Bridge2`. A masked
31
- * path proves nothing, so a guess that fires wrongly disables continuation.
32
- *
33
- * A profile key is only recognised where it actually lives: directly under a
34
- * temporary root ({@link TEMPORARY_ROOT}), or anywhere in such a path. An ordinary
35
- * segment elsewhere, whatever its case or digits, keeps its readable path.
36
- *
37
- * The preceding separator is captured and re-emitted so a Windows path keeps its
38
- * backslash; a combined character class would normalise `\` to `/`.
39
- */
40
- const PROFILE_SEGMENT = String.raw`(?:dsh|profile)-[A-Za-z0-9]{6}(?![A-Za-z0-9])`;
41
-
42
- /**
43
- * The directory names the platform's temporary root is reached through.
44
- *
45
- * `temp` is the Windows/POSIX temporary root; `tmp` and `.cache` cover the POSIX and
46
- * per-user-cache spellings. They are matched as complete, case-insensitive segment
47
- * names, so they anchor WHERE a profile key may appear rather than being redacted.
48
- */
49
- const TEMPORARY_ROOT = String.raw`(?:temp|tmp|\.cache)`;
50
-
51
- /**
52
- * Mask a profile key only where it is provably one: as a segment directly under a
53
- * temporary root. Both the separator and the temp-root segment are kept; only the key
54
- * is replaced, so `…\Temp\dsh-VG1MVl\work` becomes `…\Temp\<mask>\work` and the
55
- * platform's own separator survives (`/home/u/.cache/<mask>/x`).
56
- *
57
- * Two anchored forms, because a stored path may start at the root or continue through
58
- * it:
59
- *
60
- * 1. `…<sep><temp><sep><key>…` — separators are captured and re-emitted verbatim;
61
- * 2. `^<temp><sep><key>…` — the path begins with the root, e.g. `temp\dsh-abc123\x`.
62
- */
63
- const PATH_KEY_PATTERN = new RegExp(
64
- [
65
- String.raw`([\\/])`,
66
- `(${TEMPORARY_ROOT})`,
67
- String.raw`([\\/])`,
68
- // The placeholder itself is never rewritten again, so redaction is idempotent.
69
- String.raw`(?!(?:dsh|profile)-mask)`,
70
- PROFILE_SEGMENT,
71
- String.raw`(?=[\\/]|$)`,
72
- ].join(''),
73
- 'gi',
74
- );
75
-
76
- /** The same rule for a path that STARTS with the temporary root (`temp\dsh-abc123\x`). */
77
- const LEADING_TEMP_KEY_PATTERN = new RegExp(
78
- [`^(${TEMPORARY_ROOT})`, String.raw`([\\/])`, PROFILE_SEGMENT, String.raw`(?=[\\/]|$)`].join(''),
79
- 'i',
80
- );
81
-
82
- /** What {@link PATH_KEY_PATTERN} replaces the identifying segment with. */
83
- const PATH_KEY_SEGMENT = 'masks-user-profile-segment';
84
-
85
- /**
86
- * Exact names of model usage counters. These keys contain the substring `token`,
87
- * so the secret-key pattern alone would mask every prompt/completion count and
88
- * publish nothing about what a run actually consumed.
89
- *
90
- * The exemption is deliberately an allow-list of exact names, not a `*Tokens`
91
- * suffix rule: a suffix rule would exempt `refreshTokens` and every future
92
- * credential field that happens to end in the same letters. The listed keys are
93
- * also only exempt for a finite non-negative number (see {@link isUsageCounter});
94
- * a string, object or array behind one of these names is still masked.
95
- */
96
- const USAGE_COUNTER_KEYS = new Set([
97
- 'inputTokens',
98
- 'outputTokens',
99
- 'totalTokens',
100
- 'reasoningTokens',
101
- 'cacheTokens',
102
- 'cacheReadTokens',
103
- 'cacheWriteTokens',
104
- 'input_tokens',
105
- 'output_tokens',
106
- 'total_tokens',
107
- 'reasoning_tokens',
108
- 'cache_tokens',
109
- 'cache_read_tokens',
110
- 'cache_write_tokens',
111
- ]);
112
-
113
- /**
114
- * Whether a settings key names a secret that must be masked on the way out.
115
- * @param {string} key - object key.
116
- * @returns {boolean} true when the value behind this key is a secret.
117
- */
118
- export function isSecretKey(key) {
119
- return typeof key === 'string' && SECRET_KEY_PATTERN.test(key);
120
- }
121
-
122
- /**
123
- * Whether a key/value pair is a usage counter that may be published as a number.
124
- * Requires both an exact counter name and a finite, non-negative number, so a
125
- * credential stored under a counter-shaped name is still masked.
126
- * @param {string} key - object key.
127
- * @param {unknown} value - value behind that key.
128
- * @returns {boolean} true when the value is a plain usage count.
129
- */
130
- export function isUsageCounter(key, value) {
131
- if (typeof key !== 'string' || !USAGE_COUNTER_KEYS.has(key)) return false;
132
- return typeof value === 'number' && Number.isFinite(value) && value >= 0;
133
- }
134
-
135
- /**
136
- * Mask a secret for display. Short values are fully masked so a mask never
137
- * leaks length or a prefix of a real credential.
138
- * @param {string} value - secret value.
139
- * @returns {string} masked marker.
140
- */
141
- export function maskSecret(value) {
142
- if (typeof value !== 'string' || value === '') return '';
143
- return MASK;
144
- }
145
-
146
- /**
147
- * Replace credential-looking text inside free-form output (diff, model text,
148
- * diagnostics). This is a safety net for values we never intended to see, not a
149
- * substitute for not reading them.
150
- * @param {string} text - untrusted text.
151
- * @returns {string} text with credential-shaped substrings replaced.
152
- */
153
- export function redactText(text) {
154
- if (typeof text !== 'string' || text === '') return '';
155
- return text
156
- .replace(BEARER_PATTERN, `Bearer ${MASK}`)
157
- .replace(KEYLIKE_PATTERN, MASK)
158
- .replace(ASSIGNMENT_PATTERN, (_match, name) => `${name}=${MASK}`)
159
- // Last, and path-anchored: an ordinary workspace path is shown so an operator can
160
- // recognise the repository; only a profile key under a temporary root is masked.
161
- // The leading-root form runs first. Each pass re-emits every separator and the
162
- // temp-root segment it matched, so a POSIX `.cache` path keeps its `/`.
163
- .replace(LEADING_TEMP_KEY_PATTERN, (_match, root, separator) => `${root}${separator}${PATH_KEY_SEGMENT}`)
164
- .replace(
165
- PATH_KEY_PATTERN,
166
- (_match, before, root, separator) => `${before}${root}${separator}${PATH_KEY_SEGMENT}`,
167
- );
168
- }
169
-
170
- /**
171
- * Deep-redact a JSON-compatible value: secret-named keys become the mask and
172
- * every string is passed through {@link redactText}.
173
- *
174
- * The one exemption is a genuine model usage counter (exact known name plus a
175
- * finite non-negative number), so a job record can report what it consumed
176
- * instead of a wall of masks.
177
- * @param {unknown} value - value to project.
178
- * @param {number} [depth] - remaining recursion depth.
179
- * @returns {unknown} redacted copy.
180
- */
181
- export function redactDeep(value, depth = 0) {
182
- if (depth > 12) return '[depth-limit]';
183
- if (value === null || value === undefined) return value ?? null;
184
- if (typeof value === 'string') return redactText(value);
185
- if (typeof value === 'number' || typeof value === 'boolean') return value;
186
- if (Array.isArray(value)) return value.map((item) => redactDeep(item, depth + 1));
187
- if (typeof value === 'object') {
188
- const out = {};
189
- for (const [key, item] of Object.entries(value)) {
190
- if (isUsageCounter(key, item)) {
191
- out[key] = item;
192
- continue;
193
- }
194
- if (isSecretKey(key) && item !== null && item !== undefined && item !== '') {
195
- out[key] = typeof item === 'string' ? maskSecret(item) : MASK;
196
- continue;
197
- }
198
- out[key] = redactDeep(item, depth + 1);
199
- }
200
- return out;
201
- }
202
- return String(value);
203
- }
204
-
205
- /**
206
- * Truncate and redact a diagnostic string for durable storage.
207
- *
208
- * This lives here, beside {@link redactText}, rather than in the agent runner
209
- * that first needed it: it is a pure string transform with no harness
210
- * dependency, and the stdio MCP executable imports it too. Leaving it in
211
- * `runtime/agent-runner.js` forced that standalone process to statically import
212
- * `@deepseek-ai/dsh-llm` and `@deepseek-ai/dsh-agent` — packages only the DSH
213
- * runtime provides — so the executable died with `ERR_MODULE_NOT_FOUND` before
214
- * it could even report a missing token.
215
- * @param {unknown} value - raw error text.
216
- * @param {number} [max] - character bound.
217
- * @returns {string | null} redacted text, or null.
218
- */
219
- export function diagnostic(value, max = 800) {
220
- if (value === null || value === undefined) return null;
221
- const text = typeof value === 'string' ? value : String(value);
222
- if (text === '') return null;
223
- return redactText(text.slice(0, max));
224
- }
225
-
226
- const SENSITIVE_SUFFIXES = ['.pem', '.key', '.pfx', '.p12'];
227
- const SENSITIVE_PREFIXES = ['credentials', 'secret', 'id_rsa', 'id_ed25519'];
228
- const ENV_BASENAME = '.env';
229
-
230
- /**
231
- * Whether a workspace path names credential material whose content must never
232
- * be captured into a diff or evidence bundle. The path itself stays visible as
233
- * a changed file; only its content is withheld.
234
- * @param {string} relPath - workspace-relative path.
235
- * @returns {boolean} true when content must be withheld.
236
- */
237
- export function isSensitivePath(relPath) {
238
- const segments = String(relPath ?? '').replace(/\\/g, '/').split('/');
239
- return segments.some((raw) => {
240
- const seg = raw.toLowerCase();
241
- if (seg === ENV_BASENAME || seg.startsWith(`${ENV_BASENAME}.`)) return true;
242
- if (SENSITIVE_PREFIXES.some((prefix) => seg.startsWith(prefix))) return true;
243
- return SENSITIVE_SUFFIXES.some((suffix) => seg.endsWith(suffix));
244
- });
245
- }
1
+ // Secret masking and structural redaction.
2
+ //
3
+ // One rule governs every public surface: a stored secret value never leaves the
4
+ // module that read it. Configuration surfaces, job history, MCP results and
5
+ // logs carry a masked marker at most.
6
+
7
+ /** Masked placeholder returned wherever a credential would otherwise appear. */
8
+ export const MASK = '••••••••';
9
+
10
+ const SECRET_KEY_PATTERN = /(api[_-]?key|apikey|secret|token|password|passwd|credential[_-]?value|authorization)/i;
11
+ const BEARER_PATTERN = /\bBearer\s+[A-Za-z0-9._~+/=-]{12,}/gi;
12
+ const KEYLIKE_PATTERN = /\b(sk|pk|ak)-[A-Za-z0-9_-]{16,}\b/g;
13
+ const ASSIGNMENT_PATTERN = /\b([A-Za-z0-9_]*(?:API_?KEY|SECRET|TOKEN|PASSWORD)[A-Za-z0-9_]*)\s*=\s*("[^"]*"|'[^']*'|\S+)/gi;
14
+ /**
15
+ * A per-user profile directory under the OPERATING SYSTEM'S temporary root.
16
+ *
17
+ * The observed shape is `%TEMP%\dsh-VG1MVl\dsh-delegate-test-…` (and on some hosts
18
+ * `~/.cache/dsh-SoexNz/…`): the platform points `TEMP` at a per-profile directory
19
+ * whose six-character suffix is the account key. That suffix is exactly what is
20
+ * masked, and the marker is `dsh-`/`profile-` plus six characters plus digits —
21
+ * nothing more.
22
+ *
23
+ * Two earlier versions were wrong in opposite directions, so the rule is stated
24
+ * around what is PROVABLE instead of around what looks unusual:
25
+ *
26
+ * * the first masked every `dsh-`/`profile-` segment with six alphanumerics, so an
27
+ * ordinary repository or package name — this product's own `dsh-delegate` and its
28
+ * installed `dsh-taskbridge` — was rewritten in every published path;
29
+ * * the second tried to tell a profile key from a word by case and digit shape. That
30
+ * is a guess: a repository may be `v2-tools`, a package `dsh-Bridge2`. A masked
31
+ * path proves nothing, so a guess that fires wrongly disables continuation.
32
+ *
33
+ * A profile key is only recognised where it actually lives: directly under a
34
+ * temporary root ({@link TEMPORARY_ROOT}), or anywhere in such a path. An ordinary
35
+ * segment elsewhere, whatever its case or digits, keeps its readable path.
36
+ *
37
+ * The preceding separator is captured and re-emitted so a Windows path keeps its
38
+ * backslash; a combined character class would normalise `\` to `/`.
39
+ */
40
+ const PROFILE_SEGMENT = String.raw`(?:dsh|profile)-[A-Za-z0-9]{6}(?![A-Za-z0-9])`;
41
+
42
+ /**
43
+ * The directory names the platform's temporary root is reached through.
44
+ *
45
+ * `temp` is the Windows/POSIX temporary root; `tmp` and `.cache` cover the POSIX and
46
+ * per-user-cache spellings. They are matched as complete, case-insensitive segment
47
+ * names, so they anchor WHERE a profile key may appear rather than being redacted.
48
+ */
49
+ const TEMPORARY_ROOT = String.raw`(?:temp|tmp|\.cache)`;
50
+
51
+ /**
52
+ * Mask a profile key only where it is provably one: as a segment directly under a
53
+ * temporary root. Both the separator and the temp-root segment are kept; only the key
54
+ * is replaced, so `…\Temp\dsh-VG1MVl\work` becomes `…\Temp\<mask>\work` and the
55
+ * platform's own separator survives (`/home/u/.cache/<mask>/x`).
56
+ *
57
+ * Two anchored forms, because a stored path may start at the root or continue through
58
+ * it:
59
+ *
60
+ * 1. `…<sep><temp><sep><key>…` — separators are captured and re-emitted verbatim;
61
+ * 2. `^<temp><sep><key>…` — the path begins with the root, e.g. `temp\dsh-abc123\x`.
62
+ */
63
+ const PATH_KEY_PATTERN = new RegExp(
64
+ [
65
+ String.raw`([\\/])`,
66
+ `(${TEMPORARY_ROOT})`,
67
+ String.raw`([\\/])`,
68
+ // The placeholder itself is never rewritten again, so redaction is idempotent.
69
+ String.raw`(?!(?:dsh|profile)-mask)`,
70
+ PROFILE_SEGMENT,
71
+ String.raw`(?=[\\/]|$)`,
72
+ ].join(''),
73
+ 'gi',
74
+ );
75
+
76
+ /** The same rule for a path that STARTS with the temporary root (`temp\dsh-abc123\x`). */
77
+ const LEADING_TEMP_KEY_PATTERN = new RegExp(
78
+ [`^(${TEMPORARY_ROOT})`, String.raw`([\\/])`, PROFILE_SEGMENT, String.raw`(?=[\\/]|$)`].join(''),
79
+ 'i',
80
+ );
81
+
82
+ /** What {@link PATH_KEY_PATTERN} replaces the identifying segment with. */
83
+ const PATH_KEY_SEGMENT = 'masks-user-profile-segment';
84
+
85
+ /**
86
+ * Exact names of model usage counters. These keys contain the substring `token`,
87
+ * so the secret-key pattern alone would mask every prompt/completion count and
88
+ * publish nothing about what a run actually consumed.
89
+ *
90
+ * The exemption is deliberately an allow-list of exact names, not a `*Tokens`
91
+ * suffix rule: a suffix rule would exempt `refreshTokens` and every future
92
+ * credential field that happens to end in the same letters. The listed keys are
93
+ * also only exempt for a finite non-negative number (see {@link isUsageCounter});
94
+ * a string, object or array behind one of these names is still masked.
95
+ */
96
+ const USAGE_COUNTER_KEYS = new Set([
97
+ 'inputTokens',
98
+ 'outputTokens',
99
+ 'totalTokens',
100
+ 'reasoningTokens',
101
+ 'cacheTokens',
102
+ 'cacheReadTokens',
103
+ 'cacheWriteTokens',
104
+ 'input_tokens',
105
+ 'output_tokens',
106
+ 'total_tokens',
107
+ 'reasoning_tokens',
108
+ 'cache_tokens',
109
+ 'cache_read_tokens',
110
+ 'cache_write_tokens',
111
+ ]);
112
+
113
+ /**
114
+ * Whether a settings key names a secret that must be masked on the way out.
115
+ * @param {string} key - object key.
116
+ * @returns {boolean} true when the value behind this key is a secret.
117
+ */
118
+ export function isSecretKey(key) {
119
+ return typeof key === 'string' && SECRET_KEY_PATTERN.test(key);
120
+ }
121
+
122
+ /**
123
+ * Whether a key/value pair is a usage counter that may be published as a number.
124
+ * Requires both an exact counter name and a finite, non-negative number, so a
125
+ * credential stored under a counter-shaped name is still masked.
126
+ * @param {string} key - object key.
127
+ * @param {unknown} value - value behind that key.
128
+ * @returns {boolean} true when the value is a plain usage count.
129
+ */
130
+ export function isUsageCounter(key, value) {
131
+ if (typeof key !== 'string' || !USAGE_COUNTER_KEYS.has(key)) return false;
132
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;
133
+ }
134
+
135
+ /**
136
+ * Mask a secret for display. Short values are fully masked so a mask never
137
+ * leaks length or a prefix of a real credential.
138
+ * @param {string} value - secret value.
139
+ * @returns {string} masked marker.
140
+ */
141
+ export function maskSecret(value) {
142
+ if (typeof value !== 'string' || value === '') return '';
143
+ return MASK;
144
+ }
145
+
146
+ /**
147
+ * Replace credential-looking text inside free-form output (diff, model text,
148
+ * diagnostics). This is a safety net for values we never intended to see, not a
149
+ * substitute for not reading them.
150
+ * @param {string} text - untrusted text.
151
+ * @returns {string} text with credential-shaped substrings replaced.
152
+ */
153
+ export function redactText(text) {
154
+ if (typeof text !== 'string' || text === '') return '';
155
+ return text
156
+ .replace(BEARER_PATTERN, `Bearer ${MASK}`)
157
+ .replace(KEYLIKE_PATTERN, MASK)
158
+ .replace(ASSIGNMENT_PATTERN, (_match, name) => `${name}=${MASK}`)
159
+ // Last, and path-anchored: an ordinary workspace path is shown so an operator can
160
+ // recognise the repository; only a profile key under a temporary root is masked.
161
+ // The leading-root form runs first. Each pass re-emits every separator and the
162
+ // temp-root segment it matched, so a POSIX `.cache` path keeps its `/`.
163
+ .replace(LEADING_TEMP_KEY_PATTERN, (_match, root, separator) => `${root}${separator}${PATH_KEY_SEGMENT}`)
164
+ .replace(
165
+ PATH_KEY_PATTERN,
166
+ (_match, before, root, separator) => `${before}${root}${separator}${PATH_KEY_SEGMENT}`,
167
+ );
168
+ }
169
+
170
+ /**
171
+ * Deep-redact a JSON-compatible value: secret-named keys become the mask and
172
+ * every string is passed through {@link redactText}.
173
+ *
174
+ * The one exemption is a genuine model usage counter (exact known name plus a
175
+ * finite non-negative number), so a job record can report what it consumed
176
+ * instead of a wall of masks.
177
+ * @param {unknown} value - value to project.
178
+ * @param {number} [depth] - remaining recursion depth.
179
+ * @returns {unknown} redacted copy.
180
+ */
181
+ export function redactDeep(value, depth = 0) {
182
+ if (depth > 12) return '[depth-limit]';
183
+ if (value === null || value === undefined) return value ?? null;
184
+ if (typeof value === 'string') return redactText(value);
185
+ if (typeof value === 'number' || typeof value === 'boolean') return value;
186
+ if (Array.isArray(value)) return value.map((item) => redactDeep(item, depth + 1));
187
+ if (typeof value === 'object') {
188
+ const out = {};
189
+ for (const [key, item] of Object.entries(value)) {
190
+ if (isUsageCounter(key, item)) {
191
+ out[key] = item;
192
+ continue;
193
+ }
194
+ if (isSecretKey(key) && item !== null && item !== undefined && item !== '') {
195
+ out[key] = typeof item === 'string' ? maskSecret(item) : MASK;
196
+ continue;
197
+ }
198
+ out[key] = redactDeep(item, depth + 1);
199
+ }
200
+ return out;
201
+ }
202
+ return String(value);
203
+ }
204
+
205
+ /**
206
+ * Truncate and redact a diagnostic string for durable storage.
207
+ *
208
+ * This lives here, beside {@link redactText}, rather than in the agent runner
209
+ * that first needed it: it is a pure string transform with no harness
210
+ * dependency, and the stdio MCP executable imports it too. Leaving it in
211
+ * `runtime/agent-runner.js` forced that standalone process to statically import
212
+ * `@deepseek-ai/dsh-llm` and `@deepseek-ai/dsh-agent` — packages only the DSH
213
+ * runtime provides — so the executable died with `ERR_MODULE_NOT_FOUND` before
214
+ * it could even report a missing token.
215
+ * @param {unknown} value - raw error text.
216
+ * @param {number} [max] - character bound.
217
+ * @returns {string | null} redacted text, or null.
218
+ */
219
+ export function diagnostic(value, max = 800) {
220
+ if (value === null || value === undefined) return null;
221
+ const text = typeof value === 'string' ? value : String(value);
222
+ if (text === '') return null;
223
+ return redactText(text.slice(0, max));
224
+ }
225
+
226
+ const SENSITIVE_SUFFIXES = ['.pem', '.key', '.pfx', '.p12'];
227
+ const SENSITIVE_PREFIXES = ['credentials', 'secret', 'id_rsa', 'id_ed25519'];
228
+ const ENV_BASENAME = '.env';
229
+
230
+ /**
231
+ * Whether a workspace path names credential material whose content must never
232
+ * be captured into a diff or evidence bundle. The path itself stays visible as
233
+ * a changed file; only its content is withheld.
234
+ * @param {string} relPath - workspace-relative path.
235
+ * @returns {boolean} true when content must be withheld.
236
+ */
237
+ export function isSensitivePath(relPath) {
238
+ const segments = String(relPath ?? '').replace(/\\/g, '/').split('/');
239
+ return segments.some((raw) => {
240
+ const seg = raw.toLowerCase();
241
+ if (seg === ENV_BASENAME || seg.startsWith(`${ENV_BASENAME}.`)) return true;
242
+ if (SENSITIVE_PREFIXES.some((prefix) => seg.startsWith(prefix))) return true;
243
+ return SENSITIVE_SUFFIXES.some((suffix) => seg.endsWith(suffix));
244
+ });
245
+ }