owenloop 0.5.8 → 0.5.9

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 (87) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +4 -2
  3. package/dist/packages/work/src/agent/loop.d.ts +23 -8
  4. package/dist/packages/work/src/agent/loop.js +48 -6
  5. package/dist/packages/work/src/consumed-verifier.js +6 -17
  6. package/dist/packages/work/src/exec/loop.d.ts +1 -1
  7. package/dist/packages/work/src/exec/loop.js +181 -32
  8. package/dist/packages/work/src/exec/receipt.d.ts +7 -7
  9. package/dist/packages/work/src/exec/receipt.js +6 -6
  10. package/dist/packages/work/src/harness/claude.js +100 -0
  11. package/dist/packages/work/src/hub/client.d.ts +19 -4
  12. package/dist/packages/work/src/hub/client.js +7 -3
  13. package/dist/packages/work/src/hub/types.d.ts +84 -0
  14. package/dist/packages/work/src/main.js +1 -0
  15. package/dist/packages/work/src/roles/agent-run.js +19 -22
  16. package/dist/packages/work/src/roles/exec.js +2 -0
  17. package/dist/packages/work/src/roles/settings.js +2 -0
  18. package/dist/packages/work/src/roles/shift.js +14 -2
  19. package/dist/packages/work/src/roles/util.d.ts +1 -0
  20. package/dist/packages/work/src/roles/util.js +10 -0
  21. package/dist/packages/work/src/settings/hub-roster-cache.d.ts +68 -0
  22. package/dist/packages/work/src/settings/hub-roster-cache.js +370 -0
  23. package/dist/packages/work/src/settings/roster.d.ts +84 -0
  24. package/dist/packages/work/src/settings/roster.js +364 -5
  25. package/dist/packages/work/src/settings/serving.d.ts +17 -0
  26. package/dist/packages/work/src/settings/serving.js +79 -0
  27. package/dist/packages/work/src/settings/settings.d.ts +14 -1
  28. package/dist/packages/work/src/settings/settings.js +14 -0
  29. package/dist/packages/work/src/shift/loop.d.ts +108 -5
  30. package/dist/packages/work/src/shift/loop.js +299 -51
  31. package/dist/packages/work/src/shift/protocol.d.ts +7 -5
  32. package/dist/packages/work/src/shift/runtime.d.ts +15 -0
  33. package/dist/packages/work/src/shift/runtime.js +94 -4
  34. package/dist/packages/work/src/shift/server.js +2 -0
  35. package/dist/packages/work/src/shift/spawn.d.ts +17 -2
  36. package/dist/packages/work/src/shift/spawn.js +16 -13
  37. package/dist/packages/work/src/shift/state.d.ts +29 -2
  38. package/dist/packages/work/src/shift/state.js +45 -15
  39. package/dist/packages/work/src/usage.d.ts +1 -1
  40. package/dist/packages/work/src/usage.js +7 -1
  41. package/dist/packages/work/src/util/modifier-init.d.ts +7 -0
  42. package/dist/packages/work/src/util/modifier-init.js +73 -0
  43. package/dist/src/bundle/tar.d.ts +9 -4
  44. package/dist/src/bundle/tar.js +9 -4
  45. package/dist/src/capabilities.d.ts +6 -0
  46. package/dist/src/cli.d.ts +14 -1
  47. package/dist/src/cli.js +687 -75
  48. package/dist/src/config-dir.d.ts +1 -1
  49. package/dist/src/config-dir.js +1 -1
  50. package/dist/src/crypto/index.d.ts +1 -1
  51. package/dist/src/crypto/index.js +1 -1
  52. package/dist/src/crypto/org-root.d.ts +30 -12
  53. package/dist/src/crypto/org-root.js +162 -14
  54. package/dist/src/crypto/records.d.ts +2 -0
  55. package/dist/src/crypto/records.js +2 -0
  56. package/dist/src/defs.d.ts +6 -1
  57. package/dist/src/defs.js +203 -8
  58. package/dist/src/engine.d.ts +42 -7
  59. package/dist/src/engine.js +158 -16
  60. package/dist/src/index.d.ts +4 -4
  61. package/dist/src/index.js +2 -2
  62. package/dist/src/mcp/serve.d.ts +22 -0
  63. package/dist/src/mcp/serve.js +88 -8
  64. package/dist/src/model.d.ts +2 -0
  65. package/dist/src/model.js +32 -25
  66. package/dist/src/order-resolver.d.ts +1 -0
  67. package/dist/src/order-resolver.js +8 -1
  68. package/dist/src/schemas/index.d.ts +11 -0
  69. package/dist/src/schemas/order.v1.schema.json +7 -1
  70. package/dist/src/store.d.ts +5 -0
  71. package/dist/src/store.js +43 -8
  72. package/dist/src/types.d.ts +40 -3
  73. package/docs/authoring.md +90 -2
  74. package/docs/bundles.md +26 -2
  75. package/docs/cli.md +170 -28
  76. package/docs/crypto.md +19 -3
  77. package/docs/design.md +70 -1
  78. package/docs/routing.md +189 -34
  79. package/docs/shift-logs.md +20 -9
  80. package/docs/wire-contracts.md +50 -7
  81. package/examples/workflows/delivery.yaml +31 -14
  82. package/examples/workflows/ship.yaml +10 -2
  83. package/package.json +1 -1
  84. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  85. package/plugins/claude-code/plugin/.mcp.json +1 -1
  86. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  87. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
