heyspex 0.2.5 → 0.2.7

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 (110) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/bin/hs.mjs +349 -38
  3. package/bin/spexcode.mjs +31 -0
  4. package/dev-factory/lib/dispatch-guard.mjs +75 -0
  5. package/dev-factory/lib/local-firecrawl.mjs +294 -0
  6. package/dev-factory/lib/runner-path.mjs +51 -0
  7. package/dev-factory/lib/seat-context.mjs +20 -4
  8. package/dev-factory/model-catalog.json +222 -222
  9. package/dev-factory/spexcrawl/firecrawl-cli.mjs +755 -0
  10. package/dev-factory/spexcrawl/spexcrawl-cli.mjs +734 -0
  11. package/dist/cli/hs-connect.mjs +40 -3
  12. package/dist/cli/hs-defer.mjs +3817 -3741
  13. package/dist/cli/hs-events.mjs +1296 -0
  14. package/dist/cli/hs-export-events.mjs +1252 -0
  15. package/dist/cli/hs-handoff.mjs +2576 -0
  16. package/dist/cli/hs-index-rebuild.mjs +228 -37
  17. package/dist/cli/hs-index-reconcile.mjs +231 -40
  18. package/dist/cli/hs-init.mjs +22 -3
  19. package/dist/cli/hs-install.mjs +22 -3
  20. package/dist/cli/hs-join.mjs +40 -3
  21. package/dist/cli/hs-next-launch.mjs +2777 -0
  22. package/dist/cli/hs-pin.mjs +1336 -0
  23. package/dist/cli/hs-prereq.mjs +1380 -0
  24. package/dist/cli/hs-revalidate.mjs +3257 -0
  25. package/dist/cli/hs-spawn.mjs +12403 -0
  26. package/dist/cli/hs-test.mjs +1046 -0
  27. package/dist/cli/hs-trash.mjs +362 -0
  28. package/dist/cli/hs-trust.mjs +197 -0
  29. package/dist/cli/hs-vault-pull.mjs +233 -42
  30. package/dist/cli/hs-vault-push.mjs +231 -40
  31. package/dist/cli/hs-vault.mjs +21 -7
  32. package/dist/cli/hs-workspace.mjs +19 -1
  33. package/dist/cli-templates/customer-vault/specs/entity-model.md +1728 -1728
  34. package/dist/cli-templates/customer-vault/specs/protocols/canonical-frontmatter-templates.md +464 -464
  35. package/dist/cli-templates/customer-vault/specs/protocols/destructive-action-checklist.md +122 -122
  36. package/dist/cli-templates/customer-vault/specs/protocols/memory-protocol.md +46 -46
  37. package/dist/cli-templates/customer-vault/specs/protocols/spec-hierarchy.md +530 -530
  38. package/dist/cli-templates/customer-vault/specs/protocols/spec-summary-authoring.md +83 -83
  39. package/dist/cli-templates/harness-commands/claude/hs-backfill.md +28 -28
  40. package/dist/cli-templates/harness-commands/claude/hs-capture.md +62 -62
  41. package/dist/cli-templates/harness-commands/claude/hs-defer.md +29 -29
  42. package/dist/cli-templates/harness-commands/claude/hs-ground.md +30 -30
  43. package/dist/cli-templates/harness-commands/claude/hs-next.md +29 -29
  44. package/dist/cli-templates/harness-commands/claude/hs-promote.md +70 -70
  45. package/dist/cli-templates/harness-commands/claude/hs-push.md +35 -35
  46. package/dist/cli-templates/harness-commands/claude/hs-qc.md +27 -27
  47. package/dist/cli-templates/harness-commands/claude/hs-res.md +83 -63
  48. package/dist/cli-templates/harness-commands/claude/hs-resolve.md +23 -23
  49. package/dist/cli-templates/harness-commands/claude/hs-view.md +28 -28
  50. package/dist/cli-templates/harness-commands/claude/kill-ports.md +32 -32
  51. package/dist/cli-templates/harness-commands/claude/prototype.md +91 -91
  52. package/dist/cli-templates/harness-commands/cursor/hs-backfill.md +22 -22
  53. package/dist/cli-templates/harness-commands/cursor/hs-capture.md +56 -56
  54. package/dist/cli-templates/harness-commands/cursor/hs-defer.md +23 -23
  55. package/dist/cli-templates/harness-commands/cursor/hs-ground.md +24 -24
  56. package/dist/cli-templates/harness-commands/cursor/hs-next.md +23 -23
  57. package/dist/cli-templates/harness-commands/cursor/hs-promote.md +64 -64
  58. package/dist/cli-templates/harness-commands/cursor/hs-push.md +29 -29
  59. package/dist/cli-templates/harness-commands/cursor/hs-qc.md +21 -21
  60. package/dist/cli-templates/harness-commands/cursor/hs-res.md +78 -58
  61. package/dist/cli-templates/harness-commands/cursor/hs-resolve.md +17 -17
  62. package/dist/cli-templates/harness-commands/cursor/hs-view.md +23 -23
  63. package/dist/cli-templates/harness-commands/cursor/kill-ports.md +26 -26
  64. package/dist/cli-templates/harness-commands/cursor/prototype.md +86 -86
  65. package/docs/copilot-plugin-install.md +9 -2
  66. package/docs/mcp-client-config.md +6 -0
  67. package/package.json +266 -257
  68. package/plugins/heyspex/.claude-plugin/plugin.json +1 -1
  69. package/plugins/heyspex/.cursor-plugin/plugin.json +1 -1
  70. package/plugins/heyspex/README.md +6 -0
  71. package/plugins/heyspex/bin/launch-mcp.mjs +17 -0
  72. package/plugins/heyspex/hooks/hooks.json +418 -418
  73. package/scripts/claude-hooks/_intent-classifier-semantic.mjs +2 -2
  74. package/scripts/claude-hooks/wip-checkpoint.mjs +17 -2
  75. package/scripts/claude-statusline/statusline-command.mjs +287 -27
  76. package/scripts/hs-companion.mjs +41 -3
  77. package/scripts/install-claude-code-hooks.mjs +104 -3
  78. package/scripts/install-copilot-hooks.mjs +21 -1
  79. package/scripts/install-cursor-hooks.mjs +4 -3
  80. package/scripts/lib/capture-execution-guard.mjs +221 -0
  81. package/scripts/lib/companion-install.mjs +768 -0
  82. package/scripts/lib/customer-kit.mjs +53 -3
  83. package/scripts/lib/hs-companion-settings.mjs +26 -0
  84. package/scripts/lib/hs-source-push.mjs +386 -386
  85. package/scripts/record-grounding.mjs +38 -0
  86. package/spexharness/doctrine/baseline/SPEXCODE-DOCTRINE.baseline.json +29 -29
  87. package/spexharness/src/adapters/copilot-models.mjs +179 -0
  88. package/spexharness/src/adapters/harness-detect.mjs +148 -0
  89. package/spexharness/src/gates/directive-obligation-gate.decide.mjs +132 -132
  90. package/spexharness/src/gates/vault-write-tier-guard.decide.mjs +153 -125
  91. package/spexharness/src/seat-context.mjs +10 -5
  92. package/spexharness/src/session-bootstrap.mjs +6 -3
  93. package/vendor/heyspex-mcp/cli.mjs +6 -1
  94. package/vendor/heyspex-mcp/config-seed.yaml +15 -15
  95. package/vendor/heyspex-mcp/dev-factory-overlay.mjs +142 -0
  96. package/vendor/heyspex-mcp/http-transport.mjs +1 -1
  97. package/vendor/heyspex-mcp/memory-tools.mjs +523 -523
  98. package/vendor/heyspex-mcp/on-deck-scheduler.mjs +1708 -1708
  99. package/vendor/heyspex-mcp/procedure-handlers.mjs +327 -327
  100. package/vendor/heyspex-mcp/procedure-tools.mjs +1209 -1181
  101. package/vendor/heyspex-mcp/research-tools.mjs +22 -2
  102. package/vendor/heyspex-mcp/seat-assign-cli.mjs +242 -0
  103. package/vendor/heyspex-mcp/seat-assignment-rules.mjs +96 -0
  104. package/vendor/heyspex-mcp/seat-assignments-client.mjs +265 -0
  105. package/vendor/heyspex-mcp/seat-defaults-cli.mjs +45 -0
  106. package/vendor/heyspex-mcp/seat-defaults.mjs +232 -0
  107. package/vendor/heyspex-mcp/seat-identity.mjs +171 -0
  108. package/vendor/heyspex-mcp/test-helpers.mjs +37 -23
  109. package/vendor/heyspex-mcp/vault-io.mjs +720 -720
  110. package/bin/postinstall.mjs +0 -88
