owenloop 0.5.6 → 0.5.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/dist/packages/work/src/agent/approvals.d.ts +53 -0
- package/dist/packages/work/src/agent/approvals.js +132 -0
- package/dist/packages/work/src/agent/brief.d.ts +12 -0
- package/dist/packages/work/src/agent/brief.js +51 -0
- package/dist/packages/work/src/agent/loop.d.ts +4 -0
- package/dist/packages/work/src/agent/loop.js +33 -0
- package/dist/packages/work/src/harness/claude.d.ts +4 -0
- package/dist/packages/work/src/harness/claude.js +72 -3
- package/dist/packages/work/src/harness/codex.d.ts +37 -1
- package/dist/packages/work/src/harness/codex.js +133 -14
- package/dist/packages/work/src/harness/contract.d.ts +54 -1
- package/dist/packages/work/src/harness/session-store.d.ts +65 -15
- package/dist/packages/work/src/harness/session-store.js +53 -51
- package/dist/packages/work/src/hub/client.d.ts +13 -1
- package/dist/packages/work/src/hub/client.js +3 -0
- package/dist/packages/work/src/hub/types.d.ts +101 -0
- package/dist/packages/work/src/main.js +1 -0
- package/dist/packages/work/src/roles/agent-run.js +4 -0
- package/dist/packages/work/src/roles/approvals.d.ts +76 -0
- package/dist/packages/work/src/roles/approvals.js +231 -0
- package/dist/packages/work/src/shift/loop.d.ts +2 -0
- package/dist/packages/work/src/shift/loop.js +2 -0
- package/dist/packages/work/src/shift/runtime.js +23 -7
- package/dist/packages/work/src/shift/spawn.d.ts +4 -0
- package/dist/packages/work/src/shift/spawn.js +6 -0
- package/dist/packages/work/src/usage.d.ts +1 -1
- package/dist/packages/work/src/usage.js +5 -0
- package/dist/src/crypto/records.d.ts +2 -0
- package/dist/src/crypto/records.js +13 -0
- package/dist/src/engine.js +5 -1
- package/dist/src/model.d.ts +37 -1
- package/dist/src/model.js +47 -1
- package/dist/src/schemas/index.d.ts +11 -0
- package/dist/src/schemas/order.v1.schema.json +9 -0
- package/dist/src/types.d.ts +34 -0
- package/package.json +1 -1
- package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
- package/plugins/claude-code/plugin/.mcp.json +1 -1
- package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
- package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
|
@@ -670,17 +670,94 @@ function createTurnGate(onEvent) {
|
|
|
670
670
|
},
|
|
671
671
|
};
|
|
672
672
|
}
|
|
673
|
+
const BRIDGEABLE_APPROVALS = Object.freeze({
|
|
674
|
+
'item/commandExecution/requestApproval': { kind: 'exec', toolName: 'command', legacy: false },
|
|
675
|
+
'item/fileChange/requestApproval': { kind: 'file', toolName: 'file-change', legacy: false },
|
|
676
|
+
'execCommandApproval': { kind: 'exec', toolName: 'command', legacy: true },
|
|
677
|
+
'applyPatchApproval': { kind: 'patch', toolName: 'file-change', legacy: true },
|
|
678
|
+
});
|
|
679
|
+
/** Join a legacy `command: string[]` (or pass a v2 `command: string`) for display. */
|
|
680
|
+
function commandText(value) {
|
|
681
|
+
if (Array.isArray(value)) {
|
|
682
|
+
const parts = value.filter((p) => typeof p === 'string');
|
|
683
|
+
return parts.length > 0 ? parts.join(' ') : undefined;
|
|
684
|
+
}
|
|
685
|
+
return str(value);
|
|
686
|
+
}
|
|
687
|
+
/**
|
|
688
|
+
* Turn one approval request into the question a person will actually read.
|
|
689
|
+
*
|
|
690
|
+
* The identity (`toolUseId`) has to be stable for the life of the call and
|
|
691
|
+
* unique among live calls, because the hub keys the approval on it. `itemId` /
|
|
692
|
+
* `callId` is that identity; `approvalId` is appended when present, since one
|
|
693
|
+
* item can raise several callbacks (the zsh-exec-bridge case) and collapsing
|
|
694
|
+
* them would let one answer decide two commands.
|
|
695
|
+
*
|
|
696
|
+
* `toolInput` is trimmed rather than forwarded whole. The raw params carry full
|
|
697
|
+
* file diffs and policy-amendment proposals, and a hub row nobody can read is
|
|
698
|
+
* not evidence — the command and the paths are what the decision turns on.
|
|
699
|
+
*/
|
|
700
|
+
function describeApproval(shape, params) {
|
|
701
|
+
const p = asMap(params);
|
|
702
|
+
const base = str(p['itemId']) ?? str(p['callId']) ?? 'unknown';
|
|
703
|
+
const callback = str(p['approvalId']);
|
|
704
|
+
const toolUseId = `${shape.kind}:${base}${callback !== undefined ? `:${callback}` : ''}`;
|
|
705
|
+
const command = commandText(p['command']);
|
|
706
|
+
const cwd = str(p['cwd']);
|
|
707
|
+
const files = Object.keys(asMap(p['fileChanges']));
|
|
708
|
+
const grantRoot = str(p['grantRoot']);
|
|
709
|
+
const detail = command !== undefined
|
|
710
|
+
? command
|
|
711
|
+
: files.length > 0
|
|
712
|
+
? `writes ${files.join(', ')}`
|
|
713
|
+
: grantRoot !== undefined
|
|
714
|
+
? `writes under ${grantRoot}`
|
|
715
|
+
: 'a change this harness would not make on its own';
|
|
716
|
+
return {
|
|
717
|
+
toolUseId,
|
|
718
|
+
toolName: shape.toolName,
|
|
719
|
+
toolInput: {
|
|
720
|
+
...(command !== undefined ? { command } : {}),
|
|
721
|
+
...(cwd !== undefined ? { cwd } : {}),
|
|
722
|
+
...(files.length > 0 ? { files } : {}),
|
|
723
|
+
...(grantRoot !== undefined ? { grantRoot } : {}),
|
|
724
|
+
},
|
|
725
|
+
// The harness's own words when it supplied them. When it did not, say WHY
|
|
726
|
+
// this arrived rather than inventing a hazard nobody assessed: the step's
|
|
727
|
+
// approval policy is what escalated it.
|
|
728
|
+
reason: str(p['reason']) ??
|
|
729
|
+
"the step's approval policy escalated this call instead of running it unattended",
|
|
730
|
+
title: cap(detail),
|
|
731
|
+
};
|
|
732
|
+
}
|
|
673
733
|
/**
|
|
674
734
|
* Answer every server→client request. An unanswered one hangs the turn past the
|
|
675
735
|
* worker's lease, which is the single worst outcome available in this file.
|
|
676
736
|
*
|
|
677
|
-
*
|
|
678
|
-
*
|
|
679
|
-
*
|
|
680
|
-
*
|
|
681
|
-
*
|
|
682
|
-
*
|
|
683
|
-
*
|
|
737
|
+
* TWO THINGS CAN BE GRANTED WITHOUT A PERSON, and only two.
|
|
738
|
+
*
|
|
739
|
+
* 1. A tool call on owenloop's own MCP mount — see the
|
|
740
|
+
* `mcpServer/elicitation/request` case.
|
|
741
|
+
* 2. Nothing else.
|
|
742
|
+
*
|
|
743
|
+
* WHAT CHANGED WHEN THE APPROVAL CHANNEL LANDED. The four requests in
|
|
744
|
+
* `BRIDGEABLE_APPROVALS` used to be refused with a throw, on the reasoning that
|
|
745
|
+
* "inventing an approval the policy said would never be asked for is a security
|
|
746
|
+
* decision this adapter is not authorized to make". That reasoning still holds
|
|
747
|
+
* exactly — and it is why `approvals` is the ONLY thing that changes it. With a
|
|
748
|
+
* requester wired in, this adapter is no longer inventing anything: it is
|
|
749
|
+
* relaying a question to a person and replying with THEIR answer. With no
|
|
750
|
+
* requester, the old refusal is what still happens, byte for byte.
|
|
751
|
+
*
|
|
752
|
+
* A REFUSAL IS NEVER A HANG. Every path here replies: an approval becomes
|
|
753
|
+
* `accept`/`approved`, and a denial, a deadline, an unreachable hub, or a
|
|
754
|
+
* requester that throws all become `decline`/`denied` plus a `progress` line
|
|
755
|
+
* naming the cause. On the legacy pair the person's reason travels back to the
|
|
756
|
+
* model inside `{denied:{rejection}}`; the v2 decision enum has no message
|
|
757
|
+
* field, so there the reason reaches the log and not the model.
|
|
758
|
+
*
|
|
759
|
+
* `item/permissions/requestApproval` is still refused unconditionally — see
|
|
760
|
+
* `BRIDGEABLE_APPROVALS` for why a permission profile is not a yes/no question.
|
|
684
761
|
*
|
|
685
762
|
* `item/tool/requestUserInput` and every non-owenloop elicitation emit
|
|
686
763
|
* `needs_input` and then throw: the Phase 1 contract deliberately has no reply
|
|
@@ -688,8 +765,33 @@ function createTurnGate(onEvent) {
|
|
|
688
765
|
* error reply surfaces to the model as a failed tool call — the least-wrong
|
|
689
766
|
* behavior available (contract observation 3).
|
|
690
767
|
*/
|
|
691
|
-
function handleServerRequest(onEvent) {
|
|
768
|
+
export function handleServerRequest(onEvent, approvals) {
|
|
692
769
|
return async (method, params) => {
|
|
770
|
+
const shape = BRIDGEABLE_APPROVALS[method];
|
|
771
|
+
if (shape !== undefined && approvals !== undefined) {
|
|
772
|
+
const ask = describeApproval(shape, params);
|
|
773
|
+
let denial = 'the approval channel produced no answer';
|
|
774
|
+
try {
|
|
775
|
+
const outcome = await approvals(ask);
|
|
776
|
+
if (outcome.decision === 'approved') {
|
|
777
|
+
onEvent({ kind: 'progress', text: `approved '${method}': ${ask.title}` });
|
|
778
|
+
return shape.legacy ? { decision: 'approved' } : { decision: 'accept' };
|
|
779
|
+
}
|
|
780
|
+
denial = outcome.note !== undefined && outcome.note !== ''
|
|
781
|
+
? `${outcome.reason ?? 'denied'} — ${outcome.note}`
|
|
782
|
+
: (outcome.reason ?? 'denied');
|
|
783
|
+
}
|
|
784
|
+
catch (err) {
|
|
785
|
+
// The requester is contracted to always answer, so this is a defect in
|
|
786
|
+
// it rather than an expected path. It still cannot be allowed to hang
|
|
787
|
+
// the turn: a broken channel denies, exactly like a silent one.
|
|
788
|
+
denial = `the approval channel failed: ${describe(err)}`;
|
|
789
|
+
}
|
|
790
|
+
onEvent({ kind: 'progress', text: `denied '${method}': ${cap(denial)}` });
|
|
791
|
+
return shape.legacy
|
|
792
|
+
? { decision: { denied: { rejection: denial } } }
|
|
793
|
+
: { decision: 'decline' };
|
|
794
|
+
}
|
|
693
795
|
switch (method) {
|
|
694
796
|
case 'item/tool/requestUserInput': {
|
|
695
797
|
const questions = asMap(params)['questions'];
|
|
@@ -723,14 +825,26 @@ function handleServerRequest(onEvent) {
|
|
|
723
825
|
onEvent({ kind: 'needs_input', question: cap(message) });
|
|
724
826
|
throw new Error('owenloop hosts this session headlessly and cannot answer an elicitation');
|
|
725
827
|
}
|
|
828
|
+
case 'item/permissions/requestApproval': {
|
|
829
|
+
// Refused even WITH an approval channel: the reply is a permission
|
|
830
|
+
// profile, not a decision, so there is no question a person could be
|
|
831
|
+
// shown whose answer this would be.
|
|
832
|
+
onEvent({
|
|
833
|
+
kind: 'progress',
|
|
834
|
+
text: `refusing '${method}': granting it means synthesizing a permission profile, not answering a question`,
|
|
835
|
+
});
|
|
836
|
+
throw new Error(`'${method}' is not answerable by a headless host`);
|
|
837
|
+
}
|
|
726
838
|
case 'item/commandExecution/requestApproval':
|
|
727
839
|
case 'item/fileChange/requestApproval':
|
|
728
|
-
case 'item/permissions/requestApproval':
|
|
729
840
|
case 'applyPatchApproval':
|
|
730
841
|
case 'execCommandApproval': {
|
|
842
|
+
// Only reachable with NO approval channel wired in — with one, the
|
|
843
|
+
// branch above this switch handled it. Unchanged from before the
|
|
844
|
+
// channel existed: this adapter does not invent an approval.
|
|
731
845
|
onEvent({
|
|
732
846
|
kind: 'progress',
|
|
733
|
-
text: `refusing '${method}':
|
|
847
|
+
text: `refusing '${method}': no approval channel is wired to this session, so nobody can grant it`,
|
|
734
848
|
});
|
|
735
849
|
throw new Error(`'${method}' is not answerable by a headless host`);
|
|
736
850
|
}
|
|
@@ -742,7 +856,7 @@ function handleServerRequest(onEvent) {
|
|
|
742
856
|
};
|
|
743
857
|
}
|
|
744
858
|
/** Spawn one app-server, complete the handshake, and return the wired client. */
|
|
745
|
-
async function openClient(cwd, onEvent, gate) {
|
|
859
|
+
async function openClient(cwd, onEvent, gate, approvals) {
|
|
746
860
|
let exitReported = false;
|
|
747
861
|
const reportExit = (exitCode, error) => {
|
|
748
862
|
if (exitReported)
|
|
@@ -772,7 +886,12 @@ async function openClient(cwd, onEvent, gate) {
|
|
|
772
886
|
// — unsolicited traffic arrives before any request completes, and throwing
|
|
773
887
|
// on one would kill a healthy session.
|
|
774
888
|
onNotification: (method, params) => gate.onNotification(method, params),
|
|
775
|
-
|
|
889
|
+
// A blocked approval parks INSIDE this handler, for as long as it takes a
|
|
890
|
+
// person to answer. That is safe here and nowhere else in this file: the
|
|
891
|
+
// transport fires each server request without awaiting it (`void (async …)`
|
|
892
|
+
// in `jsonrpc-stdio.ts`), so the reader keeps draining notifications, and no
|
|
893
|
+
// timeout wraps a server request the way `client.request` wraps ours.
|
|
894
|
+
onServerRequest: handleServerRequest(onEvent, approvals),
|
|
776
895
|
onStderr: (line) => onEvent({ kind: 'progress', text: cap(line) }),
|
|
777
896
|
onExit: (code, signal) => {
|
|
778
897
|
reportExit(code, signal === null ? undefined : `killed by ${signal}`);
|
|
@@ -958,7 +1077,7 @@ export const codexAdapter = {
|
|
|
958
1077
|
const startParams = buildThreadStartParams(args, onEvent);
|
|
959
1078
|
// Handshake failure disposes the child inside `openClient` — see the catch
|
|
960
1079
|
// there. Nothing is spawned and unowned by the time this rejects.
|
|
961
|
-
const { client, reportExit } = await openClient(args.cwd, onEvent, gate);
|
|
1080
|
+
const { client, reportExit } = await openClient(args.cwd, onEvent, gate, args.approvals);
|
|
962
1081
|
let threadId;
|
|
963
1082
|
try {
|
|
964
1083
|
const res = await client.request('thread/start', startParams, SETUP_TIMEOUT_MS);
|
|
@@ -1022,7 +1141,7 @@ export const codexAdapter = {
|
|
|
1022
1141
|
SESSIONS.delete(ref.token);
|
|
1023
1142
|
await previous.client.dispose();
|
|
1024
1143
|
}
|
|
1025
|
-
const { client, reportExit } = await openClient(args.cwd, onEvent, gate);
|
|
1144
|
+
const { client, reportExit } = await openClient(args.cwd, onEvent, gate, args.approvals);
|
|
1026
1145
|
try {
|
|
1027
1146
|
await client.request('thread/resume', resumeParams, SETUP_TIMEOUT_MS);
|
|
1028
1147
|
}
|
|
@@ -202,6 +202,53 @@ export interface PermissionIssue {
|
|
|
202
202
|
field?: string;
|
|
203
203
|
message: string;
|
|
204
204
|
}
|
|
205
|
+
/**
|
|
206
|
+
* ONE escalated tool call, as the adapter hands it to the approval channel.
|
|
207
|
+
*
|
|
208
|
+
* `toolUseId` is the HARNESS's own id for the blocked call. It is the approval's
|
|
209
|
+
* identity, which is what makes a repeat of the same request the same question
|
|
210
|
+
* rather than a second one — an adapter that polls does so by re-sending an
|
|
211
|
+
* identical request.
|
|
212
|
+
*/
|
|
213
|
+
export interface ApprovalRequest {
|
|
214
|
+
toolUseId: string;
|
|
215
|
+
toolName: string;
|
|
216
|
+
/** The call's arguments, as the harness presented them. */
|
|
217
|
+
toolInput: unknown;
|
|
218
|
+
/** Why the gatekeeper would not allow the call on its own. Shown to a person. */
|
|
219
|
+
reason: string;
|
|
220
|
+
/** The harness's own one-line rendering of the prompt, when it has one. */
|
|
221
|
+
title?: string;
|
|
222
|
+
/** Aborts the wait when the harness gives up on the call (session teardown). */
|
|
223
|
+
signal?: AbortSignal;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* What came back. `note` is the deciding person's own words, when they left any.
|
|
227
|
+
*
|
|
228
|
+
* THERE IS NO THIRD OUTCOME. A timeout, a hub error, a lease that ended while
|
|
229
|
+
* the worker waited — every one of them is `denied`, with a `reason` an adapter
|
|
230
|
+
* can put in front of the agent. The alternative would be an adapter that has to
|
|
231
|
+
* decide what "no answer" means at the moment it is least able to, and the
|
|
232
|
+
* failure mode of guessing wrong is a tool call that runs because nobody said
|
|
233
|
+
* no.
|
|
234
|
+
*/
|
|
235
|
+
export interface ApprovalOutcome {
|
|
236
|
+
decision: 'approved' | 'denied';
|
|
237
|
+
/** Why, when the decision was not a person's explicit yes. */
|
|
238
|
+
reason?: string;
|
|
239
|
+
note?: string;
|
|
240
|
+
}
|
|
241
|
+
/**
|
|
242
|
+
* The channel an adapter uses to ask a PERSON about one tool call and wait.
|
|
243
|
+
*
|
|
244
|
+
* Supplied by the worker, not built by an adapter: it is the worker that holds
|
|
245
|
+
* the hub client and knows which run this session is serving. An adapter that
|
|
246
|
+
* receives no requester keeps its pre-existing behavior — refuse the call and
|
|
247
|
+
* route the agent to `ask` — which is why this is optional rather than required.
|
|
248
|
+
* Nothing about the shape is vendor-specific; every harness that can intercept a
|
|
249
|
+
* tool call can use it.
|
|
250
|
+
*/
|
|
251
|
+
export type ApprovalRequester = (req: ApprovalRequest) => Promise<ApprovalOutcome>;
|
|
205
252
|
/** Everything an adapter needs to launch one step agent. */
|
|
206
253
|
export interface StartArgs {
|
|
207
254
|
/** The fully rendered step prompt. */
|
|
@@ -244,6 +291,12 @@ export interface StartArgs {
|
|
|
244
291
|
};
|
|
245
292
|
/** Normalized from the step def by `normalizeStepPermissions`. */
|
|
246
293
|
permissions: StepPermissions;
|
|
294
|
+
/**
|
|
295
|
+
* The human approval channel for escalated tool calls, when this deployment
|
|
296
|
+
* has one. ABSENT means the adapter's existing refuse-and-route-to-`ask`
|
|
297
|
+
* behavior stands — that is a supported deployment, not a degraded one.
|
|
298
|
+
*/
|
|
299
|
+
approvals?: ApprovalRequester;
|
|
247
300
|
}
|
|
248
301
|
/**
|
|
249
302
|
* Everything an adapter needs to RESUME an existing session with one message.
|
|
@@ -271,7 +324,7 @@ export interface StartArgs {
|
|
|
271
324
|
* happened to hold, and it must NOT fall back to a minimal option set on a map
|
|
272
325
|
* miss.
|
|
273
326
|
*/
|
|
274
|
-
export type DeliverArgs = Pick<StartArgs, 'cwd' | 'owenloopMcp' | 'permissions'> & Pick<StartArgs, 'model' | 'effort'>;
|
|
327
|
+
export type DeliverArgs = Pick<StartArgs, 'cwd' | 'owenloopMcp' | 'permissions'> & Pick<StartArgs, 'model' | 'effort' | 'approvals'>;
|
|
275
328
|
/**
|
|
276
329
|
* One harness implementation.
|
|
277
330
|
*
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type Liveness } from '../shift/state.ts';
|
|
1
2
|
/** Where a step attempt is in its life. */
|
|
2
3
|
export type SessionStatus = 'active' | 'turn-ended' | 'submitted' | 'dead';
|
|
3
4
|
/** One line of `sessions.jsonl`. */
|
|
@@ -13,6 +14,14 @@ export interface SessionRecord {
|
|
|
13
14
|
attempt: number;
|
|
14
15
|
/** Adapter id (`HarnessSessionRef.harness`). */
|
|
15
16
|
harness: string;
|
|
17
|
+
/** PID of the agent-run worker that owns the active session, when recorded. */
|
|
18
|
+
pid?: number;
|
|
19
|
+
/** Stable shift name in force when the worker was dispatched, when recorded. */
|
|
20
|
+
shiftName?: string;
|
|
21
|
+
/** Stable owner key; explicit shift names use the name, unnamed shifts use stateDir. */
|
|
22
|
+
shiftOwner?: string;
|
|
23
|
+
/** Per-boot shift incarnation that dispatched the worker, for diagnostics. */
|
|
24
|
+
shiftId?: string;
|
|
16
25
|
/** Provider-native session token (`HarnessSessionRef.token`). Machine-local. */
|
|
17
26
|
token: string;
|
|
18
27
|
cwd: string;
|
|
@@ -44,6 +53,8 @@ export interface SessionStoreOptions {
|
|
|
44
53
|
* ("skipping corrupt record") or a parsed object that failed the schema
|
|
45
54
|
* ("skipping invalid record"). Default writes to stderr. */
|
|
46
55
|
warn?: (line: string) => void;
|
|
56
|
+
/** Optional debug sink for conservative reconciliation skips. */
|
|
57
|
+
debug?: (line: string) => void;
|
|
47
58
|
/** Test barrier invoked under the writer lock after a retirement snapshot. */
|
|
48
59
|
afterWriterSnapshot?: () => void;
|
|
49
60
|
/** Compaction threshold in bytes, checked after each append. Default 2 MB. */
|
|
@@ -137,8 +148,8 @@ export declare function markRunSessionsDead(file: string, workflow: string, run:
|
|
|
137
148
|
* provider-side session is intact. A reboot does not invalidate one. Leaving
|
|
138
149
|
* those rows alone is precisely what "resume still works after a reboot" means.
|
|
139
150
|
*
|
|
140
|
-
* So ONLY `active` rows are eligible, and
|
|
141
|
-
*
|
|
151
|
+
* So ONLY `active` rows are eligible, and each candidate is checked against its
|
|
152
|
+
* recorded owner and worker PID before any retirement row is appended.
|
|
142
153
|
*
|
|
143
154
|
* ── WHY RETIRING AN ORPHANED `active` ROW IS THE RIGHT DIRECTION TO BE WRONG ──
|
|
144
155
|
*
|
|
@@ -147,16 +158,33 @@ export declare function markRunSessionsDead(file: string, workflow: string, run:
|
|
|
147
158
|
* would carry a model that believes work happened which did not. The cost of
|
|
148
159
|
* retiring it is one cold replay. The cost of resuming it is silent divergence.
|
|
149
160
|
*
|
|
150
|
-
* ──
|
|
151
|
-
*
|
|
152
|
-
*
|
|
153
|
-
*
|
|
154
|
-
*
|
|
155
|
-
*
|
|
156
|
-
*
|
|
157
|
-
*
|
|
158
|
-
*
|
|
159
|
-
*
|
|
161
|
+
* ── WHY THE RUN-ID SET THIS REPLACED WAS UNSAFE ──────────────────────────────
|
|
162
|
+
*
|
|
163
|
+
* This used to take `liveRunIds` — the run ids with a live `agent-run` child in
|
|
164
|
+
* the BOOTING shift's state dir — and retire every `active` row outside it. That
|
|
165
|
+
* is correct only on a machine running exactly one shift. It does not: the
|
|
166
|
+
* sessions store is per-CACHE-DIR and therefore machine-wide, while a state dir
|
|
167
|
+
* is per-shift. So shift A booting saw shift B's currently-running workers as
|
|
168
|
+
* orphans and killed their resumable sessions out from under them, mid-turn.
|
|
169
|
+
* A prior version of this comment told the next reader NOT to put a pid on
|
|
170
|
+
* `SessionRecord`, on the grounds that the shift state dir was already the
|
|
171
|
+
* system of record for liveness. That was the mistaken premise: one shift's
|
|
172
|
+
* state dir is evidence about ONE shift, and this file is read by all of them.
|
|
173
|
+
*
|
|
174
|
+
* ── FAIL-SAFE OWNERSHIP AND LIVENESS ─────────────────────────────────────────
|
|
175
|
+
*
|
|
176
|
+
* Boot-time reconciliation is allowed to retire an `active` row only when the
|
|
177
|
+
* row names this shift, carries a valid worker PID, and that PID is provably
|
|
178
|
+
* gone. Missing or foreign ownership, an unknown PID, a live PID, and any
|
|
179
|
+
* liveness ambiguity all leave the row untouched. A stale row is cheaper than
|
|
180
|
+
* destroying a live resumable session, so the predicate intentionally errs in
|
|
181
|
+
* that direction.
|
|
182
|
+
*
|
|
183
|
+
* A CONSEQUENCE WORTH KNOWING: every row written before this landed has no
|
|
184
|
+
* `pid` and no owner, so none of them is ever retired. That is the fail-safe
|
|
185
|
+
* direction and it costs nothing — an un-retired stale row is one failed resume
|
|
186
|
+
* that falls back to a cold replay, which is what retiring it would have caused
|
|
187
|
+
* anyway.
|
|
160
188
|
*
|
|
161
189
|
* IDEMPOTENT: the rows it appends are `dead`, so a second call finds nothing
|
|
162
190
|
* `active` left and appends nothing.
|
|
@@ -164,12 +192,34 @@ export declare function markRunSessionsDead(file: string, workflow: string, run:
|
|
|
164
192
|
* FAILURE STANCE: `appendSession` propagates, and so does this — same as
|
|
165
193
|
* `markRunSessionsDead`.
|
|
166
194
|
*
|
|
167
|
-
* @param
|
|
168
|
-
*
|
|
195
|
+
* @param context the booting shift's ownership and harness identity plus the
|
|
196
|
+
* injectable PID liveness probe.
|
|
169
197
|
* @returns the records that were retired, as they were BEFORE retirement, so the
|
|
170
198
|
* caller can log what it took away.
|
|
171
199
|
*/
|
|
172
|
-
export
|
|
200
|
+
export interface SessionReconcileContext {
|
|
201
|
+
/** Public shift name in force when this shift booted. */
|
|
202
|
+
shiftName: string;
|
|
203
|
+
/** Stable owner key; falls back to `shiftName` for older callers/records. */
|
|
204
|
+
shiftOwner?: string;
|
|
205
|
+
/** Configured harness guard, when this shift has one. */
|
|
206
|
+
harness?: string;
|
|
207
|
+
/** PID probe; defaults to the existing shift-state probe. */
|
|
208
|
+
isAlive?: Liveness;
|
|
209
|
+
}
|
|
210
|
+
export interface RetireDecision {
|
|
211
|
+
retire: boolean;
|
|
212
|
+
reason: string;
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Decide whether one active session row is safe to retire.
|
|
216
|
+
*
|
|
217
|
+
* The function is deliberately independent of the JSONL writer. Callers can
|
|
218
|
+
* exercise the safety predicate with a deterministic PID probe, while the
|
|
219
|
+
* production path uses `process.kill(pid, 0)` through `defaultIsAlive`.
|
|
220
|
+
*/
|
|
221
|
+
export declare function shouldRetireSession(record: SessionRecord, context: SessionReconcileContext): RetireDecision;
|
|
222
|
+
export declare function reconcileActiveSessions(file: string, context: SessionReconcileContext, now: number, opts?: SessionStoreOptions): SessionRecord[];
|
|
173
223
|
/**
|
|
174
224
|
* Append one record, then compact when the file has grown past `maxBytes`.
|
|
175
225
|
*
|
|
@@ -52,6 +52,7 @@
|
|
|
52
52
|
import { closeSync, fstatSync, fsyncSync, mkdirSync, openSync, readFileSync, readSync, renameSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
|
|
53
53
|
import { join } from 'node:path';
|
|
54
54
|
import { acquireFileLockSync, releaseFileLock } from "../../../../src/lock.js";
|
|
55
|
+
import { defaultIsAlive } from "../shift/state.js";
|
|
55
56
|
const STATUSES = new Set(['active', 'turn-ended', 'submitted', 'dead']);
|
|
56
57
|
/** Default compaction threshold — plan §3's 2 MB. */
|
|
57
58
|
export const DEFAULT_MAX_BYTES = 2_000_000;
|
|
@@ -456,57 +457,51 @@ export function markRunSessionsDead(file, workflow, run, now, opts = {}) {
|
|
|
456
457
|
});
|
|
457
458
|
}
|
|
458
459
|
/**
|
|
459
|
-
*
|
|
460
|
-
* running, so a crash or a reboot does not leave the store claiming a turn is in
|
|
461
|
-
* flight when no process exists.
|
|
460
|
+
* Decide whether one active session row is safe to retire.
|
|
462
461
|
*
|
|
463
|
-
*
|
|
464
|
-
*
|
|
465
|
-
*
|
|
466
|
-
* says `active` forever. Nothing else ever corrects it.
|
|
467
|
-
*
|
|
468
|
-
* ── WHY THIS IS NOT `markRunSessionsDead` ────────────────────────────────────
|
|
469
|
-
*
|
|
470
|
-
* `markRunSessionsDead` retires EVERY non-`dead` newest row of a run. Reusing it
|
|
471
|
-
* here would destroy exactly the capability this phase has to keep working:
|
|
472
|
-
* `src/agent/loop.ts` refuses to resume a session whose previous status is
|
|
473
|
-
* `dead`, and a `turn-ended` or `submitted` row is a COMPLETED turn whose
|
|
474
|
-
* provider-side session is intact. A reboot does not invalidate one. Leaving
|
|
475
|
-
* those rows alone is precisely what "resume still works after a reboot" means.
|
|
476
|
-
*
|
|
477
|
-
* So ONLY `active` rows are eligible, and only for runs absent from
|
|
478
|
-
* `liveRunIds`.
|
|
479
|
-
*
|
|
480
|
-
* ── WHY RETIRING AN ORPHANED `active` ROW IS THE RIGHT DIRECTION TO BE WRONG ──
|
|
481
|
-
*
|
|
482
|
-
* An interrupted turn is the state you least want to resume into: the harness may
|
|
483
|
-
* have half-applied tool calls the worker has no record of, so a resumed session
|
|
484
|
-
* would carry a model that believes work happened which did not. The cost of
|
|
485
|
-
* retiring it is one cold replay. The cost of resuming it is silent divergence.
|
|
486
|
-
*
|
|
487
|
-
* ── KNOWN FALSE POSITIVE, STATED RATHER THAN ENGINEERED AROUND ───────────────
|
|
488
|
-
*
|
|
489
|
-
* An `owenloop work agent-run` started BY HAND, outside the shift, has no child record
|
|
490
|
-
* in the shift state dir, so a shift booting at that moment sees its `active` row
|
|
491
|
-
* as orphaned and retires it. The cost is one cold replay on a hand-run debugging
|
|
492
|
-
* session. Two things keep it small: the caller invokes this at BOOT only, which
|
|
493
|
-
* narrows the window to an instant, and every retirement is returned so the
|
|
494
|
-
* caller can log it with its `(workflow, run, step)`. Do NOT add a pid field to
|
|
495
|
-
* `SessionRecord` to close this — the record is deliberately machine-portable
|
|
496
|
-
* metadata, and the shift state dir is already the system of record for liveness.
|
|
497
|
-
*
|
|
498
|
-
* IDEMPOTENT: the rows it appends are `dead`, so a second call finds nothing
|
|
499
|
-
* `active` left and appends nothing.
|
|
500
|
-
*
|
|
501
|
-
* FAILURE STANCE: `appendSession` propagates, and so does this — same as
|
|
502
|
-
* `markRunSessionsDead`.
|
|
503
|
-
*
|
|
504
|
-
* @param liveRunIds run ids with a live `agent-run` child RIGHT NOW. A run in
|
|
505
|
-
* this set is skipped whatever its status.
|
|
506
|
-
* @returns the records that were retired, as they were BEFORE retirement, so the
|
|
507
|
-
* caller can log what it took away.
|
|
462
|
+
* The function is deliberately independent of the JSONL writer. Callers can
|
|
463
|
+
* exercise the safety predicate with a deterministic PID probe, while the
|
|
464
|
+
* production path uses `process.kill(pid, 0)` through `defaultIsAlive`.
|
|
508
465
|
*/
|
|
509
|
-
export function
|
|
466
|
+
export function shouldRetireSession(record, context) {
|
|
467
|
+
const recordOwner = record.shiftOwner ?? record.shiftName;
|
|
468
|
+
const contextOwner = context.shiftOwner ?? context.shiftName;
|
|
469
|
+
if (typeof recordOwner !== 'string' || recordOwner.trim() === '') {
|
|
470
|
+
return { retire: false, reason: 'session has no owning shift name' };
|
|
471
|
+
}
|
|
472
|
+
if (typeof contextOwner !== 'string' || contextOwner.trim() === '') {
|
|
473
|
+
return { retire: false, reason: 'booting shift has no stable owner key' };
|
|
474
|
+
}
|
|
475
|
+
if (recordOwner !== contextOwner) {
|
|
476
|
+
return {
|
|
477
|
+
retire: false,
|
|
478
|
+
reason: `session belongs to shift '${recordOwner}', not '${contextOwner}'`,
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
const pid = record.pid;
|
|
482
|
+
if (typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0) {
|
|
483
|
+
return { retire: false, reason: 'session has no valid worker pid' };
|
|
484
|
+
}
|
|
485
|
+
const isAlive = context.isAlive ?? defaultIsAlive;
|
|
486
|
+
let alive;
|
|
487
|
+
try {
|
|
488
|
+
alive = isAlive(pid);
|
|
489
|
+
}
|
|
490
|
+
catch {
|
|
491
|
+
return { retire: false, reason: `worker pid ${String(pid)} liveness is unknown` };
|
|
492
|
+
}
|
|
493
|
+
if (alive) {
|
|
494
|
+
return { retire: false, reason: `worker pid ${String(pid)} is alive` };
|
|
495
|
+
}
|
|
496
|
+
if (context.harness !== undefined && context.harness !== '' && record.harness !== context.harness) {
|
|
497
|
+
return {
|
|
498
|
+
retire: false,
|
|
499
|
+
reason: `harness mismatch: session uses '${record.harness}', shift uses '${context.harness}'`,
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
return { retire: true, reason: `worker pid ${String(pid)} is confirmed dead` };
|
|
503
|
+
}
|
|
504
|
+
export function reconcileActiveSessions(file, context, now, opts = {}) {
|
|
510
505
|
mkdirSync(join(file, '..'), { recursive: true });
|
|
511
506
|
return withWriterLock(file, () => {
|
|
512
507
|
const newest = new Map();
|
|
@@ -518,8 +513,15 @@ export function reconcileActiveSessions(file, liveRunIds, now, opts = {}) {
|
|
|
518
513
|
for (const rec of newest.values()) {
|
|
519
514
|
if (rec.status !== 'active')
|
|
520
515
|
continue; // a completed turn is still resumable
|
|
521
|
-
|
|
522
|
-
|
|
516
|
+
const decision = shouldRetireSession(rec, context);
|
|
517
|
+
if (!decision.retire) {
|
|
518
|
+
opts.debug?.(`owenloop work sessions: skipped orphan reconciliation for ${rec.workflow}/${rec.run} ` +
|
|
519
|
+
`step '${rec.step}': ${decision.reason}`);
|
|
520
|
+
if (decision.reason.startsWith('harness mismatch:')) {
|
|
521
|
+
(opts.warn ?? defaultWarn)(`owenloop work sessions: refusing to retire ${rec.workflow}/${rec.run} step '${rec.step}': ${decision.reason}`);
|
|
522
|
+
}
|
|
523
|
+
continue;
|
|
524
|
+
}
|
|
523
525
|
appendSessionUnlocked(file, { ...rec, status: 'dead', updatedAt: now }, opts);
|
|
524
526
|
retired.push(rec);
|
|
525
527
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { AskRequest, AskResponse, 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, ListPendingApprovalsResponse, RequestApprovalRequest, RequestApprovalResponse, GetOrderRequest, GetOrderResponse, HeartbeatRequest, HeartbeatResponse, PresencePingRequest, PresencePingResponse, ReleaseRequest, ReleaseResponse, RejectRequest, RejectResponse, 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;
|
|
@@ -21,6 +21,18 @@ export interface HubClient {
|
|
|
21
21
|
* `owenloop retry <workflow> <path> --text "<answer>"`.
|
|
22
22
|
*/
|
|
23
23
|
ask(req: AskRequest): Promise<AskResponse>;
|
|
24
|
+
/**
|
|
25
|
+
* TOOL APPROVAL — raise AND poll, one idempotent call. The worker is mid-flight
|
|
26
|
+
* and needs yes/no on ONE tool call; unlike `ask`, the session stays alive, the
|
|
27
|
+
* run does not close, and the answer comes back to the very same blocked call.
|
|
28
|
+
* Repeating the call with the same `tool_use_id` re-reads the existing row.
|
|
29
|
+
*/
|
|
30
|
+
requestApproval(req: RequestApprovalRequest): Promise<RequestApprovalResponse>;
|
|
31
|
+
/** The HUMAN half — the operator CLI, never a worker. An agent token is
|
|
32
|
+
* refused this verb by the hub's RBAC, deliberately. */
|
|
33
|
+
answerApproval(req: AnswerApprovalRequest): Promise<AnswerApprovalResponse>;
|
|
34
|
+
/** Every approval a worker is currently blocked on, org-wide. */
|
|
35
|
+
listPendingApprovals(): Promise<ListPendingApprovalsResponse>;
|
|
24
36
|
/**
|
|
25
37
|
* Plan §6: record what this shift resolved the order's compound capability to,
|
|
26
38
|
* BEFORE the harness launches. Idempotent on the hub by order id, so a
|
|
@@ -83,6 +83,9 @@ export function createHubClient(opts) {
|
|
|
83
83
|
submit: (req) => post('submit', req),
|
|
84
84
|
reject: (req) => post('reject', req),
|
|
85
85
|
ask: (req) => post('ask', req),
|
|
86
|
+
requestApproval: (req) => post('request_approval', req),
|
|
87
|
+
answerApproval: (req) => post('answer_approval', req),
|
|
88
|
+
listPendingApprovals: () => post('list_pending_approvals', {}),
|
|
86
89
|
reportResolution: (req) => post('report_resolution', req),
|
|
87
90
|
whoami: () => get('whoami'),
|
|
88
91
|
// Cursor is an opaque non-negative integer; omit it entirely to bootstrap
|