@@ -713,6 +713,93 @@ const DEFAULT_START_DEPENDENCIES = {
713
713
  * process that started the session — which is exactly why `stop` is documented
714
714
  * as a no-op on a token this process did not start. */
715
715
  const SESSIONS = new Map();
716
+ /** Trim a progress line to something a log can hold. Mirrors the codex adapter's
717
+ * convention deliberately — the two adapters' logs are read side by side, so
718
+ * they truncate the same way. Kept local because this adapter must stay in one
719
+ * allowlisted file. */
720
+ const PROGRESS_TEXT_CAP = 2_000;
721
+ function cap(text) {
722
+ return text.length > PROGRESS_TEXT_CAP ? `${text.slice(0, PROGRESS_TEXT_CAP)}…` : text;
723
+ }
724
+ /** Mark messages produced inside a Task-tool subagent. A flat log cannot
725
+ * otherwise tell a subagent's work from the main agent's. */
726
+ function origin(parentToolUseId) {
727
+ return parentToolUseId === null ? '' : `[subagent ${parentToolUseId}] `;
728
+ }
729
+ /** Flatten a tool_result body to loggable text. Non-text parts are named, not
730
+ * rendered — an image block has no useful string form. */
731
+ function toolResultText(content) {
732
+ if (content === undefined)
733
+ return '(no content)';
734
+ if (typeof content === 'string')
735
+ return content;
736
+ return content.map((part) => (part.type === 'text' ? part.text : `(${part.type})`)).join('\n');
737
+ }
738
+ /** One progress line per content block of an assistant message.
739
+ *
740
+ * TOOL INPUTS ARE NEVER LOGGED. A `tool_use` block's `input` can hold a Bash
741
+ * command line carrying a secret. Only `name` and `id` are emitted — the same
742
+ * two fields the codex adapter reveals for `item/started mcpToolCall`. */
743
+ function emitAssistant(message, onEvent) {
744
+ const from = origin(message.parent_tool_use_id);
745
+ if (message.error !== undefined) {
746
+ onEvent({ kind: 'progress', text: `${from}assistant error: ${message.error}` });
747
+ }
748
+ for (const block of message.message.content) {
749
+ switch (block.type) {
750
+ case 'text':
751
+ onEvent({ kind: 'progress', text: cap(`${from}assistant: ${block.text}`) });
752
+ break;
753
+ case 'thinking':
754
+ onEvent({ kind: 'progress', text: cap(`${from}thinking: ${block.thinking}`) });
755
+ break;
756
+ case 'redacted_thinking':
757
+ onEvent({ kind: 'progress', text: `${from}thinking: (redacted)` });
758
+ break;
759
+ case 'tool_use':
760
+ case 'mcp_tool_use':
761
+ onEvent({ kind: 'progress', text: `${from}tool_use ${block.name} ${block.id}` });
762
+ break;
763
+ default:
764
+ // Server-tool results, container uploads, compaction markers and any
765
+ // block the vendor adds later. Naming the type keeps the line useful
766
+ // without guessing at a shape this version does not define.
767
+ onEvent({ kind: 'progress', text: `${from}${block.type} block` });
768
+ }
769
+ }
770
+ }
771
+ /** One progress line per content block of a user message — which on this path
772
+ * means tool results coming back, plus any synthetic user text.
773
+ *
774
+ * Tool RESULTS are logged (capped); tool INPUTS are not. A result is what the
775
+ * tool produced, and the codex adapter already logs the equivalent command
776
+ * output. */
777
+ function emitUser(message, onEvent) {
778
+ const from = origin(message.parent_tool_use_id);
779
+ const content = message.message.content;
780
+ if (typeof content === 'string') {
781
+ onEvent({ kind: 'progress', text: cap(`${from}user: ${content}`) });
782
+ return;
783
+ }
784
+ for (const block of content) {
785
+ switch (block.type) {
786
+ case 'text':
787
+ onEvent({ kind: 'progress', text: cap(`${from}user: ${block.text}`) });
788
+ break;
789
+ case 'tool_result': {
790
+ const flag = block.is_error === true ? ' (error)' : '';
791
+ const body = toolResultText(block.content);
792
+ onEvent({
793
+ kind: 'progress',
794
+ text: cap(`${from}tool_result ${block.tool_use_id}${flag}: ${body}`),
795
+ });
796
+ break;
797
+ }
798
+ default:
799
+ onEvent({ kind: 'progress', text: `${from}${block.type} block` });
800
+ }
801
+ }
802
+ }
716
803
  /**
717
804
  * Drive the SDK message stream to TURN END and map it onto `AgentEvent`s.
718
805
  *
@@ -766,8 +853,21 @@ export async function consumeTurn(q, onEvent, onInit, expectedSessionId) {
766
853
  onEvent({ kind: 'turn_ended' });
767
854
  return { sessionId, sawResult: true };
768
855
  }
856
+ else if (message.type === 'assistant') {
857
+ emitAssistant(message, onEvent);
858
+ }
859
+ else if (message.type === 'user') {
860
+ emitUser(message, onEvent);
861
+ }
769
862
  // `needs_input` is NEVER emitted: this SDK path has no blocking-question
770
863
  // channel that maps to it, and the contract has no reply channel by design.
864
+ // `stream_event` is deliberately NOT mapped. The SDK only emits it when
865
+ // `Options.includePartialMessages` is set, and `buildClaudeOptions` never
866
+ // sets it — so the branch would be unreachable today, and if it ever
867
+ // became reachable it would duplicate the text the `assistant` message
868
+ // already carries. Unrecognized types stay silent by design: the vendor
869
+ // adds message kinds between releases, and a mapping that threw on one
870
+ // would turn a routine CLI upgrade into a failed order.
771
871
  }
772
872
  return { sessionId, sawResult: false };
773
873
  }
@@ -1,4 +1,4 @@
1
- import type { AnswerApprovalRequest, AnswerApprovalResponse, AskRequest, AskResponse, ListPendingApprovalsResponse, RequestApprovalRequest, RequestApprovalResponse, GetOrderRequest, GetOrderResponse, HeartbeatRequest, HeartbeatResponse, PresencePingRequest, PresencePingResponse, ReleaseRequest, ReleaseResponse, RejectRequest, RejectResponse, 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, 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;
@@ -8,7 +8,7 @@ export interface HubClientOptions {
8
8
  fetchImpl?: typeof fetch;
9
9
  }
10
10
  export interface HubClient {
11
- whatsNext(req?: WhatsNextRequest): Promise<WhatsNextResponse>;
11
+ whatsNext(req: WhatsNextRequest): Promise<WhatsNextResponse>;
12
12
  getOrder(req: GetOrderRequest): Promise<GetOrderResponse>;
13
13
  heartbeat(req: HeartbeatRequest): Promise<HeartbeatResponse>;
14
14
  release(req: ReleaseRequest): Promise<ReleaseResponse>;
@@ -18,9 +18,20 @@ export interface HubClient {
18
18
  * ESCALATION: the worker stops and asks a human about an artifact it OWES.
19
19
  * Distinct from `reject`, which is a verdict on somebody else's delivered
20
20
  * work. Holds the artifact (no counter moves) until a human answers with
21
- * `owenloop retry <workflow> <path> --text "<answer>"`.
21
+ * `owenloop retry <workflow> <path> --text "<answer>"`, or with
22
+ * `retryArtifact` on this client.
22
23
  */
23
24
  ask(req: AskRequest): Promise<AskResponse>;
25
+ /**
26
+ * The HUMAN half of the escalation channel and the answer to `ask` above:
27
+ * re-arm a stalled or rejected artifact to `owed`, resetting its reject
28
+ * counters. `text` rides to the next producer on the artifact's reason
29
+ * thread. Omit `text` for a bare stall-clear — the engine supplies its own
30
+ * default, so do NOT default it here. Human-only by hub RBAC; an agent
31
+ * token is refused. Optional on this interface for the same reason
32
+ * `getRosters` is: it was added after the existing HubClient fakes.
33
+ */
34
+ retryArtifact?(req: RetryArtifactRequest): Promise<RetryArtifactResponse>;
24
35
  /**
25
36
  * TOOL APPROVAL — raise AND poll, one idempotent call. The worker is mid-flight
26
37
  * and needs yes/no on ONE tool call; unlike `ask`, the session stays alive, the
@@ -39,7 +50,11 @@ export interface HubClient {
39
50
  * re-dispatch no-ops rather than overwriting the first (pre-spend) record.
40
51
  */
41
52
  reportResolution(req: ReportResolutionRequest): Promise<ReportResolutionResponse>;
42
- whoami(): Promise<WhoamiResponse>;
53
+ whoami(signal?: AbortSignal): Promise<WhoamiResponse>;
54
+ /** Read the org's roster cascade using this caller's scoped identity. */
55
+ getRosters?(signal?: AbortSignal): Promise<GetRostersResponse>;
56
+ /** Read the hub's known harness/model registry. */
57
+ listHarnessModels?(): Promise<ListHarnessModelsResponse>;
43
58
  /** B5 cheap wake pre-check; `cursor` rides the query string only when set. */
44
59
  wake(cursor?: number): Promise<WakeResponse>;
45
60
  /** B4 Shift presence register/refresh. */
@@ -67,27 +67,31 @@ export function createHubClient(opts) {
67
67
  });
