@ran-sh/dsh-crew 1.9.0 → 1.10.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 (151) hide show
  1. package/.claude-plugin/marketplace.json +16 -16
  2. package/.claude-plugin/plugin.json +14 -14
  3. package/LICENSE +21 -21
  4. package/README.de.md +359 -359
  5. package/README.es.md +359 -359
  6. package/README.fr.md +359 -359
  7. package/README.hi.md +359 -359
  8. package/README.id.md +359 -359
  9. package/README.ja.md +359 -359
  10. package/README.ko.md +359 -359
  11. package/README.md +126 -126
  12. package/README.pt.md +359 -359
  13. package/README.ru.md +359 -359
  14. package/README.th.md +359 -359
  15. package/README.tr.md +359 -359
  16. package/README.vi.md +359 -359
  17. package/README.zh-TW.md +359 -359
  18. package/README.zh.md +116 -116
  19. package/agents/ds-flash.md +24 -24
  20. package/agents/ds-pro.md +24 -24
  21. package/agents/ds-reviewer.md +23 -23
  22. package/agents/ds-worker.md +23 -23
  23. package/bin/dsh-crew.mjs +16 -16
  24. package/codex/agents/ds-flash.toml +34 -34
  25. package/codex/agents/ds-pro.toml +34 -34
  26. package/codex/agents/ds-reviewer.toml +32 -32
  27. package/codex/agents/ds-worker.toml +32 -32
  28. package/codex/prompts/dsh-config.md +19 -19
  29. package/codex/prompts/dsh-status.md +5 -5
  30. package/commands/config.md +23 -23
  31. package/commands/off.md +5 -5
  32. package/commands/on.md +5 -5
  33. package/commands/status.md +9 -9
  34. package/cordis.patch.yml +4 -4
  35. package/docs/gpt-relay-extension.md +103 -103
  36. package/docs/installation.md +138 -138
  37. package/docs/job-contracts.md +103 -103
  38. package/docs/readiness-matrix.md +85 -85
  39. package/docs/ui-surfaces.md +107 -107
  40. package/official-web-bridge/cordis.patch.yml +4 -4
  41. package/official-web-bridge/entry.mjs +1 -1
  42. package/official-web-bridge/overlay-entry.mjs +59 -59
  43. package/official-web-bridge/package.json +25 -25
  44. package/package.json +3 -2
  45. package/scripts/build-client.mjs +49 -49
  46. package/scripts/live-crew-smoke.mjs +39 -39
  47. package/scripts/live-policy-matrix.mjs +177 -177
  48. package/scripts/policy-probe.mjs +101 -101
  49. package/scripts/remove-legacy-official-bridge.ps1 +89 -89
  50. package/scripts/setup.mjs +393 -393
  51. package/scripts/smoke-real.mjs +110 -110
  52. package/scripts/smoke.mjs +78 -78
  53. package/scripts/verify-crew-ui-polish.mjs +145 -145
  54. package/scripts/verify-history-ui.mjs +97 -97
  55. package/scripts/verify-installer-fix.mjs +26 -26
  56. package/scripts/verify-npm-install.mjs +311 -311
  57. package/scripts/verify-official-bridge-e2e.mjs +192 -192
  58. package/src/adaptive-routing.mjs +260 -260
  59. package/src/client/activation-summary.tsx +64 -64
  60. package/src/client/collapsible-sections.mjs +55 -55
  61. package/src/client/history-panel.tsx +108 -108
  62. package/src/client/host-readiness.mjs +71 -71
  63. package/src/client/index.tsx +1711 -1711
  64. package/src/client/model-callability-view.mjs +17 -17
  65. package/src/client/panel-chrome.tsx +40 -40
  66. package/src/client/quick-entry.tsx +10 -10
  67. package/src/client/quick-panel.tsx +275 -275
  68. package/src/client/readiness-envelope.mjs +34 -34
  69. package/src/client/surface-detection.mjs +43 -43
  70. package/src/config-readiness.mjs +226 -226
  71. package/src/credential-reference.mjs +38 -38
  72. package/src/delivery.mjs +205 -205
  73. package/src/dsh-cli-runtime.mjs +1021 -1021
  74. package/src/dsh-cohort.mjs +20 -20
  75. package/src/extension-contract.mjs +104 -104
  76. package/src/failure-classification.mjs +201 -201
  77. package/src/history/admission-gate.mjs +67 -67
  78. package/src/history/archive-store.mjs +272 -272
  79. package/src/history/cleanup-plan.mjs +89 -89
  80. package/src/history/http.mjs +32 -32
  81. package/src/history/operation.mjs +86 -86
  82. package/src/history/runner-detach.mjs +34 -34
  83. package/src/history/runner.mjs +52 -52
  84. package/src/history/runtime.mjs +36 -36
  85. package/src/history/service.mjs +177 -177
  86. package/src/history/state.mjs +27 -27
  87. package/src/hub/entry.mjs +104 -104
  88. package/src/hub/index.mjs +2694 -2694
  89. package/src/hub-client.mjs +154 -154
  90. package/src/hub-compatibility.mjs +42 -42
  91. package/src/i18n.mjs +19 -19
  92. package/src/information-flow.mjs +67 -67
  93. package/src/install/cli.mjs +28 -28
  94. package/src/install/install-legacy.mjs +711 -711
  95. package/src/install/install.mjs +483 -483
  96. package/src/install/npx-lifecycle.mjs +3456 -3456
  97. package/src/install/official-frontend-assets.mjs +78 -78
  98. package/src/install/official-web.mjs +95 -95
  99. package/src/install/payload-content.mjs +88 -88
  100. package/src/install/windows-startup.mjs +236 -236
  101. package/src/install/windows-supervisor-adapter.mjs +443 -443
  102. package/src/install/windows-supervisor-lifecycle.mjs +782 -782
  103. package/src/install/zcode.mjs +397 -397
  104. package/src/job-contracts.mjs +255 -255
  105. package/src/local-request-guard.mjs +60 -60
  106. package/src/mcp-runtime.mjs +340 -340
  107. package/src/model-callability-contract.mjs +79 -79
  108. package/src/model-catalog.mjs +180 -180
  109. package/src/model-routing.mjs +586 -586
  110. package/src/model-schedule.mjs +207 -207
  111. package/src/official-web-bridge.mjs +447 -447
  112. package/src/policy.mjs +235 -235
  113. package/src/provider-delete-adapters.mjs +1934 -1934
  114. package/src/provider-health.mjs +130 -130
  115. package/src/provider-inventory.mjs +182 -182
  116. package/src/provider-layer-migration-adapters.mjs +759 -759
  117. package/src/provider-layer-migration.mjs +198 -198
  118. package/src/provider-lifecycle-state.mjs +103 -103
  119. package/src/provider-lifecycle.mjs +252 -252
  120. package/src/provider-profile-store.mjs +390 -390
  121. package/src/provider-settings-store.mjs +633 -633
  122. package/src/provider-store-lock.mjs +67 -67
  123. package/src/readiness-matrix.mjs +181 -181
  124. package/src/removable-waiter.mjs +29 -29
  125. package/src/role-profiles.mjs +107 -107
  126. package/src/runtime-controls.mjs +84 -84
  127. package/src/runtime-identity-contract.mjs +34 -34
  128. package/src/runtime-identity.mjs +235 -235
  129. package/src/runtime-readiness-snapshot.mjs +285 -285
  130. package/src/server.mjs +581 -581
  131. package/src/session-origins.mjs +60 -60
  132. package/src/standalone-sdk.mjs +23 -23
  133. package/src/status-shard.mjs +63 -63
  134. package/src/structured-error-code.mjs +38 -38
  135. package/src/supervisor/restart-request.mjs +256 -256
  136. package/src/workflow-runtime.mjs +739 -739
  137. package/src/workflow.mjs +155 -155
  138. package/src/workspace-audit.mjs +231 -231
  139. package/src/workspace-context.mjs +146 -146
  140. package/src/workspace-isolation.mjs +463 -455
  141. package/src/workspace-readiness.mjs +32 -32
  142. package/statusline/statusline.sh +14 -14
  143. package/statusline/worker-segment.sh +35 -35
  144. package/windows/start-dsh-crew.cmd +57 -57
  145. package/windows/start-dsh-crew.ps1 +1302 -1302
  146. package/windows/supervisor-control.ps1 +467 -467
  147. package/worker.cordis.yml +67 -67
  148. package/zcode/agents/ds-reviewer.md +31 -31
  149. package/zcode/agents/ds-worker.md +31 -31
  150. package/zcode/commands/dsh-config.md +17 -17
  151. package/zcode/commands/dsh-status.md +5 -5
