@hasna/workflows 0.1.3 → 0.2.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.
- package/README.md +152 -98
- package/dist/agent-tools.js +152 -959
- package/dist/cli/index.js +4130 -2329
- package/dist/handlers.js +3287 -55
- package/dist/index.js +1534 -370
- package/dist/mcp/index.js +1741 -1660
- package/dist/sdk.js +1620 -0
- package/dist/serve/admin.js +4248 -0
- package/dist/serve/index.js +3416 -1350
- package/dist/service.js +1302 -286
- package/hasna.contract.json +17 -17
- package/package.json +16 -13
- package/types/agent-tools.d.ts +3 -17
- package/types/client-error.d.ts +4 -0
- package/types/client-tools.d.ts +4 -0
- package/types/client.d.ts +60 -0
- package/types/daemon.d.ts +18 -9
- package/types/db/postgres-store.d.ts +54 -0
- package/types/graph.d.ts +7 -0
- package/types/handlers.d.ts +2 -1
- package/types/identity.d.ts +7 -0
- package/types/lanes/types.d.ts +12 -3
- package/types/openapi.d.ts +7 -0
- package/types/paths.d.ts +10 -1
- package/types/sdk/generated-api.d.ts +159 -0
- package/types/sdk.d.ts +6 -0
- package/types/serve/admin.d.ts +2 -0
- package/types/service.d.ts +75 -4
- package/types/session.d.ts +31 -8
- package/types/setup.d.ts +71 -0
- package/types/store.d.ts +35 -0
- package/types/tool-definitions.d.ts +18 -0
- package/types/types.d.ts +8 -0
- package/types/version.d.ts +1 -0
- package/types/wal.d.ts +9 -1
package/dist/mcp/index.js
CHANGED
|
@@ -1,448 +1,170 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var __defProp = Object.defineProperty;
|
|
4
|
-
var __returnValue = (v) => v;
|
|
5
|
-
function __exportSetter(name, newValue) {
|
|
6
|
-
this[name] = __returnValue.bind(null, newValue);
|
|
7
|
-
}
|
|
8
|
-
var __export = (target, all) => {
|
|
9
|
-
for (var name in all)
|
|
10
|
-
__defProp(target, name, {
|
|
11
|
-
get: all[name],
|
|
12
|
-
enumerable: true,
|
|
13
|
-
configurable: true,
|
|
14
|
-
set: __exportSetter.bind(all, name)
|
|
15
|
-
});
|
|
16
|
-
};
|
|
17
|
-
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
|
|
18
|
-
var __require = import.meta.require;
|
|
19
3
|
|
|
20
|
-
// src/
|
|
21
|
-
import {
|
|
22
|
-
function binaryOnPath(binary) {
|
|
23
|
-
const pathEntries = (process.env.PATH ?? "").split(":").filter(Boolean);
|
|
24
|
-
for (const entry of pathEntries) {
|
|
25
|
-
try {
|
|
26
|
-
const stat = statSync(`${entry}/${binary}`);
|
|
27
|
-
if (stat.isFile())
|
|
28
|
-
return true;
|
|
29
|
-
} catch {}
|
|
30
|
-
}
|
|
31
|
-
return false;
|
|
32
|
-
}
|
|
33
|
-
function withTimeout(promise, timeoutMs, what) {
|
|
34
|
-
return new Promise((resolve, reject) => {
|
|
35
|
-
const timer = setTimeout(() => {
|
|
36
|
-
reject(new Error(`${what} exceeded the ${timeoutMs}ms budget`));
|
|
37
|
-
}, timeoutMs);
|
|
38
|
-
promise.then((value) => {
|
|
39
|
-
clearTimeout(timer);
|
|
40
|
-
resolve(value);
|
|
41
|
-
}, (err) => {
|
|
42
|
-
clearTimeout(timer);
|
|
43
|
-
reject(err);
|
|
44
|
-
});
|
|
45
|
-
});
|
|
46
|
-
}
|
|
47
|
-
function spawnCli(cmd, opts) {
|
|
48
|
-
const started = Date.now();
|
|
49
|
-
const timeoutMs = opts.timeoutMs ?? DEFAULT_LANE_TIMEOUT_MS;
|
|
50
|
-
let proc;
|
|
51
|
-
try {
|
|
52
|
-
proc = Bun.spawnSync({
|
|
53
|
-
cmd,
|
|
54
|
-
cwd: opts.cwd,
|
|
55
|
-
env: { ...process.env, ...opts.env ?? {} },
|
|
56
|
-
stdout: "pipe",
|
|
57
|
-
stderr: "pipe",
|
|
58
|
-
timeout: timeoutMs
|
|
59
|
-
});
|
|
60
|
-
} catch (err) {
|
|
61
|
-
const message = String(err instanceof Error ? err.message : err);
|
|
62
|
-
if (message.includes("ENOENT") || /not found/i.test(message)) {
|
|
63
|
-
throw new LaneDependencyMissingError(`lane binary ${JSON.stringify(opts.binaryName)} not found on PATH; install it or provide ${opts.packageHint}`);
|
|
64
|
-
}
|
|
65
|
-
return { ok: false, exitCode: 1, output: "", durationMs: Date.now() - started, error: message };
|
|
66
|
-
}
|
|
67
|
-
const durationMs = Date.now() - started;
|
|
68
|
-
const stdout = proc.stdout ? new TextDecoder().decode(proc.stdout) : "";
|
|
69
|
-
const stderr = proc.stderr ? new TextDecoder().decode(proc.stderr) : "";
|
|
70
|
-
const output = stderr ? `${stdout}
|
|
71
|
-
${stderr}`.trim() : stdout.trim();
|
|
72
|
-
const exitCode = proc.exitCode ?? 1;
|
|
73
|
-
return { ok: exitCode === 0, exitCode, output, durationMs };
|
|
74
|
-
}
|
|
75
|
-
var LANE_KINDS2, LaneDependencyMissingError, LaneAdapterShapeError, DEFAULT_LANE_TIMEOUT_MS = 120000;
|
|
76
|
-
var init_types = __esm(() => {
|
|
77
|
-
LANE_KINDS2 = ["claude", "codex", "cursor", "grok"];
|
|
78
|
-
LaneDependencyMissingError = class LaneDependencyMissingError extends Error {
|
|
79
|
-
constructor(message) {
|
|
80
|
-
super(message);
|
|
81
|
-
this.name = "LaneDependencyMissingError";
|
|
82
|
-
}
|
|
83
|
-
};
|
|
84
|
-
LaneAdapterShapeError = class LaneAdapterShapeError extends Error {
|
|
85
|
-
constructor(message) {
|
|
86
|
-
super(message);
|
|
87
|
-
this.name = "LaneAdapterShapeError";
|
|
88
|
-
}
|
|
89
|
-
};
|
|
90
|
-
});
|
|
4
|
+
// src/mcp/index.ts
|
|
5
|
+
import { createInterface } from "readline";
|
|
91
6
|
|
|
92
|
-
// src/
|
|
93
|
-
function
|
|
94
|
-
return {
|
|
95
|
-
kind: "claude",
|
|
96
|
-
async probe() {
|
|
97
|
-
const loader = deps.sdkLoader ?? (async () => await import("@anthropic-ai/claude-agent-sdk"));
|
|
98
|
-
try {
|
|
99
|
-
await loader();
|
|
100
|
-
return { kind: "claude", sdk: "@anthropic-ai/claude-agent-sdk", wired: true, via: "sdk" };
|
|
101
|
-
} catch {
|
|
102
|
-
if (binaryOnPath(deps.cliPath ?? "claude")) {
|
|
103
|
-
return { kind: "claude", sdk: "@anthropic-ai/claude-agent-sdk", wired: true, via: "cli" };
|
|
104
|
-
}
|
|
105
|
-
return {
|
|
106
|
-
kind: "claude",
|
|
107
|
-
sdk: "@anthropic-ai/claude-agent-sdk",
|
|
108
|
-
wired: false,
|
|
109
|
-
reason: "neither @anthropic-ai/claude-agent-sdk nor the claude CLI is available on this machine"
|
|
110
|
-
};
|
|
111
|
-
}
|
|
112
|
-
},
|
|
113
|
-
async run(job) {
|
|
114
|
-
if (!job.prompt) {
|
|
115
|
-
return { ok: false, exitCode: 2, output: "", durationMs: 0, error: "claude lane requires a prompt" };
|
|
116
|
-
}
|
|
117
|
-
const started = Date.now();
|
|
118
|
-
const timeoutMs = job.timeoutMs ?? DEFAULT_LANE_TIMEOUT_MS;
|
|
119
|
-
const loader = deps.sdkLoader ?? (async () => await import("@anthropic-ai/claude-agent-sdk"));
|
|
120
|
-
let sdk;
|
|
121
|
-
try {
|
|
122
|
-
sdk = await loader();
|
|
123
|
-
} catch (err) {
|
|
124
|
-
return runClaudeCli(job, deps.cliPath ?? "claude", started, timeoutMs);
|
|
125
|
-
}
|
|
126
|
-
const query = sdk.query;
|
|
127
|
-
if (typeof query !== "function") {
|
|
128
|
-
throw new LaneAdapterShapeError("@anthropic-ai/claude-agent-sdk exports no query() function");
|
|
129
|
-
}
|
|
130
|
-
const prompt = job.prompt;
|
|
131
|
-
try {
|
|
132
|
-
const { output, isError } = await withTimeout((async () => {
|
|
133
|
-
const generator = await query({
|
|
134
|
-
prompt,
|
|
135
|
-
options: { model: job.model, maxTurns: 32, abortSignal: undefined }
|
|
136
|
-
});
|
|
137
|
-
let output2 = "";
|
|
138
|
-
let isError2 = false;
|
|
139
|
-
for await (const message of generator) {
|
|
140
|
-
if (message.type === "assistant") {
|
|
141
|
-
const content = message.message?.content;
|
|
142
|
-
if (Array.isArray(content)) {
|
|
143
|
-
for (const block of content) {
|
|
144
|
-
if (block && typeof block === "object" && "text" in block && typeof block.text === "string") {
|
|
145
|
-
output2 += block.text;
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
if (message.type === "error")
|
|
151
|
-
isError2 = true;
|
|
152
|
-
}
|
|
153
|
-
return { output: output2, isError: isError2 };
|
|
154
|
-
})(), timeoutMs, `claude lane (${job.prompt.slice(0, 60)})`);
|
|
155
|
-
const durationMs = Date.now() - started;
|
|
156
|
-
return { ok: !isError, exitCode: isError ? 1 : 0, output: output.trim(), durationMs };
|
|
157
|
-
} catch (err) {
|
|
158
|
-
const durationMs = Date.now() - started;
|
|
159
|
-
return { ok: false, exitCode: 1, output: "", durationMs, error: String(err instanceof Error ? err.message : err) };
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
};
|
|
163
|
-
}
|
|
164
|
-
function runClaudeCli(job, cliPath, started, timeoutMs) {
|
|
165
|
-
try {
|
|
166
|
-
const result = spawnCli([cliPath, "-p", job.prompt], {
|
|
167
|
-
binaryName: cliPath,
|
|
168
|
-
packageHint: "@anthropic-ai/claude-agent-sdk or the claude CLI",
|
|
169
|
-
timeoutMs,
|
|
170
|
-
env: job.env,
|
|
171
|
-
cwd: job.cwd
|
|
172
|
-
});
|
|
173
|
-
return { ...result, durationMs: Date.now() - started };
|
|
174
|
-
} catch (err) {
|
|
175
|
-
if (err instanceof LaneDependencyMissingError) {
|
|
176
|
-
return { ok: false, exitCode: 127, output: "", durationMs: Date.now() - started, error: err.message };
|
|
177
|
-
}
|
|
178
|
-
throw err;
|
|
179
|
-
}
|
|
7
|
+
// src/tool-definitions.ts
|
|
8
|
+
function textResult(payload) {
|
|
9
|
+
return { content: [{ type: "text", text: JSON.stringify(payload) }], isError: false };
|
|
180
10
|
}
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
return {
|
|
188
|
-
kind: "codex",
|
|
189
|
-
async probe() {
|
|
190
|
-
const loader = deps.sdkLoader ?? (async () => await import("@openai/codex-sdk"));
|
|
191
|
-
try {
|
|
192
|
-
await loader();
|
|
193
|
-
return { kind: "codex", sdk: "@openai/codex-sdk", wired: true, via: "sdk" };
|
|
194
|
-
} catch {
|
|
195
|
-
if (binaryOnPath(deps.cliPath ?? "codex")) {
|
|
196
|
-
return { kind: "codex", sdk: "@openai/codex-sdk", wired: true, via: "cli" };
|
|
197
|
-
}
|
|
198
|
-
return {
|
|
199
|
-
kind: "codex",
|
|
200
|
-
sdk: "@openai/codex-sdk",
|
|
201
|
-
wired: false,
|
|
202
|
-
reason: "neither @openai/codex-sdk nor the codex CLI is available on this machine"
|
|
203
|
-
};
|
|
204
|
-
}
|
|
11
|
+
function workflowsTools(_service) {
|
|
12
|
+
const tools = [
|
|
13
|
+
{
|
|
14
|
+
name: "workflows_version",
|
|
15
|
+
description: "Report the installed @hasna/workflows version.",
|
|
16
|
+
inputSchema: { type: "object", properties: {} }
|
|
205
17
|
},
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
18
|
+
{
|
|
19
|
+
name: "workflows_health",
|
|
20
|
+
description: "Report the workflows service health (service, version, pid, uptime).",
|
|
21
|
+
inputSchema: { type: "object", properties: {} }
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
name: "workflows_ready",
|
|
25
|
+
description: "Report the hosted workflows service readiness.",
|
|
26
|
+
inputSchema: { type: "object", properties: {} }
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
name: "workflows_validate",
|
|
30
|
+
description: "Validate a workflow graph (JSON object with name, version, nodes).",
|
|
31
|
+
inputSchema: {
|
|
32
|
+
type: "object",
|
|
33
|
+
properties: { graph: { type: "object", description: "the workflow graph" } },
|
|
34
|
+
required: ["graph"]
|
|
222
35
|
}
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
} catch (err) {
|
|
237
|
-
const durationMs = Date.now() - started;
|
|
238
|
-
return { ok: false, exitCode: 1, output: "", durationMs, error: String(err instanceof Error ? err.message : err) };
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
name: "workflows_run",
|
|
39
|
+
description: "Run a workflow graph to a terminal state (bounded cycles; command steps execute; lane steps need the lane substrate).",
|
|
40
|
+
inputSchema: {
|
|
41
|
+
type: "object",
|
|
42
|
+
properties: {
|
|
43
|
+
graph: { type: "object", description: "the workflow graph" },
|
|
44
|
+
context: { type: "object", description: "optional run context" },
|
|
45
|
+
idempotencyKey: { type: "string", description: "stable request key" },
|
|
46
|
+
maxCycles: { type: "integer", minimum: 1, maximum: 2000 }
|
|
47
|
+
},
|
|
48
|
+
required: ["graph", "idempotencyKey"]
|
|
239
49
|
}
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
env: job.env,
|
|
250
|
-
cwd: job.cwd
|
|
251
|
-
});
|
|
252
|
-
return { ...result, durationMs: Date.now() - started };
|
|
253
|
-
} catch (err) {
|
|
254
|
-
if (err instanceof LaneDependencyMissingError) {
|
|
255
|
-
return { ok: false, exitCode: 127, output: "", durationMs: Date.now() - started, error: err.message };
|
|
256
|
-
}
|
|
257
|
-
throw err;
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
var init_codex = __esm(() => {
|
|
261
|
-
init_types();
|
|
262
|
-
});
|
|
263
|
-
|
|
264
|
-
// src/lanes/cursor.ts
|
|
265
|
-
function createCursorAdapter(deps = {}) {
|
|
266
|
-
return {
|
|
267
|
-
kind: "cursor",
|
|
268
|
-
async probe() {
|
|
269
|
-
const loader = deps.sdkLoader ?? (async () => await import("@cursor/sdk"));
|
|
270
|
-
try {
|
|
271
|
-
await loader();
|
|
272
|
-
return { kind: "cursor", sdk: "@cursor/sdk", wired: true, via: "sdk (local mode)" };
|
|
273
|
-
} catch {
|
|
274
|
-
if (binaryOnPath(deps.cliPath ?? "cursor-agent")) {
|
|
275
|
-
return { kind: "cursor", sdk: "@cursor/sdk", wired: true, via: "cli" };
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
name: "workflows_runs_list",
|
|
53
|
+
description: "List recent runs from the configured hosted service.",
|
|
54
|
+
inputSchema: {
|
|
55
|
+
type: "object",
|
|
56
|
+
properties: {
|
|
57
|
+
status: { type: "string", description: "optional status filter" },
|
|
58
|
+
limit: { type: "number", description: "max rows (default 100)" }
|
|
276
59
|
}
|
|
277
|
-
return {
|
|
278
|
-
kind: "cursor",
|
|
279
|
-
sdk: "@cursor/sdk",
|
|
280
|
-
wired: false,
|
|
281
|
-
reason: "neither @cursor/sdk nor the cursor-agent CLI is available on this machine"
|
|
282
|
-
};
|
|
283
60
|
}
|
|
284
61
|
},
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
}
|
|
289
|
-
const started = Date.now();
|
|
290
|
-
const timeoutMs = job.timeoutMs ?? DEFAULT_LANE_TIMEOUT_MS;
|
|
291
|
-
const loader = deps.sdkLoader ?? (async () => await import("@cursor/sdk"));
|
|
292
|
-
let sdk;
|
|
293
|
-
try {
|
|
294
|
-
sdk = await loader();
|
|
295
|
-
} catch {
|
|
296
|
-
return runCursorCli(job, deps.cliPath ?? "cursor-agent", started, timeoutMs);
|
|
297
|
-
}
|
|
298
|
-
try {
|
|
299
|
-
const run = await withTimeout(runLocalAgent(sdk, job), timeoutMs, `cursor lane (${job.prompt.slice(0, 60)})`);
|
|
300
|
-
const durationMs = Date.now() - started;
|
|
301
|
-
const status = run?.status ?? "finished";
|
|
302
|
-
const ok = status === "finished";
|
|
303
|
-
return { ok, exitCode: ok ? 0 : 1, output: run?.result ?? "", durationMs };
|
|
304
|
-
} catch (err) {
|
|
305
|
-
const durationMs = Date.now() - started;
|
|
306
|
-
return { ok: false, exitCode: 1, output: "", durationMs, error: String(err instanceof Error ? err.message : err) };
|
|
307
|
-
}
|
|
62
|
+
{
|
|
63
|
+
name: "workflows_lanes_list",
|
|
64
|
+
description: "List the four lane adapters with their wired-vs-not-ready-with-reason registry shape.",
|
|
65
|
+
inputSchema: { type: "object", properties: {} }
|
|
308
66
|
}
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
if (typeof AgentClass !== "function" && typeof CursorClass !== "function") {
|
|
315
|
-
throw new LaneAdapterShapeError("@cursor/sdk exports no Agent/Cursor class");
|
|
316
|
-
}
|
|
317
|
-
const agent = typeof AgentClass === "function" ? new AgentClass : undefined;
|
|
318
|
-
if (!agent || typeof agent.send !== "function") {
|
|
319
|
-
throw new LaneAdapterShapeError("@cursor/sdk Agent has no send()");
|
|
320
|
-
}
|
|
321
|
-
const run = await agent.send(job.prompt, { model: job.model });
|
|
322
|
-
if (!run || typeof run !== "object") {
|
|
323
|
-
throw new LaneAdapterShapeError("@cursor/sdk Agent.send() returned no Run");
|
|
324
|
-
}
|
|
325
|
-
return run;
|
|
67
|
+
];
|
|
68
|
+
return tools.map((tool) => ({ ...tool, inputSchema: { ...tool.inputSchema, properties: {
|
|
69
|
+
...tool.inputSchema.properties,
|
|
70
|
+
agent: { type: "string", description: "calling agent identity" }
|
|
71
|
+
} } }));
|
|
326
72
|
}
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
73
|
+
// package.json
|
|
74
|
+
var package_default = {
|
|
75
|
+
name: "@hasna/workflows",
|
|
76
|
+
version: "0.2.0",
|
|
77
|
+
description: "Universal graph workflow app \u2014 graph language (start/step/decision/while/end), three-table store, session WAL, daemon with claims/leases, four lane adapters (claude/codex/cursor/grok), and a full CLI on four surfaces",
|
|
78
|
+
type: "module",
|
|
79
|
+
main: "./dist/index.js",
|
|
80
|
+
types: "./types/index.d.ts",
|
|
81
|
+
bin: {
|
|
82
|
+
workflows: "dist/cli/index.js",
|
|
83
|
+
"workflows-mcp": "dist/mcp/index.js",
|
|
84
|
+
"workflows-serve": "dist/serve/index.js"
|
|
85
|
+
},
|
|
86
|
+
exports: {
|
|
87
|
+
".": {
|
|
88
|
+
types: "./types/index.d.ts",
|
|
89
|
+
import: "./dist/index.js"
|
|
90
|
+
},
|
|
91
|
+
"./sdk": {
|
|
92
|
+
types: "./types/sdk.d.ts",
|
|
93
|
+
import: "./dist/sdk.js"
|
|
94
|
+
},
|
|
95
|
+
"./cli": {
|
|
96
|
+
types: "./types/cli/index.d.ts",
|
|
97
|
+
import: "./dist/cli/index.js"
|
|
340
98
|
}
|
|
341
|
-
|
|
99
|
+
},
|
|
100
|
+
files: [
|
|
101
|
+
"dist",
|
|
102
|
+
"types",
|
|
103
|
+
"README.md",
|
|
104
|
+
"LICENSE",
|
|
105
|
+
"hasna.contract.json"
|
|
106
|
+
],
|
|
107
|
+
scripts: {
|
|
108
|
+
build: "bun run check:sdk && bun run build:runtime && bun run build:types",
|
|
109
|
+
"generate:sdk": "bun scripts/generate-sdk.ts --write",
|
|
110
|
+
"check:sdk": "bun scripts/generate-sdk.ts",
|
|
111
|
+
"test:artifacts": "bun scripts/artifact-acceptance.ts",
|
|
112
|
+
"build:runtime": "bun build src/cli/index.ts --outdir dist/cli --target bun && bun build src/mcp/index.ts --outdir dist/mcp --target bun && bun build src/serve/index.ts src/serve/admin.ts --outdir dist/serve --target bun --packages external && bun build src/index.ts src/service.ts src/handlers.ts src/agent-tools.ts src/types.ts --root src --outdir dist --target bun --packages external && bun build src/sdk.ts --outdir dist --target node",
|
|
113
|
+
"build:types": "tsc -p tsconfig.build.json --emitDeclarationOnly --outDir types",
|
|
114
|
+
"artifact-scan": "bun scripts/contracts-cli.mjs artifact-scan dist",
|
|
115
|
+
"contract:check": "bun scripts/contracts-cli.mjs repo-conformance .",
|
|
116
|
+
typecheck: "tsc --noEmit",
|
|
117
|
+
test: "bun test",
|
|
118
|
+
"test:pg": 'WORKFLOWS_TEST_DATABASE_URL="${WORKFLOWS_TEST_DATABASE_URL:?point it at a fresh test Postgres database}" WORKFLOWS_REQUIRE_POSTGRES=1 bun test src/db/postgres-store.test.ts src/db/postgres-http.test.ts src/db/postgres-fencing.test.ts',
|
|
119
|
+
prepack: "bun run build && bun run artifact-scan",
|
|
120
|
+
prepublishOnly: "bun run test && bun run build"
|
|
121
|
+
},
|
|
122
|
+
keywords: [
|
|
123
|
+
"workflows",
|
|
124
|
+
"graph",
|
|
125
|
+
"automation",
|
|
126
|
+
"cli",
|
|
127
|
+
"typescript",
|
|
128
|
+
"bun",
|
|
129
|
+
"hasna"
|
|
130
|
+
],
|
|
131
|
+
publishConfig: {
|
|
132
|
+
registry: "https://registry.npmjs.org",
|
|
133
|
+
access: "public"
|
|
134
|
+
},
|
|
135
|
+
repository: {
|
|
136
|
+
type: "git",
|
|
137
|
+
url: "https://github.com/hasna/apps.git",
|
|
138
|
+
directory: "apps/workflows"
|
|
139
|
+
},
|
|
140
|
+
homepage: "https://github.com/hasna/apps/tree/main/apps/workflows",
|
|
141
|
+
bugs: {
|
|
142
|
+
url: "https://github.com/hasna/apps/issues"
|
|
143
|
+
},
|
|
144
|
+
engines: {
|
|
145
|
+
bun: ">=1.0.0"
|
|
146
|
+
},
|
|
147
|
+
author: "Hasna",
|
|
148
|
+
license: "Apache-2.0",
|
|
149
|
+
dependencies: {
|
|
150
|
+
"@anthropic-ai/claude-agent-sdk": "0.3.234",
|
|
151
|
+
"@cursor/sdk": "^1.0.28",
|
|
152
|
+
"@openai/codex-sdk": "0.147.0",
|
|
153
|
+
commander: "^13.1.0",
|
|
154
|
+
"@hasna/contracts": "1.3.3",
|
|
155
|
+
pg: "^8.16.3"
|
|
156
|
+
},
|
|
157
|
+
devDependencies: {
|
|
158
|
+
"@types/bun": "1.3.14",
|
|
159
|
+
"@types/pg": "^8.15.6",
|
|
160
|
+
typescript: "^5.7.3"
|
|
342
161
|
}
|
|
343
|
-
}
|
|
344
|
-
var init_cursor = __esm(() => {
|
|
345
|
-
init_types();
|
|
346
|
-
});
|
|
162
|
+
};
|
|
347
163
|
|
|
348
|
-
// src/
|
|
349
|
-
function
|
|
350
|
-
return
|
|
351
|
-
kind: "grok",
|
|
352
|
-
async probe() {
|
|
353
|
-
const cliPath = deps.cliPath ?? "grok";
|
|
354
|
-
if (binaryOnPath(cliPath)) {
|
|
355
|
-
return { kind: "grok", sdk: "no npm SDK (measured 2026-08-25)", wired: true, via: "cli" };
|
|
356
|
-
}
|
|
357
|
-
return {
|
|
358
|
-
kind: "grok",
|
|
359
|
-
sdk: "no npm SDK (measured 2026-08-25)",
|
|
360
|
-
wired: false,
|
|
361
|
-
reason: `no xAI Grok SDK exists on npm (measured 2026-08-25) and the grok CLI is not on PATH`
|
|
362
|
-
};
|
|
363
|
-
},
|
|
364
|
-
async run(job) {
|
|
365
|
-
if (!job.prompt) {
|
|
366
|
-
return { ok: false, exitCode: 2, output: "", durationMs: 0, error: "grok lane requires a prompt" };
|
|
367
|
-
}
|
|
368
|
-
const started = Date.now();
|
|
369
|
-
const timeoutMs = job.timeoutMs ?? DEFAULT_LANE_TIMEOUT_MS;
|
|
370
|
-
const cliPath = deps.cliPath ?? "grok";
|
|
371
|
-
try {
|
|
372
|
-
const result = spawnCli([cliPath, job.prompt], {
|
|
373
|
-
binaryName: cliPath,
|
|
374
|
-
packageHint: "the grok CLI (no xAI Grok SDK exists on npm \u2014 measured 2026-08-25)",
|
|
375
|
-
timeoutMs,
|
|
376
|
-
env: job.env,
|
|
377
|
-
cwd: job.cwd
|
|
378
|
-
});
|
|
379
|
-
return { ...result, durationMs: Date.now() - started };
|
|
380
|
-
} catch (err) {
|
|
381
|
-
if (err instanceof LaneDependencyMissingError) {
|
|
382
|
-
return { ok: false, exitCode: 127, output: "", durationMs: Date.now() - started, error: err.message };
|
|
383
|
-
}
|
|
384
|
-
throw err;
|
|
385
|
-
}
|
|
386
|
-
}
|
|
387
|
-
};
|
|
164
|
+
// src/version.ts
|
|
165
|
+
function packageVersion() {
|
|
166
|
+
return package_default.version;
|
|
388
167
|
}
|
|
389
|
-
var init_grok = __esm(() => {
|
|
390
|
-
init_types();
|
|
391
|
-
});
|
|
392
|
-
|
|
393
|
-
// src/lanes/index.ts
|
|
394
|
-
var exports_lanes = {};
|
|
395
|
-
__export(exports_lanes, {
|
|
396
|
-
runLaneJob: () => runLaneJob,
|
|
397
|
-
resolveLane: () => resolveLane,
|
|
398
|
-
probeLane: () => probeLane,
|
|
399
|
-
laneInventory: () => laneInventory,
|
|
400
|
-
createGrokAdapter: () => createGrokAdapter,
|
|
401
|
-
createCursorAdapter: () => createCursorAdapter,
|
|
402
|
-
createCodexAdapter: () => createCodexAdapter,
|
|
403
|
-
createClaudeAdapter: () => createClaudeAdapter,
|
|
404
|
-
binaryOnPath: () => binaryOnPath,
|
|
405
|
-
LaneDependencyMissingError: () => LaneDependencyMissingError,
|
|
406
|
-
LaneAdapterShapeError: () => LaneAdapterShapeError,
|
|
407
|
-
LANE_KINDS: () => LANE_KINDS2
|
|
408
|
-
});
|
|
409
|
-
function resolveLane(kind) {
|
|
410
|
-
const adapter = adapters.get(kind);
|
|
411
|
-
if (!adapter)
|
|
412
|
-
throw new Error(`unknown lane ${kind} (expected one of ${LANE_KINDS2.join(", ")})`);
|
|
413
|
-
return adapter;
|
|
414
|
-
}
|
|
415
|
-
async function runLaneJob(job) {
|
|
416
|
-
return resolveLane(job.lane).run(job);
|
|
417
|
-
}
|
|
418
|
-
async function probeLane(kind) {
|
|
419
|
-
return resolveLane(kind).probe();
|
|
420
|
-
}
|
|
421
|
-
async function laneInventory() {
|
|
422
|
-
return Promise.all(LANE_KINDS2.map((kind) => probeLane(kind)));
|
|
423
|
-
}
|
|
424
|
-
var adapters;
|
|
425
|
-
var init_lanes = __esm(() => {
|
|
426
|
-
init_claude();
|
|
427
|
-
init_codex();
|
|
428
|
-
init_cursor();
|
|
429
|
-
init_grok();
|
|
430
|
-
init_types();
|
|
431
|
-
init_types();
|
|
432
|
-
init_claude();
|
|
433
|
-
init_codex();
|
|
434
|
-
init_cursor();
|
|
435
|
-
init_grok();
|
|
436
|
-
adapters = new Map([
|
|
437
|
-
["claude", createClaudeAdapter()],
|
|
438
|
-
["codex", createCodexAdapter()],
|
|
439
|
-
["cursor", createCursorAdapter()],
|
|
440
|
-
["grok", createGrokAdapter()]
|
|
441
|
-
]);
|
|
442
|
-
});
|
|
443
|
-
|
|
444
|
-
// src/mcp/index.ts
|
|
445
|
-
import { createInterface } from "readline";
|
|
446
168
|
|
|
447
169
|
// src/expr.ts
|
|
448
170
|
class ExprSyntaxError extends Error {
|
|
@@ -451,13 +173,6 @@ class ExprSyntaxError extends Error {
|
|
|
451
173
|
this.name = "ExprSyntaxError";
|
|
452
174
|
}
|
|
453
175
|
}
|
|
454
|
-
|
|
455
|
-
class ExprEvalError extends Error {
|
|
456
|
-
constructor(message) {
|
|
457
|
-
super(message);
|
|
458
|
-
this.name = "ExprEvalError";
|
|
459
|
-
}
|
|
460
|
-
}
|
|
461
176
|
var COMPARISON_OPS = new Set(["==", "!=", "<", "<=", ">", ">="]);
|
|
462
177
|
function tokenize(input) {
|
|
463
178
|
const tokens = [];
|
|
@@ -627,89 +342,6 @@ class Parser {
|
|
|
627
342
|
function parseExpr(input) {
|
|
628
343
|
return new Parser(tokenize(input)).parse();
|
|
629
344
|
}
|
|
630
|
-
function resolvePath(segments, context) {
|
|
631
|
-
let current = context;
|
|
632
|
-
for (const segment of segments) {
|
|
633
|
-
if (current === null || typeof current !== "object")
|
|
634
|
-
return;
|
|
635
|
-
const record = current;
|
|
636
|
-
if (!(segment in record))
|
|
637
|
-
return;
|
|
638
|
-
current = record[segment];
|
|
639
|
-
}
|
|
640
|
-
if (typeof current === "number" || typeof current === "string" || typeof current === "boolean") {
|
|
641
|
-
return current;
|
|
642
|
-
}
|
|
643
|
-
return;
|
|
644
|
-
}
|
|
645
|
-
function evalNode(node, context) {
|
|
646
|
-
switch (node.kind) {
|
|
647
|
-
case "literal":
|
|
648
|
-
return node.value;
|
|
649
|
-
case "path":
|
|
650
|
-
return resolvePath(node.segments, context);
|
|
651
|
-
case "comparison": {
|
|
652
|
-
const left = evalNode(node.left, context);
|
|
653
|
-
const right = evalNode(node.right, context);
|
|
654
|
-
if (left === undefined || right === undefined) {
|
|
655
|
-
if (node.op === "==")
|
|
656
|
-
return left === undefined && right === undefined;
|
|
657
|
-
if (node.op === "!=")
|
|
658
|
-
return left !== right;
|
|
659
|
-
throw new ExprEvalError("cannot order-compare an unknown path");
|
|
660
|
-
}
|
|
661
|
-
if (typeof left !== typeof right) {
|
|
662
|
-
throw new ExprEvalError(`cannot compare ${JSON.stringify(left)} (${typeof left}) with ${JSON.stringify(right)} (${typeof right})`);
|
|
663
|
-
}
|
|
664
|
-
switch (node.op) {
|
|
665
|
-
case "==":
|
|
666
|
-
return left === right;
|
|
667
|
-
case "!=":
|
|
668
|
-
return left !== right;
|
|
669
|
-
case "<":
|
|
670
|
-
return left < right;
|
|
671
|
-
case "<=":
|
|
672
|
-
return left <= right;
|
|
673
|
-
case ">":
|
|
674
|
-
return left > right;
|
|
675
|
-
case ">=":
|
|
676
|
-
return left >= right;
|
|
677
|
-
default:
|
|
678
|
-
throw new ExprEvalError(`unknown operator ${node.op}`);
|
|
679
|
-
}
|
|
680
|
-
}
|
|
681
|
-
case "and": {
|
|
682
|
-
const left = evalNode(node.left, context);
|
|
683
|
-
const right = evalNode(node.right, context);
|
|
684
|
-
if (typeof left !== "boolean" || typeof right !== "boolean") {
|
|
685
|
-
throw new ExprEvalError("and requires boolean operands");
|
|
686
|
-
}
|
|
687
|
-
return left && right;
|
|
688
|
-
}
|
|
689
|
-
case "or": {
|
|
690
|
-
const left = evalNode(node.left, context);
|
|
691
|
-
const right = evalNode(node.right, context);
|
|
692
|
-
if (typeof left !== "boolean" || typeof right !== "boolean") {
|
|
693
|
-
throw new ExprEvalError("or requires boolean operands");
|
|
694
|
-
}
|
|
695
|
-
return left || right;
|
|
696
|
-
}
|
|
697
|
-
case "not": {
|
|
698
|
-
const operand = evalNode(node.operand, context);
|
|
699
|
-
if (typeof operand !== "boolean")
|
|
700
|
-
throw new ExprEvalError("not requires a boolean operand");
|
|
701
|
-
return !operand;
|
|
702
|
-
}
|
|
703
|
-
}
|
|
704
|
-
}
|
|
705
|
-
function evaluateExpr(input, context) {
|
|
706
|
-
const ast = parseExpr(input);
|
|
707
|
-
const value = evalNode(ast, context);
|
|
708
|
-
if (typeof value !== "boolean") {
|
|
709
|
-
throw new ExprEvalError(`condition must evaluate to a boolean, got ${typeof value}`);
|
|
710
|
-
}
|
|
711
|
-
return value;
|
|
712
|
-
}
|
|
713
345
|
|
|
714
346
|
// src/graph.ts
|
|
715
347
|
var GRAPH_NODE_TYPES = ["start", "step", "decision", "while", "end"];
|
|
@@ -811,16 +443,49 @@ function findCycles(graph) {
|
|
|
811
443
|
}
|
|
812
444
|
function validateGraph(graph) {
|
|
813
445
|
const issues = [];
|
|
446
|
+
if (graph === null || typeof graph !== "object" || Array.isArray(graph)) {
|
|
447
|
+
return { ok: false, issues: [{ path: "graph", message: "graph must be an object" }] };
|
|
448
|
+
}
|
|
814
449
|
if (typeof graph.name !== "string" || graph.name.trim() === "") {
|
|
815
450
|
issue(issues, "name", "graph requires a non-empty name");
|
|
816
451
|
}
|
|
817
452
|
if (typeof graph.version !== "string" || graph.version.trim() === "") {
|
|
818
453
|
issue(issues, "version", "graph requires a version string");
|
|
819
454
|
}
|
|
455
|
+
if (graph.memoWatch !== undefined) {
|
|
456
|
+
if (!Array.isArray(graph.memoWatch) || graph.memoWatch.length === 0) {
|
|
457
|
+
issue(issues, "memoWatch", "memoWatch must be a non-empty array of file paths or globs");
|
|
458
|
+
} else {
|
|
459
|
+
for (const entry of graph.memoWatch) {
|
|
460
|
+
if (typeof entry !== "string" || entry.trim() === "") {
|
|
461
|
+
issue(issues, "memoWatch", "each memoWatch entry must be a non-empty path or glob string");
|
|
462
|
+
break;
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
}
|
|
820
467
|
if (!Array.isArray(graph.nodes) || graph.nodes.length === 0) {
|
|
821
468
|
issue(issues, "nodes", "graph requires at least one node");
|
|
822
469
|
return { ok: false, issues };
|
|
823
470
|
}
|
|
471
|
+
for (let index = 0;index < graph.nodes.length; index++) {
|
|
472
|
+
const node = graph.nodes[index];
|
|
473
|
+
if (node === null || typeof node !== "object" || Array.isArray(node)) {
|
|
474
|
+
issue(issues, `nodes.${index}`, "node must be an object");
|
|
475
|
+
continue;
|
|
476
|
+
}
|
|
477
|
+
if (!GRAPH_NODE_TYPES.includes(node.type))
|
|
478
|
+
issue(issues, `nodes.${index}.type`, "type must be start, step, decision, while, or end");
|
|
479
|
+
for (const key of ["next", "then", "else", "prompt", "command"]) {
|
|
480
|
+
const value = node[key];
|
|
481
|
+
if (value !== undefined && (typeof value !== "string" || value.trim() === ""))
|
|
482
|
+
issue(issues, `nodes.${index}.${key}`, `${key} must be a non-empty string`);
|
|
483
|
+
}
|
|
484
|
+
if (node.type === "while" && (!Array.isArray(node.body) || node.body.some((id) => typeof id !== "string")))
|
|
485
|
+
issue(issues, `nodes.${index}.body`, "body must be an array of node ids");
|
|
486
|
+
}
|
|
487
|
+
if (issues.length)
|
|
488
|
+
return { ok: false, issues };
|
|
824
489
|
const starts = graph.nodes.filter((n) => n.type === "start");
|
|
825
490
|
if (starts.length === 0)
|
|
826
491
|
issue(issues, "nodes", "graph requires exactly one start node (found none)");
|
|
@@ -882,6 +547,8 @@ function nodeEdges(node) {
|
|
|
882
547
|
return node.next ? [{ kind: "next", target: node.next }] : [];
|
|
883
548
|
case "end":
|
|
884
549
|
return [];
|
|
550
|
+
default:
|
|
551
|
+
return [];
|
|
885
552
|
}
|
|
886
553
|
}
|
|
887
554
|
function validateNode(graph, node, issues) {
|
|
@@ -975,1219 +642,1602 @@ function validateNode(graph, node, issues) {
|
|
|
975
642
|
}
|
|
976
643
|
}
|
|
977
644
|
|
|
978
|
-
//
|
|
979
|
-
import {
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
}
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
];
|
|
1001
|
-
var CREDENTIAL_KEY_RE = /^(token|api[_-]?key|access[_-]?token|auth[_-]?token|client[_-]?secret|secret[_-]?key|refresh[_-]?token|session[_-]?token|bot[_-]?token)$/i;
|
|
1002
|
-
function scanString(value, path, findings) {
|
|
1003
|
-
for (const { detector, re } of VALUE_PATTERNS) {
|
|
1004
|
-
if (re.test(value)) {
|
|
1005
|
-
findings.push({ path, detector });
|
|
1006
|
-
return;
|
|
1007
|
-
}
|
|
1008
|
-
}
|
|
645
|
+
// ../../workflows-release-artifact-1/app/node_modules/@hasna/contracts/dist/client/transport.js
|
|
646
|
+
import { isIP } from "net";
|
|
647
|
+
import { spawnSync } from "child_process";
|
|
648
|
+
import { closeSync as closeSync2, fstatSync as fstatSync2, openSync as openSync2, readFileSync as readFileSync2 } from "fs";
|
|
649
|
+
import { O_NOFOLLOW as O_NOFOLLOW2, O_NONBLOCK as O_NONBLOCK2, O_RDONLY as O_RDONLY2 } from "constants";
|
|
650
|
+
import { hostname as osHostname } from "os";
|
|
651
|
+
import { isAbsolute, join as join2 } from "path";
|
|
652
|
+
import { createRequire } from "module";
|
|
653
|
+
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
654
|
+
import { closeSync, fstatSync, lstatSync, openSync, readFileSync, realpathSync, statSync } from "fs";
|
|
655
|
+
import { O_NOFOLLOW, O_NONBLOCK, O_RDONLY } from "constants";
|
|
656
|
+
import { basename, dirname, join, relative, sep } from "path";
|
|
657
|
+
import { fileURLToPath, pathToFileURL } from "url";
|
|
658
|
+
function envToken(name) {
|
|
659
|
+
return name.toUpperCase().replace(/-/g, "_");
|
|
660
|
+
}
|
|
661
|
+
function clientTransportEnvKeys(name) {
|
|
662
|
+
const envSegment = envToken(name);
|
|
663
|
+
return {
|
|
664
|
+
apiUrlKeys: [`HASNA_${envSegment}_API_URL`, `${envSegment}_API_URL`],
|
|
665
|
+
apiKeyKeys: [`HASNA_${envSegment}_API_KEY`, `${envSegment}_API_KEY`]
|
|
666
|
+
};
|
|
1009
667
|
}
|
|
1010
|
-
function
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
if (
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
668
|
+
function credentialOverrideEnvKey(name) {
|
|
669
|
+
return `HASNA_${envToken(name)}_API_KEY_OVERRIDE`;
|
|
670
|
+
}
|
|
671
|
+
var CREDENTIAL_PROFILE_ENV_KEY = "HASNA_PROFILE";
|
|
672
|
+
function credentialPointerEnvKey(name) {
|
|
673
|
+
return `HASNA_${envToken(name)}_API_KEY_REF`;
|
|
674
|
+
}
|
|
675
|
+
function e(e2, n, r) {
|
|
676
|
+
throw new Error(r ? `No known conditions for "${n}" specifier in "${e2}" package` : `Missing "${n}" specifier in "${e2}" package`);
|
|
677
|
+
}
|
|
678
|
+
function n(n2, i, o, f) {
|
|
679
|
+
let s, u, l = r(n2, o), c = function(e2) {
|
|
680
|
+
let n3 = new Set(["default", ...e2.conditions || []]);
|
|
681
|
+
return e2.unsafe || n3.add(e2.require ? "require" : "import"), e2.unsafe || n3.add(e2.browser ? "browser" : "node"), n3;
|
|
682
|
+
}(f || {}), a = i[l];
|
|
683
|
+
if (a === undefined) {
|
|
684
|
+
let e2, n3, r, t;
|
|
685
|
+
for (t in i)
|
|
686
|
+
n3 && t.length < n3.length || (t[t.length - 1] === "/" && l.startsWith(t) ? (u = l.substring(t.length), n3 = t) : t.length > 1 && (r = t.indexOf("*", 1), ~r && (e2 = RegExp("^" + t.substring(0, r) + "(.*)" + t.substring(1 + r) + "$").exec(l), e2 && e2[1] && (u = e2[1], n3 = t))));
|
|
687
|
+
a = i[n3];
|
|
688
|
+
}
|
|
689
|
+
return a || e(n2, l), s = t(a, c), s || e(n2, l, 1), u && function(e2, n3) {
|
|
690
|
+
let r, t = 0, i2 = e2.length, o2 = /[*]/g, f2 = /[/]$/;
|
|
691
|
+
for (;t < i2; t++)
|
|
692
|
+
e2[t] = o2.test(r = e2[t]) ? r.replace(o2, n3) : f2.test(r) ? r + n3 : r;
|
|
693
|
+
}(s, u), s;
|
|
694
|
+
}
|
|
695
|
+
function r(e2, n2, r2) {
|
|
696
|
+
if (e2 === n2 || n2 === ".")
|
|
697
|
+
return ".";
|
|
698
|
+
let t = e2 + "/", i = t.length, o = n2.slice(0, i) === t, f = o ? n2.slice(i) : n2;
|
|
699
|
+
return f[0] === "#" ? f : o || !r2 ? f.slice(0, 2) === "./" ? f : "./" + f : f;
|
|
700
|
+
}
|
|
701
|
+
function t(e2, n2, r2) {
|
|
702
|
+
if (e2) {
|
|
703
|
+
if (typeof e2 == "string")
|
|
704
|
+
return r2 && r2.add(e2), [e2];
|
|
705
|
+
let i, o;
|
|
706
|
+
if (Array.isArray(e2)) {
|
|
707
|
+
for (o = r2 || new Set, i = 0;i < e2.length; i++)
|
|
708
|
+
t(e2[i], n2, o);
|
|
709
|
+
if (!r2 && o.size)
|
|
710
|
+
return [...o];
|
|
711
|
+
} else
|
|
712
|
+
for (i in e2)
|
|
713
|
+
if (n2.has(i))
|
|
714
|
+
return t(e2[i], n2, r2);
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
function o(e2, r2, t2) {
|
|
718
|
+
let i, o2 = e2.exports;
|
|
719
|
+
if (o2) {
|
|
720
|
+
if (typeof o2 == "string")
|
|
721
|
+
o2 = { ".": o2 };
|
|
722
|
+
else
|
|
723
|
+
for (i in o2) {
|
|
724
|
+
i[0] !== "." && (o2 = { ".": o2 });
|
|
725
|
+
break;
|
|
726
|
+
}
|
|
727
|
+
return n(e2.name, o2, r2 || ".", t2);
|
|
1034
728
|
}
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
729
|
+
}
|
|
730
|
+
var PACKAGE = "@hasna/secrets";
|
|
731
|
+
var MAX_PACKAGE_BYTES = 1024 * 1024;
|
|
732
|
+
function entryPoint(directory) {
|
|
733
|
+
const root = realpathSync(directory);
|
|
734
|
+
const fd = openSync(join(root, "package.json"), O_RDONLY | O_NOFOLLOW | O_NONBLOCK);
|
|
735
|
+
let pkg;
|
|
736
|
+
try {
|
|
737
|
+
const stat = fstatSync(fd);
|
|
738
|
+
if (!stat.isFile() || stat.size > MAX_PACKAGE_BYTES)
|
|
739
|
+
throw new Error("Invalid Secrets package metadata");
|
|
740
|
+
pkg = JSON.parse(readFileSync(fd, "utf8"));
|
|
741
|
+
} finally {
|
|
742
|
+
closeSync(fd);
|
|
743
|
+
}
|
|
744
|
+
if (!pkg || typeof pkg !== "object" || !("name" in pkg) || pkg.name !== PACKAGE) {
|
|
745
|
+
throw new Error("Invalid Secrets package identity");
|
|
746
|
+
}
|
|
747
|
+
const target = o(pkg, ".")?.[0];
|
|
748
|
+
if (typeof target !== "string" || !target.startsWith("./"))
|
|
749
|
+
throw new Error("Missing Secrets import export");
|
|
750
|
+
const parts = target.slice(2).split("/");
|
|
751
|
+
if (/[\\%?#\0]/.test(target) || parts.some((part) => !part || part === "." || part === ".." || part === "node_modules")) {
|
|
752
|
+
throw new Error("Invalid Secrets import export");
|
|
753
|
+
}
|
|
754
|
+
const file = realpathSync(join(root, ...parts));
|
|
755
|
+
const within = relative(root, file);
|
|
756
|
+
if (!within || within === ".." || within.startsWith(`..${sep}`) || !statSync(file).isFile()) {
|
|
757
|
+
throw new Error("Secrets import export escapes its package or is not a file");
|
|
758
|
+
}
|
|
759
|
+
return pathToFileURL(file).href;
|
|
760
|
+
}
|
|
761
|
+
function resolveInstalledSecrets(parentUrl) {
|
|
762
|
+
let directory = dirname(fileURLToPath(parentUrl));
|
|
763
|
+
for (;; ) {
|
|
764
|
+
if (basename(directory) !== "node_modules") {
|
|
765
|
+
const candidate = join(directory, "node_modules", PACKAGE);
|
|
766
|
+
let absent = false;
|
|
767
|
+
try {
|
|
768
|
+
lstatSync(candidate);
|
|
769
|
+
} catch (error) {
|
|
770
|
+
if (error.code !== "ENOENT")
|
|
771
|
+
throw error;
|
|
772
|
+
absent = true;
|
|
1042
773
|
}
|
|
774
|
+
if (!absent)
|
|
775
|
+
return entryPoint(candidate);
|
|
1043
776
|
}
|
|
777
|
+
const parent = dirname(directory);
|
|
778
|
+
if (parent === directory)
|
|
779
|
+
throw new Error("Secrets SDK is not installed for this consumer");
|
|
780
|
+
directory = parent;
|
|
1044
781
|
}
|
|
1045
|
-
return findings;
|
|
1046
782
|
}
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
783
|
+
|
|
784
|
+
class CredentialResolutionError extends Error {
|
|
785
|
+
appName;
|
|
786
|
+
attempted;
|
|
787
|
+
constructor(appName, message, attempted) {
|
|
788
|
+
super(message);
|
|
789
|
+
this.name = "CredentialResolutionError";
|
|
790
|
+
this.appName = appName;
|
|
791
|
+
this.attempted = attempted;
|
|
792
|
+
}
|
|
1053
793
|
}
|
|
1054
794
|
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
795
|
+
class CredentialFileUnsafeError extends Error {
|
|
796
|
+
path;
|
|
797
|
+
constructor(path, reason) {
|
|
798
|
+
super(`Refusing unsafe credential/config file ${path}: ${reason}.`);
|
|
799
|
+
this.name = "CredentialFileUnsafeError";
|
|
800
|
+
this.path = path;
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
var HASNA_HOME_ENV_KEY = "HASNA_HOME";
|
|
804
|
+
var HASNA_CONFIG_HOME_ENV_KEY = "HASNA_CONFIG_HOME";
|
|
805
|
+
var KEYCHAIN_STATION_ENV_KEY = "HASNA_STATION";
|
|
806
|
+
var HASNA_HOME_DIR = ".hasna";
|
|
807
|
+
var CONFIG_SUBDIR = "config";
|
|
808
|
+
var CREDENTIALS_FILE = "credentials";
|
|
809
|
+
var KEYCHAIN_SECURITY_BIN = "/usr/bin/security";
|
|
810
|
+
var KEYCHAIN_SERVICE_PREFIX = "hasna.credentials";
|
|
811
|
+
var KEYCHAIN_ITEM_NOT_FOUND_STATUS = 44;
|
|
812
|
+
var KEYCHAIN_SPAWN_TIMEOUT_MS = 1e4;
|
|
813
|
+
var MAX_CREDENTIAL_FILE_BYTES = 64 * 1024;
|
|
814
|
+
var SAFE_APP_SLUG = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
|
|
815
|
+
var SAFE_PROFILE = /^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/;
|
|
816
|
+
var ILLEGAL_IN_HEADER_VALUE = /[^\t\x20-\x7e]/;
|
|
817
|
+
var VAULT_POINTER_SHAPE = /^[a-z0-9][a-z0-9-]*(?:\/[a-z0-9][a-z0-9-_.]*){2,}$/;
|
|
818
|
+
function homeDir(env) {
|
|
819
|
+
const home = env.HOME?.trim();
|
|
820
|
+
return home ? home : null;
|
|
821
|
+
}
|
|
822
|
+
function absoluteOverride(env, key) {
|
|
823
|
+
const value = env[key]?.trim();
|
|
824
|
+
return value && isAbsolute(value) ? value : null;
|
|
825
|
+
}
|
|
826
|
+
function hasnaHomeDir(env) {
|
|
827
|
+
const override = absoluteOverride(env, HASNA_HOME_ENV_KEY);
|
|
828
|
+
if (override)
|
|
829
|
+
return override;
|
|
830
|
+
const home = homeDir(env);
|
|
831
|
+
return home ? join2(home, HASNA_HOME_DIR) : null;
|
|
832
|
+
}
|
|
833
|
+
function appConfigDir(name, env) {
|
|
834
|
+
const configRoot = absoluteOverride(env, HASNA_CONFIG_HOME_ENV_KEY);
|
|
835
|
+
if (configRoot)
|
|
836
|
+
return join2(configRoot, name);
|
|
837
|
+
const root = hasnaHomeDir(env);
|
|
838
|
+
return root ? join2(root, name, CONFIG_SUBDIR) : null;
|
|
839
|
+
}
|
|
840
|
+
function credentialDiskSourceList(name, env, profile = null) {
|
|
841
|
+
if (!SAFE_APP_SLUG.test(name))
|
|
842
|
+
return [];
|
|
843
|
+
const directory = appConfigDir(name, env);
|
|
844
|
+
if (!directory)
|
|
845
|
+
return [];
|
|
846
|
+
const file = profile ? `${CREDENTIALS_FILE}-${profile}` : CREDENTIALS_FILE;
|
|
847
|
+
return [{ path: join2(directory, file), tier: "disk" }];
|
|
848
|
+
}
|
|
849
|
+
function credentialDiskSources(name, env) {
|
|
850
|
+
return credentialDiskSourceList(name, env, null).map((s) => s.path);
|
|
851
|
+
}
|
|
852
|
+
function profileDiskSources(name, env, profile) {
|
|
853
|
+
return credentialDiskSourceList(name, env, profile).map((s) => s.path);
|
|
854
|
+
}
|
|
855
|
+
function parseEnvFile(text) {
|
|
856
|
+
const values = new Map;
|
|
857
|
+
const unusable = new Set;
|
|
858
|
+
for (const rawLine of text.split(/\r?\n/)) {
|
|
859
|
+
const line = rawLine.trim();
|
|
860
|
+
if (line.length === 0 || line.startsWith("#"))
|
|
1066
861
|
continue;
|
|
1067
|
-
|
|
1068
|
-
const
|
|
1069
|
-
if (
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
} else {
|
|
1081
|
-
store.setRunStatus(run.id, "failed", {
|
|
1082
|
-
error: `torn run failed after ${maxAttempts} interrupted attempts`
|
|
1083
|
-
});
|
|
1084
|
-
for (const node of nodes) {
|
|
1085
|
-
if (node.status === "running") {
|
|
1086
|
-
store.setRunNodeStatus(node.id, "failed", { error: "run interrupted beyond retry budget" });
|
|
1087
|
-
}
|
|
862
|
+
const withoutExport = line.startsWith("export ") ? line.slice("export ".length).trim() : line;
|
|
863
|
+
const equals = withoutExport.indexOf("=");
|
|
864
|
+
if (equals <= 0)
|
|
865
|
+
continue;
|
|
866
|
+
const key = withoutExport.slice(0, equals).trim();
|
|
867
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key))
|
|
868
|
+
continue;
|
|
869
|
+
let value = withoutExport.slice(equals + 1).trim();
|
|
870
|
+
const quote = value[0];
|
|
871
|
+
if (quote === '"' || quote === "'") {
|
|
872
|
+
if (value.length < 2 || !value.endsWith(quote)) {
|
|
873
|
+
unusable.add(key);
|
|
874
|
+
continue;
|
|
1088
875
|
}
|
|
1089
|
-
|
|
876
|
+
value = value.slice(1, -1);
|
|
1090
877
|
}
|
|
878
|
+
if (value.trim().length === 0) {
|
|
879
|
+
unusable.add(key);
|
|
880
|
+
continue;
|
|
881
|
+
}
|
|
882
|
+
if (values.has(key) && values.get(key) !== value)
|
|
883
|
+
unusable.add(key);
|
|
884
|
+
values.set(key, value);
|
|
1091
885
|
}
|
|
1092
|
-
return
|
|
886
|
+
return { values, unusable };
|
|
1093
887
|
}
|
|
1094
|
-
function
|
|
1095
|
-
|
|
888
|
+
function configFileModeAllowed(mode) {
|
|
889
|
+
const permissions = mode & 4095;
|
|
890
|
+
return permissions === 256 || permissions === 384;
|
|
1096
891
|
}
|
|
1097
|
-
function
|
|
1098
|
-
return
|
|
892
|
+
function configFileReadsCoherent(before, after) {
|
|
893
|
+
return before.dev === after.dev && before.ino === after.ino && before.size === after.size && before.mtimeMs === after.mtimeMs && before.ctimeMs === after.ctimeMs;
|
|
894
|
+
}
|
|
895
|
+
function readAppConfigFile(path) {
|
|
896
|
+
const unsafe = (reason) => {
|
|
897
|
+
throw new CredentialFileUnsafeError(path, reason);
|
|
898
|
+
};
|
|
899
|
+
let fd = -1;
|
|
900
|
+
try {
|
|
901
|
+
fd = openSync2(path, O_RDONLY2 | O_NOFOLLOW2 | O_NONBLOCK2);
|
|
902
|
+
} catch (error) {
|
|
903
|
+
const code = error.code;
|
|
904
|
+
if (code === "ENOENT" || code === "ENOTDIR")
|
|
905
|
+
return null;
|
|
906
|
+
if (code === "ELOOP")
|
|
907
|
+
unsafe("the path is a symlink");
|
|
908
|
+
unsafe(`the path could not be opened (${code ?? "unknown error"})`);
|
|
909
|
+
}
|
|
910
|
+
try {
|
|
911
|
+
const before = fstatSync2(fd);
|
|
912
|
+
if (!before.isFile())
|
|
913
|
+
unsafe("the path is not a regular file");
|
|
914
|
+
if (!configFileModeAllowed(before.mode)) {
|
|
915
|
+
unsafe(`permission mode ${(before.mode & 4095).toString(8).padStart(4, "0")} is not owner-only 0400 or 0600`);
|
|
916
|
+
}
|
|
917
|
+
const uid = process.getuid?.() ?? process.geteuid?.();
|
|
918
|
+
if (uid !== undefined && before.uid !== uid)
|
|
919
|
+
unsafe("the file is not owned by the current user");
|
|
920
|
+
if (before.size > MAX_CREDENTIAL_FILE_BYTES)
|
|
921
|
+
unsafe("the file exceeds the size limit");
|
|
922
|
+
const bytes = readFileSync2(fd);
|
|
923
|
+
const after = fstatSync2(fd);
|
|
924
|
+
if (!configFileReadsCoherent(before, after)) {
|
|
925
|
+
unsafe("the file changed while being read");
|
|
926
|
+
}
|
|
927
|
+
return parseEnvFile(bytes.toString("utf8"));
|
|
928
|
+
} finally {
|
|
929
|
+
if (fd !== -1)
|
|
930
|
+
closeSync2(fd);
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
function readCredentialFile(path, apiKeyKeys, pointerKey) {
|
|
934
|
+
const parsed = readAppConfigFile(path);
|
|
935
|
+
if (!parsed)
|
|
936
|
+
return null;
|
|
937
|
+
for (const key of [...apiKeyKeys, pointerKey]) {
|
|
938
|
+
if (parsed.unusable.has(key)) {
|
|
939
|
+
throw new CredentialFileUnsafeError(path, `${key} is declared but blank or malformed`);
|
|
940
|
+
}
|
|
941
|
+
}
|
|
942
|
+
const values = apiKeyKeys.map((key) => parsed.values.get(key)?.trim()).filter((value) => Boolean(value));
|
|
943
|
+
const pointer = parsed.values.get(pointerKey)?.trim();
|
|
944
|
+
if (pointer !== undefined) {
|
|
945
|
+
if (!VAULT_POINTER_SHAPE.test(pointer))
|
|
946
|
+
throw new CredentialFileUnsafeError(path, `${pointerKey} must name a vault item`);
|
|
947
|
+
if (values.length)
|
|
948
|
+
throw new CredentialFileUnsafeError(path, "a credential file cannot select both a literal key and a vault reference");
|
|
949
|
+
return { apiKey: "", pointerVaultKey: pointer };
|
|
950
|
+
}
|
|
951
|
+
if (new Set(values).size > 1) {
|
|
952
|
+
throw new CredentialFileUnsafeError(path, "credential aliases disagree");
|
|
953
|
+
}
|
|
954
|
+
return values[0] === undefined ? null : { apiKey: values[0] };
|
|
955
|
+
}
|
|
956
|
+
var CREDENTIAL_SHAPED_KEY = /(?:^|_)(?:API_KEY|KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH)(?:_|$)/;
|
|
957
|
+
function appConfigDiskValue(name, env, keys, profile = null) {
|
|
958
|
+
if (profile !== null && !SAFE_PROFILE.test(profile)) {
|
|
959
|
+
throw new CredentialResolutionError(name, "The selected configuration profile is invalid.", ["profile"]);
|
|
960
|
+
}
|
|
961
|
+
const wanted = keys.filter((key) => !CREDENTIAL_SHAPED_KEY.test(key));
|
|
962
|
+
if (wanted.length === 0)
|
|
963
|
+
return null;
|
|
964
|
+
for (const path of profileDiskSources(name, env, profile)) {
|
|
965
|
+
const parsed = readAppConfigFile(path);
|
|
966
|
+
if (!parsed)
|
|
967
|
+
continue;
|
|
968
|
+
if (wanted.some((key) => parsed.unusable.has(key))) {
|
|
969
|
+
return { key: wanted.find((key) => parsed.unusable.has(key)), value: "", path, unusable: true };
|
|
970
|
+
}
|
|
971
|
+
const values = wanted.map((key) => parsed.values.get(key)?.trim()).filter((value) => Boolean(value));
|
|
972
|
+
if (new Set(values).size > 1)
|
|
973
|
+
throw new CredentialFileUnsafeError(path, "configuration aliases disagree");
|
|
974
|
+
for (const key of wanted) {
|
|
975
|
+
if (parsed.unusable.has(key))
|
|
976
|
+
return { key, value: "", path, unusable: true };
|
|
977
|
+
const value = parsed.values.get(key)?.trim();
|
|
978
|
+
if (value)
|
|
979
|
+
return { key, value, path };
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
return null;
|
|
1099
983
|
}
|
|
1100
|
-
function
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
984
|
+
function assertUsableCredential(appName, source, value) {
|
|
985
|
+
if (VAULT_POINTER_SHAPE.test(value)) {
|
|
986
|
+
throw new CredentialResolutionError(appName, `The credential from ${source} looks like a secrets-vault pointer (a path-shaped reference like ` + `'namespace/app/live/api_key'). A vault path is NEVER accepted as a literal API key. ` + `Use ${credentialPointerEnvKey(appName)} to resolve the key through the vault, or provide the actual key value.`, [source]);
|
|
987
|
+
}
|
|
988
|
+
if (!ILLEGAL_IN_HEADER_VALUE.test(value))
|
|
1104
989
|
return;
|
|
1105
|
-
|
|
1106
|
-
|
|
990
|
+
throw new CredentialResolutionError(appName, `The credential from ${source} contains characters that cannot be sent in an HTTP header ` + `(a control character or non-ASCII byte). A file written with CR-only line endings is the usual ` + `cause. Rewrite that credential file with one LF-terminated KEY=value line. ` + `The value is not shown here, and is deliberately never logged.`, [source]);
|
|
991
|
+
}
|
|
992
|
+
var INSPECT_CUSTOM = Symbol.for("nodejs.util.inspect.custom");
|
|
993
|
+
var CREDENTIAL_SEAL = Symbol.for("hasna:contracts:sealedCredential");
|
|
994
|
+
var CALLER_SUPPLIED_CREDENTIAL_PROVIDER_SOURCE = "caller-supplied CredentialProvider";
|
|
995
|
+
function sealCredential(fields) {
|
|
996
|
+
const { apiKey } = fields;
|
|
997
|
+
const visible = {
|
|
998
|
+
tier: fields.tier,
|
|
999
|
+
source: fields.source,
|
|
1000
|
+
deliberate: fields.deliberate,
|
|
1001
|
+
diskCandidates: Object.freeze([...fields.diskCandidates]),
|
|
1002
|
+
warning: fields.warning
|
|
1003
|
+
};
|
|
1004
|
+
const sealed = { ...visible };
|
|
1005
|
+
Object.defineProperty(sealed, "apiKey", {
|
|
1006
|
+
value: apiKey,
|
|
1007
|
+
enumerable: false,
|
|
1008
|
+
writable: false,
|
|
1009
|
+
configurable: false
|
|
1010
|
+
});
|
|
1011
|
+
if (fields.pointerVaultKey !== undefined) {
|
|
1012
|
+
Object.defineProperty(sealed, "pointerVaultKey", {
|
|
1013
|
+
value: fields.pointerVaultKey,
|
|
1014
|
+
enumerable: false,
|
|
1015
|
+
writable: false,
|
|
1016
|
+
configurable: false
|
|
1017
|
+
});
|
|
1018
|
+
}
|
|
1019
|
+
Object.defineProperty(sealed, INSPECT_CUSTOM, {
|
|
1020
|
+
value: () => ({ ...visible, apiKey: "[redacted]" }),
|
|
1021
|
+
enumerable: false,
|
|
1022
|
+
writable: false,
|
|
1023
|
+
configurable: false
|
|
1024
|
+
});
|
|
1025
|
+
Object.defineProperty(sealed, CREDENTIAL_SEAL, {
|
|
1026
|
+
value: true,
|
|
1027
|
+
enumerable: false,
|
|
1028
|
+
writable: false,
|
|
1029
|
+
configurable: false
|
|
1030
|
+
});
|
|
1031
|
+
return Object.freeze(sealed);
|
|
1032
|
+
}
|
|
1033
|
+
function isSealedCredential(credential) {
|
|
1034
|
+
return credential[CREDENTIAL_SEAL] === true;
|
|
1035
|
+
}
|
|
1036
|
+
function explicitCredential(appName, apiKey) {
|
|
1037
|
+
const source = "explicit apiKey option";
|
|
1038
|
+
assertUsableCredential(appName, source, apiKey);
|
|
1039
|
+
return sealCredential({
|
|
1040
|
+
apiKey,
|
|
1041
|
+
tier: "argument",
|
|
1042
|
+
source,
|
|
1043
|
+
deliberate: true,
|
|
1044
|
+
diskCandidates: [],
|
|
1045
|
+
warning: null
|
|
1046
|
+
});
|
|
1107
1047
|
}
|
|
1108
|
-
function
|
|
1109
|
-
const
|
|
1110
|
-
|
|
1048
|
+
function validateAndSealResolvedCredential(appName, credential) {
|
|
1049
|
+
const apiKey = credential.apiKey;
|
|
1050
|
+
assertUsableCredential(appName, CALLER_SUPPLIED_CREDENTIAL_PROVIDER_SOURCE, apiKey);
|
|
1051
|
+
if (!isSealedCredential(credential)) {
|
|
1052
|
+
return sealCredential({
|
|
1053
|
+
apiKey,
|
|
1054
|
+
tier: "argument",
|
|
1055
|
+
source: CALLER_SUPPLIED_CREDENTIAL_PROVIDER_SOURCE,
|
|
1056
|
+
deliberate: true,
|
|
1057
|
+
diskCandidates: [],
|
|
1058
|
+
warning: null
|
|
1059
|
+
});
|
|
1060
|
+
}
|
|
1061
|
+
return sealCredential({
|
|
1062
|
+
apiKey,
|
|
1063
|
+
tier: credential.tier,
|
|
1064
|
+
source: credential.source,
|
|
1065
|
+
deliberate: credential.deliberate,
|
|
1066
|
+
diskCandidates: credential.diskCandidates,
|
|
1067
|
+
warning: credential.warning,
|
|
1068
|
+
...credential.pointerVaultKey !== undefined ? { pointerVaultKey: credential.pointerVaultKey } : {}
|
|
1069
|
+
});
|
|
1111
1070
|
}
|
|
1112
|
-
function
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
} catch {}
|
|
1071
|
+
function firstEnvValue(env, keys) {
|
|
1072
|
+
for (const key of keys) {
|
|
1073
|
+
if (!Object.prototype.hasOwnProperty.call(env, key))
|
|
1074
|
+
continue;
|
|
1075
|
+
const value = env[key]?.trim();
|
|
1076
|
+
if (value)
|
|
1077
|
+
return { key, value };
|
|
1120
1078
|
}
|
|
1121
|
-
return;
|
|
1079
|
+
return null;
|
|
1122
1080
|
}
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
return new Date().toISOString();
|
|
1133
|
-
}
|
|
1134
|
-
function stripRunState(context) {
|
|
1135
|
-
const { __wf: _wf, steps: _steps, ...user } = context;
|
|
1136
|
-
return user;
|
|
1137
|
-
}
|
|
1138
|
-
function runCommand(job) {
|
|
1139
|
-
if (!job.command) {
|
|
1140
|
-
return { ok: false, exitCode: 2, output: "", durationMs: 0, error: "no command" };
|
|
1141
|
-
}
|
|
1142
|
-
const started = Date.now();
|
|
1143
|
-
const timeoutMs = job.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
1144
|
-
const proc = Bun.spawnSync({
|
|
1145
|
-
cmd: ["/bin/sh", "-c", job.command],
|
|
1146
|
-
cwd: job.cwd,
|
|
1147
|
-
env: { ...process.env, ...job.env ?? {} },
|
|
1148
|
-
stdout: "pipe",
|
|
1149
|
-
stderr: "pipe",
|
|
1150
|
-
timeout: timeoutMs
|
|
1081
|
+
var AMBIENT_ENVIRONMENT = Symbol.for("hasna:contracts:ambientClientEnvironment");
|
|
1082
|
+
function isAmbientEnvironment(env) {
|
|
1083
|
+
return env === process.env || env[AMBIENT_ENVIRONMENT] === true;
|
|
1084
|
+
}
|
|
1085
|
+
function defaultKeychainRunner(argv) {
|
|
1086
|
+
const result = spawnSync(KEYCHAIN_SECURITY_BIN, [...argv], {
|
|
1087
|
+
encoding: "utf8",
|
|
1088
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1089
|
+
timeout: KEYCHAIN_SPAWN_TIMEOUT_MS
|
|
1151
1090
|
});
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
const exitCode = proc.exitCode ?? (proc.signalCode ? 1 : 1);
|
|
1158
|
-
return { ok: exitCode === 0, exitCode, output, durationMs };
|
|
1091
|
+
return {
|
|
1092
|
+
status: result.status,
|
|
1093
|
+
stdout: result.stdout ?? "",
|
|
1094
|
+
stderr: result.error ? result.error.message : result.stderr ?? ""
|
|
1095
|
+
};
|
|
1159
1096
|
}
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
}
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1097
|
+
function keychainTierEnabled(env, options) {
|
|
1098
|
+
if ((options.platform ?? process.platform) !== "darwin")
|
|
1099
|
+
return false;
|
|
1100
|
+
if (options.enabled !== undefined)
|
|
1101
|
+
return options.enabled;
|
|
1102
|
+
return options.run !== undefined || isAmbientEnvironment(env);
|
|
1103
|
+
}
|
|
1104
|
+
function keychainAccount(env, options) {
|
|
1105
|
+
const station = env[KEYCHAIN_STATION_ENV_KEY]?.trim();
|
|
1106
|
+
if (station)
|
|
1107
|
+
return station;
|
|
1108
|
+
const host = (options.hostname ?? osHostname)().split(".")[0]?.trim() ?? "";
|
|
1109
|
+
if (host)
|
|
1110
|
+
return host;
|
|
1111
|
+
const user = env.USER?.trim();
|
|
1112
|
+
return user || null;
|
|
1113
|
+
}
|
|
1114
|
+
function keychainFailureHint(text) {
|
|
1115
|
+
const line = text.split(/\r?\n/).find((entry) => entry.trim().length > 0)?.trim() ?? "";
|
|
1116
|
+
const clean = line.replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 200);
|
|
1117
|
+
return clean ? `: ${clean}` : "";
|
|
1118
|
+
}
|
|
1119
|
+
function readKeychainItem(name, env, kind, options) {
|
|
1120
|
+
if (!SAFE_APP_SLUG.test(name) || !keychainTierEnabled(env, options))
|
|
1121
|
+
return null;
|
|
1122
|
+
const account = keychainAccount(env, options);
|
|
1123
|
+
if (!account)
|
|
1124
|
+
return null;
|
|
1125
|
+
const service = `${KEYCHAIN_SERVICE_PREFIX}.${name}.${kind}`;
|
|
1126
|
+
const source = `keychain:${service}@${account}`;
|
|
1127
|
+
const run = options.run ?? defaultKeychainRunner;
|
|
1128
|
+
let result;
|
|
1129
|
+
try {
|
|
1130
|
+
result = run(["find-generic-password", "-a", account, "-s", service, "-w"]);
|
|
1131
|
+
} catch (error) {
|
|
1132
|
+
const reason = keychainFailureHint(error instanceof Error ? error.message : String(error));
|
|
1133
|
+
throw new CredentialResolutionError(name, `The Keychain lookup for ${source} could not run${reason}. A Keychain failure is never resolved ` + `around: fix the keychain, or delete the item to fall through to the credential on disk.`, [source]);
|
|
1134
|
+
}
|
|
1135
|
+
if (result.status === KEYCHAIN_ITEM_NOT_FOUND_STATUS)
|
|
1136
|
+
return null;
|
|
1137
|
+
if (result.status !== 0) {
|
|
1138
|
+
throw new CredentialResolutionError(name, `The Keychain lookup for ${source} failed (security exited ` + `${result.status ?? "without a status"}${keychainFailureHint(result.stderr)}). A Keychain item that ` + `exists but cannot be read is never resolved around: unlock the keychain, run from a session that ` + `may use it, or delete the item to fall through to the credential on disk.`, [source]);
|
|
1139
|
+
}
|
|
1140
|
+
const value = result.stdout.trim();
|
|
1141
|
+
if (!value) {
|
|
1142
|
+
throw new CredentialResolutionError(name, `${source} exists but holds an empty value; a declared item never falls through to another ` + `identity. Store a value in it or delete the item.`, [source]);
|
|
1143
|
+
}
|
|
1144
|
+
return { value, source };
|
|
1145
|
+
}
|
|
1146
|
+
function keychainConfigValue(name, env, options = {}) {
|
|
1147
|
+
return readKeychainItem(name, env, "api-url", options);
|
|
1148
|
+
}
|
|
1149
|
+
function snapshotClientEnvironment(name, env) {
|
|
1150
|
+
const keys = clientTransportEnvKeys(name);
|
|
1151
|
+
const ambient = isAmbientEnvironment(env);
|
|
1152
|
+
const snapshot = Object.create(null);
|
|
1153
|
+
for (const key of [
|
|
1154
|
+
...keys.apiUrlKeys,
|
|
1155
|
+
...keys.apiKeyKeys,
|
|
1156
|
+
credentialOverrideEnvKey(name),
|
|
1157
|
+
credentialPointerEnvKey(name),
|
|
1158
|
+
CREDENTIAL_PROFILE_ENV_KEY,
|
|
1159
|
+
"HOME",
|
|
1160
|
+
HASNA_HOME_ENV_KEY,
|
|
1161
|
+
HASNA_CONFIG_HOME_ENV_KEY,
|
|
1162
|
+
KEYCHAIN_STATION_ENV_KEY,
|
|
1163
|
+
"USER"
|
|
1164
|
+
]) {
|
|
1165
|
+
const descriptor = Object.getOwnPropertyDescriptor(env, key);
|
|
1166
|
+
if (!descriptor)
|
|
1167
|
+
continue;
|
|
1168
|
+
if (!("value" in descriptor)) {
|
|
1169
|
+
throw new CredentialResolutionError(name, `${key} is accessor-backed; client configuration requires own data properties.`, [key]);
|
|
1200
1170
|
}
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
const now = this.time();
|
|
1204
|
-
for (const [runId, lease] of this.leases) {
|
|
1205
|
-
if (lease.expiresAtMs <= now)
|
|
1206
|
-
this.leases.delete(runId);
|
|
1171
|
+
if (descriptor.value !== undefined && typeof descriptor.value !== "string") {
|
|
1172
|
+
throw new CredentialResolutionError(name, `${key} must be a string data property.`, [key]);
|
|
1207
1173
|
}
|
|
1208
|
-
|
|
1174
|
+
snapshot[key] = descriptor.value;
|
|
1209
1175
|
}
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1176
|
+
if (ambient) {
|
|
1177
|
+
Object.defineProperty(snapshot, AMBIENT_ENVIRONMENT, {
|
|
1178
|
+
value: true,
|
|
1179
|
+
enumerable: false,
|
|
1180
|
+
writable: false,
|
|
1181
|
+
configurable: false
|
|
1182
|
+
});
|
|
1183
|
+
}
|
|
1184
|
+
return Object.freeze(snapshot);
|
|
1185
|
+
}
|
|
1186
|
+
function resolveCredential(name, env, options = {}) {
|
|
1187
|
+
env = snapshotClientEnvironment(name, env);
|
|
1188
|
+
const { apiKeyKeys } = clientTransportEnvKeys(name);
|
|
1189
|
+
const diskPaths = credentialDiskSources(name, env);
|
|
1190
|
+
if (options.apiKey !== undefined) {
|
|
1191
|
+
const explicitKey = options.apiKey.trim();
|
|
1192
|
+
if (!explicitKey) {
|
|
1193
|
+
throw new CredentialResolutionError(name, "The explicit apiKey argument is blank; an explicit credential never falls through to another identity.", ["explicit apiKey argument"]);
|
|
1194
|
+
}
|
|
1195
|
+
assertUsableCredential(name, "the explicit apiKey argument", explicitKey);
|
|
1196
|
+
return sealCredential({
|
|
1197
|
+
apiKey: explicitKey,
|
|
1198
|
+
tier: "argument",
|
|
1199
|
+
source: "explicit apiKey argument",
|
|
1200
|
+
deliberate: true,
|
|
1201
|
+
diskCandidates: diskPaths,
|
|
1202
|
+
warning: null
|
|
1203
|
+
});
|
|
1204
|
+
}
|
|
1205
|
+
const overrideKeyName = credentialOverrideEnvKey(name);
|
|
1206
|
+
const overrideRaw = Object.prototype.hasOwnProperty.call(env, overrideKeyName) ? env[overrideKeyName] : undefined;
|
|
1207
|
+
if (overrideRaw !== undefined) {
|
|
1208
|
+
const override = overrideRaw.trim();
|
|
1209
|
+
if (!override) {
|
|
1210
|
+
throw new CredentialResolutionError(name, `${overrideKeyName} is set but empty. It is a deliberate override, so it is not resolved around: ` + `either give it a real key or unset it to fall back to the credential on disk.`, [overrideKeyName]);
|
|
1211
|
+
}
|
|
1212
|
+
assertUsableCredential(name, overrideKeyName, override);
|
|
1213
|
+
return sealCredential({
|
|
1214
|
+
apiKey: override,
|
|
1215
|
+
tier: "override",
|
|
1216
|
+
source: overrideKeyName,
|
|
1217
|
+
deliberate: true,
|
|
1218
|
+
diskCandidates: diskPaths,
|
|
1219
|
+
warning: null
|
|
1220
|
+
});
|
|
1221
|
+
}
|
|
1222
|
+
const pointerKeyName = credentialPointerEnvKey(name);
|
|
1223
|
+
const pointerRaw = Object.prototype.hasOwnProperty.call(env, pointerKeyName) ? env[pointerKeyName] : undefined;
|
|
1224
|
+
if (pointerRaw !== undefined) {
|
|
1225
|
+
const pointer = pointerRaw.trim();
|
|
1226
|
+
if (!pointer) {
|
|
1227
|
+
throw new CredentialResolutionError(name, `${pointerKeyName} is set but empty. It is a deliberate vault pointer, so it is not resolved around: ` + `either give it a vault item key or unset it to fall back to the credential on disk.`, [pointerKeyName]);
|
|
1228
|
+
}
|
|
1229
|
+
if (!VAULT_POINTER_SHAPE.test(pointer)) {
|
|
1230
|
+
throw new CredentialResolutionError(name, `${pointerKeyName} must name a vault ITEM KEY (a path-shaped reference like ` + `'namespace/app/live/api_key'), not a credential value. A pointer that carries a literal is refused.`, [pointerKeyName]);
|
|
1231
|
+
}
|
|
1232
|
+
return sealCredential({
|
|
1233
|
+
apiKey: "",
|
|
1234
|
+
pointerVaultKey: pointer,
|
|
1235
|
+
tier: "pointer",
|
|
1236
|
+
source: pointerKeyName,
|
|
1237
|
+
deliberate: true,
|
|
1238
|
+
diskCandidates: diskPaths,
|
|
1239
|
+
warning: null
|
|
1240
|
+
});
|
|
1241
|
+
}
|
|
1242
|
+
if (options.profile !== undefined && !options.profile.trim()) {
|
|
1243
|
+
throw new CredentialResolutionError(name, "The explicit profile argument is blank; an explicit identity selection never falls through.", ["explicit profile argument"]);
|
|
1244
|
+
}
|
|
1245
|
+
const profileRaw = Object.prototype.hasOwnProperty.call(env, CREDENTIAL_PROFILE_ENV_KEY) ? env[CREDENTIAL_PROFILE_ENV_KEY] : undefined;
|
|
1246
|
+
if (profileRaw !== undefined && !profileRaw.trim()) {
|
|
1247
|
+
throw new CredentialResolutionError(name, `${CREDENTIAL_PROFILE_ENV_KEY} is set but blank.`, [CREDENTIAL_PROFILE_ENV_KEY]);
|
|
1248
|
+
}
|
|
1249
|
+
const profile = options.profile?.trim() || profileRaw?.trim();
|
|
1250
|
+
if (profile) {
|
|
1251
|
+
const profileSource = options.profile?.trim() ? "explicit profile argument" : CREDENTIAL_PROFILE_ENV_KEY;
|
|
1252
|
+
if (!SAFE_PROFILE.test(profile)) {
|
|
1253
|
+
throw new CredentialResolutionError(name, `Profile name from ${profileSource} is not usable in a path. ` + `Use letters, digits, dot, dash, or underscore.`, [profileSource]);
|
|
1254
|
+
}
|
|
1255
|
+
const paths = profileDiskSources(name, env, profile);
|
|
1256
|
+
for (const path of paths) {
|
|
1257
|
+
const value = readCredentialFile(path, apiKeyKeys, pointerKeyName);
|
|
1258
|
+
if (value) {
|
|
1259
|
+
if (!value.pointerVaultKey)
|
|
1260
|
+
assertUsableCredential(name, path, value.apiKey);
|
|
1261
|
+
return sealCredential({
|
|
1262
|
+
...value,
|
|
1263
|
+
tier: value.pointerVaultKey ? "pointer" : "profile",
|
|
1264
|
+
source: path,
|
|
1265
|
+
deliberate: true,
|
|
1266
|
+
diskCandidates: paths,
|
|
1267
|
+
warning: null
|
|
1268
|
+
});
|
|
1269
|
+
}
|
|
1215
1270
|
}
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1271
|
+
throw new CredentialResolutionError(name, `Profile '${profile}' (from ${profileSource}) has no ${apiKeyKeys[0]} or ${pointerKeyName} for '${name}'. ` + `Looked in: ${paths.join(", ") || "<no HOME in this environment>"}. ` + `A profile names WHICH identity to use, so it is never resolved around \u2014 ` + `create the profile's credential file or unset ${CREDENTIAL_PROFILE_ENV_KEY}.`, paths);
|
|
1272
|
+
}
|
|
1273
|
+
const definedEnvEntries = apiKeyKeys.filter((key) => Object.prototype.hasOwnProperty.call(env, key) && env[key] !== undefined).map((key) => ({ key, value: String(env[key]).trim() }));
|
|
1274
|
+
const blankEnv = definedEnvEntries.find((entry) => entry.value.length === 0);
|
|
1275
|
+
if (blankEnv) {
|
|
1276
|
+
throw new CredentialResolutionError(name, `${blankEnv.key} is set but blank; a declared credential never falls through to another alias or identity.`, [blankEnv.key]);
|
|
1277
|
+
}
|
|
1278
|
+
if (definedEnvEntries.length > 1 && new Set(definedEnvEntries.map((entry) => entry.value)).size > 1) {
|
|
1279
|
+
throw new CredentialResolutionError(name, `${definedEnvEntries.map((entry) => entry.key).join(" and ")} disagree; credential aliases must be identical or only one may be set.`, definedEnvEntries.map((entry) => entry.key));
|
|
1280
|
+
}
|
|
1281
|
+
const envHit = firstEnvValue(env, apiKeyKeys);
|
|
1282
|
+
const keychainHit = readKeychainItem(name, env, "api-key", options.keychain ?? {});
|
|
1283
|
+
if (keychainHit) {
|
|
1284
|
+
assertUsableCredential(name, keychainHit.source, keychainHit.value);
|
|
1285
|
+
const warning = envHit && envHit.value !== keychainHit.value ? `Credential sources disagree for '${name}': ${keychainHit.source} and ${envHit.key} hold ` + `different keys. ${keychainHit.source} wins, because the Keychain is re-read on every call while ` + `an environment variable is a snapshot. Reconcile them \u2014 a rotation that updated only one leaves ` + `the other to fail 401 wherever it is loaded first.` : null;
|
|
1286
|
+
return sealCredential({
|
|
1287
|
+
apiKey: keychainHit.value,
|
|
1288
|
+
tier: "keychain",
|
|
1289
|
+
source: keychainHit.source,
|
|
1290
|
+
deliberate: false,
|
|
1291
|
+
diskCandidates: diskPaths,
|
|
1292
|
+
warning
|
|
1293
|
+
});
|
|
1294
|
+
}
|
|
1295
|
+
const diskSourceList = credentialDiskSourceList(name, env, null);
|
|
1296
|
+
const diskHits = diskSourceList.map((src) => ({ src, value: readCredentialFile(src.path, apiKeyKeys, pointerKeyName) })).filter((hit) => hit.value !== null);
|
|
1297
|
+
if (diskHits.length > 0) {
|
|
1298
|
+
const winner = diskHits[0];
|
|
1299
|
+
if (winner.value.pointerVaultKey) {
|
|
1300
|
+
return sealCredential({
|
|
1301
|
+
...winner.value,
|
|
1302
|
+
tier: "pointer",
|
|
1303
|
+
source: winner.src.path,
|
|
1304
|
+
deliberate: false,
|
|
1305
|
+
diskCandidates: diskPaths,
|
|
1306
|
+
warning: null
|
|
1307
|
+
});
|
|
1220
1308
|
}
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1309
|
+
assertUsableCredential(name, winner.src.path, winner.value.apiKey);
|
|
1310
|
+
const divergentSources = [
|
|
1311
|
+
...diskHits.slice(1).filter((hit) => hit.value.apiKey !== winner.value.apiKey || hit.value.pointerVaultKey !== winner.value.pointerVaultKey).map((hit) => hit.src.path),
|
|
1312
|
+
...envHit && envHit.value !== winner.value.apiKey ? [envHit.key] : []
|
|
1313
|
+
];
|
|
1314
|
+
const warning = divergentSources.length > 0 ? `Credential sources disagree for '${name}': ${winner.src.path} and ` + `${divergentSources.join(", ")} hold different keys. ${winner.src.path} wins, because a file on ` + `disk is re-read on every call while an environment variable is a snapshot. Reconcile them \u2014 ` + `a rotation that updated only one leaves the other to fail 401 wherever it is loaded first.` : null;
|
|
1315
|
+
return sealCredential({
|
|
1316
|
+
apiKey: winner.value.apiKey,
|
|
1317
|
+
tier: winner.src.tier,
|
|
1318
|
+
source: winner.src.path,
|
|
1319
|
+
deliberate: false,
|
|
1320
|
+
diskCandidates: diskPaths,
|
|
1321
|
+
warning
|
|
1232
1322
|
});
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1323
|
+
}
|
|
1324
|
+
if (envHit) {
|
|
1325
|
+
assertUsableCredential(name, envHit.key, envHit.value);
|
|
1326
|
+
return sealCredential({
|
|
1327
|
+
apiKey: envHit.value,
|
|
1328
|
+
tier: "env",
|
|
1329
|
+
source: envHit.key,
|
|
1330
|
+
deliberate: false,
|
|
1331
|
+
diskCandidates: diskPaths,
|
|
1332
|
+
warning: null
|
|
1333
|
+
});
|
|
1334
|
+
}
|
|
1335
|
+
return null;
|
|
1336
|
+
}
|
|
1337
|
+
var requireSecretsSdk = createRequire(import.meta.url);
|
|
1338
|
+
async function completePointerCredential(name, pointerResolution, env = process.env) {
|
|
1339
|
+
const secretsEnv = snapshotClientEnvironment("secrets", env);
|
|
1340
|
+
const vaultKey = pointerResolution.pointerVaultKey;
|
|
1341
|
+
const pointerEnvKey = pointerResolution.source;
|
|
1342
|
+
if (!vaultKey) {
|
|
1343
|
+
throw new CredentialResolutionError(name, `Pointer resolution from ${pointerEnvKey} carries no vault item key; this is a defect in the resolver.`, [pointerEnvKey]);
|
|
1344
|
+
}
|
|
1345
|
+
if (name === "secrets") {
|
|
1346
|
+
throw new CredentialResolutionError(name, "The Secrets bootstrap credential cannot reference the same hosted vault; configure an independent bootstrap provider.", [pointerEnvKey]);
|
|
1347
|
+
}
|
|
1348
|
+
let secretsSdk;
|
|
1349
|
+
try {
|
|
1350
|
+
const sdkUrl = resolveInstalledSecrets(import.meta.url);
|
|
1351
|
+
secretsSdk = requireSecretsSdk(fileURLToPath2(sdkUrl));
|
|
1352
|
+
} catch {
|
|
1353
|
+
throw new CredentialResolutionError(name, `${pointerEnvKey} names vault item '${vaultKey}', but the secrets SDK (@hasna/secrets) is not installed ` + `in this process. A vault pointer is TERMINAL: install @hasna/secrets to resolve it, or unset ${pointerEnvKey}.`, [pointerEnvKey]);
|
|
1354
|
+
}
|
|
1355
|
+
let client;
|
|
1356
|
+
try {
|
|
1357
|
+
const bootstrap = resolveCredential("secrets", secretsEnv);
|
|
1358
|
+
if (!bootstrap || bootstrap.tier === "pointer") {
|
|
1359
|
+
throw new CredentialResolutionError("secrets", "The Secrets vault requires an independent, non-reference bootstrap credential.", bootstrap ? [bootstrap.source] : []);
|
|
1360
|
+
}
|
|
1361
|
+
client = secretsSdk.createSecretsClientFromEnv(secretsEnv);
|
|
1362
|
+
} catch {
|
|
1363
|
+
throw new CredentialResolutionError(name, `${pointerEnvKey} names vault item '${vaultKey}', but the secrets client could not be configured from this ` + `environment (the secrets service URL and key env are missing or invalid). A vault pointer is TERMINAL and ` + `never falls through to a literal or disk credential.`, [pointerEnvKey]);
|
|
1364
|
+
}
|
|
1365
|
+
let secret;
|
|
1366
|
+
try {
|
|
1367
|
+
secret = await client.getSecret({ key: vaultKey });
|
|
1368
|
+
} catch {
|
|
1369
|
+
throw new CredentialResolutionError(name, `${pointerEnvKey} names vault item '${vaultKey}', but the vault could not be reached or the item is ` + `unavailable. A vault pointer is TERMINAL and never falls through to a literal or disk credential.`, [pointerEnvKey]);
|
|
1370
|
+
}
|
|
1371
|
+
const value = secret.value;
|
|
1372
|
+
if (!value) {
|
|
1373
|
+
throw new CredentialResolutionError(name, `${pointerEnvKey} resolved vault item '${vaultKey}', but it holds no value. A vault pointer is TERMINAL.`, [pointerEnvKey]);
|
|
1374
|
+
}
|
|
1375
|
+
assertUsableCredential(name, `${pointerEnvKey} -> vault:${vaultKey}`, value);
|
|
1376
|
+
return sealCredential({
|
|
1377
|
+
apiKey: value,
|
|
1378
|
+
tier: "pointer",
|
|
1379
|
+
source: `${pointerEnvKey} -> vault:${vaultKey}`,
|
|
1380
|
+
deliberate: pointerResolution.deliberate,
|
|
1381
|
+
diskCandidates: pointerResolution.diskCandidates,
|
|
1382
|
+
warning: null
|
|
1383
|
+
});
|
|
1384
|
+
}
|
|
1385
|
+
var DEFAULT_FLEET_GATEWAY_ORIGIN = "https://api.hasna.com";
|
|
1386
|
+
var DEFAULT_AUTHORITY_SOURCE = "default";
|
|
1387
|
+
function defaultFleetGatewayBaseUrl(name) {
|
|
1388
|
+
return `${DEFAULT_FLEET_GATEWAY_ORIGIN}/${validateAppSlug(name)}`;
|
|
1389
|
+
}
|
|
1390
|
+
var ASCII_CONTROL_PATTERN = /[\u0000-\u001f\u007f]/;
|
|
1391
|
+
var DNS_LABEL_PATTERN = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
|
|
1392
|
+
function isValidDnsDomain(value) {
|
|
1393
|
+
if (value.length === 0 || value.length > 253 || ASCII_CONTROL_PATTERN.test(value) || /[^\x00-\x7f]/.test(value)) {
|
|
1394
|
+
return false;
|
|
1395
|
+
}
|
|
1396
|
+
return value.split(".").every((label) => label.length <= 63 && !label.startsWith("xn--") && DNS_LABEL_PATTERN.test(label));
|
|
1397
|
+
}
|
|
1398
|
+
function validateAppSlug(name) {
|
|
1399
|
+
if (name.length > 63 || !DNS_LABEL_PATTERN.test(name)) {
|
|
1400
|
+
throw new Error("App name must be one lowercase DNS label.");
|
|
1401
|
+
}
|
|
1402
|
+
return name;
|
|
1403
|
+
}
|
|
1404
|
+
function rawAuthority(value) {
|
|
1405
|
+
const match = /^[a-z][a-z0-9+.-]*:\/\//i.exec(value);
|
|
1406
|
+
if (!match)
|
|
1407
|
+
throw new Error("API URL must be absolute.");
|
|
1408
|
+
const afterScheme = value.slice(match[0].length);
|
|
1409
|
+
const boundary = afterScheme.search(/[/?#]/);
|
|
1410
|
+
const authority = boundary === -1 ? afterScheme : afterScheme.slice(0, boundary);
|
|
1411
|
+
if (!authority)
|
|
1412
|
+
throw new Error("API URL must include a hostname.");
|
|
1413
|
+
return authority;
|
|
1414
|
+
}
|
|
1415
|
+
function assertCanonicalPort(port) {
|
|
1416
|
+
if (!/^[0-9]+$/.test(port) || port.length > 1 && port.startsWith("0")) {
|
|
1417
|
+
throw new Error("API URL authority must contain a canonical port between 1 and 65535.");
|
|
1418
|
+
}
|
|
1419
|
+
const numericPort = Number(port);
|
|
1420
|
+
if (!Number.isSafeInteger(numericPort) || numericPort < 1 || numericPort > 65535) {
|
|
1421
|
+
throw new Error("API URL authority must contain a canonical port between 1 and 65535.");
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
function canonicalAuthorityHostname(authority) {
|
|
1425
|
+
let rawHostname;
|
|
1426
|
+
if (authority.startsWith("[")) {
|
|
1427
|
+
const closingBracket = authority.indexOf("]");
|
|
1428
|
+
if (closingBracket === -1) {
|
|
1429
|
+
throw new Error("API URL authority must contain a canonical hostname.");
|
|
1430
|
+
}
|
|
1431
|
+
rawHostname = authority.slice(0, closingBracket + 1);
|
|
1432
|
+
const portSuffix = authority.slice(closingBracket + 1);
|
|
1433
|
+
if (portSuffix) {
|
|
1434
|
+
if (!portSuffix.startsWith(":")) {
|
|
1435
|
+
throw new Error("API URL authority must contain a canonical hostname and port.");
|
|
1257
1436
|
}
|
|
1437
|
+
assertCanonicalPort(portSuffix.slice(1));
|
|
1258
1438
|
}
|
|
1259
|
-
if (
|
|
1260
|
-
|
|
1261
|
-
report.interrupted += repair.interrupted;
|
|
1262
|
-
report.requeued += repair.requeued;
|
|
1263
|
-
report.failed += repair.failed;
|
|
1439
|
+
if (isIP(rawHostname.slice(1, -1)) !== 6) {
|
|
1440
|
+
throw new Error("API URL authority must contain a canonical IPv6 literal.");
|
|
1264
1441
|
}
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
}
|
|
1276
|
-
const running = this.store.listRuns({ status: "running", limit: this.maxStepsPerCycle });
|
|
1277
|
-
let steps = 0;
|
|
1278
|
-
for (const run of running) {
|
|
1279
|
-
if (this.isolatedRunId !== null && run.id !== this.isolatedRunId)
|
|
1280
|
-
continue;
|
|
1281
|
-
if (steps >= this.maxStepsPerCycle)
|
|
1282
|
-
break;
|
|
1283
|
-
const outcome = await this.advanceRun(run.id);
|
|
1284
|
-
steps++;
|
|
1285
|
-
if (outcome.kind === "completed")
|
|
1286
|
-
report.completed++;
|
|
1287
|
-
if (outcome.kind === "failed")
|
|
1288
|
-
report.failed++;
|
|
1289
|
-
if (outcome.kind === "advanced")
|
|
1290
|
-
report.advanced++;
|
|
1291
|
-
}
|
|
1292
|
-
return report;
|
|
1293
|
-
}
|
|
1294
|
-
startRun(graph, context) {
|
|
1295
|
-
const validation = validateGraph(graph);
|
|
1296
|
-
if (!validation.ok) {
|
|
1297
|
-
throw new Error(`graph validation failed: ${validation.issues.map((i) => `${i.path}: ${i.message}`).join("; ")}`);
|
|
1298
|
-
}
|
|
1299
|
-
assertNoSecrets(context, "run context");
|
|
1300
|
-
assertNoSecrets(graph, "graph definition");
|
|
1301
|
-
const existing = this.graphCache.get(graph.name);
|
|
1302
|
-
const serialized = JSON.stringify(graph);
|
|
1303
|
-
if (!existing || JSON.stringify(existing) !== serialized) {
|
|
1304
|
-
this.graphCache.set(graph.name, graph);
|
|
1305
|
-
this.wal.append({ op: "graph_registered", name: graph.name, version: graph.version, graph, at: nowIso() });
|
|
1442
|
+
} else {
|
|
1443
|
+
const firstColon = authority.indexOf(":");
|
|
1444
|
+
const lastColon = authority.lastIndexOf(":");
|
|
1445
|
+
if (firstColon !== lastColon) {
|
|
1446
|
+
throw new Error("IPv6 API URL authorities must use brackets.");
|
|
1447
|
+
}
|
|
1448
|
+
if (lastColon !== -1) {
|
|
1449
|
+
const port = authority.slice(lastColon + 1);
|
|
1450
|
+
assertCanonicalPort(port);
|
|
1451
|
+
rawHostname = authority.slice(0, lastColon);
|
|
1306
1452
|
} else {
|
|
1307
|
-
|
|
1308
|
-
}
|
|
1309
|
-
return this.store.createRun({ graphName: graph.name, graphVersion: graph.version, context: context ?? {} });
|
|
1310
|
-
}
|
|
1311
|
-
async advanceRun(runId) {
|
|
1312
|
-
const run = this.store.getRun(runId);
|
|
1313
|
-
if (!run || run.status !== "running")
|
|
1314
|
-
return { kind: "noop" };
|
|
1315
|
-
const lease = this.leases.get(runId);
|
|
1316
|
-
if (!lease || lease.expiresAtMs <= this.time())
|
|
1317
|
-
return { kind: "blocked" };
|
|
1318
|
-
const graph = this.loadGraph(run.graphName);
|
|
1319
|
-
if (!graph) {
|
|
1320
|
-
this.failRun(run, `graph ${run.graphName} not found in daemon graph cache`);
|
|
1321
|
-
return { kind: "failed", error: "graph not found" };
|
|
1322
|
-
}
|
|
1323
|
-
const context = JSON.parse(run.contextJson);
|
|
1324
|
-
const rawWf = context.__wf ?? {};
|
|
1325
|
-
const wf = {
|
|
1326
|
-
...rawWf,
|
|
1327
|
-
cursor: typeof rawWf.cursor === "string" ? rawWf.cursor : undefined,
|
|
1328
|
-
loops: rawWf.loops ?? {},
|
|
1329
|
-
completedLoops: rawWf.completedLoops ?? {}
|
|
1330
|
-
};
|
|
1331
|
-
try {
|
|
1332
|
-
const cursor = wf.cursor;
|
|
1333
|
-
const node = cursor === undefined ? graph.nodes.find((n) => n.type === "start") : findNode(graph, cursor);
|
|
1334
|
-
if (!node) {
|
|
1335
|
-
this.failRun(run, `cursor ${cursor ?? "<start>"} resolves to no node`);
|
|
1336
|
-
return { kind: "failed", error: "no node at cursor" };
|
|
1337
|
-
}
|
|
1338
|
-
switch (node.type) {
|
|
1339
|
-
case "start": {
|
|
1340
|
-
wf.cursor = node.next;
|
|
1341
|
-
this.persistContext(run, context, wf);
|
|
1342
|
-
return { kind: "advanced", nodeId: node.id };
|
|
1343
|
-
}
|
|
1344
|
-
case "step": {
|
|
1345
|
-
return await this.executeStep(run, graph, context, wf, node);
|
|
1346
|
-
}
|
|
1347
|
-
case "decision": {
|
|
1348
|
-
const value = evaluateExpr(node.condition, this.conditionScope(context));
|
|
1349
|
-
const next = value ? node.then : node.else;
|
|
1350
|
-
if (!next) {
|
|
1351
|
-
this.failRun(run, `decision ${node.id} evaluated ${value} but no ${value ? "then" : "else"} edge`);
|
|
1352
|
-
return { kind: "failed", error: "missing decision edge" };
|
|
1353
|
-
}
|
|
1354
|
-
wf.cursor = next;
|
|
1355
|
-
this.persistContext(run, context, wf);
|
|
1356
|
-
return { kind: "advanced", nodeId: node.id };
|
|
1357
|
-
}
|
|
1358
|
-
case "while": {
|
|
1359
|
-
return this.executeWhile(run, graph, context, wf, node);
|
|
1360
|
-
}
|
|
1361
|
-
case "end": {
|
|
1362
|
-
this.completeRun(run, context);
|
|
1363
|
-
return { kind: "completed" };
|
|
1364
|
-
}
|
|
1365
|
-
}
|
|
1366
|
-
} catch (err) {
|
|
1367
|
-
if (err instanceof ExprEvalError || err instanceof ExprSyntaxError) {
|
|
1368
|
-
this.failRun(run, `condition error at ${wf.cursor ?? "<start>"}: ${err.message}`);
|
|
1369
|
-
return { kind: "failed", error: err.message };
|
|
1370
|
-
}
|
|
1371
|
-
throw err;
|
|
1372
|
-
}
|
|
1373
|
-
}
|
|
1374
|
-
loadGraph(name) {
|
|
1375
|
-
return this.graphCache.get(name);
|
|
1376
|
-
}
|
|
1377
|
-
conditionScope(context) {
|
|
1378
|
-
return { ...context, steps: context.steps ?? {} };
|
|
1379
|
-
}
|
|
1380
|
-
persistContext(run, context, wf) {
|
|
1381
|
-
context.__wf = wf;
|
|
1382
|
-
this.store.setRunContext(run.id, context);
|
|
1383
|
-
}
|
|
1384
|
-
async executeStep(run, graph, context, wf, node) {
|
|
1385
|
-
const nodeId = node.id;
|
|
1386
|
-
const existing = this.store.listRunNodes(run.id).find((n) => n.nodeId === nodeId);
|
|
1387
|
-
const nodeRow = existing ?? this.store.createRunNode({ runId: run.id, nodeId, lane: node.lane ?? "claude" });
|
|
1388
|
-
if (node.memo) {
|
|
1389
|
-
const memoInput = { command: node.command, prompt: node.prompt, context: stripRunState(context) };
|
|
1390
|
-
const hit = tryMemoHit(this.store, run.graphName, nodeId, memoInput);
|
|
1391
|
-
if (hit) {
|
|
1392
|
-
const cached = JSON.parse(hit.outputJson);
|
|
1393
|
-
this.store.setRunNodeStatus(nodeRow.id, "completed", { exitCode: Number(cached.exitCode ?? 0), output: { ...cached, memoHit: true } });
|
|
1394
|
-
this.wal.append({ op: "node_finished", runId: run.id, nodeId, status: "completed", at: nowIso() });
|
|
1395
|
-
this.recordStepResult(context, nodeId, { ...cached, memoHit: true });
|
|
1396
|
-
return this.afterNode(run, context, wf, node.next);
|
|
1397
|
-
}
|
|
1453
|
+
rawHostname = authority;
|
|
1398
1454
|
}
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1455
|
+
const ipVersion = isIP(rawHostname);
|
|
1456
|
+
const numericAddressParts = rawHostname.split(".");
|
|
1457
|
+
const looksLikeNonCanonicalIpv4 = numericAddressParts.every((part) => /^(?:0x[0-9a-f]+|[0-9]+)$/i.test(part));
|
|
1458
|
+
if (ipVersion !== 4 && looksLikeNonCanonicalIpv4 || ipVersion !== 4 && !isValidDnsDomain(rawHostname.toLowerCase())) {
|
|
1459
|
+
throw new Error("API URL authority must contain a canonical ASCII hostname.");
|
|
1402
1460
|
}
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1461
|
+
}
|
|
1462
|
+
return rawHostname.toLowerCase();
|
|
1463
|
+
}
|
|
1464
|
+
function isDeliberateLoopbackHttpAuthority(authority) {
|
|
1465
|
+
return /^(?:localhost|127\.0\.0\.1|\[::1\])(?::[0-9]+)?$/i.test(authority);
|
|
1466
|
+
}
|
|
1467
|
+
function toV1BaseUrl(apiUrl) {
|
|
1468
|
+
if (ASCII_CONTROL_PATTERN.test(apiUrl)) {
|
|
1469
|
+
throw new Error("API URL must not contain ASCII control characters.");
|
|
1470
|
+
}
|
|
1471
|
+
const input = apiUrl.trim();
|
|
1472
|
+
const authority = rawAuthority(input);
|
|
1473
|
+
if (authority.includes("@") || authority.includes("\\") || authority.includes("%") || /[^\x00-\x7f]/.test(authority)) {
|
|
1474
|
+
throw new Error("API URL authority must be canonical ASCII without credentials.");
|
|
1475
|
+
}
|
|
1476
|
+
const canonicalHostname = canonicalAuthorityHostname(authority);
|
|
1477
|
+
const url = new URL(input);
|
|
1478
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
1479
|
+
throw new Error("API URL must use http or https.");
|
|
1480
|
+
}
|
|
1481
|
+
if (url.username || url.password) {
|
|
1482
|
+
throw new Error("API URL must not include credentials.");
|
|
1483
|
+
}
|
|
1484
|
+
if (!url.hostname || url.hostname.endsWith(".")) {
|
|
1485
|
+
throw new Error("API URL must include a canonical hostname.");
|
|
1486
|
+
}
|
|
1487
|
+
if (url.hostname.toLowerCase() !== canonicalHostname) {
|
|
1488
|
+
throw new Error("API URL authority must not rely on parser hostname normalization.");
|
|
1489
|
+
}
|
|
1490
|
+
if (url.hostname.split(".").some((label) => label.toLowerCase().startsWith("xn--"))) {
|
|
1491
|
+
throw new Error("API URL must not use IDN or punycode hostnames.");
|
|
1492
|
+
}
|
|
1493
|
+
if (url.protocol === "http:" && !isDeliberateLoopbackHttpAuthority(authority)) {
|
|
1494
|
+
throw new Error("API URL may use http only for an exact loopback authority.");
|
|
1495
|
+
}
|
|
1496
|
+
if (url.search || url.hash) {
|
|
1497
|
+
throw new Error("API URL must not include a query string or fragment.");
|
|
1498
|
+
}
|
|
1499
|
+
let path = url.pathname.replace(/\/+$/, "");
|
|
1500
|
+
if (path.endsWith("/v1"))
|
|
1501
|
+
path = path.slice(0, -"/v1".length);
|
|
1502
|
+
url.pathname = `${path}/v1`;
|
|
1503
|
+
return url.toString().replace(/\/+$/, "");
|
|
1504
|
+
}
|
|
1505
|
+
class ClientTransportConfigurationError extends Error {
|
|
1506
|
+
appName;
|
|
1507
|
+
sources;
|
|
1508
|
+
constructor(appName, message, sources = []) {
|
|
1509
|
+
super(message);
|
|
1510
|
+
this.name = "ClientTransportConfigurationError";
|
|
1511
|
+
this.appName = appName;
|
|
1512
|
+
this.sources = Object.freeze([...sources]);
|
|
1513
|
+
}
|
|
1514
|
+
}
|
|
1515
|
+
|
|
1516
|
+
class ClientCredentialMissingError extends ClientTransportConfigurationError {
|
|
1517
|
+
authorityConfigured;
|
|
1518
|
+
constructor(name, message, sources, authorityConfigured) {
|
|
1519
|
+
super(name, message, sources);
|
|
1520
|
+
this.authorityConfigured = authorityConfigured;
|
|
1521
|
+
this.name = "ClientCredentialMissingError";
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
function resolveClientAuthoritySnapshot(name, env = process.env, options = {}) {
|
|
1525
|
+
env = snapshotClientEnvironment(name, env);
|
|
1526
|
+
const keys = clientTransportEnvKeys(name);
|
|
1527
|
+
const definedUrlEntries = keys.apiUrlKeys.filter((key) => Object.prototype.hasOwnProperty.call(env, key) && env[key] !== undefined).map((key) => ({ key, raw: String(env[key]) }));
|
|
1528
|
+
const blankUrl = definedUrlEntries.find((entry) => entry.raw.trim().length === 0);
|
|
1529
|
+
if (blankUrl) {
|
|
1530
|
+
throw new ClientTransportConfigurationError(name, `${blankUrl.key} is set but blank; public clients require an explicit HTTPS API URL and never select local storage.`, [blankUrl.key]);
|
|
1531
|
+
}
|
|
1532
|
+
const controlledUrl = definedUrlEntries.find((entry) => ASCII_CONTROL_PATTERN.test(entry.raw));
|
|
1533
|
+
if (controlledUrl) {
|
|
1534
|
+
throw new ClientTransportConfigurationError(name, `${controlledUrl.key} contains ASCII control characters.`, [controlledUrl.key]);
|
|
1535
|
+
}
|
|
1536
|
+
const usableUrlEntries = definedUrlEntries.map((entry) => ({ key: entry.key, value: entry.raw.trim() }));
|
|
1537
|
+
const normalizedAuthority = (entry) => {
|
|
1411
1538
|
try {
|
|
1412
|
-
|
|
1413
|
-
} catch
|
|
1414
|
-
|
|
1415
|
-
}
|
|
1416
|
-
const output = { ok: result.ok, exitCode: result.exitCode, output: result.output, durationMs: result.durationMs };
|
|
1417
|
-
if (!result.ok) {
|
|
1418
|
-
const shouldRetry = nodeRow.attempts < (node.maxRetries ?? 0);
|
|
1419
|
-
this.store.bumpAttemptsNode(nodeRow.id);
|
|
1420
|
-
if (shouldRetry) {
|
|
1421
|
-
this.store.setRunNodeStatus(nodeRow.id, "pending", { error: result.error ?? `exit ${result.exitCode}` });
|
|
1422
|
-
return { kind: "advanced", nodeId };
|
|
1423
|
-
}
|
|
1424
|
-
const error = result.error ?? `step ${nodeId} failed with exit ${result.exitCode}`;
|
|
1425
|
-
this.store.setRunNodeStatus(nodeRow.id, "failed", { exitCode: result.exitCode, error });
|
|
1426
|
-
this.wal.append({ op: "node_finished", runId: run.id, nodeId, status: "failed", at: nowIso() });
|
|
1427
|
-
this.failRun(run, error);
|
|
1428
|
-
return { kind: "failed", error };
|
|
1539
|
+
return toV1BaseUrl(entry.value);
|
|
1540
|
+
} catch {
|
|
1541
|
+
throw new ClientTransportConfigurationError(name, `Invalid API URL from ${entry.key}; use an absolute HTTPS URL or exact loopback HTTP authority without credentials, query or fragment.`, [entry.key]);
|
|
1429
1542
|
}
|
|
1543
|
+
};
|
|
1544
|
+
if (usableUrlEntries.length > 1 && new Set(usableUrlEntries.map(normalizedAuthority)).size > 1) {
|
|
1545
|
+
throw new ClientTransportConfigurationError(name, `${usableUrlEntries.map((entry) => entry.key).join(" and ")} disagree; client authority aliases must select the same versioned API authority or only one may be set.`, usableUrlEntries.map((entry) => entry.key));
|
|
1546
|
+
}
|
|
1547
|
+
const envUrlHit = usableUrlEntries[0] ?? null;
|
|
1548
|
+
const keychainUrlHit = keychainConfigValue(name, env, options.credentials?.keychain);
|
|
1549
|
+
const profile = options.bindUnpairedCredentialsToFleet ? options.credentials?.profile?.trim() || env.HASNA_PROFILE?.trim() || null : null;
|
|
1550
|
+
const diskConfigUrlHit = appConfigDiskValue(name, env, keys.apiUrlKeys, profile);
|
|
1551
|
+
if (diskConfigUrlHit?.unusable) {
|
|
1552
|
+
throw new ClientTransportConfigurationError(name, `${diskConfigUrlHit.key} in ${diskConfigUrlHit.path} is declared but blank or malformed; public clients require a valid HTTPS service authority.`, [diskConfigUrlHit.path]);
|
|
1553
|
+
}
|
|
1554
|
+
const urlCandidates = [
|
|
1555
|
+
...envUrlHit ? [envUrlHit] : [],
|
|
1556
|
+
...keychainUrlHit ? [{ key: keychainUrlHit.source, value: keychainUrlHit.value }] : [],
|
|
1557
|
+
...diskConfigUrlHit ? [{ key: diskConfigUrlHit.path, value: diskConfigUrlHit.value.trim() }] : []
|
|
1558
|
+
];
|
|
1559
|
+
const configuredUrl = urlCandidates[0] ?? null;
|
|
1560
|
+
const normalizedUrls = urlCandidates.map(normalizedAuthority);
|
|
1561
|
+
const divergentUrls = urlCandidates.filter((_, index) => normalizedUrls[index] !== normalizedUrls[0]);
|
|
1562
|
+
if (configuredUrl && divergentUrls.length > 0) {
|
|
1563
|
+
throw new ClientTransportConfigurationError(name, `${configuredUrl.key} and ${divergentUrls.map((candidate) => candidate.key).join(" and ")} select different service authorities; refusing to send a credential written for one authority to the other.`, urlCandidates.map((candidate) => candidate.key));
|
|
1564
|
+
}
|
|
1565
|
+
if (configuredUrl && options.bindUnpairedCredentialsToFleet) {
|
|
1430
1566
|
try {
|
|
1431
|
-
|
|
1432
|
-
} catch (
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
this.persistContext(run, context, wf);
|
|
1462
|
-
return { kind: "advanced", nodeId: wf.cursor };
|
|
1463
|
-
}
|
|
1464
|
-
wf.loops[whileNode.id] = (wf.loops[whileNode.id] ?? 0) + 1;
|
|
1465
|
-
wf.cursor = whileNode.id;
|
|
1466
|
-
this.persistContext(run, context, wf);
|
|
1467
|
-
return { kind: "advanced", nodeId: whileNode.id };
|
|
1468
|
-
}
|
|
1469
|
-
this.completeRun(run, context);
|
|
1470
|
-
return { kind: "completed" };
|
|
1471
|
-
}
|
|
1472
|
-
executeWhile(run, graph, context, wf, node) {
|
|
1473
|
-
const iteration = wf.loops[node.id] ?? 0;
|
|
1474
|
-
if (iteration >= node.maxIterations) {
|
|
1475
|
-
const error = `while node ${node.id} exceeded maxIterations (${node.maxIterations})`;
|
|
1476
|
-
this.failRun(run, error);
|
|
1477
|
-
return { kind: "failed", error };
|
|
1478
|
-
}
|
|
1479
|
-
const scope = { ...this.conditionScope(context), i: iteration };
|
|
1480
|
-
const keepGoing = evaluateExpr(node.condition, scope);
|
|
1481
|
-
if (!keepGoing) {
|
|
1482
|
-
wf.completedLoops[node.id] = iteration;
|
|
1483
|
-
delete wf.loops[node.id];
|
|
1484
|
-
wf.cursor = node.next;
|
|
1485
|
-
this.persistContext(run, context, wf);
|
|
1486
|
-
return { kind: "advanced", nodeId: node.id };
|
|
1487
|
-
}
|
|
1488
|
-
wf.cursor = node.body[0];
|
|
1489
|
-
this.persistContext(run, context, wf);
|
|
1490
|
-
return { kind: "advanced", nodeId: node.id };
|
|
1491
|
-
}
|
|
1492
|
-
recordStepResult(context, nodeId, output) {
|
|
1493
|
-
const steps = context.steps ?? {};
|
|
1494
|
-
steps[nodeId] = output;
|
|
1495
|
-
context.steps = steps;
|
|
1496
|
-
}
|
|
1497
|
-
completeRun(run, context) {
|
|
1498
|
-
const result = {
|
|
1499
|
-
steps: context.steps ?? {},
|
|
1500
|
-
iterations: context.__wf?.completedLoops ?? {}
|
|
1501
|
-
};
|
|
1567
|
+
toV1BaseUrl(configuredUrl.value);
|
|
1568
|
+
} catch (error) {
|
|
1569
|
+
throw new ClientTransportConfigurationError(name, `Invalid API URL from ${configuredUrl.key}: ${error instanceof Error ? error.message : String(error)}`, [configuredUrl.key]);
|
|
1570
|
+
}
|
|
1571
|
+
}
|
|
1572
|
+
return { keys, configuredUrl, envUrlHit, keychainUrlHit, diskConfigUrlHit };
|
|
1573
|
+
}
|
|
1574
|
+
function resolveClientTransportSnapshot(name, env = process.env, options = {}) {
|
|
1575
|
+
env = snapshotClientEnvironment(name, env);
|
|
1576
|
+
const { keys, configuredUrl, envUrlHit, keychainUrlHit, diskConfigUrlHit } = resolveClientAuthoritySnapshot(name, env, options);
|
|
1577
|
+
const warnings = [];
|
|
1578
|
+
if (configuredUrl && !envUrlHit) {
|
|
1579
|
+
warnings.push(`No ${keys.apiUrlKeys[0]} in the environment; the server URL in ${configuredUrl.key} was used, so this client connects to the server. ` + `Keep that entry aligned with the intended service authority.`);
|
|
1580
|
+
}
|
|
1581
|
+
const credential = resolveCredential(name, env, options.credentials);
|
|
1582
|
+
if (!credential) {
|
|
1583
|
+
const diskHint = credentialDiskSourcesForMessage(name, env);
|
|
1584
|
+
const lead = configuredUrl ? `${configuredUrl.key} selects the HTTP server for '${name}', but no API key could be resolved` : `${keys.apiUrlKeys[0]} is not set and no API key could be resolved for '${name}'; a credential is required before the default fleet gateway authority applies`;
|
|
1585
|
+
warnings.push(`${lead}; refusing to create an unauthenticated client \u2014 public clients never fall back to SQLite or another local store. ` + `Looked in the Keychain (macOS only), then for a credential file at ${diskHint}, then for ${keys.apiKeyKeys[0]} in the environment.`);
|
|
1586
|
+
const sources = [configuredUrl?.key ?? keys.apiUrlKeys[0]];
|
|
1587
|
+
if (options.bindUnpairedCredentialsToFleet)
|
|
1588
|
+
throw new ClientCredentialMissingError(name, warnings.join(" "), sources, configuredUrl !== null);
|
|
1589
|
+
throw new ClientTransportConfigurationError(name, warnings.join(" "), sources);
|
|
1590
|
+
}
|
|
1591
|
+
if (credential.warning)
|
|
1592
|
+
warnings.push(credential.warning);
|
|
1593
|
+
let urlHit;
|
|
1594
|
+
if (configuredUrl) {
|
|
1595
|
+
urlHit = configuredUrl;
|
|
1596
|
+
} else {
|
|
1502
1597
|
try {
|
|
1503
|
-
|
|
1504
|
-
} catch (
|
|
1505
|
-
const message =
|
|
1506
|
-
|
|
1507
|
-
return;
|
|
1598
|
+
urlHit = { key: DEFAULT_AUTHORITY_SOURCE, value: defaultFleetGatewayBaseUrl(name) };
|
|
1599
|
+
} catch (error) {
|
|
1600
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1601
|
+
throw new ClientTransportConfigurationError(name, `No ${keys.apiUrlKeys[0]} is configured and the default fleet gateway authority cannot be composed for '${name}': ${message}`, [keys.apiUrlKeys[0]]);
|
|
1508
1602
|
}
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
}
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
if (job.command)
|
|
1525
|
-
return runCommand(job);
|
|
1526
|
-
const { runLaneJob: runLaneJob2 } = await Promise.resolve().then(() => (init_lanes(), exports_lanes));
|
|
1527
|
-
return runLaneJob2(job);
|
|
1528
|
-
};
|
|
1529
|
-
async function runGraphToCompletion(store, wal, graph, context, options = {}) {
|
|
1530
|
-
const daemon = new WorkflowsDaemon(store, wal, {
|
|
1531
|
-
worker: "local",
|
|
1532
|
-
laneRunner: options.laneRunner,
|
|
1533
|
-
time: options.time,
|
|
1534
|
-
env: options.env,
|
|
1535
|
-
isolatedRunId: options.isolatedRunId
|
|
1536
|
-
});
|
|
1537
|
-
const run = daemon.startRun(graph, context);
|
|
1538
|
-
daemon.isolateRun(run.id);
|
|
1539
|
-
const maxCycles = options.maxCycles ?? 500;
|
|
1540
|
-
for (let cycle = 0;cycle < maxCycles; cycle++) {
|
|
1541
|
-
const report = await daemon.reap();
|
|
1542
|
-
const current = store.getRun(run.id);
|
|
1543
|
-
if (current.status !== "running")
|
|
1544
|
-
return current;
|
|
1545
|
-
if (report.advanced === 0 && report.dispatched === 0) {
|
|
1546
|
-
return store.getRun(run.id);
|
|
1603
|
+
}
|
|
1604
|
+
const apiUrlSource = urlHit.key;
|
|
1605
|
+
let baseUrl;
|
|
1606
|
+
try {
|
|
1607
|
+
baseUrl = toV1BaseUrl(urlHit.value);
|
|
1608
|
+
} catch (error) {
|
|
1609
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1610
|
+
throw new ClientTransportConfigurationError(name, `Invalid API URL from ${apiUrlSource}: ${message}`, [apiUrlSource]);
|
|
1611
|
+
}
|
|
1612
|
+
if (options.bindUnpairedCredentialsToFleet && baseUrl !== toV1BaseUrl(defaultFleetGatewayBaseUrl(name))) {
|
|
1613
|
+
const pairedDisk = diskConfigUrlHit?.path === credential.source && (credential.tier === "disk" || credential.tier === "profile" || credential.tier === "pointer");
|
|
1614
|
+
const pairedKeychain = credential.tier === "keychain" && keychainUrlHit?.source === credential.source.replace(".api-key@", ".api-url@");
|
|
1615
|
+
const deliberatePair = envUrlHit !== null && (credential.tier === "argument" || credential.tier === "override");
|
|
1616
|
+
if (!pairedDisk && !pairedKeychain && !deliberatePair) {
|
|
1617
|
+
throw new ClientTransportConfigurationError(name, "An unpaired legacy credential is bound to the fleet gateway. Configure a stored authority/credential pair or an explicit API key override for the intended authority; no credential was sent.");
|
|
1547
1618
|
}
|
|
1548
1619
|
}
|
|
1549
|
-
return store.getRun(run.id);
|
|
1550
|
-
}
|
|
1551
|
-
|
|
1552
|
-
// src/agent-tools.ts
|
|
1553
|
-
init_lanes();
|
|
1554
|
-
|
|
1555
|
-
// src/store.ts
|
|
1556
|
-
import { Database } from "bun:sqlite";
|
|
1557
|
-
import { mkdirSync } from "fs";
|
|
1558
|
-
import { join } from "path";
|
|
1559
|
-
import { randomUUID } from "crypto";
|
|
1560
|
-
function nowIso2() {
|
|
1561
|
-
return new Date().toISOString();
|
|
1562
|
-
}
|
|
1563
|
-
function openStore(dataDir) {
|
|
1564
|
-
mkdirSync(dataDir, { recursive: true });
|
|
1565
|
-
const db = new Database(join(dataDir, "workflows.db"));
|
|
1566
|
-
db.exec("PRAGMA journal_mode = WAL");
|
|
1567
|
-
db.exec("PRAGMA foreign_keys = ON");
|
|
1568
|
-
db.exec(`
|
|
1569
|
-
CREATE TABLE IF NOT EXISTS runs (
|
|
1570
|
-
id TEXT PRIMARY KEY,
|
|
1571
|
-
graph_name TEXT NOT NULL,
|
|
1572
|
-
graph_version TEXT NOT NULL,
|
|
1573
|
-
status TEXT NOT NULL,
|
|
1574
|
-
attempts INTEGER NOT NULL DEFAULT 0,
|
|
1575
|
-
context_json TEXT NOT NULL,
|
|
1576
|
-
result_json TEXT,
|
|
1577
|
-
error TEXT,
|
|
1578
|
-
started_at TEXT,
|
|
1579
|
-
finished_at TEXT,
|
|
1580
|
-
created_at TEXT NOT NULL,
|
|
1581
|
-
updated_at TEXT NOT NULL
|
|
1582
|
-
);
|
|
1583
|
-
CREATE TABLE IF NOT EXISTS run_nodes (
|
|
1584
|
-
id TEXT PRIMARY KEY,
|
|
1585
|
-
run_id TEXT NOT NULL REFERENCES runs(id) ON DELETE CASCADE,
|
|
1586
|
-
node_id TEXT NOT NULL,
|
|
1587
|
-
status TEXT NOT NULL,
|
|
1588
|
-
attempts INTEGER NOT NULL DEFAULT 0,
|
|
1589
|
-
lane TEXT,
|
|
1590
|
-
exit_code INTEGER,
|
|
1591
|
-
output_json TEXT,
|
|
1592
|
-
error TEXT,
|
|
1593
|
-
started_at TEXT,
|
|
1594
|
-
finished_at TEXT
|
|
1595
|
-
);
|
|
1596
|
-
CREATE TABLE IF NOT EXISTS memos (
|
|
1597
|
-
key TEXT PRIMARY KEY,
|
|
1598
|
-
graph_name TEXT NOT NULL,
|
|
1599
|
-
node_id TEXT NOT NULL,
|
|
1600
|
-
input_hash TEXT NOT NULL,
|
|
1601
|
-
output_json TEXT NOT NULL,
|
|
1602
|
-
hit_count INTEGER NOT NULL DEFAULT 0,
|
|
1603
|
-
created_at TEXT NOT NULL
|
|
1604
|
-
);
|
|
1605
|
-
CREATE INDEX IF NOT EXISTS idx_runs_status ON runs(status);
|
|
1606
|
-
CREATE INDEX IF NOT EXISTS idx_runs_created ON runs(created_at);
|
|
1607
|
-
CREATE INDEX IF NOT EXISTS idx_run_nodes_run ON run_nodes(run_id);
|
|
1608
|
-
`);
|
|
1609
|
-
const rowToRun = (r) => ({
|
|
1610
|
-
id: String(r.id),
|
|
1611
|
-
graphName: String(r.graph_name),
|
|
1612
|
-
graphVersion: String(r.graph_version),
|
|
1613
|
-
status: r.status,
|
|
1614
|
-
attempts: Number(r.attempts),
|
|
1615
|
-
contextJson: String(r.context_json),
|
|
1616
|
-
resultJson: r.result_json === null ? null : String(r.result_json),
|
|
1617
|
-
error: r.error === null ? null : String(r.error),
|
|
1618
|
-
startedAt: r.started_at === null ? null : String(r.started_at),
|
|
1619
|
-
finishedAt: r.finished_at === null ? null : String(r.finished_at),
|
|
1620
|
-
createdAt: String(r.created_at),
|
|
1621
|
-
updatedAt: String(r.updated_at)
|
|
1622
|
-
});
|
|
1623
|
-
const rowToNode = (r) => ({
|
|
1624
|
-
id: String(r.id),
|
|
1625
|
-
runId: String(r.run_id),
|
|
1626
|
-
nodeId: String(r.node_id),
|
|
1627
|
-
status: r.status,
|
|
1628
|
-
attempts: Number(r.attempts),
|
|
1629
|
-
lane: r.lane === null ? null : String(r.lane),
|
|
1630
|
-
exitCode: r.exit_code === null ? null : Number(r.exit_code),
|
|
1631
|
-
outputJson: r.output_json === null ? null : String(r.output_json),
|
|
1632
|
-
error: r.error === null ? null : String(r.error),
|
|
1633
|
-
startedAt: r.started_at === null ? null : String(r.started_at),
|
|
1634
|
-
finishedAt: r.finished_at === null ? null : String(r.finished_at)
|
|
1635
|
-
});
|
|
1636
|
-
const rowToMemo = (r) => ({
|
|
1637
|
-
key: String(r.key),
|
|
1638
|
-
graphName: String(r.graph_name),
|
|
1639
|
-
nodeId: String(r.node_id),
|
|
1640
|
-
inputHash: String(r.input_hash),
|
|
1641
|
-
outputJson: String(r.output_json),
|
|
1642
|
-
hitCount: Number(r.hit_count),
|
|
1643
|
-
createdAt: String(r.created_at)
|
|
1644
|
-
});
|
|
1645
1620
|
return {
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
db.query(`INSERT INTO runs (id, graph_name, graph_version, status, attempts, context_json, created_at, updated_at)
|
|
1657
|
-
VALUES (?, ?, ?, 'pending', 0, ?, ?, ?)`).run(id, input.graphName, input.graphVersion, JSON.stringify(input.context ?? {}), now, now);
|
|
1658
|
-
return this.getRun(id);
|
|
1659
|
-
},
|
|
1660
|
-
getRun(id) {
|
|
1661
|
-
const row = db.query(`SELECT * FROM runs WHERE id = ?`).get(id);
|
|
1662
|
-
return row ? rowToRun(row) : undefined;
|
|
1663
|
-
},
|
|
1664
|
-
listRuns(opts = {}) {
|
|
1665
|
-
const limit = Math.min(opts.limit ?? 100, 1000);
|
|
1666
|
-
if (opts.status) {
|
|
1667
|
-
const rows2 = db.query(`SELECT * FROM runs WHERE status = ? ORDER BY created_at DESC, id DESC LIMIT ?`).all(opts.status, limit);
|
|
1668
|
-
return rows2.map((r) => rowToRun(r));
|
|
1669
|
-
}
|
|
1670
|
-
const rows = db.query(`SELECT * FROM runs ORDER BY created_at DESC, id DESC LIMIT ?`).all(limit);
|
|
1671
|
-
return rows.map((r) => rowToRun(r));
|
|
1672
|
-
},
|
|
1673
|
-
setRunStatus(id, status, patch = {}) {
|
|
1674
|
-
const now = nowIso2();
|
|
1675
|
-
const existing = this.getRun(id);
|
|
1676
|
-
const resultJson = patch.result !== undefined ? JSON.stringify(patch.result) : existing?.resultJson ?? null;
|
|
1677
|
-
const error = patch.error !== undefined ? patch.error : existing?.error ?? null;
|
|
1678
|
-
const startedAt = patch.startedAt !== undefined ? patch.startedAt : status === "running" && existing?.startedAt === null ? now : existing?.startedAt ?? null;
|
|
1679
|
-
const terminal = status === "completed" || status === "failed" || status === "cancelled" || status === "interrupted";
|
|
1680
|
-
const finishedAt = patch.finishedAt !== undefined ? patch.finishedAt : terminal && existing?.finishedAt === null ? now : existing?.finishedAt ?? null;
|
|
1681
|
-
db.query(`UPDATE runs SET status = ?, result_json = ?, error = ?, started_at = ?, finished_at = ?, updated_at = ? WHERE id = ?`).run(status, resultJson, error, startedAt, finishedAt, now, id);
|
|
1682
|
-
},
|
|
1683
|
-
bumpAttempts(id) {
|
|
1684
|
-
db.query(`UPDATE runs SET attempts = attempts + 1, updated_at = ? WHERE id = ?`).run(nowIso2(), id);
|
|
1685
|
-
},
|
|
1686
|
-
setRunContext(id, context) {
|
|
1687
|
-
db.query(`UPDATE runs SET context_json = ?, updated_at = ? WHERE id = ?`).run(JSON.stringify(context), nowIso2(), id);
|
|
1688
|
-
},
|
|
1689
|
-
createRunNode(input) {
|
|
1690
|
-
const id = randomUUID();
|
|
1691
|
-
db.query(`INSERT INTO run_nodes (id, run_id, node_id, status, attempts, lane)
|
|
1692
|
-
VALUES (?, ?, ?, 'pending', 0, ?)`).run(id, input.runId, input.nodeId, input.lane ?? null);
|
|
1693
|
-
return this.getRunNode(id);
|
|
1694
|
-
},
|
|
1695
|
-
getRunNode(id) {
|
|
1696
|
-
const row = db.query(`SELECT * FROM run_nodes WHERE id = ?`).get(id);
|
|
1697
|
-
return row ? rowToNode(row) : undefined;
|
|
1698
|
-
},
|
|
1699
|
-
listRunNodes(runId) {
|
|
1700
|
-
const rows = db.query(`SELECT * FROM run_nodes WHERE run_id = ? ORDER BY rowid ASC`).all(runId);
|
|
1701
|
-
return rows.map((r) => rowToNode(r));
|
|
1702
|
-
},
|
|
1703
|
-
setRunNodeStatus(id, status, patch = {}) {
|
|
1704
|
-
const now = nowIso2();
|
|
1705
|
-
const existing = this.getRunNode(id);
|
|
1706
|
-
if (!existing)
|
|
1707
|
-
return;
|
|
1708
|
-
const exitCode = patch.exitCode !== undefined ? patch.exitCode : existing.exitCode;
|
|
1709
|
-
const outputJson = patch.output !== undefined ? JSON.stringify(patch.output) : existing.outputJson;
|
|
1710
|
-
const error = patch.error !== undefined ? patch.error : existing.error;
|
|
1711
|
-
const startedAt = patch.startedAt !== undefined ? patch.startedAt : status === "running" && existing.startedAt === null ? now : existing.startedAt;
|
|
1712
|
-
const terminal = status === "completed" || status === "failed" || status === "skipped";
|
|
1713
|
-
const finishedAt = patch.finishedAt !== undefined ? patch.finishedAt : terminal && existing.finishedAt === null ? now : existing.finishedAt;
|
|
1714
|
-
db.query(`UPDATE run_nodes SET status = ?, exit_code = ?, output_json = ?, error = ?, started_at = ?, finished_at = ? WHERE id = ?`).run(status, exitCode, outputJson, error, startedAt, finishedAt, id);
|
|
1715
|
-
},
|
|
1716
|
-
bumpAttemptsNode(id) {
|
|
1717
|
-
db.query(`UPDATE run_nodes SET attempts = attempts + 1 WHERE id = ?`).run(id);
|
|
1718
|
-
},
|
|
1719
|
-
memoPut(key, graphName, nodeId, inputHash2, outputJson) {
|
|
1720
|
-
db.query(`INSERT INTO memos (key, graph_name, node_id, input_hash, output_json, hit_count, created_at)
|
|
1721
|
-
VALUES (?, ?, ?, ?, ?, 0, ?)
|
|
1722
|
-
ON CONFLICT(key) DO UPDATE SET output_json = excluded.output_json`).run(key, graphName, nodeId, inputHash2, outputJson, nowIso2());
|
|
1621
|
+
resolution: {
|
|
1622
|
+
transport: "http",
|
|
1623
|
+
transportSource: urlHit.key,
|
|
1624
|
+
baseUrl,
|
|
1625
|
+
apiUrlSource,
|
|
1626
|
+
apiKeyPresent: true,
|
|
1627
|
+
apiKeySource: credential.source,
|
|
1628
|
+
apiKeyTier: credential.tier,
|
|
1629
|
+
misconfigured: false,
|
|
1630
|
+
warning: warnings.length > 0 ? warnings.join(" ") : null
|
|
1723
1631
|
},
|
|
1724
|
-
|
|
1725
|
-
const row = db.query(`SELECT * FROM memos WHERE key = ?`).get(key);
|
|
1726
|
-
return row ? rowToMemo(row) : undefined;
|
|
1727
|
-
},
|
|
1728
|
-
memoHit(key) {
|
|
1729
|
-
db.query(`UPDATE memos SET hit_count = hit_count + 1 WHERE key = ?`).run(key);
|
|
1730
|
-
},
|
|
1731
|
-
memoList() {
|
|
1732
|
-
const rows = db.query(`SELECT * FROM memos ORDER BY created_at DESC LIMIT 1000`).all();
|
|
1733
|
-
return rows.map((r) => rowToMemo(r));
|
|
1734
|
-
},
|
|
1735
|
-
memoClear() {
|
|
1736
|
-
db.exec(`DELETE FROM memos`);
|
|
1737
|
-
}
|
|
1632
|
+
credential
|
|
1738
1633
|
};
|
|
1739
1634
|
}
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
import { appendFileSync, existsSync, mkdirSync as mkdirSync2, readFileSync, renameSync, truncateSync, writeFileSync } from "fs";
|
|
1744
|
-
import { join as join2 } from "path";
|
|
1745
|
-
var WAL_FILE_NAME = "session.wal";
|
|
1746
|
-
var SESSIONS_DIR_NAME = "sessions";
|
|
1747
|
-
var MAX_WAL_BYTES = 256 * 1024 * 1024;
|
|
1748
|
-
function checksumOf(op) {
|
|
1749
|
-
if (op === undefined || op === null)
|
|
1750
|
-
return "";
|
|
1751
|
-
return createHash3("sha256").update(JSON.stringify(op)).digest("hex");
|
|
1635
|
+
function credentialDiskSourcesForMessage(name, env) {
|
|
1636
|
+
const paths = credentialDiskSources(name, env);
|
|
1637
|
+
return paths.length > 0 ? paths.join(" or ") : "<no HOME or HASNA_HOME set in this environment, so no credential file was consulted>";
|
|
1752
1638
|
}
|
|
1753
1639
|
|
|
1754
|
-
class
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
const
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1640
|
+
class HasnaHttpError extends Error {
|
|
1641
|
+
status;
|
|
1642
|
+
method;
|
|
1643
|
+
path;
|
|
1644
|
+
credentialSource;
|
|
1645
|
+
credentialTier;
|
|
1646
|
+
constructor(method, path, status, body, credential) {
|
|
1647
|
+
const guidance = credential ? `. ${credential.guidance}` : "";
|
|
1648
|
+
super(`Hasna cloud request failed: ${method} ${path} -> ${status}${guidance}`);
|
|
1649
|
+
this.name = "HasnaHttpError";
|
|
1650
|
+
this.status = status;
|
|
1651
|
+
this.method = method;
|
|
1652
|
+
this.path = path;
|
|
1653
|
+
Object.defineProperty(this, "body", {
|
|
1654
|
+
value: body,
|
|
1655
|
+
enumerable: status !== 401 && status !== 403,
|
|
1656
|
+
writable: false,
|
|
1657
|
+
configurable: false
|
|
1658
|
+
});
|
|
1659
|
+
this.credentialSource = credential?.source ?? null;
|
|
1660
|
+
this.credentialTier = credential?.tier ?? null;
|
|
1661
|
+
}
|
|
1662
|
+
}
|
|
1663
|
+
function currentCredential(name, apiKey) {
|
|
1664
|
+
if (typeof apiKey === "function") {
|
|
1665
|
+
return validateAndSealResolvedCredential(name, apiKey());
|
|
1666
|
+
}
|
|
1667
|
+
return explicitCredential(name, apiKey);
|
|
1668
|
+
}
|
|
1669
|
+
async function resolveRequestCredential(name, apiKey, env = process.env) {
|
|
1670
|
+
const resolved = currentCredential(name, apiKey);
|
|
1671
|
+
if (resolved.tier === "pointer") {
|
|
1672
|
+
return completePointerCredential(name, resolved, env);
|
|
1673
|
+
}
|
|
1674
|
+
return resolved;
|
|
1675
|
+
}
|
|
1676
|
+
function authFailureGuidance(credential) {
|
|
1677
|
+
const origin = `The API key for this request came from ${credential.source}`;
|
|
1678
|
+
if (credential.deliberate) {
|
|
1679
|
+
const remedy = credential.source === CALLER_SUPPLIED_CREDENTIAL_PROVIDER_SOURCE ? `Fix that provider so it returns the current key, or replace it with resolveCredential() ` + `so diagnostics can name the original source.` : `Rotate that key, or unset the override to use the credential on disk.`;
|
|
1680
|
+
return `${origin} \u2014 a credential you selected deliberately. It was NOT substituted with any other key: ` + `falling back here would authenticate as a different principal than the one you named, which is ` + `exactly the failure an override exists to prevent. ${remedy}`;
|
|
1681
|
+
}
|
|
1682
|
+
if (credential.tier === "env") {
|
|
1683
|
+
const target = credential.diskCandidates[0];
|
|
1684
|
+
const remedy = target ? `Store the CURRENT key in the Keychain or write it to ${target} \u2014 both are re-read on every call, so ` + `rotations take effect immediately and in every shell. Do not simply unset ${credential.source}: ` + `nothing was found in the Keychain or on disk, so that would leave this client with no credential at all.` : `This environment has no HOME or HASNA_HOME, so no credential file could be consulted; the disk tier is ` + `unavailable here and there is nothing to fall back to. Set HOME, or supply the key explicitly.`;
|
|
1685
|
+
return `${origin}, a variable in this process's environment. If a wrapper injected it for this one process, the ` + `wrapper re-reads its store on every invocation and the stored key itself is being rejected \u2014 rotate it. ` + `If this SHELL exported it, the export is a snapshot taken when the shell started: a STALE SHELL that ` + `exported the key before it was rotated keeps sending the old one until it exits. ${remedy}`;
|
|
1686
|
+
}
|
|
1687
|
+
if (credential.tier === "keychain") {
|
|
1688
|
+
return `${origin}, which was re-read from the Keychain on this very call \u2014 so a stale shell is NOT the cause ` + `here. The stored item is genuinely being rejected: update it with the current key, or re-run the fleet ` + `key distribution so this machine gets the current key.`;
|
|
1689
|
+
}
|
|
1690
|
+
return `${origin}, which was re-read from disk on this very call \u2014 so a stale shell is NOT the cause here. ` + `The stored credential is genuinely being rejected: rotate it, or re-run the fleet key distribution ` + `so this machine gets the current key.`;
|
|
1691
|
+
}
|
|
1692
|
+
var DEFAULT_RETRY_STATUSES = [408, 425, 429, 500, 502, 503, 504];
|
|
1693
|
+
var IDEMPOTENT_METHODS = new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]);
|
|
1694
|
+
var AUTHORITY_OVERRIDE_HEADERS = new Set([
|
|
1695
|
+
"host",
|
|
1696
|
+
":authority",
|
|
1697
|
+
"forwarded",
|
|
1698
|
+
"x-forwarded-host",
|
|
1699
|
+
"x-original-host"
|
|
1700
|
+
]);
|
|
1701
|
+
function assertNoAuthorityOverrideHeaders(headers, source) {
|
|
1702
|
+
if (!headers)
|
|
1703
|
+
return;
|
|
1704
|
+
const forbidden = Object.keys(headers).find((name) => AUTHORITY_OVERRIDE_HEADERS.has(name.trim().toLowerCase()));
|
|
1705
|
+
if (forbidden) {
|
|
1706
|
+
throw new Error(`Authenticated ${source} headers must not set authority header '${forbidden}'.`);
|
|
1707
|
+
}
|
|
1708
|
+
}
|
|
1709
|
+
function appendQuery(path, query) {
|
|
1710
|
+
if (!query)
|
|
1711
|
+
return path;
|
|
1712
|
+
const params = query instanceof URLSearchParams ? query : new URLSearchParams;
|
|
1713
|
+
if (!(query instanceof URLSearchParams)) {
|
|
1714
|
+
for (const [key, value] of Object.entries(query)) {
|
|
1715
|
+
if (value === null || value === undefined)
|
|
1716
|
+
continue;
|
|
1717
|
+
if (Array.isArray(value)) {
|
|
1718
|
+
for (const v of value)
|
|
1719
|
+
params.append(key, String(v));
|
|
1720
|
+
} else {
|
|
1721
|
+
params.append(key, String(value));
|
|
1768
1722
|
}
|
|
1769
1723
|
}
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
return
|
|
1774
|
-
}
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1724
|
+
}
|
|
1725
|
+
const qs = params.toString();
|
|
1726
|
+
if (!qs)
|
|
1727
|
+
return path;
|
|
1728
|
+
return `${path}${path.includes("?") ? "&" : "?"}${qs}`;
|
|
1729
|
+
}
|
|
1730
|
+
var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
1731
|
+
function createHasnaHttpTransportInternal(options, requestBindingProvider) {
|
|
1732
|
+
const fetchImpl = options.fetchImpl ?? ((input, init) => fetch(input, init));
|
|
1733
|
+
const base = toV1BaseUrl(options.baseUrl);
|
|
1734
|
+
const timeoutMs = options.timeoutMs ?? 30000;
|
|
1735
|
+
const sleep = options.sleepImpl ?? defaultSleep;
|
|
1736
|
+
const defaultRetry = options.retry;
|
|
1737
|
+
function resolveRetry(callRetry) {
|
|
1738
|
+
const chosen = callRetry !== undefined ? callRetry : defaultRetry;
|
|
1739
|
+
if (chosen === false)
|
|
1740
|
+
return null;
|
|
1741
|
+
const r2 = chosen ?? {};
|
|
1742
|
+
return {
|
|
1743
|
+
retries: r2.retries ?? 2,
|
|
1744
|
+
baseDelayMs: r2.baseDelayMs ?? 200,
|
|
1745
|
+
maxDelayMs: r2.maxDelayMs ?? 2000,
|
|
1746
|
+
retryStatuses: r2.retryStatuses ?? [...DEFAULT_RETRY_STATUSES]
|
|
1747
|
+
};
|
|
1748
|
+
}
|
|
1749
|
+
async function once(method, rel, body, opts, bind) {
|
|
1750
|
+
const materializeHeaders = (input) => Object.fromEntries(Object.entries(input ?? {}).map(([key, value]) => [key, String(value)]));
|
|
1751
|
+
const transportHeaders = materializeHeaders(options.headers);
|
|
1752
|
+
const requestHeaders = materializeHeaders(opts.headers);
|
|
1753
|
+
assertNoAuthorityOverrideHeaders(transportHeaders, "transport");
|
|
1754
|
+
assertNoAuthorityOverrideHeaders(requestHeaders, "request");
|
|
1755
|
+
const headers = {
|
|
1756
|
+
Accept: "application/json",
|
|
1757
|
+
...transportHeaders,
|
|
1758
|
+
...requestHeaders
|
|
1759
|
+
};
|
|
1760
|
+
const idempotencyKey = opts.idempotencyKey;
|
|
1761
|
+
if (idempotencyKey)
|
|
1762
|
+
headers["Idempotency-Key"] = String(idempotencyKey);
|
|
1763
|
+
const init = {
|
|
1764
|
+
method,
|
|
1765
|
+
headers,
|
|
1766
|
+
redirect: "manual"
|
|
1767
|
+
};
|
|
1768
|
+
if (body !== undefined) {
|
|
1769
|
+
headers["Content-Type"] = "application/json";
|
|
1770
|
+
init.body = JSON.stringify(body);
|
|
1771
|
+
}
|
|
1772
|
+
const controller = new AbortController;
|
|
1773
|
+
const onAbort = () => controller.abort();
|
|
1774
|
+
const callerSignal = opts.signal;
|
|
1775
|
+
if (callerSignal) {
|
|
1776
|
+
if (callerSignal.aborted)
|
|
1777
|
+
controller.abort();
|
|
1778
|
+
else
|
|
1779
|
+
callerSignal.addEventListener("abort", onAbort, { once: true });
|
|
1780
|
+
}
|
|
1781
|
+
const timer = setTimeout(() => controller.abort(), opts.timeoutMs ?? timeoutMs);
|
|
1782
|
+
init.signal = controller.signal;
|
|
1783
|
+
let response;
|
|
1784
|
+
let credential;
|
|
1793
1785
|
try {
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
if (content === "") {
|
|
1802
|
-
return { entries, torn, repaired, liveClaims: () => new Map };
|
|
1803
|
-
}
|
|
1804
|
-
const lines = content.split(`
|
|
1805
|
-
`);
|
|
1806
|
-
let badOffset = null;
|
|
1807
|
-
let expectedSeq = 1;
|
|
1808
|
-
for (let i = 0;i < lines.length; i++) {
|
|
1809
|
-
const line = lines[i];
|
|
1810
|
-
if (line === "")
|
|
1811
|
-
continue;
|
|
1812
|
-
if (badOffset !== null)
|
|
1813
|
-
break;
|
|
1814
|
-
const lineOffset = cumulativeOffset(lines, i);
|
|
1815
|
-
let entry;
|
|
1786
|
+
const binding = bind();
|
|
1787
|
+
credential = binding.credential;
|
|
1788
|
+
init.headers = {
|
|
1789
|
+
"x-api-key": credential.apiKey,
|
|
1790
|
+
Authorization: `Bearer ${credential.apiKey}`,
|
|
1791
|
+
...headers
|
|
1792
|
+
};
|
|
1816
1793
|
try {
|
|
1817
|
-
|
|
1818
|
-
} catch {
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
badOffset = lineOffset;
|
|
1824
|
-
break;
|
|
1794
|
+
response = await fetchImpl(`${binding.baseUrl}${rel}`, init);
|
|
1795
|
+
} catch (error) {
|
|
1796
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
1797
|
+
if (callerSignal?.aborted)
|
|
1798
|
+
return { ok: false, retryable: false, error: err };
|
|
1799
|
+
return { ok: false, retryable: true, error: err };
|
|
1825
1800
|
}
|
|
1826
|
-
|
|
1827
|
-
|
|
1801
|
+
} finally {
|
|
1802
|
+
clearTimeout(timer);
|
|
1803
|
+
if (callerSignal)
|
|
1804
|
+
callerSignal.removeEventListener("abort", onAbort);
|
|
1828
1805
|
}
|
|
1829
|
-
|
|
1830
|
-
|
|
1806
|
+
const authenticationFailure = response.status === 401 || response.status === 403;
|
|
1807
|
+
let parsed = undefined;
|
|
1808
|
+
if (authenticationFailure) {
|
|
1831
1809
|
try {
|
|
1832
|
-
|
|
1833
|
-
repaired = true;
|
|
1810
|
+
await response.body?.cancel();
|
|
1834
1811
|
} catch {}
|
|
1812
|
+
} else {
|
|
1813
|
+
const text = await response.text();
|
|
1814
|
+
if (text.length > 0) {
|
|
1815
|
+
try {
|
|
1816
|
+
parsed = JSON.parse(text);
|
|
1817
|
+
} catch {
|
|
1818
|
+
parsed = text;
|
|
1819
|
+
}
|
|
1820
|
+
}
|
|
1835
1821
|
}
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
for (const entry of entries) {
|
|
1855
|
-
const op = entry.op;
|
|
1856
|
-
if (op.op === "claim_acquired") {
|
|
1857
|
-
claims.set(op.runId, { worker: op.worker, fencing: op.fencing, expiresAtMs: Date.parse(op.expiresAt) });
|
|
1858
|
-
} else if (op.op === "claim_released") {
|
|
1859
|
-
const existing = claims.get(op.runId);
|
|
1860
|
-
if (existing && existing.fencing === op.fencing) {
|
|
1861
|
-
claims.delete(op.runId);
|
|
1822
|
+
if (!response.ok) {
|
|
1823
|
+
if (response.status >= 300 && response.status < 400) {
|
|
1824
|
+
return {
|
|
1825
|
+
ok: false,
|
|
1826
|
+
retryable: false,
|
|
1827
|
+
error: new HasnaHttpError(method, rel, response.status, parsed)
|
|
1828
|
+
};
|
|
1829
|
+
}
|
|
1830
|
+
if (authenticationFailure) {
|
|
1831
|
+
return {
|
|
1832
|
+
ok: false,
|
|
1833
|
+
retryable: false,
|
|
1834
|
+
error: new HasnaHttpError(method, rel, response.status, undefined, {
|
|
1835
|
+
source: credential.source,
|
|
1836
|
+
tier: credential.tier,
|
|
1837
|
+
guidance: authFailureGuidance(credential)
|
|
1838
|
+
})
|
|
1839
|
+
};
|
|
1862
1840
|
}
|
|
1841
|
+
const retry = resolveRetry(opts.retry);
|
|
1842
|
+
const retryable = retry ? retry.retryStatuses.includes(response.status) : false;
|
|
1843
|
+
return { ok: false, retryable, error: new HasnaHttpError(method, rel, response.status, parsed) };
|
|
1844
|
+
}
|
|
1845
|
+
return { ok: true, value: parsed };
|
|
1846
|
+
}
|
|
1847
|
+
async function request(method, path, body, opts = {}) {
|
|
1848
|
+
const upper = method.toUpperCase();
|
|
1849
|
+
const rel = appendQuery(path.startsWith("/") ? path : `/${path}`, opts.query);
|
|
1850
|
+
const retry = resolveRetry(opts.retry);
|
|
1851
|
+
const methodRetryable = IDEMPOTENT_METHODS.has(upper) || Boolean(opts.idempotencyKey);
|
|
1852
|
+
const maxAttempts = retry && methodRetryable ? retry.retries + 1 : 1;
|
|
1853
|
+
let finalize;
|
|
1854
|
+
if (requestBindingProvider) {
|
|
1855
|
+
const prepared = requestBindingProvider();
|
|
1856
|
+
finalize = typeof prepared === "function" ? prepared : await prepared;
|
|
1857
|
+
} else {
|
|
1858
|
+
const credential = await resolveRequestCredential(options.name, options.apiKey);
|
|
1859
|
+
finalize = () => ({ baseUrl: base, credential });
|
|
1860
|
+
}
|
|
1861
|
+
let binding;
|
|
1862
|
+
const bind = () => binding ??= finalize();
|
|
1863
|
+
let last = null;
|
|
1864
|
+
for (let attempt = 1;attempt <= maxAttempts; attempt++) {
|
|
1865
|
+
const result = await once(upper, rel, body, opts, bind);
|
|
1866
|
+
if (result.ok)
|
|
1867
|
+
return result.value;
|
|
1868
|
+
last = result;
|
|
1869
|
+
const canRetry = retry !== null && methodRetryable && result.retryable && attempt < maxAttempts;
|
|
1870
|
+
if (!canRetry)
|
|
1871
|
+
break;
|
|
1872
|
+
const backoff = Math.min(retry.maxDelayMs, retry.baseDelayMs * 2 ** (attempt - 1));
|
|
1873
|
+
const jitter = Math.floor(Math.random() * (backoff / 2 + 1));
|
|
1874
|
+
await sleep(backoff + jitter);
|
|
1863
1875
|
}
|
|
1876
|
+
throw last.error;
|
|
1864
1877
|
}
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
return { content: [{ type: "text", text: JSON.stringify(payload) }], isError: false };
|
|
1878
|
+
return {
|
|
1879
|
+
baseUrl: base,
|
|
1880
|
+
request,
|
|
1881
|
+
get: (path, opts) => request("GET", path, undefined, opts),
|
|
1882
|
+
post: (path, body, opts) => request("POST", path, body, opts),
|
|
1883
|
+
put: (path, body, opts) => request("PUT", path, body, opts),
|
|
1884
|
+
patch: (path, body, opts) => request("PATCH", path, body, opts),
|
|
1885
|
+
del: (path, body, opts) => request("DELETE", path, body, opts)
|
|
1886
|
+
};
|
|
1875
1887
|
}
|
|
1876
|
-
function
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
{
|
|
1889
|
-
name: "workflows_ready",
|
|
1890
|
-
description: "Report the workflows service readiness (version check).",
|
|
1891
|
-
inputSchema: { type: "object", properties: {} }
|
|
1892
|
-
},
|
|
1893
|
-
{
|
|
1894
|
-
name: "workflows_validate",
|
|
1895
|
-
description: "Validate a workflow graph (JSON object with name, version, nodes).",
|
|
1896
|
-
inputSchema: {
|
|
1897
|
-
type: "object",
|
|
1898
|
-
properties: { graph: { type: "object", description: "the workflow graph" } },
|
|
1899
|
-
required: ["graph"]
|
|
1900
|
-
}
|
|
1901
|
-
},
|
|
1902
|
-
{
|
|
1903
|
-
name: "workflows_run",
|
|
1904
|
-
description: "Run a workflow graph to a terminal state (bounded cycles; command steps execute; lane steps need the lane substrate).",
|
|
1905
|
-
inputSchema: {
|
|
1906
|
-
type: "object",
|
|
1907
|
-
properties: {
|
|
1908
|
-
graph: { type: "object", description: "the workflow graph" },
|
|
1909
|
-
context: { type: "object", description: "optional run context" }
|
|
1910
|
-
},
|
|
1911
|
-
required: ["graph"]
|
|
1912
|
-
}
|
|
1913
|
-
},
|
|
1914
|
-
{
|
|
1915
|
-
name: "workflows_runs_list",
|
|
1916
|
-
description: "List recent runs from the local store.",
|
|
1917
|
-
inputSchema: {
|
|
1918
|
-
type: "object",
|
|
1919
|
-
properties: {
|
|
1920
|
-
status: { type: "string", description: "optional status filter" },
|
|
1921
|
-
limit: { type: "number", description: "max rows (default 100)" }
|
|
1922
|
-
}
|
|
1923
|
-
}
|
|
1924
|
-
},
|
|
1925
|
-
{
|
|
1926
|
-
name: "workflows_lanes_list",
|
|
1927
|
-
description: "List the four lane adapters with their wired-vs-not-ready-with-reason registry shape.",
|
|
1928
|
-
inputSchema: { type: "object", properties: {} }
|
|
1888
|
+
function createClientTransport(name, env = process.env, overrides) {
|
|
1889
|
+
const credentialOptions = overrides?.credentials;
|
|
1890
|
+
const snapshotOptions = {
|
|
1891
|
+
...credentialOptions ? { credentials: credentialOptions } : {},
|
|
1892
|
+
...overrides?.bindUnpairedCredentialsToFleet === undefined ? {} : { bindUnpairedCredentialsToFleet: overrides.bindUnpairedCredentialsToFleet }
|
|
1893
|
+
};
|
|
1894
|
+
const resolution = resolveClientTransportSnapshot(name, env, snapshotOptions).resolution;
|
|
1895
|
+
const sameBinding = (left, right) => left.resolution.baseUrl === right.resolution.baseUrl && left.credential.apiKey === right.credential.apiKey && left.credential.pointerVaultKey === right.credential.pointerVaultKey && left.credential.source === right.credential.source && left.credential.tier === right.credential.tier;
|
|
1896
|
+
const unstableConfiguration = () => new ClientTransportConfigurationError(name, "The configured service authority or credential changed while a request was being prepared; no authenticated request was sent.");
|
|
1897
|
+
const assertPinnedAuthority = (snapshot) => {
|
|
1898
|
+
if (snapshot.resolution.baseUrl !== resolution.baseUrl) {
|
|
1899
|
+
throw new ClientTransportConfigurationError(name, "The configured service authority changed; rebuild the client before sending credentials.");
|
|
1929
1900
|
}
|
|
1930
|
-
|
|
1901
|
+
};
|
|
1902
|
+
const requestBindingProvider = () => {
|
|
1903
|
+
const first = resolveClientTransportSnapshot(name, env, snapshotOptions);
|
|
1904
|
+
assertPinnedAuthority(first);
|
|
1905
|
+
const finalize = (reviewed2, completed) => () => {
|
|
1906
|
+
const final = resolveClientTransportSnapshot(name, env, snapshotOptions);
|
|
1907
|
+
if (!sameBinding(reviewed2, final))
|
|
1908
|
+
throw unstableConfiguration();
|
|
1909
|
+
assertPinnedAuthority(final);
|
|
1910
|
+
return {
|
|
1911
|
+
baseUrl: final.resolution.baseUrl,
|
|
1912
|
+
credential: completed ?? currentCredential(name, () => final.credential)
|
|
1913
|
+
};
|
|
1914
|
+
};
|
|
1915
|
+
if (first.credential.tier !== "pointer")
|
|
1916
|
+
return finalize(first);
|
|
1917
|
+
const reviewed = resolveClientTransportSnapshot(name, env, snapshotOptions);
|
|
1918
|
+
if (!sameBinding(first, reviewed))
|
|
1919
|
+
throw unstableConfiguration();
|
|
1920
|
+
assertPinnedAuthority(reviewed);
|
|
1921
|
+
return resolveRequestCredential(name, () => reviewed.credential, env).then((credential) => finalize(reviewed, credential));
|
|
1922
|
+
};
|
|
1923
|
+
return {
|
|
1924
|
+
transport: "http",
|
|
1925
|
+
client: createHasnaHttpTransportInternal({
|
|
1926
|
+
name,
|
|
1927
|
+
baseUrl: resolution.baseUrl,
|
|
1928
|
+
apiKey: () => {
|
|
1929
|
+
throw new Error("The authenticated request binding provider was not invoked.");
|
|
1930
|
+
},
|
|
1931
|
+
...overrides?.fetchImpl ? { fetchImpl: overrides.fetchImpl } : {},
|
|
1932
|
+
...overrides?.headers ? { headers: overrides.headers } : {},
|
|
1933
|
+
...overrides?.timeoutMs ? { timeoutMs: overrides.timeoutMs } : {},
|
|
1934
|
+
...overrides?.retry !== undefined ? { retry: overrides.retry } : {},
|
|
1935
|
+
...overrides?.sleepImpl ? { sleepImpl: overrides.sleepImpl } : {}
|
|
1936
|
+
}, requestBindingProvider),
|
|
1937
|
+
resolution
|
|
1938
|
+
};
|
|
1931
1939
|
}
|
|
1932
|
-
|
|
1940
|
+
|
|
1941
|
+
// src/client-error.ts
|
|
1942
|
+
class WorkflowInputError extends Error {
|
|
1943
|
+
}
|
|
1944
|
+
var guidance = {
|
|
1945
|
+
invalid_graph: "graph must match the workflow graph schema; use workflows validate <file>",
|
|
1946
|
+
graph_required: "body.graph must be a workflow graph object",
|
|
1947
|
+
invalid_context: "context must be a JSON object",
|
|
1948
|
+
reserved_context: "context.__wf and context.steps are reserved",
|
|
1949
|
+
invalid_max_cycles: "maxCycles must be an integer from 1 to 2000",
|
|
1950
|
+
invalid_idempotency_key: "idempotencyKey must contain 1 to 128 ASCII letters, digits, or _.:-",
|
|
1951
|
+
invalid_query: "limit must be 1 to 1000 and status must be a supported run status",
|
|
1952
|
+
invalid_run_id: "run id must contain 1 to 128 ASCII letters, digits, underscores or hyphens",
|
|
1953
|
+
invalid_lane: "lane must be claude, codex, cursor or grok",
|
|
1954
|
+
run_not_found: "run id does not exist",
|
|
1955
|
+
idempotency_conflict: "idempotencyKey is already bound to a different request",
|
|
1956
|
+
invalid_run_status: "run status does not permit this action",
|
|
1957
|
+
run_status_conflict: "run changed before this action",
|
|
1958
|
+
execution_active: "previous execution must finish or be reconciled before resume",
|
|
1959
|
+
graph_unavailable: "legacy run requires its original graph from the server operator",
|
|
1960
|
+
invalid_schema: "PostgreSQL workflow schema requires explicit initialization or a reviewed migration",
|
|
1961
|
+
storage_unavailable: "PostgreSQL workflow storage is unavailable"
|
|
1962
|
+
};
|
|
1963
|
+
function workflowErrorMessage(error) {
|
|
1964
|
+
if (error instanceof WorkflowInputError)
|
|
1965
|
+
return error.message;
|
|
1966
|
+
if (error instanceof ClientCredentialMissingError)
|
|
1967
|
+
return "Workflows credential is missing; configure it through this station's supported credential resolver";
|
|
1968
|
+
if (error instanceof ClientTransportConfigurationError)
|
|
1969
|
+
return "Workflows API URL or credential binding was refused; use an absolute HTTPS URL and its paired credential (exact loopback HTTP is supported)";
|
|
1970
|
+
if (error instanceof HasnaHttpError) {
|
|
1971
|
+
const code = error.body && typeof error.body === "object" ? error.body.error : undefined;
|
|
1972
|
+
const known = typeof code === "string" && Object.hasOwn(guidance, code) ? `: ${guidance[code]}` : "";
|
|
1973
|
+
return `Workflows API returned HTTP ${error.status}${known}`;
|
|
1974
|
+
}
|
|
1975
|
+
return "Workflows request failed; verify the API connection and configured credential";
|
|
1976
|
+
}
|
|
1977
|
+
|
|
1978
|
+
// src/client-tools.ts
|
|
1979
|
+
async function callClientTool(client, name, args) {
|
|
1933
1980
|
switch (name) {
|
|
1934
1981
|
case "workflows_version":
|
|
1935
|
-
return textResult({ service:
|
|
1982
|
+
return textResult({ service: "workflows", version: packageVersion() });
|
|
1983
|
+
case "workflows_validate":
|
|
1984
|
+
return textResult(validateGraph(args.graph));
|
|
1936
1985
|
case "workflows_health":
|
|
1937
|
-
return textResult(
|
|
1986
|
+
return textResult(await client().health());
|
|
1938
1987
|
case "workflows_ready":
|
|
1939
|
-
return textResult(
|
|
1940
|
-
case "workflows_validate": {
|
|
1941
|
-
const graph = args.graph;
|
|
1942
|
-
const result = validateGraph(graph);
|
|
1943
|
-
return textResult(result);
|
|
1944
|
-
}
|
|
1988
|
+
return textResult(await client().ready());
|
|
1945
1989
|
case "workflows_run": {
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
result: final.resultJson ? JSON.parse(final.resultJson) : null
|
|
1956
|
-
});
|
|
1957
|
-
} finally {
|
|
1958
|
-
store.close();
|
|
1959
|
-
}
|
|
1960
|
-
}
|
|
1961
|
-
case "workflows_runs_list": {
|
|
1962
|
-
const store = openStore(service.config.dataDir);
|
|
1963
|
-
try {
|
|
1964
|
-
const status = typeof args.status === "string" ? args.status : undefined;
|
|
1965
|
-
const limit = typeof args.limit === "number" ? args.limit : 100;
|
|
1966
|
-
return textResult(store.listRuns({ status, limit }));
|
|
1967
|
-
} finally {
|
|
1968
|
-
store.close();
|
|
1969
|
-
}
|
|
1970
|
-
}
|
|
1990
|
+
if (typeof args.idempotencyKey !== "string" || !/^[A-Za-z0-9_.:-]{1,128}$/.test(args.idempotencyKey))
|
|
1991
|
+
throw new WorkflowInputError("workflows_run requires a stable idempotencyKey with 1 to 128 ASCII identity characters");
|
|
1992
|
+
return textResult(await client().triggerRun(args.graph, args.context ?? {}, {
|
|
1993
|
+
idempotencyKey: args.idempotencyKey,
|
|
1994
|
+
maxCycles: args.maxCycles
|
|
1995
|
+
}));
|
|
1996
|
+
}
|
|
1997
|
+
case "workflows_runs_list":
|
|
1998
|
+
return textResult(await client().listRuns({ status: args.status, limit: args.limit }));
|
|
1971
1999
|
case "workflows_lanes_list":
|
|
1972
|
-
return textResult(await
|
|
2000
|
+
return textResult(await client().lanes());
|
|
1973
2001
|
default:
|
|
1974
|
-
throw new Error(
|
|
2002
|
+
throw new Error("unknown_workflows_tool");
|
|
1975
2003
|
}
|
|
1976
2004
|
}
|
|
1977
|
-
// package.json
|
|
1978
|
-
var package_default = {
|
|
1979
|
-
name: "@hasna/workflows",
|
|
1980
|
-
version: "0.1.3",
|
|
1981
|
-
description: "Universal graph workflow app \u2014 graph language (start/step/decision/while/end), three-table store, session WAL, daemon with claims/leases, four lane adapters (claude/codex/cursor/grok), and a full CLI on four surfaces",
|
|
1982
|
-
type: "module",
|
|
1983
|
-
main: "./dist/index.js",
|
|
1984
|
-
types: "./types/index.d.ts",
|
|
1985
|
-
bin: {
|
|
1986
|
-
workflows: "dist/cli/index.js",
|
|
1987
|
-
"workflows-mcp": "dist/mcp/index.js",
|
|
1988
|
-
"workflows-serve": "dist/serve/index.js"
|
|
1989
|
-
},
|
|
1990
|
-
exports: {
|
|
1991
|
-
".": {
|
|
1992
|
-
types: "./types/index.d.ts",
|
|
1993
|
-
import: "./dist/index.js"
|
|
1994
|
-
},
|
|
1995
|
-
"./sdk": {
|
|
1996
|
-
types: "./types/index.d.ts",
|
|
1997
|
-
import: "./dist/index.js"
|
|
1998
|
-
},
|
|
1999
|
-
"./cli": {
|
|
2000
|
-
types: "./types/cli/index.d.ts",
|
|
2001
|
-
import: "./dist/cli/index.js"
|
|
2002
|
-
}
|
|
2003
|
-
},
|
|
2004
|
-
files: [
|
|
2005
|
-
"dist",
|
|
2006
|
-
"types",
|
|
2007
|
-
"README.md",
|
|
2008
|
-
"LICENSE",
|
|
2009
|
-
"hasna.contract.json"
|
|
2010
|
-
],
|
|
2011
|
-
scripts: {
|
|
2012
|
-
build: "bun run build:runtime && bun run build:types",
|
|
2013
|
-
"build:runtime": "rm -rf dist && bun build src/cli/index.ts --outdir dist/cli --target bun --packages external && bun build src/mcp/index.ts --outdir dist/mcp --target bun --packages external && bun build src/serve/index.ts --outdir dist/serve --target bun --packages external && bun build src/index.ts src/service.ts src/handlers.ts src/agent-tools.ts src/types.ts --root src --outdir dist --target bun --packages external",
|
|
2014
|
-
"build:types": "rm -rf types && tsc -p tsconfig.build.json --emitDeclarationOnly --outDir types",
|
|
2015
|
-
"artifact-scan": "bun scripts/contracts-cli.mjs artifact-scan dist",
|
|
2016
|
-
"contract:check": "bun scripts/contracts-cli.mjs repo-conformance .",
|
|
2017
|
-
typecheck: "tsc --noEmit",
|
|
2018
|
-
test: "bun test",
|
|
2019
|
-
"test:pg": 'WORKFLOWS_TEST_DATABASE_URL="${WORKFLOWS_TEST_DATABASE_URL:?point it at a throwaway Postgres; the live-PG gate must not pass without one}" WORKFLOWS_REQUIRE_POSTGRES=1 bun test src/db/pg-live.test.ts',
|
|
2020
|
-
prepack: "bun run build && bun run artifact-scan",
|
|
2021
|
-
prepublishOnly: "bun run test && bun run build"
|
|
2022
|
-
},
|
|
2023
|
-
keywords: [
|
|
2024
|
-
"workflows",
|
|
2025
|
-
"graph",
|
|
2026
|
-
"automation",
|
|
2027
|
-
"cli",
|
|
2028
|
-
"typescript",
|
|
2029
|
-
"bun",
|
|
2030
|
-
"hasna"
|
|
2031
|
-
],
|
|
2032
|
-
publishConfig: {
|
|
2033
|
-
registry: "https://registry.npmjs.org",
|
|
2034
|
-
access: "public"
|
|
2035
|
-
},
|
|
2036
|
-
repository: {
|
|
2037
|
-
type: "git",
|
|
2038
|
-
url: "git+https://github.com/hasna/apps.git"
|
|
2039
|
-
},
|
|
2040
|
-
homepage: "https://github.com/hasna/apps/tree/main/apps/workflows",
|
|
2041
|
-
bugs: {
|
|
2042
|
-
url: "https://github.com/hasna/apps/issues"
|
|
2043
|
-
},
|
|
2044
|
-
engines: {
|
|
2045
|
-
bun: ">=1.0.0"
|
|
2046
|
-
},
|
|
2047
|
-
author: "Hasna",
|
|
2048
|
-
license: "Apache-2.0",
|
|
2049
|
-
dependencies: {
|
|
2050
|
-
"@anthropic-ai/claude-agent-sdk": "0.3.234",
|
|
2051
|
-
"@cursor/sdk": "^1.0.28",
|
|
2052
|
-
"@hasna/paths": "0.1.0",
|
|
2053
|
-
"@openai/codex-sdk": "0.147.0",
|
|
2054
|
-
commander: "^13.1.0"
|
|
2055
|
-
},
|
|
2056
|
-
devDependencies: {
|
|
2057
|
-
"@hasna/contracts": "0.14.1",
|
|
2058
|
-
"@types/bun": "latest",
|
|
2059
|
-
"@types/pg": "^8.15.6",
|
|
2060
|
-
pg: "^8.16.3",
|
|
2061
|
-
typescript: "^5.7.3"
|
|
2062
|
-
}
|
|
2063
|
-
};
|
|
2064
2005
|
|
|
2065
|
-
// src/
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
}
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
}
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2006
|
+
// src/sdk/generated-api.ts
|
|
2007
|
+
class WorkflowsApi {
|
|
2008
|
+
async inspectDaemon() {
|
|
2009
|
+
return this.apiRequest("GET", `/daemon/status`, {
|
|
2010
|
+
body: undefined,
|
|
2011
|
+
query: undefined
|
|
2012
|
+
});
|
|
2013
|
+
}
|
|
2014
|
+
async getHealth() {
|
|
2015
|
+
return this.apiRequest("GET", `/health`, {
|
|
2016
|
+
body: undefined,
|
|
2017
|
+
query: undefined
|
|
2018
|
+
});
|
|
2019
|
+
}
|
|
2020
|
+
async listLanes() {
|
|
2021
|
+
return this.apiRequest("GET", `/lanes`, {
|
|
2022
|
+
body: undefined,
|
|
2023
|
+
query: undefined
|
|
2024
|
+
});
|
|
2025
|
+
}
|
|
2026
|
+
async probeLane(lane) {
|
|
2027
|
+
return this.apiRequest("GET", `/lanes/${encodeURIComponent(String(lane))}`, {
|
|
2028
|
+
body: undefined,
|
|
2029
|
+
query: undefined
|
|
2030
|
+
});
|
|
2031
|
+
}
|
|
2032
|
+
async listServerMachines() {
|
|
2033
|
+
return this.apiRequest("GET", `/machines/list`, {
|
|
2034
|
+
body: undefined,
|
|
2035
|
+
query: undefined
|
|
2036
|
+
});
|
|
2037
|
+
}
|
|
2038
|
+
async inspectServerMachine() {
|
|
2039
|
+
return this.apiRequest("GET", `/machines/status`, {
|
|
2040
|
+
body: undefined,
|
|
2041
|
+
query: undefined
|
|
2042
|
+
});
|
|
2043
|
+
}
|
|
2044
|
+
async listMemoRecords() {
|
|
2045
|
+
return this.apiRequest("GET", `/memos/list`, {
|
|
2046
|
+
body: undefined,
|
|
2047
|
+
query: undefined
|
|
2048
|
+
});
|
|
2049
|
+
}
|
|
2050
|
+
async getReadiness() {
|
|
2051
|
+
return this.apiRequest("GET", `/ready`, {
|
|
2052
|
+
body: undefined,
|
|
2053
|
+
query: undefined
|
|
2054
|
+
});
|
|
2055
|
+
}
|
|
2056
|
+
async listRunRecords(query) {
|
|
2057
|
+
return this.apiRequest("GET", `/runs`, {
|
|
2058
|
+
body: undefined,
|
|
2059
|
+
query
|
|
2060
|
+
});
|
|
2061
|
+
}
|
|
2062
|
+
async getRunRecord(id) {
|
|
2063
|
+
return this.apiRequest("GET", `/runs/${encodeURIComponent(String(id))}`, {
|
|
2064
|
+
body: undefined,
|
|
2065
|
+
query: undefined
|
|
2066
|
+
});
|
|
2067
|
+
}
|
|
2068
|
+
async cancelWorkflow(id) {
|
|
2069
|
+
return this.apiRequest("POST", `/runs/${encodeURIComponent(String(id))}/cancel`, {
|
|
2070
|
+
body: undefined,
|
|
2071
|
+
query: undefined
|
|
2072
|
+
});
|
|
2073
|
+
}
|
|
2074
|
+
async getRunEvents(id) {
|
|
2075
|
+
return this.apiRequest("GET", `/runs/${encodeURIComponent(String(id))}/events`, {
|
|
2076
|
+
body: undefined,
|
|
2077
|
+
query: undefined
|
|
2078
|
+
});
|
|
2079
|
+
}
|
|
2080
|
+
async getRunNodes(id) {
|
|
2081
|
+
return this.apiRequest("GET", `/runs/${encodeURIComponent(String(id))}/nodes`, {
|
|
2082
|
+
body: undefined,
|
|
2083
|
+
query: undefined
|
|
2084
|
+
});
|
|
2085
|
+
}
|
|
2086
|
+
async resumeWorkflow(id) {
|
|
2087
|
+
return this.apiRequest("POST", `/runs/${encodeURIComponent(String(id))}/resume`, {
|
|
2088
|
+
body: undefined,
|
|
2089
|
+
query: undefined
|
|
2090
|
+
});
|
|
2091
|
+
}
|
|
2092
|
+
async listSessionEvents() {
|
|
2093
|
+
return this.apiRequest("GET", `/sessions/list`, {
|
|
2094
|
+
body: undefined,
|
|
2095
|
+
query: undefined
|
|
2096
|
+
});
|
|
2097
|
+
}
|
|
2098
|
+
async inspectSession() {
|
|
2099
|
+
return this.apiRequest("GET", `/sessions/pull`, {
|
|
2100
|
+
body: undefined,
|
|
2101
|
+
query: undefined
|
|
2102
|
+
});
|
|
2103
|
+
}
|
|
2104
|
+
async triggerWorkflow(body) {
|
|
2105
|
+
return this.apiRequest("POST", `/trigger`, {
|
|
2106
|
+
body,
|
|
2107
|
+
query: undefined
|
|
2108
|
+
});
|
|
2109
|
+
}
|
|
2110
|
+
async validateWorkflow(body) {
|
|
2111
|
+
return this.apiRequest("POST", `/validate`, {
|
|
2112
|
+
body,
|
|
2113
|
+
query: undefined
|
|
2114
|
+
});
|
|
2115
|
+
}
|
|
2116
|
+
async getVersion() {
|
|
2117
|
+
return this.apiRequest("GET", `/version`, {
|
|
2118
|
+
body: undefined,
|
|
2119
|
+
query: undefined
|
|
2120
|
+
});
|
|
2121
|
+
}
|
|
2090
2122
|
}
|
|
2091
2123
|
|
|
2092
|
-
// src/
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
function
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
function envString(names) {
|
|
2099
|
-
for (const name of names) {
|
|
2100
|
-
const value = process.env[name];
|
|
2101
|
-
if (value !== undefined && value !== "")
|
|
2102
|
-
return value;
|
|
2124
|
+
// src/identity.ts
|
|
2125
|
+
import { createHash } from "crypto";
|
|
2126
|
+
import { hostname } from "os";
|
|
2127
|
+
function name(value) {
|
|
2128
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._:@-]{0,127}$/.test(value) || /^(owner|andrei-hasna)$/i.test(value)) {
|
|
2129
|
+
throw new WorkflowInputError("agent must be a non-owner identity with 1 to 128 identity characters");
|
|
2103
2130
|
}
|
|
2104
|
-
return;
|
|
2105
|
-
}
|
|
2106
|
-
function envInt(names, fallback) {
|
|
2107
|
-
const value = envString(names);
|
|
2108
|
-
if (value === undefined)
|
|
2109
|
-
return fallback;
|
|
2110
|
-
const parsed = Number(value);
|
|
2111
|
-
return Number.isFinite(parsed) ? parsed : fallback;
|
|
2131
|
+
return value;
|
|
2112
2132
|
}
|
|
2113
|
-
function
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2133
|
+
function station(env) {
|
|
2134
|
+
const value = (env.HASNA_STATION ?? hostname()).split(".")[0].toLowerCase();
|
|
2135
|
+
return value.replace(/[^a-z0-9-]/g, "-").slice(0, 63) || "unknown";
|
|
2136
|
+
}
|
|
2137
|
+
function workflowAgent(env = process.env, explicit) {
|
|
2138
|
+
if (explicit !== undefined)
|
|
2139
|
+
return { name: name(explicit), source: "argument" };
|
|
2140
|
+
if (env.HASNA_WORKFLOWS_AGENT !== undefined)
|
|
2141
|
+
return { name: name(env.HASNA_WORKFLOWS_AGENT), source: "HASNA_WORKFLOWS_AGENT" };
|
|
2142
|
+
for (const [harness, key] of [["claude", "CLAUDE_CODE_SESSION_ID"], ["codex", "CODEX_THREAD_ID"]]) {
|
|
2143
|
+
if (env[key] !== undefined)
|
|
2144
|
+
return {
|
|
2145
|
+
name: `${harness}-${createHash("sha256").update(JSON.stringify([env[key], null])).digest("hex").slice(0, 32)}`,
|
|
2146
|
+
source: key
|
|
2147
|
+
};
|
|
2148
|
+
}
|
|
2149
|
+
return { name: `cli@${station(env)}`, source: "station" };
|
|
2150
|
+
}
|
|
2151
|
+
function workflowMcpAgent(env, harness, explicit, meta) {
|
|
2152
|
+
if (explicit !== undefined) {
|
|
2153
|
+
if (typeof explicit !== "string")
|
|
2154
|
+
throw new WorkflowInputError("agent must be a string");
|
|
2155
|
+
return { name: name(explicit), source: "argument" };
|
|
2156
|
+
}
|
|
2157
|
+
if (env.HASNA_WORKFLOWS_AGENT !== undefined)
|
|
2158
|
+
return workflowAgent(env);
|
|
2159
|
+
const label = harness.toLowerCase().replace(/[^a-z0-9_-]/g, "-").slice(0, 32) || "mcp";
|
|
2160
|
+
const id = meta && typeof meta === "object" ? meta["claudecode/agentId"] : undefined;
|
|
2161
|
+
if (typeof id === "string" && /^[A-Za-z0-9_-]{1,64}$/.test(id))
|
|
2162
|
+
return { name: `${label}:${id}@${station(env)}`, source: "mcp-meta" };
|
|
2163
|
+
const native = workflowAgent(env);
|
|
2164
|
+
if (native.source !== "station")
|
|
2165
|
+
return native;
|
|
2166
|
+
return { name: `${label}@${station(env)}`, source: "mcp-client" };
|
|
2121
2167
|
}
|
|
2122
2168
|
|
|
2123
|
-
|
|
2169
|
+
// src/client.ts
|
|
2170
|
+
class WorkflowsClient extends WorkflowsApi {
|
|
2124
2171
|
name = "workflows";
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2172
|
+
resolution;
|
|
2173
|
+
http;
|
|
2174
|
+
constructor(options = {}) {
|
|
2175
|
+
super();
|
|
2176
|
+
const env = { ...options.env ?? process.env };
|
|
2177
|
+
if (options.apiUrl !== undefined) {
|
|
2178
|
+
env.HASNA_WORKFLOWS_API_URL = options.apiUrl;
|
|
2179
|
+
delete env.WORKFLOWS_API_URL;
|
|
2180
|
+
}
|
|
2181
|
+
const { client, resolution } = createClientTransport("workflows", env, {
|
|
2182
|
+
credentials: { keychain: { enabled: options.env === undefined }, ...options.apiKey === undefined ? {} : { apiKey: options.apiKey } },
|
|
2183
|
+
bindUnpairedCredentialsToFleet: true,
|
|
2184
|
+
fetchImpl: options.fetchImpl,
|
|
2185
|
+
timeoutMs: options.timeoutMs ?? 120000,
|
|
2186
|
+
retry: false,
|
|
2187
|
+
headers: { "user-agent": `hasna-workflows-sdk/${packageVersion()}`, "x-hasna-agent": workflowAgent(env, options.agent).name }
|
|
2188
|
+
});
|
|
2189
|
+
this.http = client;
|
|
2190
|
+
this.resolution = resolution;
|
|
2191
|
+
}
|
|
2192
|
+
request(method, path, body) {
|
|
2193
|
+
return this.http.request(method, path, body);
|
|
2194
|
+
}
|
|
2195
|
+
apiRequest(method, path, opts) {
|
|
2196
|
+
const query = new URLSearchParams;
|
|
2197
|
+
for (const [key, value] of Object.entries(opts.query ?? {}))
|
|
2198
|
+
if (value !== undefined && value !== null)
|
|
2199
|
+
query.set(key, String(value));
|
|
2200
|
+
return this.request(method, `${path}${query.size ? `?${query}` : ""}`, opts.body);
|
|
2131
2201
|
}
|
|
2132
2202
|
health() {
|
|
2133
|
-
return
|
|
2134
|
-
ok: true,
|
|
2135
|
-
service: this.name,
|
|
2136
|
-
version: this.version,
|
|
2137
|
-
pid: process.pid,
|
|
2138
|
-
uptimeMs: Date.now() - this.startedAt
|
|
2139
|
-
};
|
|
2203
|
+
return this.getHealth();
|
|
2140
2204
|
}
|
|
2141
2205
|
ready() {
|
|
2142
|
-
return
|
|
2143
|
-
ok: true,
|
|
2144
|
-
service: this.name,
|
|
2145
|
-
version: this.version,
|
|
2146
|
-
checks: { version: "ok" }
|
|
2147
|
-
};
|
|
2206
|
+
return this.getReadiness();
|
|
2148
2207
|
}
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
|
|
2164
|
-
|
|
2165
|
-
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
runId: final.id,
|
|
2179
|
-
status: final.status,
|
|
2180
|
-
error: final.error ?? null,
|
|
2181
|
-
result: final.resultJson ? JSON.parse(final.resultJson) : null,
|
|
2182
|
-
reused: false
|
|
2183
|
-
};
|
|
2184
|
-
} finally {
|
|
2185
|
-
store.close();
|
|
2186
|
-
}
|
|
2208
|
+
version() {
|
|
2209
|
+
return this.getVersion();
|
|
2210
|
+
}
|
|
2211
|
+
validate(graph) {
|
|
2212
|
+
return this.validateWorkflow({ graph });
|
|
2213
|
+
}
|
|
2214
|
+
triggerRun(graph, context = {}, opts = {}) {
|
|
2215
|
+
return this.triggerWorkflow({ graph, context, ...opts });
|
|
2216
|
+
}
|
|
2217
|
+
listRuns(options = {}) {
|
|
2218
|
+
return this.listRunRecords(options);
|
|
2219
|
+
}
|
|
2220
|
+
getRun(id) {
|
|
2221
|
+
return this.getRunRecord(id);
|
|
2222
|
+
}
|
|
2223
|
+
listNodes(id) {
|
|
2224
|
+
return this.getRunNodes(id);
|
|
2225
|
+
}
|
|
2226
|
+
events(id) {
|
|
2227
|
+
return this.getRunEvents(id);
|
|
2228
|
+
}
|
|
2229
|
+
cancelRun(id) {
|
|
2230
|
+
return this.cancelWorkflow(id);
|
|
2231
|
+
}
|
|
2232
|
+
resumeRun(id) {
|
|
2233
|
+
return this.resumeWorkflow(id);
|
|
2234
|
+
}
|
|
2235
|
+
lanes() {
|
|
2236
|
+
return this.listLanes();
|
|
2187
2237
|
}
|
|
2188
2238
|
}
|
|
2189
|
-
function
|
|
2190
|
-
return new
|
|
2239
|
+
function createWorkflowsClient(options = {}) {
|
|
2240
|
+
return new WorkflowsClient(options);
|
|
2191
2241
|
}
|
|
2192
2242
|
|
|
2193
2243
|
// src/mcp/index.ts
|
|
@@ -2209,34 +2259,60 @@ if (argv.includes("--help") || argv.includes("-h")) {
|
|
|
2209
2259
|
console.log(HELP_TEXT);
|
|
2210
2260
|
process.exit(0);
|
|
2211
2261
|
}
|
|
2262
|
+
if (argv.some((argument) => argument !== "--stdio")) {
|
|
2263
|
+
console.error("unknown workflows-mcp argument; use --help");
|
|
2264
|
+
process.exit(2);
|
|
2265
|
+
}
|
|
2212
2266
|
function respond(id, result) {
|
|
2213
|
-
if (id ===
|
|
2267
|
+
if (id === undefined)
|
|
2214
2268
|
return;
|
|
2215
2269
|
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, result }) + `
|
|
2216
2270
|
`);
|
|
2217
2271
|
}
|
|
2218
2272
|
function respondError(id, code, message) {
|
|
2219
|
-
if (id ===
|
|
2273
|
+
if (id === undefined)
|
|
2220
2274
|
return;
|
|
2221
2275
|
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, error: { code, message } }) + `
|
|
2222
2276
|
`);
|
|
2223
2277
|
}
|
|
2224
|
-
var
|
|
2278
|
+
var harness = "mcp";
|
|
2279
|
+
var protocols = ["2025-06-18", "2025-03-26", "2024-11-05"];
|
|
2225
2280
|
var rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
2226
2281
|
rl.on("line", (line) => {
|
|
2227
2282
|
const trimmed = line.trim();
|
|
2228
2283
|
if (trimmed === "")
|
|
2229
2284
|
return;
|
|
2230
|
-
|
|
2285
|
+
if (Buffer.byteLength(trimmed) > 1048576) {
|
|
2286
|
+
respondError(null, -32600, "Frame exceeds 1 MiB");
|
|
2287
|
+
return;
|
|
2288
|
+
}
|
|
2289
|
+
let candidate;
|
|
2231
2290
|
try {
|
|
2232
|
-
|
|
2291
|
+
candidate = JSON.parse(trimmed);
|
|
2233
2292
|
} catch {
|
|
2293
|
+
respondError(null, -32700, "Parse error");
|
|
2294
|
+
return;
|
|
2295
|
+
}
|
|
2296
|
+
if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) {
|
|
2297
|
+
respondError(null, -32600, "Invalid request");
|
|
2298
|
+
return;
|
|
2299
|
+
}
|
|
2300
|
+
const msg = candidate;
|
|
2301
|
+
if (msg.jsonrpc !== "2.0" || typeof msg.method !== "string" || msg.id !== undefined && msg.id !== null && typeof msg.id !== "number" && typeof msg.id !== "string") {
|
|
2302
|
+
respondError(null, -32600, "Invalid request");
|
|
2234
2303
|
return;
|
|
2235
2304
|
}
|
|
2236
|
-
|
|
2305
|
+
if (msg.params !== undefined && (!msg.params || typeof msg.params !== "object" || Array.isArray(msg.params))) {
|
|
2306
|
+
respondError(msg.id, -32602, "params must be an object");
|
|
2307
|
+
return;
|
|
2308
|
+
}
|
|
2309
|
+
const method = msg.method;
|
|
2237
2310
|
if (method === "initialize") {
|
|
2238
|
-
|
|
2239
|
-
|
|
2311
|
+
const info = msg.params?.clientInfo;
|
|
2312
|
+
if (info && typeof info === "object" && typeof info.name === "string")
|
|
2313
|
+
harness = info.name;
|
|
2314
|
+
respond(msg.id, {
|
|
2315
|
+
protocolVersion: protocols.includes(msg.params?.protocolVersion) ? msg.params.protocolVersion : protocols[0],
|
|
2240
2316
|
capabilities: { tools: {} },
|
|
2241
2317
|
serverInfo: { name: "workflows-mcp", version: packageVersion() }
|
|
2242
2318
|
});
|
|
@@ -2245,28 +2321,33 @@ rl.on("line", (line) => {
|
|
|
2245
2321
|
if (method.startsWith("notifications/"))
|
|
2246
2322
|
return;
|
|
2247
2323
|
if (method === "ping") {
|
|
2248
|
-
respond(msg.id
|
|
2324
|
+
respond(msg.id, {});
|
|
2249
2325
|
return;
|
|
2250
2326
|
}
|
|
2251
2327
|
if (method === "tools/list") {
|
|
2252
|
-
respond(msg.id
|
|
2328
|
+
respond(msg.id, { tools: workflowsTools() });
|
|
2253
2329
|
return;
|
|
2254
2330
|
}
|
|
2255
2331
|
if (method === "tools/call") {
|
|
2256
2332
|
const params = msg.params ?? {};
|
|
2257
|
-
const
|
|
2333
|
+
const name2 = typeof params.name === "string" ? params.name : "";
|
|
2258
2334
|
const args = params.arguments ?? {};
|
|
2335
|
+
if (!name2 || !args || typeof args !== "object" || Array.isArray(args)) {
|
|
2336
|
+
respondError(msg.id, -32602, "name must be a tool name and arguments must be an object");
|
|
2337
|
+
return;
|
|
2338
|
+
}
|
|
2259
2339
|
(async () => {
|
|
2260
2340
|
try {
|
|
2261
|
-
|
|
2341
|
+
const agent = workflowMcpAgent(process.env, harness, args.agent, params._meta);
|
|
2342
|
+
respond(msg.id, await callClientTool(() => createWorkflowsClient({ agent: agent.name }), name2, args));
|
|
2262
2343
|
} catch (err) {
|
|
2263
|
-
respond(msg.id
|
|
2264
|
-
content: [{ type: "text", text:
|
|
2344
|
+
respond(msg.id, {
|
|
2345
|
+
content: [{ type: "text", text: workflowErrorMessage(err) }],
|
|
2265
2346
|
isError: true
|
|
2266
2347
|
});
|
|
2267
2348
|
}
|
|
2268
2349
|
})();
|
|
2269
2350
|
return;
|
|
2270
2351
|
}
|
|
2271
|
-
respondError(msg.id
|
|
2352
|
+
respondError(msg.id, -32601, "Method not found");
|
|
2272
2353
|
});
|