owenloop 0.5.27 → 0.5.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/packages/work/src/agent/brief.d.ts +10 -0
  3. package/dist/packages/work/src/agent/brief.js +38 -0
  4. package/dist/packages/work/src/agent/loop.js +4 -0
  5. package/dist/packages/work/src/contained-path.d.ts +18 -0
  6. package/dist/packages/work/src/contained-path.js +42 -0
  7. package/dist/packages/work/src/harness/claude.js +21 -0
  8. package/dist/packages/work/src/harness/codex.js +29 -0
  9. package/dist/packages/work/src/harness/contract.d.ts +26 -0
  10. package/dist/packages/work/src/hold/mcp.d.ts +3 -40
  11. package/dist/packages/work/src/hold/mcp.js +121 -2
  12. package/dist/packages/work/src/hub/client.d.ts +10 -1
  13. package/dist/packages/work/src/hub/client.js +23 -0
  14. package/dist/packages/work/src/hub/types.d.ts +31 -0
  15. package/dist/packages/work/src/roles/shift.js +7 -1
  16. package/dist/packages/work/src/settings/settings.d.ts +12 -1
  17. package/dist/packages/work/src/settings/settings.js +7 -0
  18. package/dist/packages/work/src/shift/disk-floor.d.ts +107 -0
  19. package/dist/packages/work/src/shift/disk-floor.js +148 -0
  20. package/dist/packages/work/src/shift/host-preflight.d.ts +85 -0
  21. package/dist/packages/work/src/shift/host-preflight.js +112 -0
  22. package/dist/packages/work/src/shift/loop.d.ts +18 -0
  23. package/dist/packages/work/src/shift/loop.js +179 -7
  24. package/dist/packages/work/src/shift/protocol.d.ts +62 -1
  25. package/dist/packages/work/src/shift/runtime.d.ts +2 -0
  26. package/dist/packages/work/src/shift/runtime.js +17 -0
  27. package/dist/packages/work/src/submit-file.d.ts +3 -2
  28. package/dist/packages/work/src/submit-file.js +6 -22
  29. package/docs/cli.md +8 -5
  30. package/docs/shift-logs.md +64 -7
  31. package/package.json +1 -1
  32. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  33. package/plugins/claude-code/plugin/.mcp.json +1 -1
  34. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  35. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