@@ -1,60 +1,60 @@
1
- // Durable provenance for sessions the Crew hub created.
2
- //
3
- // Cleanup needs to tell a session Crew dispatched apart from one the operator
4
- // opened in the same UI, because they are otherwise identical: both are ordinary
5
- // Harness sessions in one shared store, with the same header shape (no field
6
- // records who asked for them). Provenance has to be recorded at the moment of
7
- // creation, which only the hub knows.
8
- //
9
- // This is deliberately an append-only JSONL file rather than a rewrite of the
10
- // status shards: a shard removes itself on clean process exit, so it is a
11
- // best-effort view of live writers, not a record of what was ever created.
12
- //
13
- // Absence is not proof of user authorship — a session predating this ledger, or
14
- // one whose line was lost, simply stays unclaimed. Unclaimed sessions are treated
15
- // as the operator's and are never removed by a Crew-scoped cleanup.
16
- import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
17
- import { homedir } from 'node:os';
18
- import { dirname, join } from 'node:path';
19
-
20
- export function sessionOriginsFile({ home = homedir() } = {}) {
21
- return join(home, '.config', 'dsh-crew', 'session-origins.jsonl');
22
- }
23
-
24
- /**
25
- * Record that Crew created one session. Best effort: losing a line weakens a
26
- * later cleanup's scope, so it must never fail a dispatch that already started.
27
- */
28
- export function appendSessionOrigin({ home = homedir(), sessionId, role = null, jobId = null, now = Date.now } = {}) {
29
- if (typeof sessionId !== 'string' || !sessionId) return false;
30
- try {
31
- const file = sessionOriginsFile({ home });
32
- mkdirSync(dirname(file), { recursive: true });
33
- appendFileSync(file, `${JSON.stringify({ sessionId, role, jobId, createdAt: now() })}\n`);
34
- return true;
35
- } catch { return false; }
36
- }
37
-
38
- /**
39
- * Session ids Crew is known to have created.
40
- *
41
- * A malformed or truncated line is skipped rather than thrown: the ledger is an
42
- * optimization for scope, and a damaged tail must not make cleanup unusable. The
43
- * failure direction is safe — an unread session is treated as the operator's.
44
- */
45
- export function readSessionOrigins({ home = homedir() } = {}) {
46
- const file = sessionOriginsFile({ home });
47
- if (!existsSync(file)) return new Set();
48
- try {
49
- const ids = new Set();
50
- for (const line of readFileSync(file, 'utf8').split('\n')) {
51
- const trimmed = line.trim();
52
- if (!trimmed) continue;
53
- try {
54
- const row = JSON.parse(trimmed);
55
- if (typeof row?.sessionId === 'string' && row.sessionId) ids.add(row.sessionId);
56
- } catch { /* skip a torn line */ }
57
- }
58
- return ids;
59
- } catch { return new Set(); }
60
- }
1
+ // Durable provenance for sessions the Crew hub created.
2
+ //
3
+ // Cleanup needs to tell a session Crew dispatched apart from one the operator
4
+ // opened in the same UI, because they are otherwise identical: both are ordinary
5
+ // Harness sessions in one shared store, with the same header shape (no field
6
+ // records who asked for them). Provenance has to be recorded at the moment of
7
+ // creation, which only the hub knows.
8
+ //
9
+ // This is deliberately an append-only JSONL file rather than a rewrite of the
10
+ // status shards: a shard removes itself on clean process exit, so it is a
11
+ // best-effort view of live writers, not a record of what was ever created.
12
+ //
13
+ // Absence is not proof of user authorship — a session predating this ledger, or
14
+ // one whose line was lost, simply stays unclaimed. Unclaimed sessions are treated
15
+ // as the operator's and are never removed by a Crew-scoped cleanup.
16
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
17
+ import { homedir } from 'node:os';
18
+ import { dirname, join } from 'node:path';
19
+
20
+ export function sessionOriginsFile({ home = homedir() } = {}) {
21
+ return join(home, '.config', 'dsh-crew', 'session-origins.jsonl');
22
+ }
23
+
24
+ /**
25
+ * Record that Crew created one session. Best effort: losing a line weakens a
26
+ * later cleanup's scope, so it must never fail a dispatch that already started.
27
+ */
28
+ export function appendSessionOrigin({ home = homedir(), sessionId, role = null, jobId = null, now = Date.now } = {}) {
29
+ if (typeof sessionId !== 'string' || !sessionId) return false;
30
+ try {
31
+ const file = sessionOriginsFile({ home });
32
+ mkdirSync(dirname(file), { recursive: true });
33
+ appendFileSync(file, `${JSON.stringify({ sessionId, role, jobId, createdAt: now() })}\n`);
34
+ return true;
35
+ } catch { return false; }
36
+ }
37
+
38
+ /**
39
+ * Session ids Crew is known to have created.
40
+ *
41
+ * A malformed or truncated line is skipped rather than thrown: the ledger is an
42
+ * optimization for scope, and a damaged tail must not make cleanup unusable. The
43
+ * failure direction is safe — an unread session is treated as the operator's.
44
+ */
45
+ export function readSessionOrigins({ home = homedir() } = {}) {
46
+ const file = sessionOriginsFile({ home });
47
+ if (!existsSync(file)) return new Set();
48
+ try {
49
+ const ids = new Set();
50
+ for (const line of readFileSync(file, 'utf8').split('\n')) {
51
+ const trimmed = line.trim();
52
+ if (!trimmed) continue;
53
+ try {
54
+ const row = JSON.parse(trimmed);
55
+ if (typeof row?.sessionId === 'string' && row.sessionId) ids.add(row.sessionId);
56
+ } catch { /* skip a torn line */ }
57
+ }
58
+ return ids;
59
+ } catch { return new Set(); }
60
+ }
@@ -1,23 +1,23 @@
1
- /** Keep Hub-only MCP clients independent of optional standalone host peers. */
2
- export function createStandaloneHarness(options, { load = () => import('@deepseek-ai/dsh-sdk-client') } = {}) {
3
- let loading;
4
- let harness;
5
- let closed = false;
6
- return {
7
- async run(...args) {
8
- if (closed) throw Error('standalone job cancelled before startup');
9
- loading ??= load().catch(error => {
10
- if (error?.code !== 'ERR_MODULE_NOT_FOUND' && error?.code !== 'MODULE_NOT_FOUND') throw error;
11
- throw Object.assign(new Error('Standalone DSH SDK is unavailable. Repair the Crew-owned installation before using standalone mode; Hub mode does not require this SDK.'), { code: 'STANDALONE_SDK_UNAVAILABLE' });
12
- });
13
- const { DeepSeekHarness } = await loading;
14
- if (closed) throw Error('standalone job cancelled before startup');
15
- harness ??= new DeepSeekHarness(options);
16
- return harness.run(...args);
17
- },
18
- async close() {
19
- closed = true;
20
- if (harness) await harness.close();
21
- },
22
- };
23
- }
1
+ /** Keep Hub-only MCP clients independent of optional standalone host peers. */
2
+ export function createStandaloneHarness(options, { load = () => import('@deepseek-ai/dsh-sdk-client') } = {}) {
3
+ let loading;
4
+ let harness;
5
+ let closed = false;
6
+ return {
7
+ async run(...args) {
8
+ if (closed) throw Error('standalone job cancelled before startup');
9
+ loading ??= load().catch(error => {
10
+ if (error?.code !== 'ERR_MODULE_NOT_FOUND' && error?.code !== 'MODULE_NOT_FOUND') throw error;
11
+ throw Object.assign(new Error('Standalone DSH SDK is unavailable. Repair the Crew-owned installation before using standalone mode; Hub mode does not require this SDK.'), { code: 'STANDALONE_SDK_UNAVAILABLE' });
12
+ });
13
+ const { DeepSeekHarness } = await loading;
14
+ if (closed) throw Error('standalone job cancelled before startup');
15
+ harness ??= new DeepSeekHarness(options);
16
+ return harness.run(...args);
17
+ },
18
+ async close() {
19
+ closed = true;
20
+ if (harness) await harness.close();
21
+ },
22
+ };
23
+ }
@@ -1,63 +1,63 @@
1
- // Sharded worker-status publishing: every writer (hub process, per-session
2
- // standalone MCP server) owns one file under ~/.config/dsh-crew/status.d/
3
- // and readers merge all fresh shards. Kills the last-writer-wins race that a
4
- // single shared status.json had with multiple concurrent writers.
5
-
6
- import { writeFileSync, mkdirSync, rmSync, readdirSync, readFileSync, renameSync } from 'node:fs';
7
- import { join } from 'node:path';
8
- import { homedir } from 'node:os';
9
-
10
- const CONFIG_DIR = join(homedir(), '.config', 'dsh-crew');
11
- const SHARD_DIR = join(CONFIG_DIR, 'status.d');
12
- export const SHARD_FRESH_MS = 30 * 60 * 1000;
13
-
14
- export function createShardWriter(kind) {
15
- const writer = `${kind}-${process.pid}`;
16
- const file = join(SHARD_DIR, `${writer}.json`);
17
- const cleanup = () => { try { rmSync(file, { force: true }); } catch {} };
18
- process.once('exit', cleanup);
19
- process.once('SIGINT', () => { cleanup(); process.exit(130); });
20
- process.once('SIGTERM', () => { cleanup(); process.exit(143); });
21
- return {
22
- writer,
23
- publish(jobs) {
24
- // Same durability pattern as the profile/workspace registries: write a
25
- // same-directory temp file as 0600 and rename it over the shard, so a
26
- // reader never observes a partially written shard (parse failures are
27
- // silently ignored, which would make the writer look vanished).
28
- try {
29
- mkdirSync(SHARD_DIR, { recursive: true });
30
- const temp = `${file}.tmp-${Date.now()}`;
31
- try {
32
- writeFileSync(temp, JSON.stringify({ updatedAt: new Date().toISOString(), writer, jobs }, null, 2), { encoding: 'utf8', mode: 0o600 });
33
- renameSync(temp, file);
34
- } catch (error) {
35
- try { rmSync(temp, { force: true }); } catch {}
36
- throw error;
37
- }
38
- } catch {}
39
- },
40
- dispose: cleanup,
41
- };
42
- }
43
-
44
- /** Merge fresh shards (plus the legacy status.json during transition). */
45
- export function readMergedStatus({ excludeWriter } = {}) {
46
- const jobs = [];
47
- const now = Date.now();
48
- const consume = (raw) => {
49
- try {
50
- const shard = JSON.parse(raw);
51
- if (shard.writer === excludeWriter) return;
52
- if (now - +new Date(shard.updatedAt) > SHARD_FRESH_MS) return;
53
- for (const job of shard.jobs ?? []) jobs.push({ ...job, origin: shard.writer ?? 'legacy' });
54
- } catch {}
55
- };
56
- try {
57
- for (const f of readdirSync(SHARD_DIR)) {
58
- if (f.endsWith('.json')) { try { consume(readFileSync(join(SHARD_DIR, f), 'utf8')); } catch {} }
59
- }
60
- } catch {}
61
- try { consume(readFileSync(join(CONFIG_DIR, 'status.json'), 'utf8')); } catch {}
62
- return jobs;
63
- }
1
+ // Sharded worker-status publishing: every writer (hub process, per-session
2
+ // standalone MCP server) owns one file under ~/.config/dsh-crew/status.d/
3
+ // and readers merge all fresh shards. Kills the last-writer-wins race that a
4
+ // single shared status.json had with multiple concurrent writers.
5
+
6
+ import { writeFileSync, mkdirSync, rmSync, readdirSync, readFileSync, renameSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ import { homedir } from 'node:os';
9
+
10
+ const CONFIG_DIR = join(homedir(), '.config', 'dsh-crew');
11
+ const SHARD_DIR = join(CONFIG_DIR, 'status.d');
12
+ export const SHARD_FRESH_MS = 30 * 60 * 1000;
13
+
14
+ export function createShardWriter(kind) {
15
+ const writer = `${kind}-${process.pid}`;
16
+ const file = join(SHARD_DIR, `${writer}.json`);
17
+ const cleanup = () => { try { rmSync(file, { force: true }); } catch {} };
18
+ process.once('exit', cleanup);
19
+ process.once('SIGINT', () => { cleanup(); process.exit(130); });
20
+ process.once('SIGTERM', () => { cleanup(); process.exit(143); });
21
+ return {
22
+ writer,
23
+ publish(jobs) {
24
+ // Same durability pattern as the profile/workspace registries: write a
25
+ // same-directory temp file as 0600 and rename it over the shard, so a
26
+ // reader never observes a partially written shard (parse failures are
27
+ // silently ignored, which would make the writer look vanished).
28
+ try {
29
+ mkdirSync(SHARD_DIR, { recursive: true });
30
+ const temp = `${file}.tmp-${Date.now()}`;
31
+ try {
32
+ writeFileSync(temp, JSON.stringify({ updatedAt: new Date().toISOString(), writer, jobs }, null, 2), { encoding: 'utf8', mode: 0o600 });
33
+ renameSync(temp, file);
34
+ } catch (error) {
35
+ try { rmSync(temp, { force: true }); } catch {}
36
+ throw error;
37
+ }
38
+ } catch {}
39
+ },
40
+ dispose: cleanup,
41
+ };
42
+ }
43
+
44
+ /** Merge fresh shards (plus the legacy status.json during transition). */
45
+ export function readMergedStatus({ excludeWriter } = {}) {
46
+ const jobs = [];
47
+ const now = Date.now();
48
+ const consume = (raw) => {
49
+ try {
50
+ const shard = JSON.parse(raw);
51
+ if (shard.writer === excludeWriter) return;
52
+ if (now - +new Date(shard.updatedAt) > SHARD_FRESH_MS) return;
53
+ for (const job of shard.jobs ?? []) jobs.push({ ...job, origin: shard.writer ?? 'legacy' });
54
+ } catch {}
55
+ };
56
+ try {
57
+ for (const f of readdirSync(SHARD_DIR)) {
58
+ if (f.endsWith('.json')) { try { consume(readFileSync(join(SHARD_DIR, f), 'utf8')); } catch {} }
59
+ }
60
+ } catch {}
61
+ try { consume(readFileSync(join(CONFIG_DIR, 'status.json'), 'utf8')); } catch {}
62
+ return jobs;
63
+ }
@@ -1,39 +1,39 @@
1
- // Shared bounded machine error-code contract for the Hub service boundary.
2
- //
3
- // A machine code is an uppercase snake-style identifier (A-Z, 0-9, single
4
- // underscores) of at most 64 characters. Only such values may cross the Hub
5
- // service/client boundary as a top-level `code`: values are taken from
6
- // err.code / err.policyCode only and are never derived from error text or from
7
- // arbitrary response payload fields. Invalid values are treated as absent and
8
- // callers fall back to their own constant (e.g. HUB_REQUEST_FAILED).
9
-
10
- export const MACHINE_CODE_MAX_LENGTH = 64;
11
- const MACHINE_CODE_RE = /^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*$/;
12
-
13
- /**
14
- * True when `value` is a string that satisfies the bounded machine-code
15
- * contract (uppercase snake-style identifier, length 1..64). Null, non-strings,
16
- * lowercase/mixed-case, blank, leading/trailing/double-underscore, and
17
- * over-length values are rejected.
18
- */
19
- export function isBoundedMachineCode(value) {
20
- return typeof value === 'string'
21
- && value.length > 0
22
- && value.length <= MACHINE_CODE_MAX_LENGTH
23
- && MACHINE_CODE_RE.test(value);
24
- }
25
-
26
- /**
27
- * First valid bounded machine code found on an error object: `code` wins over
28
- * `policyCode`. Returns null when neither field is a valid bounded machine
29
- * code, so callers can keep the raw error text unchanged and only add the
30
- * optional top-level `code` when one genuinely exists.
31
- */
32
- export function boundedMachineCodeFromError(err) {
33
- if (!err || typeof err !== 'object') return null;
34
- for (const key of ['code', 'policyCode']) {
35
- const value = err[key];
36
- if (isBoundedMachineCode(value)) return value;
37
- }
38
- return null;
1
+ // Shared bounded machine error-code contract for the Hub service boundary.
2
+ //
3
+ // A machine code is an uppercase snake-style identifier (A-Z, 0-9, single
4
+ // underscores) of at most 64 characters. Only such values may cross the Hub
5
+ // service/client boundary as a top-level `code`: values are taken from
6
+ // err.code / err.policyCode only and are never derived from error text or from
7
+ // arbitrary response payload fields. Invalid values are treated as absent and
8
+ // callers fall back to their own constant (e.g. HUB_REQUEST_FAILED).
9
+
10
+ export const MACHINE_CODE_MAX_LENGTH = 64;
11
+ const MACHINE_CODE_RE = /^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)*$/;
12
+
13
+ /**
14
+ * True when `value` is a string that satisfies the bounded machine-code
15
+ * contract (uppercase snake-style identifier, length 1..64). Null, non-strings,
16
+ * lowercase/mixed-case, blank, leading/trailing/double-underscore, and
17
+ * over-length values are rejected.
18
+ */
19
+ export function isBoundedMachineCode(value) {
20
+ return typeof value === 'string'
21
+ && value.length > 0
22
+ && value.length <= MACHINE_CODE_MAX_LENGTH
23
+ && MACHINE_CODE_RE.test(value);
24
+ }
25
+
26
+ /**
27
+ * First valid bounded machine code found on an error object: `code` wins over
28
+ * `policyCode`. Returns null when neither field is a valid bounded machine
29
+ * code, so callers can keep the raw error text unchanged and only add the
30
+ * optional top-level `code` when one genuinely exists.
31
+ */
32
+ export function boundedMachineCodeFromError(err) {
33
+ if (!err || typeof err !== 'object') return null;
34
+ for (const key of ['code', 'policyCode']) {
35
+ const value = err[key];
36
+ if (isBoundedMachineCode(value)) return value;
37
+ }
38
+ return null;
39
39
  }