@@ -0,0 +1,1336 @@
1
+ import { createRequire as __hsCreateRequire } from 'node:module';
2
+ const require = __hsCreateRequire(import.meta.url);
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __esm = (fn, res) => function __init() {
5
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
6
+ };
7
+
8
+ // scripts/lib/heyspex-home.mjs
9
+ import { homedir } from "node:os";
10
+ function heyspexHome(env = process.env) {
11
+ const override = env?.HEYSPEX_HOME;
12
+ if (typeof override === "string" && override.trim().length > 0) {
13
+ return override.trim();
14
+ }
15
+ return homedir();
16
+ }
17
+ var init_heyspex_home = __esm({
18
+ "scripts/lib/heyspex-home.mjs"() {
19
+ "use strict";
20
+ }
21
+ });
22
+
23
+ // vendor/heyspex-mcp/credentials.mjs
24
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
25
+ import os, { homedir as homedir2 } from "node:os";
26
+ import { dirname as dirname2, join as join2, resolve } from "node:path";
27
+ function credentialsFilePath(homeDir = heyspexHome()) {
28
+ return join2(homeDir, ".heyspex", "credentials.yaml");
29
+ }
30
+ function parseMcpToken(raw) {
31
+ if (typeof raw !== "string" || raw.length === 0) return null;
32
+ const token = raw.match(MCP_TOKEN_LINE_RE)?.[1]?.trim();
33
+ return token ? token : null;
34
+ }
35
+ function isValidAccountId(id) {
36
+ return typeof id === "string" && ACCOUNT_ID_RE.test(id);
37
+ }
38
+ function topLevelScalar(raw, key) {
39
+ const re = new RegExp(`^${key}:[ \\t]*["']?([^"'\\r\\n#]+)`, "m");
40
+ const value = raw.match(re)?.[1]?.trim();
41
+ return value ? value : null;
42
+ }
43
+ function decodeScalar(text) {
44
+ const t = text.trim();
45
+ if (t === "" || t === "null" || t === "~") return null;
46
+ if (t.startsWith('"')) {
47
+ try {
48
+ const v = JSON.parse(t);
49
+ return typeof v === "string" && v ? v : null;
50
+ } catch {
51
+ return t.replace(/^"|"$/g, "") || null;
52
+ }
53
+ }
54
+ if (t.startsWith("'")) return t.replace(/^'|'$/g, "") || null;
55
+ const bare = t.replace(/\s+#.*$/, "").trim();
56
+ return bare || null;
57
+ }
58
+ function emptyAccount() {
59
+ return { mcp_token: null, console_url: null, email: null, paired_at: null };
60
+ }
61
+ function findAccountsBlock(lines) {
62
+ const start = lines.findIndex((l) => /^accounts:[ \t]*(#.*)?$/.test(l));
63
+ if (start < 0) return null;
64
+ let end = start + 1;
65
+ while (end < lines.length && (lines[end].trim() === "" || /^[ \t]/.test(lines[end]))) end += 1;
66
+ while (end > start + 1 && lines[end - 1].trim() === "") end -= 1;
67
+ return { start, end };
68
+ }
69
+ function parseAccountsBlock(lines) {
70
+ const accounts = {};
71
+ const block = findAccountsBlock(lines);
72
+ if (!block) return accounts;
73
+ let current = null;
74
+ for (const line of lines.slice(block.start + 1, block.end)) {
75
+ const header = line.match(/^ {2}([^\s:#][^:]*):[ \t]*(#.*)?$/);
76
+ if (header) {
77
+ const id = decodeScalar(header[1]);
78
+ current = isValidAccountId(id) ? id : null;
79
+ if (current) accounts[current] = emptyAccount();
80
+ continue;
81
+ }
82
+ const field = line.match(/^ {4}([a-z_]+):(.*)$/);
83
+ if (field && current && ACCOUNT_FIELDS.includes(field[1])) {
84
+ accounts[current][field[1]] = decodeScalar(field[2]);
85
+ }
86
+ }
87
+ return accounts;
88
+ }
89
+ function parseCredentialsStore(raw) {
90
+ const text = typeof raw === "string" ? raw : "";
91
+ if (topLevelScalar(text, "schema_version") !== String(CREDENTIALS_SCHEMA_VERSION)) {
92
+ const token = parseMcpToken(text);
93
+ if (!token) return { schemaVersion: 1, currentAccountId: null, accounts: {} };
94
+ return {
95
+ schemaVersion: 1,
96
+ currentAccountId: LEGACY_ACCOUNT_ID,
97
+ accounts: {
98
+ [LEGACY_ACCOUNT_ID]: { ...emptyAccount(), mcp_token: token, console_url: topLevelScalar(text, "console_url") }
99
+ }
100
+ };
101
+ }
102
+ const accounts = parseAccountsBlock(text.split(/\r?\n/));
103
+ const current = topLevelScalar(text, "current_account_id");
104
+ return {
105
+ schemaVersion: 2,
106
+ currentAccountId: current && accounts[current] ? current : null,
107
+ accounts
108
+ };
109
+ }
110
+ function resolveBearer({ envToken, credentialsText, accountId, legacyAccountId } = {}) {
111
+ const fromEnv = typeof envToken === "string" ? envToken.trim() : "";
112
+ if (fromEnv) return { token: fromEnv, source: "env" };
113
+ const store = parseCredentialsStore(credentialsText);
114
+ let entry;
115
+ if (typeof accountId === "string" && accountId.trim()) {
116
+ const wanted = accountId.trim();
117
+ entry = store.accounts[wanted];
118
+ if (!entry && store.schemaVersion === 1 && legacyAccountId && wanted === legacyAccountId) {
119
+ entry = store.accounts[LEGACY_ACCOUNT_ID];
120
+ }
121
+ } else {
122
+ entry = store.currentAccountId ? store.accounts[store.currentAccountId] : void 0;
123
+ }
124
+ if (entry?.mcp_token) return { token: entry.mcp_token, source: "credentials-file" };
125
+ return { token: null, source: null };
126
+ }
127
+ function readTextOrNull(read, path3) {
128
+ try {
129
+ const raw = read(path3);
130
+ return typeof raw === "string" ? raw : null;
131
+ } catch {
132
+ return null;
133
+ }
134
+ }
135
+ function readLegacyConfigAccountId(read, homeDir) {
136
+ const raw = readTextOrNull(read, join2(homeDir, ".heyspex", "config.yaml"));
137
+ const value = raw?.match(CONFIG_ACCOUNT_ID_RE)?.[1]?.trim() ?? "";
138
+ return value || null;
139
+ }
140
+ function readBearer({ env = process.env, homeDir = heyspexHome(), readFile, accountId } = {}) {
141
+ const read = readFile ?? ((p) => readFileSync(p, "utf8"));
142
+ const credentialsText = readTextOrNull(read, credentialsFilePath(homeDir));
143
+ const named = typeof accountId === "string" && accountId.trim() ? accountId.trim() : null;
144
+ const legacyAccountId = named && parseCredentialsStore(credentialsText).schemaVersion === 1 ? readLegacyConfigAccountId(read, homeDir) : null;
145
+ return resolveBearer({ envToken: env?.[MCP_TOKEN_ENV], credentialsText, accountId: named, legacyAccountId });
146
+ }
147
+ function readCurrentAccountId({ homeDir = heyspexHome(), readFile } = {}) {
148
+ const read = readFile ?? ((p) => readFileSync(p, "utf8"));
149
+ const store = parseCredentialsStore(readTextOrNull(read, credentialsFilePath(homeDir)));
150
+ if (store.schemaVersion === 2 && store.currentAccountId && store.currentAccountId !== LEGACY_ACCOUNT_ID) {
151
+ return store.currentAccountId;
152
+ }
153
+ if (store.schemaVersion === 2 && store.currentAccountId === null) return null;
154
+ return readLegacyConfigAccountId(read, homeDir);
155
+ }
156
+ var MCP_TOKEN_ENV, MCP_TOKEN_LINE_RE, CREDENTIALS_SCHEMA_VERSION, LEGACY_ACCOUNT_ID, ACCOUNT_FIELDS, ACCOUNT_ID_RE, CONFIG_ACCOUNT_ID_RE;
157
+ var init_credentials = __esm({
158
+ "vendor/heyspex-mcp/credentials.mjs"() {
159
+ "use strict";
160
+ init_heyspex_home();
161
+ MCP_TOKEN_ENV = "HEYSPEX_MCP_TOKEN";
162
+ MCP_TOKEN_LINE_RE = /^mcp_token:[ \t]*["']?([^"'\r\n#]+)/m;
163
+ CREDENTIALS_SCHEMA_VERSION = 2;
164
+ LEGACY_ACCOUNT_ID = "legacy";
165
+ ACCOUNT_FIELDS = ["mcp_token", "console_url", "email", "paired_at"];
166
+ ACCOUNT_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_.@+-]*$/;
167
+ CONFIG_ACCOUNT_ID_RE = /^account_id:\s*["']?([^"'\r\n#]+)/m;
168
+ }
169
+ });
170
+
171
+ // scripts/lib/dev-mode.mjs
172
+ import { mkdirSync as mkdirSync5, readFileSync as readFileSync8, writeFileSync as writeFileSync5 } from "node:fs";
173
+ import { homedir as homedir8 } from "node:os";
174
+ import { join as join8 } from "node:path";
175
+ function devModeFilePath(homeDir = heyspexHome()) {
176
+ return join8(homeDir, ".heyspex", DEV_MODE_FILENAME);
177
+ }
178
+ function normalizeMode(raw) {
179
+ const v = String(raw ?? "").trim().toLowerCase();
180
+ if (v === "prod" || v === "production") return { mode: "prod", reliance: "cloud" };
181
+ if (v === "dev") return { mode: "dev", reliance: null };
182
+ if (v === "local") return { mode: "dev", reliance: "local" };
183
+ if (v === "cloud") return { mode: "dev", reliance: "cloud" };
184
+ return null;
185
+ }
186
+ function normalizeReliance(raw) {
187
+ const v = String(raw ?? "").trim().toLowerCase();
188
+ return v === "local" || v === "cloud" ? v : null;
189
+ }
190
+ function deriveSemantics(mode, reliance) {
191
+ const effectiveReliance = mode === "prod" ? "cloud" : reliance ?? "local";
192
+ const local = mode === "dev" && effectiveReliance === "local";
193
+ return {
194
+ reliance: effectiveReliance,
195
+ consoleUrl: local ? LOCAL_CONSOLE_URL : CLOUD_CONSOLE_URL,
196
+ readTier: local ? "disk" : "neon",
197
+ vaultWriteMode: local ? "local" : "cloud"
198
+ };
199
+ }
200
+ function readLocalDevModeRecord({ homeDir = heyspexHome(), readFile = defaultReadFile } = {}) {
201
+ let raw;
202
+ try {
203
+ raw = readFile(devModeFilePath(homeDir));
204
+ } catch {
205
+ return { record: null, parseError: null };
206
+ }
207
+ try {
208
+ const parsed = JSON.parse(raw);
209
+ const mode = parsed?.mode === "prod" || parsed?.mode === "dev" ? parsed.mode : null;
210
+ const reliance = normalizeReliance(parsed?.reliance);
211
+ if (!mode || mode === "dev" && !reliance) {
212
+ return { record: null, parseError: `invalid dev-mode record: ${JSON.stringify(parsed)}` };
213
+ }
214
+ return {
215
+ record: {
216
+ mode,
217
+ reliance: mode === "prod" ? "cloud" : reliance,
218
+ console_url: typeof parsed.console_url === "string" ? parsed.console_url : null,
219
+ updated_at: typeof parsed.updated_at === "string" ? parsed.updated_at : null,
220
+ source: typeof parsed.source === "string" ? parsed.source : null
221
+ },
222
+ parseError: null
223
+ };
224
+ } catch (err) {
225
+ return { record: null, parseError: `unparseable dev-mode.json: ${String(err?.message ?? err)}` };
226
+ }
227
+ }
228
+ function overrideCloudCheck(source, cloudKnown, staleAgainstCloud) {
229
+ if (source !== "local-override") return "not-applicable";
230
+ if (!cloudKnown) return "unverified";
231
+ return staleAgainstCloud ? "stale" : "in-sync";
232
+ }
233
+ function resolveDevMode({
234
+ env = process.env,
235
+ homeDir = heyspexHome(),
236
+ readFile = defaultReadFile,
237
+ cloudSetting = void 0
238
+ } = {}) {
239
+ const local = readLocalDevModeRecord({ homeDir, readFile });
240
+ const cloudKnown = cloudSetting !== void 0;
241
+ const cloudValue = cloudKnown && cloudSetting ? {
242
+ mode: cloudSetting.mode === "dev" ? "dev" : "prod",
243
+ reliance: normalizeReliance(cloudSetting.reliance) ?? "cloud"
244
+ } : null;
245
+ let mode;
246
+ let reliance;
247
+ let source;
248
+ let relianceSource;
249
+ const envParsed = normalizeMode(env.HEYSPEX_DEV_MODE);
250
+ if (envParsed) {
251
+ mode = envParsed.mode;
252
+ const envReliance = envParsed.reliance ?? normalizeReliance(env.HEYSPEX_DEV_RELIANCE);
253
+ reliance = envReliance ?? "local";
254
+ source = "env";
255
+ relianceSource = envReliance ? "env" : "assumed-local";
256
+ } else if (local.record) {
257
+ mode = local.record.mode;
258
+ reliance = local.record.reliance;
259
+ source = "local-override";
260
+ } else if (cloudValue) {
261
+ mode = cloudValue.mode;
262
+ reliance = cloudValue.reliance;
263
+ source = "cloud-setting";
264
+ } else {
265
+ mode = "prod";
266
+ reliance = "cloud";
267
+ source = "default";
268
+ }
269
+ const semantics = deriveSemantics(mode, reliance);
270
+ const consoleUrl = source === "local-override" && local.record?.console_url ? local.record.console_url.replace(/\/+$/, "") : semantics.consoleUrl;
271
+ const staleAgainstCloud = source === "local-override" && cloudValue !== null && (cloudValue.mode !== mode || mode === "dev" && cloudValue.reliance !== semantics.reliance);
272
+ const cloudCheck = overrideCloudCheck(source, cloudKnown, staleAgainstCloud);
273
+ return {
274
+ mode,
275
+ reliance: semantics.reliance,
276
+ consoleUrl,
277
+ readTier: semantics.readTier,
278
+ vaultWriteMode: semantics.vaultWriteMode,
279
+ sources: {
280
+ mode: source,
281
+ reliance: relianceSource ?? source,
282
+ consoleUrl: source === "local-override" && local.record?.console_url ? "local-override" : "derived",
283
+ readTier: "derived",
284
+ vaultWriteMode: "derived"
285
+ },
286
+ localOverride: {
287
+ present: local.record !== null,
288
+ record: local.record,
289
+ parseError: local.parseError,
290
+ staleAgainstCloud,
291
+ cloudCheck
292
+ },
293
+ cloudSetting: { known: cloudKnown, value: cloudValue }
294
+ };
295
+ }
296
+ var CLOUD_CONSOLE_URL, LOCAL_CONSOLE_URL, DEV_MODE_FILENAME, defaultReadFile;
297
+ var init_dev_mode = __esm({
298
+ "scripts/lib/dev-mode.mjs"() {
299
+ "use strict";
300
+ init_heyspex_home();
301
+ init_credentials();
302
+ CLOUD_CONSOLE_URL = "https://app.heyspex.com";
303
+ LOCAL_CONSOLE_URL = "http://localhost:3000";
304
+ DEV_MODE_FILENAME = "dev-mode.json";
305
+ defaultReadFile = (p) => readFileSync8(p, "utf8");
306
+ }
307
+ });
308
+
309
+ // spex-console/bin/hs-pin.ts
310
+ import { readFileSync as readFileSync10 } from "node:fs";
311
+ import process3 from "node:process";
312
+
313
+ // spex-console/src/lib/cli/control-shared.ts
314
+ import path2 from "node:path";
315
+
316
+ // scripts/lib/hs-command.mjs
317
+ import { existsSync } from "node:fs";
318
+ import { delimiter, dirname, join } from "node:path";
319
+ import { fileURLToPath } from "node:url";
320
+ var HS_BIN_NAME = "hs";
321
+ var HS_DISPATCHER_PATH = (() => {
322
+ try {
323
+ const here = dirname(fileURLToPath(import.meta.url));
324
+ return join(dirname(dirname(here)), "bin", "hs.mjs");
325
+ } catch {
326
+ return null;
327
+ }
328
+ })();
329
+ function shellQuote(p) {
330
+ return /[\\\s]/.test(p) ? `"${p}"` : p;
331
+ }
332
+ var HS_DISPATCHER_PREFIX = HS_DISPATCHER_PATH ? `node ${shellQuote(HS_DISPATCHER_PATH)}` : HS_BIN_NAME;
333
+ function candidateNames(name, env) {
334
+ if (process.platform !== "win32") return [name];
335
+ const pathext = (env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";").map((e) => e.trim().toLowerCase()).filter(Boolean);
336
+ const extensions = [.../* @__PURE__ */ new Set([...pathext, ".ps1"])];
337
+ return [name, ...extensions.map((ext) => name + ext)];
338
+ }
339
+ function findOnPath(name, { env = process.env, exists = existsSync } = {}) {
340
+ try {
341
+ const raw = env.PATH ?? env.Path ?? env.path ?? "";
342
+ for (const dir of String(raw).split(delimiter)) {
343
+ const trimmed = dir.trim().replace(/^"(.*)"$/, "$1");
344
+ if (!trimmed) continue;
345
+ for (const candidate of candidateNames(name, env)) {
346
+ const full = join(trimmed, candidate);
347
+ try {
348
+ if (exists(full)) return full;
349
+ } catch {
350
+ }
351
+ }
352
+ }
353
+ } catch {
354
+ }
355
+ return null;
356
+ }
357
+ var cached = null;
358
+ var HS_ON_PATH_OVERRIDE_ENV = "HEYSPEX_HS_ON_PATH";
359
+ function onPathOverride(env) {
360
+ const raw = String(env?.[HS_ON_PATH_OVERRIDE_ENV] ?? "");
361
+ if (raw === "1") return true;
362
+ if (raw === "0") return false;
363
+ return void 0;
364
+ }
365
+ function describeHsCommand({ env, exists, useCache = true } = {}) {
366
+ const injected = env !== void 0 || exists !== void 0;
367
+ const effectiveEnv = env ?? process.env;
368
+ const override = onPathOverride(effectiveEnv);
369
+ if (override !== void 0) {
370
+ return {
371
+ onPath: override,
372
+ prefix: override ? HS_BIN_NAME : HS_DISPATCHER_PREFIX,
373
+ resolvedPath: null,
374
+ dispatcherPath: HS_DISPATCHER_PATH
375
+ };
376
+ }
377
+ if (useCache && !injected && cached) return cached;
378
+ const resolvedPath = findOnPath(HS_BIN_NAME, {
379
+ env: env ?? process.env,
380
+ exists: exists ?? existsSync
381
+ });
382
+ const answer = {
383
+ onPath: resolvedPath !== null,
384
+ prefix: resolvedPath !== null ? HS_BIN_NAME : HS_DISPATCHER_PREFIX,
385
+ resolvedPath,
386
+ dispatcherPath: HS_DISPATCHER_PATH
387
+ };
388
+ if (useCache && !injected) cached = answer;
389
+ return answer;
390
+ }
391
+ function hsCommand(args = "", options = {}) {
392
+ let prefix = HS_DISPATCHER_PREFIX;
393
+ try {
394
+ prefix = describeHsCommand(options).prefix;
395
+ } catch {
396
+ }
397
+ const tail = String(args ?? "").trim();
398
+ return tail ? `${prefix} ${tail}` : prefix;
399
+ }
400
+
401
+ // vendor/heyspex-mcp/console-fetch.mjs
402
+ init_heyspex_home();
403
+ init_credentials();
404
+ import { readFileSync as readFileSync6 } from "node:fs";
405
+ import { homedir as homedir6 } from "node:os";
406
+ import { join as join6 } from "node:path";
407
+
408
+ // vendor/heyspex-mcp/session-owner.mjs
409
+ init_heyspex_home();
410
+ init_credentials();
411
+ import { readFileSync as readFileSync2 } from "node:fs";
412
+ import { homedir as homedir3 } from "node:os";
413
+ import { join as join3 } from "node:path";
414
+ function resolveSessionOwnerUncached({ env = process.env, homeDir = heyspexHome(), readFile } = {}) {
415
+ const fromEnv = typeof env?.HS_ACCOUNT_ID === "string" ? env.HS_ACCOUNT_ID.trim() : "";
416
+ if (fromEnv) return fromEnv;
417
+ return readCurrentAccountId({ homeDir, readFile });
418
+ }
419
+
420
+ // vendor/heyspex-mcp/vault-less-endpoints.mjs
421
+ var VAULT_LESS_ENDPOINTS = Object.freeze([
422
+ "* /api/mcp/session",
423
+ "* /api/mcp/pairing-codes",
424
+ "POST /api/vaults",
425
+ "GET /api/vaults",
426
+ "POST /api/workspaces",
427
+ "GET /api/workspaces",
428
+ "* /api/admin/dev-mode"
429
+ ]);
430
+ function pathnameOf(path3) {
431
+ const raw = String(path3 ?? "").split("?")[0].split("#")[0];
432
+ const noTrailing = raw.length > 1 ? raw.replace(/\/+$/, "") : raw;
433
+ return noTrailing || "/";
434
+ }
435
+ function isVaultLessEndpoint(method, path3) {
436
+ const m = String(method || "GET").toUpperCase();
437
+ const pathname = pathnameOf(path3);
438
+ return VAULT_LESS_ENDPOINTS.some((row) => {
439
+ const [rowMethod, rowPath] = row.split(" ");
440
+ return rowPath === pathname && (rowMethod === "*" || rowMethod === m);
441
+ });
442
+ }
443
+
444
+ // vendor/heyspex-mcp/write-outbox.mjs
445
+ import {
446
+ readdirSync,
447
+ readFileSync as readFileSync3,
448
+ writeFileSync as writeFileSync2,
449
+ mkdirSync as mkdirSync2,
450
+ existsSync as existsSync2,
451
+ renameSync as renameSync2,
452
+ rmSync
453
+ } from "node:fs";
454
+ import { basename, join as join4, isAbsolute as isAbsolute2 } from "node:path";
455
+
456
+ // scripts/lib/shared-path-helpers.mjs
457
+ import { realpathSync } from "node:fs";
458
+ import { isAbsolute, resolve as resolve2, sep } from "node:path";
459
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
460
+
461
+ // vendor/heyspex-mcp/vault-resolve.mjs
462
+ init_heyspex_home();
463
+ import { existsSync as existsSync4, readFileSync as readFileSync5, realpathSync as realpathSync3, statSync as statSync3 } from "node:fs";
464
+ import { homedir as homedir5, tmpdir } from "node:os";
465
+
466
+ // vendor/heyspex-mcp/usable-dir-env.mjs
467
+ import { statSync } from "node:fs";
468
+ import { isAbsolute as isAbsolute3 } from "node:path";
469
+
470
+ // vendor/heyspex-mcp/vault-resolve.mjs
471
+ import { basename as basename2, dirname as dirname3, join as join5, resolve as resolve3 } from "node:path";
472
+
473
+ // vendor/heyspex-mcp/vault-binding.mjs
474
+ import {
475
+ copyFileSync,
476
+ existsSync as existsSync3,
477
+ mkdirSync as mkdirSync3,
478
+ readFileSync as readFileSync4,
479
+ realpathSync as realpathSync2,
480
+ renameSync as renameSync3,
481
+ statSync as statSync2,
482
+ unlinkSync,
483
+ writeFileSync as writeFileSync3
484
+ } from "node:fs";
485
+ import { homedir as homedir4 } from "node:os";
486
+ import path from "node:path";
487
+
488
+ // vendor/heyspex-mcp/console-fetch.mjs
489
+ var VAULT_NOT_REGISTERED = "VAULT_NOT_REGISTERED";
490
+ var VaultNotRegisteredError = class extends Error {
491
+ /**
492
+ * @param {string | null | undefined} repoRootAbs the root the resolver settled on
493
+ * @param {string | null | undefined} source the resolver tier that produced it
494
+ * @param {{ reason?: 'unregistered' | 'legacy-id', legacyId?: string | null }} [detail]
495
+ */
496
+ constructor(repoRootAbs, source, { reason = "unregistered", legacyId = null } = {}) {
497
+ const root = typeof repoRootAbs === "string" && repoRootAbs.trim() ? repoRootAbs.trim() : null;
498
+ const where = root ? ` (${root})` : "";
499
+ const why = reason === "legacy-id" ? `This repo${where} is registered on this machine under a legacy id (\`${legacyId}\`), not the vault id the console knows, and its heyspex.yaml carries no \`vault_id\` to stand in for it, ` : `This repo${where} is not connected to a HeySpex vault on this machine (\`hs connect\` has not registered it), `;
500
+ super(
501
+ why + `so the console call was refused before it was sent. Run \`${hsCommand("connect")}\`${root ? ` in ${root}` : ""} to ${reason === "legacy-id" ? "re-register" : "connect"} it, then try again. Nothing was sent.`
502
+ );
503
+ this.name = "VaultNotRegisteredError";
504
+ this.code = VAULT_NOT_REGISTERED;
505
+ this.reason = reason;
506
+ this.repoRootAbs = root;
507
+ this.source = typeof source === "string" ? source : null;
508
+ this.legacyId = legacyId;
509
+ }
510
+ };
511
+ var CLOUD_VAULT_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
512
+ function isCloudVaultId(value) {
513
+ return typeof value === "string" && CLOUD_VAULT_ID_RE.test(value.trim());
514
+ }
515
+ var MARKER_VAULT_ID_RE = /^vault_id:[ \t]*["']?([^"'\r\n#]+)/m;
516
+ function readMarkerVaultId(repoRootAbs, { readFile } = {}) {
517
+ if (typeof repoRootAbs !== "string" || !repoRootAbs.trim()) return null;
518
+ const read = readFile ?? ((p) => readFileSync6(p, "utf8"));
519
+ try {
520
+ const raw = read(join6(repoRootAbs, "heyspex.yaml"));
521
+ const value = String(raw ?? "").match(MARKER_VAULT_ID_RE)?.[1]?.trim() ?? "";
522
+ return value || null;
523
+ } catch {
524
+ return null;
525
+ }
526
+ }
527
+ function cloudVaultIdFor(resolved, { readMarkerVaultId: readMarker = readMarkerVaultId } = {}) {
528
+ const rowId = resolved.vaultId.trim();
529
+ if (isCloudVaultId(rowId)) return rowId;
530
+ const marker = readMarker(resolved.repoRootAbs);
531
+ if (isCloudVaultId(marker)) return marker.trim();
532
+ throw new VaultNotRegisteredError(resolved.repoRootAbs, resolved.source, { reason: "legacy-id", legacyId: rowId });
533
+ }
534
+ var SCOPE_REFUSAL_CODES = Object.freeze(["VAULT_SCOPE_MISMATCH", "ACCOUNT_MISMATCH", "VAULT_NOT_REGISTERED"]);
535
+
536
+ // spex-console/src/lib/cli/control-shared.ts
537
+ init_credentials();
538
+
539
+ // spex-console/src/lib/vault-registry/registry-file.ts
540
+ import { existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync7, renameSync as renameSync4, writeFileSync as writeFileSync4 } from "node:fs";
541
+ import { dirname as dirname4, join as join7, resolve as resolve4 } from "node:path";
542
+
543
+ // spex-console/src/lib/heyspex-home.ts
544
+ import { homedir as homedir7 } from "node:os";
545
+ function heyspexHome2(env = process.env) {
546
+ const override = env?.HEYSPEX_HOME;
547
+ if (typeof override === "string" && override.trim().length > 0) {
548
+ return override.trim();
549
+ }
550
+ return homedir7();
551
+ }
552
+
553
+ // spex-console/src/lib/vault-registry/types.ts
554
+ var LEGACY_REGISTRY_ACCOUNT_ID = "legacy";
555
+ var VAULT_REGISTRY_SCHEMA_VERSION = 2;
556
+ function emptyVaultRegistry() {
557
+ return {
558
+ schema_version: VAULT_REGISTRY_SCHEMA_VERSION,
559
+ current_account_id: null,
560
+ accounts: {},
561
+ workspaces: [],
562
+ vaults: []
563
+ };
564
+ }
565
+
566
+ // spex-console/src/lib/vault-registry/registry-file.ts
567
+ function vaultRegistryDir(opts = {}) {
568
+ return opts.registryDir ?? join7(heyspexHome2(), ".heyspex");
569
+ }
570
+ function vaultRegistryFilePath(opts = {}) {
571
+ return join7(vaultRegistryDir(opts), "registry.json");
572
+ }
573
+ function isNonEmptyString(v) {
574
+ return typeof v === "string" && v.trim().length > 0;
575
+ }
576
+ function accountOf(o) {
577
+ return isNonEmptyString(o.account_id) ? o.account_id : LEGACY_REGISTRY_ACCOUNT_ID;
578
+ }
579
+ function normalizeWorkspace(raw) {
580
+ if (!raw || typeof raw !== "object") return null;
581
+ const o = raw;
582
+ if (!isNonEmptyString(o.id)) return null;
583
+ if (!isNonEmptyString(o.display_name)) return null;
584
+ if (!isNonEmptyString(o.created_at)) return null;
585
+ const record = {
586
+ id: o.id,
587
+ display_name: o.display_name,
588
+ created_at: o.created_at,
589
+ archived: o.archived === true,
590
+ account_id: accountOf(o)
591
+ };
592
+ if (isNonEmptyString(o.github_org)) record.github_org = o.github_org;
593
+ return record;
594
+ }
595
+ function normalizeVault(raw) {
596
+ if (!raw || typeof raw !== "object") return null;
597
+ const o = raw;
598
+ if (!isNonEmptyString(o.id)) return null;
599
+ if (!isNonEmptyString(o.workspace_id)) return null;
600
+ if (!isNonEmptyString(o.display_name)) return null;
601
+ if (!isNonEmptyString(o.repo_root_abs)) return null;
602
+ if (typeof o.schema_version !== "number") return null;
603
+ if (!isNonEmptyString(o.registered_at)) return null;
604
+ const record = {
605
+ id: o.id,
606
+ workspace_id: o.workspace_id,
607
+ display_name: o.display_name,
608
+ repo_root_abs: o.repo_root_abs,
609
+ schema_version: o.schema_version,
610
+ registered_at: o.registered_at,
611
+ archived: o.archived === true,
612
+ account_id: accountOf(o)
613
+ };
614
+ if (isNonEmptyString(o.github_remote)) record.github_remote = o.github_remote;
615
+ return record;
616
+ }
617
+ function normalizeStoredPointers(raw) {
618
+ const o = raw && typeof raw === "object" ? raw : {};
619
+ const out = {};
620
+ for (const field of ["active_vault_id", "active_workspace_id"]) {
621
+ const v = o[field];
622
+ if (v === null || isNonEmptyString(v)) out[field] = v;
623
+ }
624
+ return out;
625
+ }
626
+ function normalizePointers(raw) {
627
+ const o = raw && typeof raw === "object" ? raw : {};
628
+ return {
629
+ active_vault_id: isNonEmptyString(o.active_vault_id) ? o.active_vault_id : null,
630
+ active_workspace_id: isNonEmptyString(o.active_workspace_id) ? o.active_workspace_id : null
631
+ };
632
+ }
633
+ function registryFileSchemaOf(json) {
634
+ if (!json || typeof json !== "object" || Array.isArray(json)) return null;
635
+ return json.schema_version === 2 ? 2 : 1;
636
+ }
637
+ function parseVaultRegistryFile(json) {
638
+ const schema = registryFileSchemaOf(json);
639
+ if (schema === null) return emptyVaultRegistry();
640
+ const o = json;
641
+ const workspacesRaw = Array.isArray(o.workspaces) ? o.workspaces : [];
642
+ const workspaces = workspacesRaw.map(normalizeWorkspace).filter((w) => w !== null);
643
+ const vaultsRaw = Array.isArray(o.vaults) ? o.vaults : [];
644
+ const vaults = vaultsRaw.map(normalizeVault).filter((v) => v !== null);
645
+ if (schema === 1) {
646
+ const legacy = normalizePointers(o);
647
+ const hasLegacyState = legacy.active_vault_id !== null || legacy.active_workspace_id !== null || workspaces.length > 0 || vaults.length > 0;
648
+ return {
649
+ schema_version: VAULT_REGISTRY_SCHEMA_VERSION,
650
+ current_account_id: hasLegacyState ? LEGACY_REGISTRY_ACCOUNT_ID : null,
651
+ accounts: hasLegacyState ? { [LEGACY_REGISTRY_ACCOUNT_ID]: legacy } : {},
652
+ workspaces,
653
+ vaults
654
+ };
655
+ }
656
+ const accounts = {};
657
+ if (o.accounts && typeof o.accounts === "object" && !Array.isArray(o.accounts)) {
658
+ for (const [id, pointers] of Object.entries(o.accounts)) {
659
+ if (isNonEmptyString(id)) accounts[id] = normalizeStoredPointers(pointers);
660
+ }
661
+ }
662
+ return {
663
+ schema_version: VAULT_REGISTRY_SCHEMA_VERSION,
664
+ current_account_id: isNonEmptyString(o.current_account_id) ? o.current_account_id : null,
665
+ accounts,
666
+ workspaces,
667
+ vaults
668
+ };
669
+ }
670
+ function readRegistryJson(opts) {
671
+ const filePath = vaultRegistryFilePath(opts);
672
+ if (!existsSync5(filePath)) return { kind: "missing" };
673
+ try {
674
+ const raw = readFileSync7(filePath, "utf8");
675
+ const json = JSON.parse(raw);
676
+ if (registryFileSchemaOf(json) === null) return { kind: "unreadable" };
677
+ return { kind: "ok", raw, json };
678
+ } catch {
679
+ return { kind: "unreadable" };
680
+ }
681
+ }
682
+ function inspectVaultRegistry(opts = {}) {
683
+ const read = readRegistryJson(opts);
684
+ if (read.kind !== "ok") {
685
+ return {
686
+ registry: emptyVaultRegistry(),
687
+ file_schema_version: null,
688
+ registry_unreadable: read.kind === "unreadable"
689
+ };
690
+ }
691
+ return {
692
+ registry: parseVaultRegistryFile(read.json),
693
+ file_schema_version: registryFileSchemaOf(read.json),
694
+ registry_unreadable: false
695
+ };
696
+ }
697
+ function loadVaultRegistry(opts = {}) {
698
+ return inspectVaultRegistry(opts).registry;
699
+ }
700
+
701
+ // spex-console/src/lib/cli/control-shared.ts
702
+ var EXIT = {
703
+ /** Success. */
704
+ OK: 0,
705
+ /**
706
+ * A read-only CHECK ran correctly and its answer is "no" — `hs connect
707
+ * --check` on an unconnected repo. Distinct from {@link EXIT.USAGE} so a
708
+ * script can tell "you typed the command wrong" from "the command worked,
709
+ * the repo is not connected". Both were `1` until 2026-09-18, which made
710
+ * `--check` unusable in a conditional: every caller had to parse stdout to
711
+ * find out which of the two had happened.
712
+ */
713
+ CHECK_FAILED: 2,
714
+ /** Usage error — unknown subcommand/flag, or a missing required argument. */
715
+ USAGE: 1,
716
+ /** Claim race lost — the spec is already claimed by another agent (409). */
717
+ CONFLICT: 9,
718
+ /** Target not found — release of an unheld claim, etc. (404). */
719
+ NOT_FOUND: 10,
720
+ /** Invalid argument — bad `--ttl`, unknown `--kind`, unparseable date. */
721
+ INVALID_ARG: 11,
722
+ /** SpexConsole unreachable (network error reaching the dev server). */
723
+ CONSOLE_UNREACHABLE: 12,
724
+ /** Server failure — a non-OK response that isn't 400/402/404/409. */
725
+ WRITE_FAILED: 13,
726
+ /** Neon control plane absent — the endpoint returned 402 (upgrade required). */
727
+ NEON_REQUIRED: 14,
728
+ /**
729
+ * A cross-account `--account <id>` override was refused — the caller is
730
+ * not a builder/admin (`resolveScopedAccountId`'s `forbidden_account_override`,
731
+ * [[HS-X3GB-EKLJ-TASK-hs-cli-account-flag-for-cross-account]]). Distinct
732
+ * from `USAGE`/`INVALID_ARG` — this is an authorization refusal, not a
733
+ * malformed command.
734
+ */
735
+ FORBIDDEN: 15,
736
+ /**
737
+ * A CLOUD write refused because no account id could be resolved (no
738
+ * `HS_ACCOUNT_ID` env var, no `account_id:` in `~/.heyspex/config.yaml`) --
739
+ * `resolveCloudAccountIdOrRefuse` in `vault-workspace-shared.ts`
740
+ * ([[HS-YU1S-UAGY-TASK-cloud-writes-refuse-without-a]]). Distinct from
741
+ * `FORBIDDEN` -- this is "not signed in at all", not "signed in but not
742
+ * authorized for this override".
743
+ */
744
+ SIGN_IN_REQUIRED: 16,
745
+ /**
746
+ * Signed in, but the account a repo would be attached to was not confirmed:
747
+ * a non-interactive install/connect with no matching `--account` / `--yes`,
748
+ * an `account_id` that disagrees with the bearer's user, or the human
749
+ * aborting the identity prompt (`install-identity.ts`,
750
+ * [[HS-HAQI-KODY-DIAG-hs-install-and-hs-connect-bind-a-new]]).
751
+ */
752
+ IDENTITY_UNCONFIRMED: 17,
753
+ /**
754
+ * The repo this verb runs in is not registered on this machine (no
755
+ * `~/.heyspex/registry.json` row for its root, or a legacy slug row with no
756
+ * cloud `vault_id` in its heyspex.yaml), so the call was refused LOCALLY —
757
+ * nothing was sent. Names `hs connect`
758
+ * ([[HS-MVG4-WW9R-TASK-mcp-and-hs-name-account-vault-on-every]]).
759
+ */
760
+ VAULT_NOT_REGISTERED: 18,
761
+ /**
762
+ * The local half of a setup verb (`hs connect`, `hs vault *`, `hs workspace
763
+ * *`) was written but the CLOUD half did not land -- the console refused
764
+ * it or was never reached. The verb's receipt names the failed half and the
765
+ * exact command to re-run
766
+ * ([[HS-STCY-WW9R-TASK-add-a-shared-receipt-that-reads-back]], invariant 6).
767
+ * Distinct from {@link EXIT.WRITE_FAILED} so a script can tell "re-run to
768
+ * sync the cloud" from a generic server failure.
769
+ */
770
+ CLOUD_WRITE_FAILED: 19,
771
+ /**
772
+ * The repo's committed `heyspex.yaml` records `account: <A>` but the machine
773
+ * is signed in as another account, so `hs connect` refused and wrote
774
+ * nothing (marker, registry, cloud). Repair: `hs login --switch-account <A>`
775
+ * ([[HS-VWUD-WW9R-TASK-record-the-connecting-account-in]], invariant 4).
776
+ */
777
+ ACCOUNT_MISMATCH: 20,
778
+ /**
779
+ * Both sides of a setup verb's receipt were read back and still DISAGREE
780
+ * after a short bounded re-read of the cloud side (a briefly stale read is
781
+ * absorbed first). The write may well have landed; what the verb cannot
782
+ * claim is that this machine and the console now say the same thing. The
783
+ * receipt prints the diffs and the command to re-run
784
+ * ([[HS-FKSR-WW9R-TASK-make-one-hs-connect-run-create-a-cloud]], invariant 6).
785
+ * Distinct from {@link EXIT.CLOUD_WRITE_FAILED} (a write that did not land).
786
+ */
787
+ RECEIPT_DISAGREE: 21
788
+ };
789
+ var VAULT_ID_HEADER = "x-heyspex-vault-id";
790
+ var ACCOUNT_ID_HEADER = "x-heyspex-account-id";
791
+ function readPairedBearer(opts = {}) {
792
+ return readBearer(opts);
793
+ }
794
+ function readPairedToken(opts = {}) {
795
+ return readPairedBearer(opts).token ?? void 0;
796
+ }
797
+ function bearerHeaderFor(consoleUrl, opts = {}) {
798
+ try {
799
+ const host = new URL(consoleUrl).hostname;
800
+ if (host === "localhost" || host === "127.0.0.1" || host === "0.0.0.0" || host === "::1") {
801
+ return {};
802
+ }
803
+ const token = readPairedToken(opts);
804
+ return token ? { authorization: `Bearer ${token}` } : {};
805
+ } catch {
806
+ return {};
807
+ }
808
+ }
809
+ function scopeHeadersFor(scope, method, path3) {
810
+ if (scope === "none") {
811
+ if (!isVaultLessEndpoint(method, path3)) {
812
+ throw new Error(
813
+ `controlRequest: scope "none" is only allowed for the vault-less endpoints (${VAULT_LESS_ENDPOINTS.join(", ")}); ${method.toUpperCase()} ${path3} is vault-scoped and must name { accountId, vaultId }.`
814
+ );
815
+ }
816
+ return {};
817
+ }
818
+ return { [VAULT_ID_HEADER]: scope.vaultId, [ACCOUNT_ID_HEADER]: scope.accountId };
819
+ }
820
+ async function controlRequest(deps, req) {
821
+ const url = `${deps.consoleUrl}${req.path}`;
822
+ const scopeHeaders = scopeHeadersFor(deps.scope, req.method, req.path);
823
+ let res;
824
+ try {
825
+ res = await deps.fetchImpl(url, {
826
+ method: req.method,
827
+ headers: {
828
+ "content-type": "application/json",
829
+ // A remote console (cloud vault write mode, [[HS-PH7O-ILNC-DIAG-hs-check-report-cannot-authenticate]])
830
+ // authenticates every control call; loopback never asked, so the header
831
+ // is attached only when the target is non-loopback and a paired token
832
+ // exists. Same `hsmcp_` bearer the MCP server presents.
833
+ ...bearerHeaderFor(deps.consoleUrl),
834
+ // Invariant 2: name the vault and the account on every call, or the
835
+ // console serves whatever its leftover pointer says.
836
+ ...scopeHeaders
837
+ },
838
+ ...req.body !== void 0 ? { body: JSON.stringify(req.body) } : {}
839
+ });
840
+ } catch (err) {
841
+ const message = err instanceof Error ? err.message : String(err);
842
+ return {
843
+ ok: false,
844
+ error: {
845
+ code: EXIT.CONSOLE_UNREACHABLE,
846
+ message: `could not reach console at ${deps.consoleUrl}: ${message}
847
+ Start the dev server or set HEYSPEX_CONSOLE_URL.`,
848
+ payload: {
849
+ ok: false,
850
+ error: "console_unreachable",
851
+ url: deps.consoleUrl,
852
+ message
853
+ },
854
+ isError: true
855
+ }
856
+ };
857
+ }
858
+ let parsed = null;
859
+ try {
860
+ parsed = await res.json();
861
+ } catch {
862
+ }
863
+ if (res.status === 402) {
864
+ return {
865
+ ok: false,
866
+ error: {
867
+ code: EXIT.NEON_REQUIRED,
868
+ message: "this command requires the Neon control plane, which is not configured (console returned 402).",
869
+ payload: {
870
+ ok: false,
871
+ error: "neon_required",
872
+ status: 402,
873
+ console_response: parsed
874
+ },
875
+ isError: true
876
+ }
877
+ };
878
+ }
879
+ return { ok: true, status: res.status, body: parsed };
880
+ }
881
+ function envelopeMessage(body) {
882
+ if (body && typeof body === "object" && "message" in body) {
883
+ const m = body.message;
884
+ if (typeof m === "string") return m;
885
+ }
886
+ return "";
887
+ }
888
+ function writeFailed(status, body) {
889
+ const detail = envelopeMessage(body);
890
+ return {
891
+ code: EXIT.WRITE_FAILED,
892
+ message: `console returned ${status}${detail ? `: ${detail}` : ""}`,
893
+ payload: { ok: false, error: "write_failed", status, console_response: body },
894
+ isError: true
895
+ };
896
+ }
897
+ function parseTtl(token) {
898
+ const trimmed = token.trim().toLowerCase();
899
+ if (trimmed === "none" || trimmed === "null") return { value: null };
900
+ const n = Number(trimmed);
901
+ if (!Number.isFinite(n) || n < 0) {
902
+ return { error: `--ttl must be a non-negative number of ms, or "none"` };
903
+ }
904
+ return { value: n };
905
+ }
906
+ function normalizeRoot(p) {
907
+ return path2.resolve(p).replace(/[\\/]+/g, "/").replace(/\/+$/, "").toLowerCase();
908
+ }
909
+ function resolveControlScope(input) {
910
+ const target = normalizeRoot(input.vaultRoot);
911
+ const row = input.vaults.find((v) => normalizeRoot(v.repo_root_abs) === target) ?? null;
912
+ if (!row) {
913
+ return {
914
+ ok: false,
915
+ error: {
916
+ code: EXIT.VAULT_NOT_REGISTERED,
917
+ message: `this repo (${input.vaultRoot}) is not connected to a HeySpex vault on this machine (\`hs connect\` has not registered it), so the call was refused before it was sent. Run \`${hsCommand("connect")}\` in ${input.vaultRoot}, then try again.`,
918
+ payload: {
919
+ ok: false,
920
+ error: "vault_not_registered",
921
+ reason: "unregistered",
922
+ vault_root: input.vaultRoot
923
+ },
924
+ isError: true
925
+ }
926
+ };
927
+ }
928
+ let vaultId;
929
+ try {
930
+ vaultId = cloudVaultIdFor(
931
+ { vaultId: row.id, repoRootAbs: row.repo_root_abs, source: "registry" },
932
+ input.readMarkerVaultId ? { readMarkerVaultId: input.readMarkerVaultId } : {}
933
+ );
934
+ } catch (err) {
935
+ if (!(err instanceof VaultNotRegisteredError)) throw err;
936
+ const refused = err;
937
+ return {
938
+ ok: false,
939
+ error: {
940
+ code: EXIT.VAULT_NOT_REGISTERED,
941
+ message: refused.message,
942
+ payload: {
943
+ ok: false,
944
+ error: "vault_not_registered",
945
+ reason: refused.reason ?? "legacy-id",
946
+ vault_root: input.vaultRoot,
947
+ legacy_id: refused.legacyId ?? row.id
948
+ },
949
+ isError: true
950
+ }
951
+ };
952
+ }
953
+ const accountId = input.accountId?.trim() ?? "";
954
+ if (!accountId) {
955
+ return {
956
+ ok: false,
957
+ error: {
958
+ code: EXIT.SIGN_IN_REQUIRED,
959
+ message: `no HeySpex account is configured on this machine (\`hs login\` has not been run), so the call was refused before it was sent. Run \`${hsCommand("login")}\` on this machine, then try again.`,
960
+ payload: { ok: false, error: "sign_in_required", vault_root: input.vaultRoot },
961
+ isError: true
962
+ }
963
+ };
964
+ }
965
+ return { ok: true, scope: { accountId, vaultId } };
966
+ }
967
+ function resolveControlScopeFromMachine(vaultRoot, opts = {}) {
968
+ const registry = loadVaultRegistry(opts.registry);
969
+ const accountId = resolveSessionOwnerUncached({ env: opts.env, homeDir: opts.homeDir });
970
+ return resolveControlScope({ vaultRoot, accountId, vaults: registry.vaults });
971
+ }
972
+
973
+ // scripts/lib/console-url-resolver.mjs
974
+ init_heyspex_home();
975
+ init_dev_mode();
976
+ import { readFileSync as readFileSync9 } from "node:fs";
977
+ import { homedir as homedir9 } from "node:os";
978
+ import { join as join9 } from "node:path";
979
+ var DEFAULT_CONSOLE_URL = LOCAL_CONSOLE_URL;
980
+ function trimTrailingSlash(url) {
981
+ return url.replace(/\/+$/, "");
982
+ }
983
+ var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "::1", "[::1]", "0.0.0.0"]);
984
+ function isLoopbackConsoleUrl(url) {
985
+ if (typeof url !== "string" || !url) return false;
986
+ try {
987
+ return LOOPBACK_HOSTS.has(new URL(url).hostname.toLowerCase());
988
+ } catch {
989
+ return false;
990
+ }
991
+ }
992
+ var staleLoopbackCredentialsWarned = false;
993
+ function warnStaleLoopbackCredentialsOnce(credentialsUrl, derivedUrl, { log }) {
994
+ if (staleLoopbackCredentialsWarned) return;
995
+ staleLoopbackCredentialsWarned = true;
996
+ try {
997
+ log(
998
+ `[heyspex] ignoring console_url ${credentialsUrl} from ~/.heyspex/credentials.yaml: the resolved reliance is cloud, and a loopback console cannot serve it \u2014 using ${derivedUrl} (set HEYSPEX_CONSOLE_URL to override explicitly, or run \`hs dev mode:local\` to go back to a local console).
999
+ `
1000
+ );
1001
+ } catch {
1002
+ }
1003
+ }
1004
+ function readCredentialsConsoleUrl({ homeDir = heyspexHome(), readFile = defaultReadFile2 } = {}) {
1005
+ try {
1006
+ const raw = readFile(join9(homeDir, ".heyspex", "credentials.yaml"));
1007
+ const match = String(raw ?? "").match(/^console_url:\s*["']?([^"'\r\n#]+)/m);
1008
+ const value = match?.[1]?.trim();
1009
+ return value && value.length > 0 ? trimTrailingSlash(value) : null;
1010
+ } catch {
1011
+ return null;
1012
+ }
1013
+ }
1014
+ function defaultReadFile2(p) {
1015
+ return readFileSync9(p, "utf8");
1016
+ }
1017
+ function readDiscoveryFileConsoleUrl(repoRoot, { readDiscovery: readDiscovery2 = defaultReadFile2 } = {}) {
1018
+ if (!repoRoot) return null;
1019
+ try {
1020
+ const discovery = String(readDiscovery2(join9(repoRoot, ".heyspex", "console-url")) ?? "").trim();
1021
+ if (discovery.length > 0) return trimTrailingSlash(discovery);
1022
+ } catch {
1023
+ }
1024
+ return null;
1025
+ }
1026
+ var ConsoleUrlUnresolvedError = class extends Error {
1027
+ constructor() {
1028
+ super(
1029
+ "resolveConsoleUrl: local reliance with no HEYSPEX_CONSOLE_URL env, no console_url: in ~/.heyspex/credentials.yaml, and no .heyspex/console-url discovery file \u2014 refusing to silently fall back to the localhost:3000 default in strict mode."
1030
+ );
1031
+ this.name = "ConsoleUrlUnresolvedError";
1032
+ }
1033
+ };
1034
+ function resolveModeEnvelope({ env, homeDir }) {
1035
+ try {
1036
+ const resolved = resolveDevMode({ env, homeDir });
1037
+ return {
1038
+ reliance: resolved.reliance === "cloud" ? "cloud" : "local",
1039
+ consoleUrl: resolved.consoleUrl || DEFAULT_CONSOLE_URL
1040
+ };
1041
+ } catch {
1042
+ return { reliance: "local", consoleUrl: DEFAULT_CONSOLE_URL };
1043
+ }
1044
+ }
1045
+ function resolveConsoleUrl({
1046
+ repoRoot,
1047
+ env = process.env,
1048
+ homeDir = heyspexHome(),
1049
+ strict = false,
1050
+ devMode,
1051
+ log = (line) => process.stderr.write(line),
1052
+ readFile = defaultReadFile2,
1053
+ readDiscovery: readDiscovery2 = defaultReadFile2
1054
+ } = {}) {
1055
+ const envUrl = env.HEYSPEX_CONSOLE_URL?.trim();
1056
+ if (envUrl) return trimTrailingSlash(envUrl);
1057
+ const mode = devMode ?? resolveModeEnvelope({ env, homeDir });
1058
+ const cloud = mode.reliance === "cloud";
1059
+ const derivedUrl = trimTrailingSlash(
1060
+ cloud && isLoopbackConsoleUrl(mode.consoleUrl) ? CLOUD_CONSOLE_URL : mode.consoleUrl || DEFAULT_CONSOLE_URL
1061
+ );
1062
+ const credentialsUrl = readCredentialsConsoleUrl({ homeDir, readFile });
1063
+ if (credentialsUrl) {
1064
+ if (cloud && isLoopbackConsoleUrl(credentialsUrl)) {
1065
+ warnStaleLoopbackCredentialsOnce(credentialsUrl, derivedUrl, { log });
1066
+ } else {
1067
+ return credentialsUrl;
1068
+ }
1069
+ }
1070
+ if (!cloud) {
1071
+ const discoveryUrl = readDiscoveryFileConsoleUrl(repoRoot, { readDiscovery: readDiscovery2 });
1072
+ if (discoveryUrl) return discoveryUrl;
1073
+ if (strict) throw new ConsoleUrlUnresolvedError();
1074
+ }
1075
+ return derivedUrl;
1076
+ }
1077
+
1078
+ // spex-console/src/lib/cli/defer.ts
1079
+ function resolveSpexConsoleUrl(vaultRoot, readDiscovery2, opts = {}) {
1080
+ return resolveConsoleUrl({
1081
+ repoRoot: vaultRoot,
1082
+ env: opts.env,
1083
+ homeDir: opts.homeDir,
1084
+ readFile: opts.readFile,
1085
+ readDiscovery: readDiscovery2,
1086
+ log: opts.log
1087
+ });
1088
+ }
1089
+ var HELP = [
1090
+ "Usage:",
1091
+ " hs defer <spec-id> [--until <when>] [--json] [--no-daemon]",
1092
+ " hs undefer <spec-id> [--json] [--no-daemon]",
1093
+ "",
1094
+ "Time-shift a spec via its `defer_until` frontmatter field. A deferred spec is",
1095
+ "scheduler-invisible until the date passes, then auto-revives.",
1096
+ "",
1097
+ "Arguments:",
1098
+ " <spec-id> The spec to defer/undefer (e.g. HS-TASK-EWL5).",
1099
+ "",
1100
+ "Flags:",
1101
+ " --until <when> ISO date, or relative offset +Nd / +Nw / +Nm / +Ny.",
1102
+ " Defaults to +1y (matches the console Defer button).",
1103
+ " Ignored by `undefer` (which always clears the field).",
1104
+ " --json Emit a machine-readable JSON result.",
1105
+ " --no-daemon Write straight to the vault (no console needed; CI path).",
1106
+ " --help, -h Show this help.",
1107
+ "",
1108
+ "Exit codes: 0 ok \xB7 1 usage \xB7 10 not-found \xB7 11 bad-arg \xB7 12 console-unreachable \xB7 13 write-failed"
1109
+ ].join("\n");
1110
+
1111
+ // spex-console/src/lib/cli/agent-identity.ts
1112
+ function resolveAgentIdentity(argAgent, argSession) {
1113
+ const trimmedAgent = typeof argAgent === "string" ? argAgent.trim() : "";
1114
+ const trimmedSession = typeof argSession === "string" ? argSession.trim() : "";
1115
+ if (trimmedAgent && trimmedSession) {
1116
+ return { agent: trimmedAgent, sessionId: trimmedSession };
1117
+ }
1118
+ const claudeSession = (process.env.CLAUDE_CODE_SESSION_ID || process.env.CLAUDE_SESSION_ID || "").trim();
1119
+ if (claudeSession) {
1120
+ return {
1121
+ agent: trimmedAgent || "Claude Code",
1122
+ sessionId: trimmedSession || claudeSession
1123
+ };
1124
+ }
1125
+ const cursorSession = (process.env.CURSOR_TRACE_ID || process.env.CURSOR_SESSION_ID || process.env.COMPOSER_SESSION_ID || "").trim();
1126
+ if (cursorSession) {
1127
+ return {
1128
+ agent: trimmedAgent || "Cursor",
1129
+ sessionId: trimmedSession || cursorSession
1130
+ };
1131
+ }
1132
+ return {
1133
+ agent: trimmedAgent || process.env.HEYSPEX_AGENT?.trim() || "External agent",
1134
+ sessionId: trimmedSession || process.env.HEYSPEX_SESSION_ID?.trim() || process.env.HEYSPEX_AGENT_SESSION?.trim() || "local"
1135
+ };
1136
+ }
1137
+
1138
+ // spex-console/src/lib/cli/pin.ts
1139
+ function parsePinArgs(argv) {
1140
+ const subRaw = argv[0];
1141
+ if (subRaw === "--help" || subRaw === "-h" || subRaw === void 0) {
1142
+ return { help: true };
1143
+ }
1144
+ if (subRaw !== "get" && subRaw !== "set" && subRaw !== "clear") {
1145
+ return {
1146
+ error: { code: EXIT.USAGE, message: `unknown subcommand: ${subRaw}` }
1147
+ };
1148
+ }
1149
+ const sub = subRaw;
1150
+ let specId;
1151
+ let by;
1152
+ let ttlMs;
1153
+ let json = false;
1154
+ for (let i = 1; i < argv.length; i++) {
1155
+ const arg = argv[i];
1156
+ if (arg === "--help" || arg === "-h") return { help: true };
1157
+ else if (arg === "--json") json = true;
1158
+ else if (arg === "--by") {
1159
+ by = argv[++i];
1160
+ if (by === void 0) {
1161
+ return { error: { code: EXIT.INVALID_ARG, message: "--by requires a value" } };
1162
+ }
1163
+ } else if (arg.startsWith("--by=")) {
1164
+ by = arg.slice("--by=".length);
1165
+ } else if (arg === "--ttl" || arg.startsWith("--ttl=")) {
1166
+ const token = arg === "--ttl" ? argv[++i] : arg.slice("--ttl=".length);
1167
+ if (token === void 0) {
1168
+ return { error: { code: EXIT.INVALID_ARG, message: "--ttl requires a value" } };
1169
+ }
1170
+ const res = parseTtl(token);
1171
+ if ("error" in res) {
1172
+ return { error: { code: EXIT.INVALID_ARG, message: res.error } };
1173
+ }
1174
+ ttlMs = res.value;
1175
+ } else if (arg.startsWith("-")) {
1176
+ return { error: { code: EXIT.USAGE, message: `unknown flag: ${arg}` } };
1177
+ } else if (sub === "set" && specId === void 0) {
1178
+ specId = arg;
1179
+ } else {
1180
+ return { error: { code: EXIT.USAGE, message: `unexpected argument: ${arg}` } };
1181
+ }
1182
+ }
1183
+ if (sub === "set" && !specId) {
1184
+ return { error: { code: EXIT.USAGE, message: "pin set requires a spec id" } };
1185
+ }
1186
+ return { args: { sub, specId, by, ttlMs, json } };
1187
+ }
1188
+ function describePin(pin) {
1189
+ if (!pin || !pin.specId) return "(no pin)";
1190
+ const fuse = pin.expiresAt ? ` \xB7 fuse ${pin.expiresAt}` : " \xB7 no fuse";
1191
+ return `${pin.specId}${pin.pinnedBy ? ` (by ${pin.pinnedBy})` : ""}${fuse}`;
1192
+ }
1193
+ async function runPin(args, deps) {
1194
+ if (args.sub === "get") {
1195
+ const res2 = await controlRequest(deps, { method: "GET", path: "/api/control/pin" });
1196
+ if (!res2.ok) return res2.error;
1197
+ if (res2.status !== 200) return writeFailed(res2.status, res2.body);
1198
+ const pin = res2.body?.pin ?? null;
1199
+ return {
1200
+ code: EXIT.OK,
1201
+ message: describePin(pin),
1202
+ payload: { ok: true, pin },
1203
+ isError: false
1204
+ };
1205
+ }
1206
+ const pinnedBy = args.by?.trim() || resolveAgentIdentity(deps.argAgent, deps.argSession).agent;
1207
+ const body = args.sub === "set" ? {
1208
+ spec_id: args.specId,
1209
+ pinned_by: pinnedBy,
1210
+ ...args.ttlMs !== void 0 ? { ttl_ms: args.ttlMs } : {}
1211
+ } : { spec_id: null, pinned_by: pinnedBy };
1212
+ const res = await controlRequest(deps, {
1213
+ method: "PUT",
1214
+ path: "/api/control/pin",
1215
+ body
1216
+ });
1217
+ if (!res.ok) return res.error;
1218
+ if (res.status === 400) {
1219
+ const detail = envelopeMessage(res.body);
1220
+ return {
1221
+ code: EXIT.INVALID_ARG,
1222
+ message: `console rejected the request${detail ? `: ${detail}` : ""}`,
1223
+ payload: { ok: false, error: "invalid_request", message: detail },
1224
+ isError: true
1225
+ };
1226
+ }
1227
+ if (res.status !== 200) return writeFailed(res.status, res.body);
1228
+ if (args.sub === "set") {
1229
+ const pin = res.body?.pin ?? null;
1230
+ return {
1231
+ code: EXIT.OK,
1232
+ message: `Pinned \u2192 ${describePin(pin)}`,
1233
+ payload: { ok: true, pin },
1234
+ isError: false
1235
+ };
1236
+ }
1237
+ const cleared = Boolean(res.body?.cleared);
1238
+ return {
1239
+ code: EXIT.OK,
1240
+ message: cleared ? "Pin cleared" : "No pin to clear",
1241
+ payload: { ok: true, cleared },
1242
+ isError: false
1243
+ };
1244
+ }
1245
+ var HELP2 = [
1246
+ "Usage:",
1247
+ " hs pin get Print the current pinned spec",
1248
+ " hs pin set <spec-id> [flags] Pin a spec to the top (on-deck)",
1249
+ " hs pin clear [flags] Clear the on-deck pin",
1250
+ "",
1251
+ "Wraps GET/PUT /api/control/pin (Neon control plane). Requires a",
1252
+ "reachable console with Neon configured.",
1253
+ "",
1254
+ "Flags:",
1255
+ " --by <actor> Who is pinning (default: detected agent identity).",
1256
+ " --ttl <ms|none> Fuse in ms; `none` = no fuse (default: server 7-day fuse).",
1257
+ " (set only)",
1258
+ " --json Emit a machine-readable JSON result.",
1259
+ " --help, -h Show this help.",
1260
+ "",
1261
+ "Exit codes: 0 ok \xB7 1 usage \xB7 11 bad-arg \xB7 12 console-unreachable \xB7 13 server-error \xB7 14 neon-required"
1262
+ ].join("\n");
1263
+
1264
+ // spex-console/bin/run-entry.ts
1265
+ import process2 from "node:process";
1266
+ var BinExit = class extends Error {
1267
+ code;
1268
+ constructor(code) {
1269
+ super(`exit ${code}`);
1270
+ this.name = "BinExit";
1271
+ this.code = code;
1272
+ }
1273
+ };
1274
+ function runEntry(name, main2, options = {}) {
1275
+ const { fallbackCode = 1, unhandledLabel = "unhandled" } = options;
1276
+ void (async () => {
1277
+ try {
1278
+ await main2();
1279
+ } catch (err) {
1280
+ if (err instanceof BinExit) {
1281
+ process2.exitCode = err.code;
1282
+ return;
1283
+ }
1284
+ const message = err instanceof Error ? err.message : String(err);
1285
+ process2.stderr.write(`${name}: ${unhandledLabel}: ${message}
1286
+ `);
1287
+ process2.exitCode = fallbackCode;
1288
+ }
1289
+ })();
1290
+ }
1291
+
1292
+ // spex-console/bin/hs-pin.ts
1293
+ function readDiscovery(p) {
1294
+ try {
1295
+ return readFileSync10(p, "utf-8");
1296
+ } catch {
1297
+ return null;
1298
+ }
1299
+ }
1300
+ async function main() {
1301
+ const vaultRoot = process3.env.HS_VAULT_ROOT;
1302
+ if (!vaultRoot) {
1303
+ process3.stderr.write(
1304
+ "hs pin: HS_VAULT_ROOT is not set (the dispatcher must resolve and pass it).\n"
1305
+ );
1306
+ process3.exitCode = EXIT.USAGE;
1307
+ return;
1308
+ }
1309
+ const parsed = parsePinArgs(process3.argv.slice(3));
1310
+ if (parsed.help) {
1311
+ process3.stdout.write(`${HELP2}
1312
+ `);
1313
+ process3.exitCode = EXIT.OK;
1314
+ return;
1315
+ }
1316
+ if (parsed.error) {
1317
+ process3.stderr.write(`hs pin: ${parsed.error.message}
1318
+ `);
1319
+ process3.exitCode = parsed.error.code;
1320
+ return;
1321
+ }
1322
+ const consoleUrl = resolveSpexConsoleUrl(vaultRoot, readDiscovery);
1323
+ const scoped = resolveControlScopeFromMachine(vaultRoot);
1324
+ if (!scoped.ok) {
1325
+ process3.stderr.write(`hs pin: ${scoped.error.message}
1326
+ `);
1327
+ process3.exitCode = scoped.error.code;
1328
+ return;
1329
+ }
1330
+ const result = await runPin(parsed.args, { fetchImpl: fetch, consoleUrl, scope: scoped.scope });
1331
+ const sink = result.isError ? process3.stderr : process3.stdout;
1332
+ sink.write(`${parsed.args.json ? JSON.stringify(result.payload) : result.message}
1333
+ `);
1334
+ process3.exitCode = result.code;
1335
+ }
1336
+ runEntry("hs pin", main, { fallbackCode: EXIT.WRITE_FAILED });