68
68
  return parse(res);
69
69
  }
70
- async function get(verb, query) {
70
+ async function get(verb, query, signal) {
71
71
  const url = query !== undefined && query !== '' ? `${base}/api/${verb}?${query}` : `${base}/api/${verb}`;
72
72
  const res = await fetchImpl(url, {
73
73
  method: 'GET',
74
74
  headers: await authHeaders(),
75
+ ...(signal === undefined ? {} : { signal }),
75
76
  });
76
77
  return parse(res);
77
78
  }
78
79
  return {
79
- whatsNext: (req = {}) => post('whats_next', req),
80
+ whatsNext: (req) => post('whats_next', req),
80
81
  getOrder: (req) => post('get_order', req),
81
82
  heartbeat: (req) => post('heartbeat', req),
82
83
  release: (req) => post('release', req),
83
84
  submit: (req) => post('submit', req),
84
85
  reject: (req) => post('reject', req),
85
86
  ask: (req) => post('ask', req),
87
+ retryArtifact: (req) => post('retry_artifact', req),
86
88
  requestApproval: (req) => post('request_approval', req),
87
89
  answerApproval: (req) => post('answer_approval', req),
88
90
  listPendingApprovals: () => post('list_pending_approvals', {}),
89
91
  reportResolution: (req) => post('report_resolution', req),
90
- whoami: () => get('whoami'),
92
+ whoami: (signal) => get('whoami', undefined, signal),
93
+ getRosters: (signal) => get('rosters', undefined, signal),
94
+ listHarnessModels: () => get('harness_models'),
91
95
  // Cursor is an opaque non-negative integer; omit it entirely to bootstrap
92
96
  // (the hub treats missing/invalid as a `changed: true` first sweep).
93
97
  wake: (cursor) => get('wake', typeof cursor === 'number' ? `cursor=${encodeURIComponent(String(cursor))}` : undefined),
@@ -11,6 +11,12 @@ export interface WhatsNextRequest {
11
11
  workflow?: string;
12
12
  /** Server-side filter for which serve crews this caller will accept. */
13
13
  serve_crews?: string[];
14
+ /**
15
+ * Capability keys in this shift's effective merged rosters. Keys are raw:
16
+ * bare names and exact compounds may be mixed; the hub applies bare-name
17
+ * matching. An empty array legitimately means the shift serves nothing.
18
+ */
19
+ serve_capabilities: string[];
14
20
  }
15
21
  /**
16
22
  * One work order from a per-workflow `whats_next` sweep. `run` is the order
@@ -26,6 +32,14 @@ export interface WorkOrder {
26
32
  key?: string;
27
33
  index?: number;
28
34
  defDigest?: string;
35
+ /** The composed capabilities the hub offered this order under. */
36
+ capabilities?: string[];
37
+ /**
38
+ * THE CREWS THE HUB MATCHED for this order's capabilities, in match order.
39
+ * Hub → worker; this is not `serve_crews`, which travels worker → hub to
40
+ * narrow the orders a shift wants.
41
+ */
42
+ crews?: string[];
29
43
  /** Authoritative worker lane on modern whats_next responses. */
30
44
  worker?: string;
31
45
  consumedFingerprint?: Record<string, number>;
@@ -112,6 +126,12 @@ export interface WakeResponse extends HubResponse {
112
126
  export interface PresencePingRequest {
113
127
  name: string;
114
128
  serve_crews?: string[];
129
+ /**
130
+ * Capability keys in this shift's effective merged rosters. Keys are raw:
131
+ * bare names and exact compounds may be mixed; the hub applies bare-name
132
+ * matching. An empty array legitimately means the shift serves nothing.
133
+ */
134
+ serve_capabilities: string[];
115
135
  shift_id?: string;
116
136
  started_at?: number;
117
137
  /** Epoch-millisecond timestamp of the last accepted local shift attendance. */
@@ -192,6 +212,24 @@ export interface OrderPacket {
192
212
  * guessing.
193
213
  */
194
214
  capabilities?: string[];
215
+ /**
216
+ * THE CREWS THE HUB MATCHED for this order's capabilities, in match order.
217
+ *
218
+ * Hub → worker. This is the hub's answer to "whose roster decides the model
219
+ * for this order", computed at offer time from `capability_routes`. The
220
+ * worker resolves each named crew's merged roster IN THIS ORDER and takes the
221
+ * first crew that carries a row for one of `capabilities`.
222
+ *
223
+ * NOT `serve_crews`. `serve_crews` travels the other way — worker → hub,
224
+ * on `whats_next`/`presence_ping` — and narrows WHICH ORDERS THIS SHIFT
225
+ * WANTS. This field narrows WHICH ROSTER DECIDES an order the shift already
226
+ * has.
227
+ *
228
+ * Optional on the wire because a hub that predates the stamp sends nothing.
229
+ * It is NOT optional in effect: a worker built from this commit REFUSES every
230
+ * capability-bearing order that arrives without it. There is no fallback.
231
+ */
232
+ crews?: string[];
195
233
  /** The run's routing modifier (`deep`), as the caller asked for at start_run. */
196
234
  modifier?: string;
197
235
  /**
@@ -261,6 +299,7 @@ export interface ReasonEntry {
261
299
  by: string;
262
300
  text: string;
263
301
  fromVersion?: number;
302
+ requested?: string;
264
303
  }
265
304
  export interface GetOrderResponse extends HubResponse {
266
305
  workflow: string;
@@ -384,6 +423,22 @@ export interface RejectResponse extends HubResponse {
384
423
  ok: boolean;
385
424
  closed?: boolean;
386
425
  }
426
+ /**
427
+ * The HUMAN stall-clearing lever and answer path for ask. Re-arms a stalled or
428
+ * rejected artifact to owed, resetting its reject counters. text rides to the
429
+ * next producer on the artifact's reason thread; omit it for a bare
430
+ * stall-clear so the engine supplies its own default.
431
+ */
432
+ export interface RetryArtifactRequest {
433
+ workflow: string;
434
+ path: string;
435
+ text?: string;
436
+ }
437
+ /** The retry-artifact verb's flattened response envelope. */
438
+ export interface RetryArtifactResponse extends HubResponse {
439
+ ok: boolean;
440
+ closed?: boolean;
441
+ }
387
442
  /**
388
443
  * ESCALATION: the claiming worker cannot honestly build what it owes and stops
389
444
  * to ask a person. `path` is one of the order's OWED paths — unlike `reject`,
@@ -510,6 +565,35 @@ export interface WhoamiResponse extends HubResponse {
510
565
  authMethod: 'token' | 'oauth' | 'session' | 'debug';
511
566
  email?: string;
512
567
  }
568
+ /** One model choice in an org-owned roster row. */
569
+ export interface RosterCandidateWire {
570
+ harness: string;
571
+ model: string;
572
+ effort: string;
573
+ }
574
+ /** The agent-readable org roster cascade. */
575
+ export interface GetRostersResponse extends HubResponse {
576
+ global: Record<string, RosterCandidateWire[]>;
577
+ crews: Array<{
578
+ crewId: string;
579
+ crewName: string | null;
580
+ roster: Record<string, RosterCandidateWire[]>;
581
+ }>;
582
+ }
583
+ /** The hub's current harness/model registry, for roster administration. */
584
+ export interface ListHarnessModelsResponse extends HubResponse {
585
+ harnesses: Array<{
586
+ harness: string;
587
+ displayName: string;
588
+ }>;
589
+ models: Array<{
590
+ harness: string;
591
+ model: string;
592
+ efforts: string[];
593
+ updatedAt: number;
594
+ updatedBy: string;
595
+ }>;
596
+ }
513
597
  /**
514
598
  * Thrown for any non-2xx hub response. `code` is the hub's `error` slug
515
599
  * (e.g. `bad_request`) when the body parsed as the hub's `{ error, message }`
@@ -27,6 +27,7 @@ const ROLES = {
27
27
  join: () => import("./roles/join.js"),
28
28
  sessions: () => import("./roles/sessions.js"),
29
29
  approvals: () => import("./roles/approvals.js"),
30
+ util: () => import("./roles/util.js"),
30
31
  };
31
32
  export async function mainAsync(argv) {
32
33
  const [first, ...rest] = argv;
@@ -86,13 +86,13 @@ import "../harnesses.js";
86
86
  // ─────────────────────────────────────────────────────────────────────────────
87
87
  import { hostname } from 'node:os';
88
88
  import { resolveCacheDir } from "../bundle/cache.js";
89
- import { createAgentRunLoop } from "../agent/loop.js";
89
+ import { createAgentRunLoop, } from "../agent/loop.js";
90
90
  import { createDefaultStoreInstructionResolver } from "../exec/instructions.js";
91
91
  import { createConsumedVerifier } from "../consumed-verifier.js";
92
92
  import { createHubClient } from "../hub/client.js";
93
93
  import { resolveBearer } from "../credentials/resolve.js";
94
94
  import { loadSettings } from "../settings/settings.js";
95
- import { machineRosterLayers, mergeRosterLayers } from "../settings/roster.js";
95
+ import { effectiveRosterLayers, mergeRosterLayers } from "../settings/roster.js";
96
96
  import { adapterFor, defaultHarnessId, registeredHarnessIds } from "../harness/registry.js";
97
97
  import { parseHarnessCarrier } from "../bundle/fetch.js";
98
98
  import { normalizeStepPermissions, validateHarnessOptions } from "../harness/permissions.js";
@@ -198,6 +198,8 @@ export function exitCodeFor(outcome) {
198
198
  case 'no-template':
199
199
  case 'no-harness':
200
200
  case 'incompatible-harness-policy':
201
+ case 'unstamped-order':
202
+ case 'unresolvable-crew':
201
203
  case 'unresolvable-capability':
202
204
  case 'unverified-consumed':
203
205
  case 'session-store-failed':
@@ -264,25 +266,6 @@ export async function run(args, deps = {}) {
264
266
  err(`owenloop work agent-run: ${errMsg(e)}`);
265
267
  return 1;
266
268
  }
267
- // Phase 1 interim rule: choose crew rosters in the order the shift was
268
- // started with. Phase 2 replaces this handoff with crews stamped by the hub
269
- // on each offer. A hand-run worker and a shift started with --all see only
270
- // the machine-global settings layer.
271
- const servedCrews = (env['OWENLOOP_SERVE_CREWS'] ?? '')
272
- .split(',')
273
- .map((crew) => crew.trim())
274
- .filter((crew) => crew !== '');
275
- let rosters;
276
- try {
277
- rosters =
278
- servedCrews.length > 0
279
- ? servedCrews.map((crew) => mergeRosterLayers(machineRosterLayers(env, crew)))
280
- : [mergeRosterLayers(machineRosterLayers(env, undefined))];
281
- }
282
- catch (e) {
283
- err(`owenloop work agent-run: ${errMsg(e)}`);
284
- return 1;
285
- }
286
269
  const origin = parsed.origin ?? settings.hubOrigin;
287
270
  if (origin === undefined || origin.trim() === '') {
288
271
  err('owenloop work agent-run: no hub origin — pass --origin <url> or set hubOrigin in settings');
@@ -337,6 +320,20 @@ export async function run(args, deps = {}) {
337
320
  'Authenticate the account instead: `owenloop login --hub <origin> --as agent:<account>`.');
338
321
  }
339
322
  const account = workerEnv['OWENLOOP_ACCOUNT'] ?? 'default';
323
+ // The crews the HUB STAMPED on the order decide which rosters apply, so this
324
+ // runs per order inside the loop — the stamp does not exist at process start.
325
+ const resolveCrewRosters = (crews) => {
326
+ const rosters = [];
327
+ for (const crew of crews) {
328
+ try {
329
+ rosters.push(mergeRosterLayers(effectiveRosterLayers(env, crew, { origin, account })));
330
+ }
331
+ catch (e) {
332
+ return { ok: false, crew, detail: errMsg(e) };
333
+ }
334
+ }
335
+ return { ok: true, rosters };
336
+ };
340
337
  let hub = deps.hub;
341
338
  if (hub === undefined) {
342
339
  const bearer = await resolveBearer({ origin, account, env: workerEnv });
@@ -507,7 +504,7 @@ export async function run(args, deps = {}) {
507
504
  allowedWorkdirRoots: resolveAllowedWorkdirRoots(env, settings.allowedWorkdirRoots, process.cwd()),
508
505
  loadStep,
509
506
  resolveAdapter,
510
- rosters,
507
+ resolveCrewRosters,
511
508
  // Phase-1 availability means registry membership. A real binary or
512
509
  // credential probe requires new HarnessAdapter contract surface.
513
510
  harnessAvailable: (id) => adapterFor(id) !== undefined,
@@ -130,6 +130,8 @@ export function exitCodeFor(outcome) {
130
130
  case 'hub-unreachable':
131
131
  case 'submit-rejected':
132
132
  case 'submit-failed':
133
+ case 'command-failed':
134
+ case 'ask-failed':
133
135
  case 'judge-no-verdict':
134
136
  case 'reject-failed':
135
137
  case 'stopped':
@@ -23,6 +23,8 @@ import { inspectSettings, KNOWN_SETTINGS_KEYS } from "../settings/settings.js";
23
23
  */
24
24
  const DEFAULT_NOTE = {
25
25
  dispatchCap: '3',
26
+ execReserve: '1',
27
+ localQueueHoldMs: '0',
26
28
  commandRouting: 'shift',
27
29
  defPolicy: 'warn',
28
30
  };
@@ -12,7 +12,7 @@ import { noDaemonMessage, parseNextArgs, parseStateDirArgs, requestShift, ShiftC
12
12
  import { isShiftError } from "../shift/protocol.js";
13
13
  function usage() {
14
14
  process.stderr.write('usage: owenloop shift start <crew...> [--all] [--origin <url>] [--as <account>] [--name <n>]\n' +
15
- ' [--cap <n>] [--max-agents <n>] [--poll-interval <ms>] [--once]\n' +
15
+ ' [--cap <n>] [--max-agents <n>] [--exec-reserve <n>] [--local-queue-hold <ms>] [--poll-interval <ms>] [--once]\n' +
16
16
  ' [--cache-dir <p>] [--state-dir <p>]\n' +
17
17
  ' [--log-dir <p>] [--log-max-age <ms>]\n' +
18
18
  ' [--work-root <dir>]... restrict this shift to these directories\n' +
@@ -30,7 +30,7 @@ function intValue(raw, flag) {
30
30
  function parseStartArgs(args) {
31
31
  const parsed = { crews: [] };
32
32
  const valueFlags = new Set([
33
- '--origin', '--as', '--name', '--cap', '--max-agents', '--poll-interval',
33
+ '--origin', '--as', '--name', '--cap', '--max-agents', '--exec-reserve', '--local-queue-hold', '--poll-interval',
34
34
  '--cache-dir', '--state-dir', '--log-dir', '--log-max-age', '--work-root',
35
35
  ]);
36
36
  for (let i = 0; i < args.length; i++) {
@@ -82,6 +82,18 @@ function parseStartArgs(args) {
82
82
  return { crews: parsed.crews, error: n };
83
83
  parsed.maxAgents = n;
84
84
  }
85
+ else if (name === '--exec-reserve') {
86
+ const n = intValue(value, '--exec-reserve');
87
+ if (typeof n !== 'number')
88
+ return { crews: parsed.crews, error: n };
89
+ parsed.execReserve = n;
90
+ }
91
+ else if (name === '--local-queue-hold') {
92
+ const n = intValue(value, '--local-queue-hold');
93
+ if (typeof n !== 'number')
94
+ return { crews: parsed.crews, error: n };
95
+ parsed.localQueueHoldMs = n;
96
+ }
85
97
  else if (name === '--poll-interval') {
86
98
  const n = intValue(value, '--poll-interval');
87
99
  if (typeof n !== 'number')
@@ -0,0 +1 @@
1
+ export declare function run(args: string[]): Promise<number>;
@@ -0,0 +1,10 @@
1
+ import { runModifierInit } from "../util/modifier-init.js";
2
+ export async function run(args) {
3
+ const [command, ...rest] = args;
4
+ if (command !== 'modifier-init') {
5
+ process.stderr.write(`owenloop util: unknown command '${command ?? ''}'\n`);
6
+ process.stderr.write('usage: owenloop util modifier-init --default <value>\n');
7
+ return 2;
8
+ }
9
+ return runModifierInit(rest);
10
+ }
@@ -0,0 +1,68 @@
1
+ import { type Roster } from '../agent/capability-model.ts';
2
+ import type { HubClient } from '../hub/client.ts';
3
+ import type { RosterLayer } from './roster.ts';
4
+ export interface HubRosterCacheCrew {
5
+ crewId: string;
6
+ crewName: string | null;
7
+ roster: Roster;
8
+ }
9
+ export interface HubRosterCacheEntry {
10
+ version: 1;
11
+ origin: string;
12
+ orgId: string;
13
+ orgName: string;
14
+ account: string;
15
+ fetchedAt: number;
16
+ global: Roster;
17
+ crews: HubRosterCacheCrew[];
18
+ }
19
+ export type HubRosterCacheRead = {
20
+ kind: 'hit';
21
+ path: string;
22
+ data: HubRosterCacheEntry;
23
+ } | {
24
+ kind: 'miss';
25
+ path: string;
26
+ reason: string;
27
+ };
28
+ type Env = Record<string, string | undefined>;
29
+ export declare const DEFAULT_HUB_ROSTER_SYNC_TIMEOUT_MS = 10000;
30
+ /** Bound a refresh even when a test seam or non-fetch client ignores abort. */
31
+ export declare function withHubRosterSyncTimeout<T>(run: (signal: AbortSignal) => Promise<T>, timeoutMs?: number): Promise<T>;
32
+ export declare function hubRosterCacheDir(env: Env): string;
33
+ /** A filename is an index only; readers always verify the fields inside it. */
34
+ export declare function sanitizeOriginForFilename(origin: string): string;
35
+ /** Org ids are hub data, so they are filename-encoded rather than interpolated. */
36
+ export declare function sanitizeOrgIdForFilename(orgId: string): string;
37
+ export declare function hubRosterCachePath(env: Env, origin: string, orgId: string, account?: string): string;
38
+ export interface HubRosterCacheWriteOptions {
39
+ /** Test seam for an unlink failure after the new snapshot has landed. */
40
+ remove?: (path: string) => void;
41
+ /** Test seam; the production default makes concurrent writers distinct. */
42
+ tempSuffix?: () => string;
43
+ /** Test seam for a partial/failed temp-file write after exclusive creation. */
44
+ writeTemp?: (fd: number, contents: string) => void;
45
+ /** Test seam for a failed rename after the complete temp file is closed. */
46
+ rename?: (from: string, to: string) => void;
47
+ }
48
+ /** Atomically write a verified snapshot, then drop a prior org snapshot for
49
+ * the same origin/account pair so a re-pointed token cannot be served stale. */
50
+ export declare function writeHubRosterCache(env: Env, entry: HubRosterCacheEntry, options?: HubRosterCacheWriteOptions): void;
51
+ /**
52
+ * Find a cache by the information an offline child actually has (origin plus
53
+ * account), never by trusting its filename. Every bad cache state degrades to
54
+ * a miss; this is deliberately the opposite of `readCrewRoster`.
55
+ */
56
+ export declare function readHubRosterCache(env: Env, origin: string, account: string): HubRosterCacheRead;
57
+ /** The hub's two layers, strongest first. Missing cache remains visible as
58
+ * absent layers, so `roster show` can explain an offline child's routing. */
59
+ export declare function hubRosterLayers(read: HubRosterCacheRead, crew: string | undefined): RosterLayer[];
60
+ /** Refresh the disk snapshot with the same agent credential a shift uses. */
61
+ export declare function syncHubRosterCache(deps: {
62
+ client: HubClient;
63
+ env: Env;
64
+ origin: string;
65
+ account: string;
66
+ signal?: AbortSignal;
67
+ }): Promise<void>;
68
+ export {};