package/CHANGELOG.md CHANGED
@@ -4,6 +4,20 @@ All notable changes to this project are documented here. The format is based on
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project
5
5
  adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [0.5.28](https://github.com/typicalday/owenloop/compare/v0.5.27...v0.5.28) (2026-09-05)
8
+
9
+
10
+ ### Features
11
+
12
+ * **shift:** refuse new work when the disk is nearly full ([#307](https://github.com/typicalday/owenloop/issues/307)) ([fa5ab16](https://github.com/typicalday/owenloop/commit/fa5ab1662e797af1a0715cdac498ecd4018cc330))
13
+ * **work:** let a step store a file as an artifact ([#308](https://github.com/typicalday/owenloop/issues/308)) ([9972635](https://github.com/typicalday/owenloop/commit/997263516b4b3998b28ab7fd58cda139d6454ead))
14
+ * **work:** tell a step up front when its sandbox grants it nowhere to write ([#309](https://github.com/typicalday/owenloop/issues/309)) ([9c0c109](https://github.com/typicalday/owenloop/commit/9c0c10903a9cb37bdb4f1638fd4e036d07c4c573))
15
+
16
+
17
+ ### Bug Fixes
18
+
19
+ * **work:** stop a shift whose host is broken instead of wedging silently ([#305](https://github.com/typicalday/owenloop/issues/305)) ([594f0d8](https://github.com/typicalday/owenloop/commit/594f0d8a290e768ee16385d6c55b3d046c44b5cd))
20
+
7
21
  ## [0.5.27](https://github.com/typicalday/owenloop/compare/v0.5.26...v0.5.27) (2026-09-05)
8
22
 
9
23
 
@@ -82,6 +82,16 @@ export interface BriefSpec {
82
82
  * were written to close.
83
83
  */
84
84
  owes?: readonly OwedBrief[];
85
+ /**
86
+ * Whether this step's sandbox grants it no writable location at all, as
87
+ * resolved by the harness adapter from the step's own permissions.
88
+ *
89
+ * ONLY `true` RENDERS. Absent or `false` both mean "not known to be shut out",
90
+ * which is not the same as "may write freely" — this brief deliberately makes
91
+ * no positive claim about where a step may write, because no claim it could
92
+ * make would stay true (see `renderWorkspaceLine`).
93
+ */
94
+ deniesAllWrites?: boolean;
85
95
  }
86
96
  /**
87
97
  * One owed output as the brief sees it: the path, plus how many times a prior
@@ -36,6 +36,7 @@ export function renderBrief(templateContent, spec) {
36
36
  .join(spec.shiftId ?? '');
37
37
  const blocks = [
38
38
  renderRoutingLine(spec),
39
+ renderWorkspaceLine(spec),
39
40
  renderInputContract(spec),
40
41
  renderSubmitContract(spec),
41
42
  renderShapeContract(spec),
@@ -323,6 +324,43 @@ function renderRoutingLine(spec) {
323
324
  : '';
324
325
  return `Routing: this run was started at the '${spec.modifier}' depth modifier.${escalated}`;
325
326
  }
327
+ /**
328
+ * That this step cannot write anywhere, stated before it tries.
329
+ *
330
+ * WHY THIS EXISTS. Measured on a live fleet: read-only steps discovered their
331
+ * own containment one denial at a time -- 87 `EPERM` refusals inside a single
332
+ * step family, every one of them a temporary directory the subject repository's
333
+ * OWN test helpers create. The cost is not the wasted attempts. It is what the
334
+ * agent then reported: one grounding step wrote that "34 file tests were not
335
+ * executed because mkdtemp is blocked by the read-only sandbox", and other
336
+ * attempts filed the same unrun checks as failures OF THE SUBJECT. A step that
337
+ * does not know it cannot write will eventually blame the thing it is judging.
338
+ *
339
+ * ONLY THE NEGATIVE IS STATED. An earlier draft also named the writable roots
340
+ * when there were some. That half was removed: a vendor composes its writable
341
+ * set from sources this process cannot see, so any list would eventually lie,
342
+ * and a vendor with roots to name already names them itself. The silence worth
343
+ * breaking is the other one -- a vendor that grants nothing says nothing.
344
+ *
345
+ * "Not executed" and "failed" are different findings, and only the agent can
346
+ * tell them apart at the moment of the denial. That distinction is the whole
347
+ * point of the line.
348
+ *
349
+ * Vendor-neutral by construction: no sandbox mode or vendor name appears here,
350
+ * only the fact the adapter resolved.
351
+ */
352
+ function renderWorkspaceLine(spec) {
353
+ if (spec.deniesAllWrites !== true)
354
+ return '';
355
+ return ("Workspace: this step's sandbox grants it no writable location — not your" +
356
+ ' working directory, not the system temp directory, not /tmp. A write is' +
357
+ ' refused unless a person separately approves that one action, so treat' +
358
+ ' writing as unavailable: creating a temporary directory fails, and any check' +
359
+ ' that cannot run without writing will not run here. Report such a check as' +
360
+ ' NOT EXECUTED and say why. Do NOT report it as a failure of the thing you' +
361
+ ' are examining, and do not count it against the subject — an unrun check is' +
362
+ ' missing evidence, not adverse evidence.');
363
+ }
326
364
  /**
327
365
  * The born-bound work-holder mount handed to `HarnessAdapter.start` as
328
366
  * `StartArgs.owenloopMcp`. The adapter never constructs or changes the bound
@@ -724,6 +724,10 @@ export function createAgentRunLoop(opts) {
724
724
  ...(packet.modifier !== undefined ? { modifier: packet.modifier } : {}),
725
725
  ...(packet.escalated === true ? { escalated: true } : {}),
726
726
  owes: briefOwes(packet),
727
+ // Only the adapter knows whether its own sandbox leaves this step a place
728
+ // to write. `false`/absent render nothing, so a `false` here is silence,
729
+ // not a claim that writing is permitted.
730
+ deniesAllWrites: active.deniesAllWrites?.(step.permissions) === true,
727
731
  };
728
732
  const permissions = step.permissions;
729
733
  // Adapter-owned configuration is resolved once per worker life. Passing
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Resolve a caller-supplied path to a real file inside one containment root.
3
+ *
4
+ * Two checks, in this order and for two different attacks. The LEXICAL check
5
+ * rejects traversal (`../../etc/passwd`) before the filesystem is touched at
6
+ * all, so a probe cannot learn whether a path outside the root exists. The
7
+ * CANONICAL check then resolves symlinks on both sides and re-tests, because a
8
+ * name that is lexically inside the root can still POINT outside it — the
9
+ * lexical check alone would happily read the target of `evidence.json ->
10
+ * /Users/me/.ssh/id_ed25519`.
11
+ *
12
+ * `errorPrefix` is a machine-readable family name the caller owns, so each
13
+ * consumer keeps its own stable error vocabulary (`submit-value-file-…`,
14
+ * `file-artifact-…`) while the containment logic itself is written once. It is
15
+ * written once deliberately: two copies of a security check drift, and the copy
16
+ * that drifts is the one nobody is looking at.
17
+ */
18
+ export declare function resolveContainedPath(workdir: string, relativePath: string, errorPrefix: string): Promise<string>;
@@ -0,0 +1,42 @@
1
+ import { realpath } from 'node:fs/promises';
2
+ import { resolve } from 'node:path';
3
+ import { isInside } from "./harness/gatekeeper.js";
4
+ function errorMessage(error) {
5
+ return error instanceof Error ? error.message : String(error);
6
+ }
7
+ /**
8
+ * Resolve a caller-supplied path to a real file inside one containment root.
9
+ *
10
+ * Two checks, in this order and for two different attacks. The LEXICAL check
11
+ * rejects traversal (`../../etc/passwd`) before the filesystem is touched at
12
+ * all, so a probe cannot learn whether a path outside the root exists. The
13
+ * CANONICAL check then resolves symlinks on both sides and re-tests, because a
14
+ * name that is lexically inside the root can still POINT outside it — the
15
+ * lexical check alone would happily read the target of `evidence.json ->
16
+ * /Users/me/.ssh/id_ed25519`.
17
+ *
18
+ * `errorPrefix` is a machine-readable family name the caller owns, so each
19
+ * consumer keeps its own stable error vocabulary (`submit-value-file-…`,
20
+ * `file-artifact-…`) while the containment logic itself is written once. It is
21
+ * written once deliberately: two copies of a security check drift, and the copy
22
+ * that drifts is the one nobody is looking at.
23
+ */
24
+ export async function resolveContainedPath(workdir, relativePath, errorPrefix) {
25
+ const candidate = resolve(workdir, relativePath);
26
+ if (!isInside(workdir, candidate)) {
27
+ throw new Error(`${errorPrefix}-outside-workdir: ${relativePath} is outside the run workdir`);
28
+ }
29
+ try {
30
+ const canonicalWorkdir = await realpath(workdir);
31
+ const canonicalCandidate = await realpath(candidate);
32
+ if (!isInside(canonicalWorkdir, canonicalCandidate)) {
33
+ throw new Error(`${errorPrefix}-outside-workdir: ${relativePath} is outside the run workdir`);
34
+ }
35
+ return canonicalCandidate;
36
+ }
37
+ catch (error) {
38
+ if (error instanceof Error && error.message.startsWith(`${errorPrefix}-outside-workdir:`))
39
+ throw error;
40
+ throw new Error(`${errorPrefix}-read-failed: could not read ${relativePath}: ${errorMessage(error)}`);
41
+ }
42
+ }
@@ -542,6 +542,26 @@ function effectiveClaudeTools(permissions) {
542
542
  return [...OWENLOOP_ONLY_NETWORK_TOOLS];
543
543
  return undefined;
544
544
  }
545
+ /**
546
+ * Whether this step is left with no way to write anything.
547
+ *
548
+ * This adapter has no path sandbox: `filesystem: 'read-only'` is enforced by
549
+ * NARROWING THE TOOL SET, so the honest test is whether a write-capable tool
550
+ * survives. `preflight` already refuses `read-only` alongside an authored
551
+ * non-read-only tool, but this recomputes the condition rather than trusting
552
+ * that it ran -- a brief that states containment must not rest on a check
553
+ * happening somewhere else.
554
+ */
555
+ function deniesAllWrites(permissions) {
556
+ if (permissions.filesystem !== 'read-only')
557
+ return false;
558
+ const effective = effectiveClaudeTools(permissions);
559
+ // The `undefined` arm is a type guard, not a case: `read-only` always resolves
560
+ // to a concrete set. It is spelled out so the write-capability test below is
561
+ // the only thing deciding the answer.
562
+ return (effective !== undefined &&
563
+ effective.every((tool) => READ_ONLY_TOOLS.has(tool) || OWENLOOP_CONTROL_TOOLS.has(tool)));
564
+ }
545
565
  function strictWorkdirToolIssue(permissions) {
546
566
  const effective = effectiveClaudeTools(permissions);
547
567
  if (effective === undefined) {
@@ -1644,6 +1664,7 @@ export const claudeAdapter = {
1644
1664
  deliver: deliverClaude,
1645
1665
  stop,
1646
1666
  lintStep,
1667
+ deniesAllWrites,
1647
1668
  resumeCommand,
1648
1669
  };
1649
1670
  // Self-registration at import time: importing this module is what puts the
@@ -1078,11 +1078,40 @@ function lintStep(bag, step) {
1078
1078
  }
1079
1079
  return findings;
1080
1080
  }
1081
+ /**
1082
+ * What this sandbox lets the step write, as plain paths.
1083
+ *
1084
+ * The three modes map cleanly: `read-only` writes nowhere; `danger-full-access`
1085
+ * writes everywhere, which no finite list describes, so it answers `undefined`
1086
+ * rather than a list that would read as a restriction; `workspace-write` writes
1087
+ * to the working directory plus the two temp roots this vendor grants by
1088
+ * default, minus whichever of those two the step excluded itself.
1089
+ *
1090
+ * A permissions bag this adapter would refuse at preflight answers `undefined`
1091
+ * too: `resolveSandbox` throws on it, and a brief line is not the place to
1092
+ * surface a configuration error that `preflight` already reports properly.
1093
+ */
1094
+ function deniesAllWrites(permissions) {
1095
+ let sandbox;
1096
+ try {
1097
+ sandbox = resolveSandbox(permissions);
1098
+ }
1099
+ catch {
1100
+ // A bag this adapter refuses is a bag it cannot reason about. Claiming the
1101
+ // step is shut out would be a guess, and the honest answer to a guess here
1102
+ // is silence.
1103
+ return false;
1104
+ }
1105
+ // Only `read-only` grants no writable root. The other two modes grant at
1106
+ // least one, and the vendor names those itself, so this adapter does not.
1107
+ return sandbox === 'read-only';
1108
+ }
1081
1109
  export const codexAdapter = {
1082
1110
  id: HARNESS_ID,
1083
1111
  resumeTier: 'native-token',
1084
1112
  preflight: codexPreflight,
1085
1113
  lintStep,
1114
+ deniesAllWrites,
1086
1115
  /**
1087
1116
  * The command a human runs to re-open this thread in an interactive terminal.
1088
1117
  *
@@ -443,6 +443,32 @@ export interface HarnessAdapter {
443
443
  * NOT throw from here — a lint pass over a malformed bag returns findings.
444
444
  */
445
445
  lintStep?(bag: Record<string, unknown>, step: string): LintFinding[];
446
+ /**
447
+ * Whether this step's sandbox grants it NO writable location at all.
448
+ *
449
+ * DELIBERATELY NARROW, AND THE NARROWNESS IS THE POINT. An earlier draft of
450
+ * this member returned the list of writable roots. That could not be made
451
+ * true: a vendor composes its writable set from sources this process cannot
452
+ * see -- on-disk configuration layers, roots granted by a human mid-turn, and
453
+ * read-only carve-outs the vendor keeps INSIDE each writable root (a `.git`
454
+ * pointer to an external gitdir, for one). Every one of those makes a list
455
+ * either overstate or understate what the step may touch, and a brief that
456
+ * misstates containment is worse than one that says nothing. The vendor also
457
+ * already tells the model its writable roots when it has any.
458
+ *
459
+ * The negative has none of those problems. "No writable root was granted" is
460
+ * decidable from the step's own resolved permissions, it is the case the
461
+ * vendor says NOTHING about (it has no roots to name), and it is the case that
462
+ * cost real work: measured on a live fleet, read-only steps discovered their
463
+ * own containment one `EPERM` at a time and then filed the resulting unrun
464
+ * checks as failures of the subject under review rather than as checks that
465
+ * never ran.
466
+ *
467
+ * `false` is not a promise that a write will succeed -- it means only that
468
+ * this adapter cannot say the step is shut out. An adapter that does not model
469
+ * a sandbox omits the member entirely.
470
+ */
471
+ deniesAllWrites?(permissions: StepPermissions): boolean;
446
472
  /**
447
473
  * OPTIONAL — the command a HUMAN would run to open this session interactively,
448
474
  * for `owenloop work sessions` to print.
@@ -1,40 +1,3 @@
1
- /**
2
- * The `owenloop work hold --mcp` stdio-MCP mount (plan part 2).
3
- *
4
- * A born-bound work-holder: the D2 stamped Step Agent's frontmatter declares
5
- * `mcpServers.owenloop = owenloop work hold --order <wf>/<run> --origin <url> --mcp`,
6
- * so when the Step Agent session boots it launches THIS as a stdio MCP server. The
7
- * server exposes four bare tools the model uses to do its order:
8
- * - `get_order` → the order packet (prompt, inputs, owed outputs) for the run
9
- * this holder is bound to. No ids are arguments — they came in on argv, never
10
- * through the model.
11
- * - `submit` → post a receipt for an owed output path; when the hub reports
12
- * the submit CLOSED the run, the lease loop is stopped with `release:false`
13
- * (the claim is already gone).
14
- * - `reject` → invalidate a consumed artifact through the claiming step's
15
- * server-derived authority; the client never supplies `by`. A CLOSED reject
16
- * also stops the lease loop without releasing the already-closed claim.
17
- * - `ask` → stop and escalate to a human about an OWED output path. The
18
- * third exit. `submit` and `reject` both assume the worker can finish; until
19
- * `ask` existed a worker that genuinely could not had only two moves, and
20
- * both damaged the run: submit something it did not believe (greens a
21
- * fabrication that every downstream step then builds on), or end its turn
22
- * silently (the task re-arms and a fresh worker relearns the same blocker
23
- * until the stall cap). `ask` holds the artifact with no counter movement
24
- * and surfaces the question to an operator, who answers with
25
- * `owenloop retry <workflow> <path> --text "<answer>"`.
26
- *
27
- * Underneath the tools, the SAME lease loop the CLI `hold` runs keeps the order's
28
- * lease warm: `createHoldMcp` builds the loop with `onOrder` wired to capture the
29
- * first-contact packet (so `get_order` needn't re-fetch) and both output sinks
30
- * routed to stderr (stdout is the JSON-RPC channel). The role starts the loop and
31
- * pumps stdin into the server; loop and server share one process, and stdin EOF
32
- * (the session died) stops the loop for its final-breath release.
33
- *
34
- * This module is pure wiring + tool handlers — no stdio, no process, no timers of
35
- * its own — so a unit test drives the tools with a fake hub and a scriptable
36
- * clock. The role (`src/roles/hold.ts`) owns the real stdin/stdout pump.
37
- */
38
1
  import { type ToolRegistration } from '../mcp/server.ts';
39
2
  import type { HubClient } from '../hub/client.ts';
40
3
  import type { ContactHolder } from '../hub/types.ts';
@@ -42,7 +5,7 @@ import { type SubmissionKeyManager } from '../submit-proof.ts';
42
5
  import type { SshProcessAdapter } from '../../../../src/crypto/ssh.ts';
43
6
  import type { ConsumedVerifier } from '../consumed-verifier.ts';
44
7
  import { type HoldLoop } from './loop.ts';
45
- export declare const HOLD_MCP_TOOL_NAMES: readonly ["get_order", "submit", "reject", "ask"];
8
+ export declare const HOLD_MCP_TOOL_NAMES: readonly ["get_order", "submit", "reject", "ask", "put_file_artifact"];
46
9
  export type HoldMcpToolName = (typeof HOLD_MCP_TOOL_NAMES)[number];
47
10
  export interface HoldMcpDeps {
48
11
  hub: HubClient;
@@ -50,7 +13,7 @@ export interface HoldMcpDeps {
50
13
  run: string;
51
14
  /** Sole containment root for submit value files. */
52
15
  workdir: string;
53
- /** Positive registration list. Absent exposes the full three-tool server. */
16
+ /** Positive registration list. Absent exposes every tool in `HOLD_MCP_TOOL_NAMES`. */
54
17
  tools?: readonly HoldMcpToolName[];
55
18
  /** Hub origin used to resolve the local machine signing key. */
56
19
  origin?: string;
@@ -71,7 +34,7 @@ export interface HoldMcpDeps {
71
34
  jumpToleranceMs?: number;
72
35
  }
73
36
  export interface HoldMcpMount {
74
- /** Exactly the selected registrations; full mode has all three tools. */
37
+ /** Exactly the selected registrations; full mode has every tool. */
75
38
  tools: ToolRegistration[];
76
39
  /** The lease loop kept warm underneath — the role runs and stops it. */
77
40
  loop: HoldLoop;
@@ -4,7 +4,7 @@
4
4
  * A born-bound work-holder: the D2 stamped Step Agent's frontmatter declares
5
5
  * `mcpServers.owenloop = owenloop work hold --order <wf>/<run> --origin <url> --mcp`,
6
6
  * so when the Step Agent session boots it launches THIS as a stdio MCP server. The
7
- * server exposes four bare tools the model uses to do its order:
7
+ * server exposes five bare tools the model uses to do its order:
8
8
  * - `get_order` → the order packet (prompt, inputs, owed outputs) for the run
9
9
  * this holder is bound to. No ids are arguments — they came in on argv, never
10
10
  * through the model.
@@ -23,6 +23,13 @@
23
23
  * until the stall cap). `ask` holds the artifact with no counter movement
24
24
  * and surfaces the question to an operator, who answers with
25
25
  * `owenloop retry <workflow> <path> --text "<answer>"`.
26
+ * - `put_file_artifact` → store a file the step produced and get back the small
27
+ * JSON envelope that names it. An artifact value lives in the org's database
28
+ * and is size-capped for good reason, but a rendered video or a screenshot is
29
+ * an artifact too. Rather than let a step choose between truncating its own
30
+ * output and base64-inflating it past the cap, the bytes go to blob storage
31
+ * and the envelope — hash, size, content type — goes in the value, where a
32
+ * def's ordinary JSON Schema can still constrain it.
26
33
  *
27
34
  * Underneath the tools, the SAME lease loop the CLI `hold` runs keeps the order's
28
35
  * lease warm: `createHoldMcp` builds the loop with `onOrder` wired to capture the
@@ -35,15 +42,55 @@
35
42
  * its own — so a unit test drives the tools with a fake hub and a scriptable
36
43
  * clock. The role (`src/roles/hold.ts`) owns the real stdin/stdout pump.
37
44
  */
45
+ import { readFile } from 'node:fs/promises';
46
+ import { basename, extname } from 'node:path';
38
47
  import { textResult } from "../mcp/server.js";
39
48
  import { buildSubmitProof } from "../submit-proof.js";
40
49
  import { readSubmitValueFile } from "../submit-file.js";
50
+ import { resolveContainedPath } from "../contained-path.js";
41
51
  import { normalizeSubmitValue } from "../submit-value.js";
42
52
  import { createHoldLoop } from "./loop.js";
43
- export const HOLD_MCP_TOOL_NAMES = ['get_order', 'submit', 'reject', 'ask'];
53
+ export const HOLD_MCP_TOOL_NAMES = ['get_order', 'submit', 'reject', 'ask', 'put_file_artifact'];
44
54
  function errMsg(e) {
45
55
  return e instanceof Error ? e.message : String(e);
46
56
  }
57
+ /**
58
+ * Extension-to-MIME map for `put_file_artifact`'s optional `contentType`.
59
+ *
60
+ * Deliberately short. This is a convenience for the common case, not a content
61
+ * sniffer: the map covers what a step actually renders — images, video, audio,
62
+ * documents, archives, text — and everything else falls through to
63
+ * `application/octet-stream`, which is the honest answer for bytes whose type
64
+ * this process did not determine. A step that knows better passes `contentType`
65
+ * explicitly and this map is never consulted.
66
+ */
67
+ const CONTENT_TYPE_BY_EXTENSION = {
68
+ '.png': 'image/png',
69
+ '.jpg': 'image/jpeg',
70
+ '.jpeg': 'image/jpeg',
71
+ '.gif': 'image/gif',
72
+ '.webp': 'image/webp',
73
+ '.svg': 'image/svg+xml',
74
+ '.avif': 'image/avif',
75
+ '.mp4': 'video/mp4',
76
+ '.webm': 'video/webm',
77
+ '.mov': 'video/quicktime',
78
+ '.mp3': 'audio/mpeg',
79
+ '.wav': 'audio/wav',
80
+ '.pdf': 'application/pdf',
81
+ '.zip': 'application/zip',
82
+ '.tar': 'application/x-tar',
83
+ '.gz': 'application/gzip',
84
+ '.json': 'application/json',
85
+ '.txt': 'text/plain',
86
+ '.md': 'text/markdown',
87
+ '.csv': 'text/csv',
88
+ '.html': 'text/html',
89
+ '.log': 'text/plain',
90
+ };
91
+ function guessContentType(path) {
92
+ return CONTENT_TYPE_BY_EXTENSION[extname(path).toLowerCase()] ?? 'application/octet-stream';
93
+ }
47
94
  /** A lean, model-facing view of the order packet. */
48
95
  function orderView(res) {
49
96
  return { workflow: res.workflow, run: res.run, order: res.order, text: res.text };
@@ -342,11 +389,83 @@ export function createHoldMcp(deps) {
342
389
  }
343
390
  },
344
391
  };
392
+ const putFileArtifactTool = {
393
+ name: 'put_file_artifact',
394
+ description: 'Store a FILE you produced (image, video, PDF, archive, log, any bytes) and get back a small JSON envelope that names it. Use this whenever an owed output IS a file, or CONTAINS one: upload the file, then call submit with the envelope as the value, or embedded inside your value, e.g. {"summary": "...", "render": <envelope>}. The bytes are stored outside the database, so a large asset does not count against the artifact value size limit — the envelope is what the workflow stores, schema-checks and shows a judge. Do NOT base64 a file into a submit value; upload it here instead.',
395
+ inputSchema: {
396
+ type: 'object',
397
+ required: ['file'],
398
+ properties: {
399
+ file: {
400
+ type: 'string',
401
+ description: 'Path to the file to store. Relative paths resolve against the run working directory, and the file must be inside it.',
402
+ },
403
+ contentType: {
404
+ type: 'string',
405
+ description: 'MIME type of the bytes, e.g. image/png or video/mp4. Inferred from the file extension when omitted.',
406
+ },
407
+ filename: {
408
+ type: 'string',
409
+ description: 'Optional display name recorded in the envelope. Defaults to the file name.',
410
+ },
411
+ },
412
+ additionalProperties: false,
413
+ },
414
+ handler: async (args) => {
415
+ const gone = terminalGuard();
416
+ if (gone !== undefined)
417
+ return gone;
418
+ const file = args['file'];
419
+ if (typeof file !== 'string' || file.trim() === '') {
420
+ return textResult({ error: 'file-artifact-invalid: file must be a non-empty string' }, true);
421
+ }
422
+ const contentTypeArg = args['contentType'];
423
+ if (contentTypeArg !== undefined && (typeof contentTypeArg !== 'string' || contentTypeArg.trim() === '')) {
424
+ return textResult({ error: 'file-artifact-invalid: contentType must be a non-empty string when present' }, true);
425
+ }
426
+ const filenameArg = args['filename'];
427
+ if (filenameArg !== undefined && (typeof filenameArg !== 'string' || filenameArg.trim() === '')) {
428
+ return textResult({ error: 'file-artifact-invalid: filename must be a non-empty string when present' }, true);
429
+ }
430
+ try {
431
+ // Same two-phase containment as a submit value file, under this tool's
432
+ // own error family: the working directory is the only root a step's
433
+ // outputs may come from, and a symlink out of it is an exfiltration
434
+ // path, not a convenience.
435
+ const resolved = await resolveContainedPath(deps.workdir, file, 'file-artifact');
436
+ const bytes = new Uint8Array(await readFile(resolved));
437
+ if (bytes.byteLength === 0) {
438
+ return textResult({ error: `file-artifact-empty: ${file} is zero bytes` }, true);
439
+ }
440
+ const contentType = typeof contentTypeArg === 'string' ? contentTypeArg.trim() : guessContentType(resolved);
441
+ const filename = typeof filenameArg === 'string' ? filenameArg.trim() : basename(resolved);
442
+ const res = await hub.putFileArtifact({ workflow, bytes, contentType, filename });
443
+ // Hand back the envelope EXACTLY as it must be submitted. The hub's
444
+ // `text` is dropped from the pointer so the model cannot paste a field
445
+ // the artifact schema does not know about.
446
+ const pointer = {
447
+ __file: res.__file,
448
+ hash: res.hash,
449
+ size: res.size,
450
+ contentType: res.contentType,
451
+ ...(res.filename !== undefined ? { filename: res.filename } : {}),
452
+ };
453
+ return textResult({
454
+ pointer,
455
+ text: `Stored ${String(bytes.byteLength)} bytes as ${contentType}. Submit this pointer as your value, or embed it in one.`,
456
+ });
457
+ }
458
+ catch (e) {
459
+ return textResult({ error: errMsg(e) }, true);
460
+ }
461
+ },
462
+ };
345
463
  const registrations = {
346
464
  get_order: getOrderTool,
347
465
  submit: submitTool,
348
466
  reject: rejectTool,
349
467
  ask: askTool,
468
+ put_file_artifact: putFileArtifactTool,
350
469
  };
351
470
  const selected = deps.tools ?? HOLD_MCP_TOOL_NAMES;
352
471
  return { tools: selected.map((name) => registrations[name]), loop };
@@ -1,4 +1,4 @@
1
- import type { AnswerApprovalRequest, AnswerApprovalResponse, AskRequest, AskResponse, GetRostersResponse, ListHarnessModelsResponse, ListPendingApprovalsResponse, RequestApprovalRequest, RequestApprovalResponse, GetOrderRequest, GetOrderResponse, HeartbeatRequest, HeartbeatResponse, PresencePingRequest, PresencePingResponse, ReleaseRequest, ReleaseResponse, RejectRequest, RejectResponse, RetryArtifactRequest, RetryArtifactResponse, ReportResolutionRequest, ReportResolutionResponse, SubmitRequest, SubmitResponse, WakeResponse, WhatsNextRequest, WhatsNextResponse, WhoamiResponse } from './types.ts';
1
+ import type { AnswerApprovalRequest, AnswerApprovalResponse, AskRequest, AskResponse, GetRostersResponse, ListHarnessModelsResponse, ListPendingApprovalsResponse, RequestApprovalRequest, RequestApprovalResponse, GetOrderRequest, GetOrderResponse, HeartbeatRequest, HeartbeatResponse, PresencePingRequest, PresencePingResponse, PutFileArtifactRequest, PutFileArtifactResponse, ReleaseRequest, ReleaseResponse, RejectRequest, RejectResponse, RetryArtifactRequest, RetryArtifactResponse, ReportResolutionRequest, ReportResolutionResponse, SubmitRequest, SubmitResponse, WakeResponse, WhatsNextRequest, WhatsNextResponse, WhoamiResponse } from './types.ts';
2
2
  export interface HubClientOptions {
3
3
  /** Hub origin, e.g. `https://hub.owenloop.dev` (no trailing slash needed). */
4
4
  origin: string;
@@ -59,5 +59,14 @@ export interface HubClient {
59
59
  wake(cursor?: number): Promise<WakeResponse>;
60
60
  /** B4 Shift presence register/refresh. */
61
61
  presencePing(req: PresencePingRequest): Promise<PresencePingResponse>;
62
+ /**
63
+ * Store opaque bytes as a file artifact and return the envelope naming them.
64
+ *
65
+ * The only byte-bodied call on this client. Everything else sends JSON, so
66
+ * this one bypasses `post` rather than teaching `post` a second body mode:
67
+ * one call site with an explicit content type is easier to audit than a
68
+ * shared helper that silently means two different things.
69
+ */
70
+ putFileArtifact(req: PutFileArtifactRequest): Promise<PutFileArtifactResponse>;
62
71
  }
63
72
  export declare function createHubClient(opts: HubClientOptions): HubClient;
@@ -9,6 +9,11 @@
9
9
  * for `whoami`), and parses the `{ text, ...data }` envelope. Non-2xx becomes a
10
10
  * `HubError`.
11
11
  *
12
+ * `putFileArtifact` is the single exception to the JSON rule: its body is the
13
+ * asset's raw bytes under the asset's own content type. Base64 in a JSON field
14
+ * would inflate every upload by a third and force a multi-megabyte file through
15
+ * a JavaScript string, so the bytes travel as bytes.
16
+ *
12
17
  * PRESENCE (B4) + WAKE (B5): the C1 client deliberately omitted these because
13
18
  * their hub surface did not exist yet. Both are merged now, so C3 adds
14
19
  * `presencePing` (POST `/api/presence_ping`) and `wake` (GET `/api/wake`,
@@ -76,6 +81,23 @@ export function createHubClient(opts) {
76
81
  });
77
82
  return parse(res);
78
83
  }
84
+ async function postBytes(path, req) {
85
+ const token = await opts.getToken();
86
+ const headers = {
87
+ authorization: `Bearer ${token}`,
88
+ 'content-type': req.contentType,
89
+ };
90
+ // The name rides a header rather than the body because the body IS the
91
+ // bytes. It is a display label only; the hub never resolves it as a path.
92
+ if (req.filename !== undefined)
93
+ headers['x-file-name'] = req.filename;
94
+ const res = await fetchImpl(`${base}${path}?workflow=${encodeURIComponent(req.workflow)}`, {
95
+ method: 'POST',
96
+ headers,
97
+ body: req.bytes,
98
+ });
99
+ return parse(res);
100
+ }
79
101
  return {
80
102
  whatsNext: (req) => post('whats_next', req),
81
103
  getOrder: (req) => post('get_order', req),
@@ -96,5 +118,6 @@ export function createHubClient(opts) {
96
118
  // (the hub treats missing/invalid as a `changed: true` first sweep).
97
119
  wake: (cursor) => get('wake', typeof cursor === 'number' ? `cursor=${encodeURIComponent(String(cursor))}` : undefined),
98
120
  presencePing: (req) => post('presence_ping', req),
121
+ putFileArtifact: (req) => postBytes('/api/file-artifacts', req),
99
122
  };
100
123
  }
@@ -412,6 +412,37 @@ export interface SubmitResponse extends HubResponse {
412
412
  outcome?: string;
413
413
  closed?: boolean;
414
414
  }
415
+ /**
416
+ * Upload opaque bytes and get back the small JSON envelope that names them.
417
+ *
418
+ * This is the one hub call that does NOT send JSON. The bytes go up as the raw
419
+ * request body with their own content type, because a base64 round-trip would
420
+ * inflate a large asset by a third and force the whole file through a string.
421
+ */
422
+ export interface PutFileArtifactRequest {
423
+ /** Workflow the blob belongs to — it scopes the R2 key and its retention. */
424
+ workflow: string;
425
+ bytes: Uint8Array;
426
+ /** MIME type recorded in the envelope and served back on download. */
427
+ contentType: string;
428
+ /** Optional display name; the hub records it verbatim and never trusts it as a path. */
429
+ filename?: string;
430
+ }
431
+ /**
432
+ * The envelope, which IS the artifact value. `__file` is the discriminator the
433
+ * hub's pointer walk looks for; `hash` is the content address (so re-uploading
434
+ * identical bytes is free); `size` and `contentType` describe bytes a def can
435
+ * constrain with ordinary JSON Schema even though it can never see them.
436
+ */
437
+ export interface FileArtifactPointer {
438
+ __file: true;
439
+ hash: string;
440
+ size: number;
441
+ contentType: string;
442
+ filename?: string;
443
+ }
444
+ export interface PutFileArtifactResponse extends HubResponse, FileArtifactPointer {
445
+ }
415
446
  /**
416
447
  * Invalidate an artifact through the claiming worker's consume-edge authority.
417
448
  * `by` is deliberately absent: the hub derives the actor from the claiming
@@ -31,7 +31,7 @@ function parseStartArgs(args) {
31
31
  const parsed = { crews: [] };
32
32
  const valueFlags = new Set([
33
33
  '--origin', '--as', '--name', '--cap', '--max-agents', '--exec-reserve', '--local-queue-hold', '--poll-interval',
34
- '--cache-dir', '--state-dir', '--log-dir', '--log-max-age', '--work-root',
34
+ '--cache-dir', '--state-dir', '--log-dir', '--log-max-age', '--work-root', '--disk-floor',
35
35
  ]);
36
36
  for (let i = 0; i < args.length; i++) {
37
37
  const raw = args[i];
@@ -94,6 +94,12 @@ function parseStartArgs(args) {
94
94
  return { crews: parsed.crews, error: n };
95
95
  parsed.localQueueHoldMs = n;
96
96
  }
97
+ else if (name === '--disk-floor') {
98
+ const n = intValue(value, '--disk-floor');
99
+ if (typeof n !== 'number')
100
+ return { crews: parsed.crews, error: n };
101
+ parsed.diskFloorBytes = n;
102
+ }
97
103
  else if (name === '--poll-interval') {
98
104
  const n = intValue(value, '--poll-interval');
99
105
  if (typeof n !== 'number')