pi-durable-subagents 1.0.45 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,71 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.1.0
4
+
5
+ - Caller wakes: a subagent can run `run --request <id> --wake caller -- <program> [args…]`, then end its turn. The
6
+ durable command keeps running; each workflow completion sends the caller a follow-up with workflow and call
7
+ statuses, durations, command exit codes or signals, and an output tail (at most 20 call lines and 4000 characters
8
+ total). A sealed caller opens a new generation; a running one gets the existing forwarded-follow-up behaviour,
9
+ including reopening after an undelivered turn. Retries and recovery reuse each completion's first wake decision.
10
+ - Wake admission and limits: `--wake` accepts only `caller` and needs a valid `DSA_CALL`; without it the CLI refuses
11
+ before submitting anything. The caller must be an agent call in an existing, unpruned workflow's current revision;
12
+ invalid callers are rejected with `wake caller: …` and no workflow is created. The main-session tool has no wake
13
+ option. A stopped caller is skipped (`caller stopped`); a pruned or retired caller or broken pins can reject
14
+ delivery. These outcomes are durable and final; holds and the ordinary follow-up rules still apply.
15
+ - Command shorthand and version: `run --request <id> -- <program> [args…]` submits an argv command call without a spec
16
+ file; `--timeout-ms` (positive integer milliseconds) and `--name` apply only to that form. `--spec` and `--` are
17
+ mutually exclusive; both forms accept `--wake caller`, `--cwd`, labels and the existing request-id options. Arguments
18
+ after `--` are literal; use `-- sh -c '…'` for shell syntax. `version` and `--version` print the package version.
19
+ - Read-only fields: `describe` adds top-level `wake: {to, state, rev?, generation?, reason?}` (`pending`, `applied`,
20
+ `skipped`, `rejected`). Each caller's `awaiting: [{request, wid?, state}]` is admission-ordered, limited to its current
21
+ revision and absent when empty; states are `pending` (admitted, no workflow), `running`, and `finished` (wake
22
+ undecided). `status <wid> --json` carries it too. A described sealed call has `sealedAt`, its latest generation's seal
23
+ timestamp in milliseconds; an unsealed one omits it. Pending wakes prevent prune and lazy settlement; prune after
24
+ delivery keeps the wake receipt. `wake` participates in the request digest; `caller` is provenance, excluded, so
25
+ retries from another generation of the same caller keep their identity. Requests without wake keep their digests.
26
+ - Agent process lifecycle and diagnostics: every derived agent system prompt ends with a reminder to use a durable
27
+ command call for work that must outlive the turn. Agent fences record best-effort `ended` entries before signalling
28
+ SIGKILL to targets other than the direct pi child: at most 20 pid/command pairs per entry, `more` for the rest,
29
+ command lines clipped to 200 characters (empty when unreadable). Linux reads `/proc`, macOS uses `ps`. `describe`
30
+ projects these as `endedAtSeal` (at most 20 across the latest generation) and `endedAtSealMore`, absent when empty.
31
+ This records signal targets, not proof of death; identity rechecks can prevent a signal after recording. Recording
32
+ has a total 500 ms budget per fence and never prevents cleanup. Crash recovery without a persisted child identity
33
+ omits roots, including orphaned descendants, from diagnostics but still fences them. Command calls and gates are
34
+ not recorded. Command arguments may be sensitive; processes that clear their tag and escape the tree before
35
+ tracking can still evade containment.
36
+ - Command PATH: after merging `env`, command calls append `$DSA_HOME/bin` once as the last PATH entry, so they can find
37
+ the CLI shim while custom and inherited tools keep precedence. Empty entries and earlier copies of that directory
38
+ are removed; an explicitly empty PATH contains only the shim directory. Agent PATH is unchanged.
39
+ - Lease priorities: `hold --priority <n>` accepts integers -100..100 (default 0). Waiters rank by higher priority, then
40
+ sequence; incompatible granted holders always block. Exclusive requests wait behind every ranked-ahead waiter,
41
+ shared behind exclusive waiters, counted behind every ranked-ahead waiter and until its slot limit permits a grant.
42
+ Every final grant is checked under the resource lock. Equal priorities keep the existing rules; lower priorities
43
+ can starve. `--no-wait` can pass lower-priority waiters, never incompatible holders or blockers of equal or higher priority,
44
+ and creates no waiting ticket.
45
+ - Yield and expected duration: `hold --yield` stops its command and descendants for a live waiter it blocks, even one
46
+ with lower priority, releases the lease and exits 75; detection is within the poll interval plus one second.
47
+ Compatible waiters and no-wait probes do not trigger it; the command is not resumed or retried. `--expect` accepts
48
+ whole seconds, optionally `s`, `m` or `h` (`90`, `90s`, `25m`, `2h`), from one second through seven days; it is only an
49
+ estimate, not a timeout or reservation. Holder text shows `3m of ~25m`, waiters `expects 25m`; `leases --json` includes
50
+ optional ticket fields `priority`, `yield: true` and `expectMs`. Exit 75 with
51
+ `hold: <resource> is not free now (…); not running the command (exit 75)`,
52
+ `hold: <resource> still held by … after …; not running the command (exit 75)` or
53
+ `hold: yielded <resource> to <who> after <age>; the command was stopped (exit 75)` is a stable program interface:
54
+ the first two never ran the command, the third stopped it, and none is a completed check verdict.
55
+ - Lease process cleanup: held commands inherit `DSA_HOLD=<resource>:<seq>` without changing `DSA_EXEC` or `DSA_CALL`.
56
+ Before release on exit, yield or wrapper cleanup, hold ends the command group and exact-tagged descendants with
57
+ TERM, grace, KILL and rescans, bounded to five seconds; surviving tags produce a warning and the lease is released
58
+ anyway. After a killed wrapper's command ends, group or tagged leftovers keep the ticket live until a queued waiter
59
+ reclaims and ends them (with the same bound). Linux finds tags in `/proc/<pid>/environ`, including detached sessions;
60
+ macOS uses `ps` when it exposes tags, otherwise falls back to group-only cleanup. Clearing the tag and leaving the
61
+ group can escape; tags are cooperative, not a security boundary. Separate homes should use distinct resource names
62
+ to avoid identical tags.
63
+ - Upgrade: caller wakes need a 1.1.0 orchestrator. With the 1.1.0 CLI, a new wake request to a live 1.0.45 orchestrator
64
+ exits 1 before recording anything, with `the running orchestrator 1.0.45 predates run --wake (new in 1.1.0)` and
65
+ restart guidance, not a silently ignored flag. The gate applies only when the running version predates both 1.1.0
66
+ and the loaded CLI; already recorded requests retain their first outcome. Lease priorities and yield take effect
67
+ once every hold wrapper for the resource runs 1.1.0; upgrading the orchestrator alone does not update wrappers.
68
+
3
69
  ## 1.0.45
4
70
 
5
71
  - 1.0.44 was tagged but never published: its release checks failed on macOS. 1.0.45 is the first release with
package/README.md CHANGED
@@ -58,7 +58,7 @@ the npx cache, so `install-service` refuses to run from there.
58
58
  | A provider's usage window runs out (`No available accounts`, usage limit, quota exceeded, a daily quota at 0) | Found at the second refusal in a row, while pi is still retrying. A call in a pool continues **in the same session** on the pool's next model (within pi's next retry or two); new calls skip that provider. After 15 minutes the next call that wants it tries it once; when it answers, new calls and new generations use it again. A call with a single model waits for it instead of failing. Billing errors (402, insufficient balance) still fail at once. |
59
59
  | Two subagents would write in the same worktree | Only one runs there at a time. A call that can write (its tools include `edit` or `write`, which pi's default tools do) holds its git worktree's writer lock from its launch until it ends, also while it waits for an answer. Another writer for that worktree waits in order, and status shows `waiting for writer lock: <root> held by <wid>/<key>`. `writer: false` (a call that does not write there), `isolation: "worktree"` and `"writerLock": "off"` opt out. |
60
60
  | A subagent waits for an answer for a long time | It releases its model slot and memory, then resumes exactly once when you answer. A forwarded answer prevents planned hibernation. If an execution was stopped after consuming the answer, recovery continues the same session without another answer. The question survives orchestrator restarts (also forced ones) and crashes, including one that hits before the subagent released its slot. |
61
- | A subagent's work ends (finished, stopped, or cut off) | Every process its tools started ends with that execution, also ones started with `nohup`, `setsid` or `&`: they carry the execution's tag (see the limit below). Anything that must outlive the subagent has to be started by you or the parent session. A command run under `hold` is no exception: a forced restart stops it and its lease is released. |
61
+ | A subagent's work ends (finished, stopped, or cut off) | Every process its tools started ends with that execution, also ones started with `nohup`, `setsid` or `&`: they carry the execution's tag (see the limit below). For work that must outlive its turn, the subagent can start a durable command call with `run --wake caller -- …` (below). A `hold` run directly by its tools is no exception: a forced restart stops it and its lease is released. |
62
62
  | A subagent runs in a worktree you made (`isolation: "none"`, the default, with `cwd`) | Durable Subagents never creates, cleans, moves or deletes that directory or its branch, also not on `prune`; `prune` deletes only its own state and the worktrees it created for `isolation: "worktree"`. |
63
63
 
64
64
  ## Use it
@@ -239,7 +239,13 @@ empty; stdout and stderr go, interleaved, to `output.log` in the attempt's
239
239
  directory. The command sees the orchestrator's environment plus `env`,
240
240
  `DSA_CALL` (its call id), `DSA_EXEC` (its attempt) and `DSA_HOME`, so a
241
241
  `pi-durable-subagents` command inside it (`hold`, `run`, `send`) addresses
242
- the same home; it cannot force a restart.
242
+ the same home; it cannot force a restart. After merging `env`, the command's
243
+ `PATH` is `env.PATH`, else the orchestrator's `PATH`, with `$DSA_HOME/bin`
244
+ appended once as the last entry. Custom and inherited tools keep precedence,
245
+ and the CLI shim is still found. Empty entries and earlier copies of the
246
+ shim directory are removed; an explicitly empty PATH searches only that
247
+ directory, not the current directory or system tools. Agent PATH is unchanged
248
+ (the shim stays first).
243
249
 
244
250
  | The command | Result |
245
251
  |---|---|
@@ -264,6 +270,28 @@ exit or a crash leaves it running, and the next orchestrator takes it over or
264
270
  records its result if it ended meanwhile. The restart busy list does not count
265
271
  it.
266
272
 
273
+ A subagent can start a command that must outlive its own turn, then end the
274
+ turn instead of waiting in a tool:
275
+
276
+ ```sh
277
+ pi-durable-subagents run --request build-42 --wake caller -- npm test
278
+ ```
279
+
280
+ When the workflow ends, the caller gets a follow-up with its status, each
281
+ call's status and duration, command exit code or signal when known, and an
282
+ output tail. Its first line is:
283
+
284
+ ```text
285
+ Durable run build-42 (<wid>) that you started with --wake caller finished: done.
286
+ ```
287
+
288
+ A sealed caller continues as a new generation; a running one gets the usual
289
+ forwarded follow-up, reopened after its turn if it did not take it.
290
+ Each workflow completion has one durable wake decision, reused
291
+ after retries and crashes. The ordinary finished notice to the CLI origin
292
+ is unchanged. Every derived agent system prompt includes this lifecycle
293
+ reminder; the pinned agent definition is not changed.
294
+
267
295
  A hold (`drain`, `stop-all`, a quit pi) prevents starting, never stops what
268
296
  started. A command call that has not started yet (also one waiting for its
269
297
  worktree's writer lock) waits while its workflow is held and starts after
@@ -395,6 +423,7 @@ unchanged, with zero edited lines.
395
423
  ## Command line
396
424
 
397
425
  ```text
426
+ pi-durable-subagents version print pi-durable-subagents <package version> (also --version)
398
427
  pi-durable-subagents smoke check this machine and this pi (offline, < 60 s)
399
428
  pi-durable-subagents chaos run the fault suite (offline, about 2 minutes)
400
429
  pi-durable-subagents drill failover [--keep] [--json]
@@ -410,7 +439,8 @@ pi-durable-subagents start start the orchestrator if work is pendin
410
439
  pi-durable-subagents resume [wid] continue unfinished or parked work (undoes drain / stop-all)
411
440
  pi-durable-subagents drain hold existing workflows: running calls finish, nothing new starts in them
412
441
  pi-durable-subagents stop <wid|call>
413
- pi-durable-subagents run --request <id> --spec <file|-> [--labels <json>] [--session <id>] [--cwd <dir>] [--json] [--wait-ms <n>]
442
+ pi-durable-subagents run --request <id> [--wake caller] --spec <file|-> [--labels <json>] [--session <id>] [--cwd <dir>] [--json] [--wait-ms <n>]
443
+ pi-durable-subagents run --request <id> [--wake caller] [--cwd <dir>] [--timeout-ms <n>] [--name <text>] [--labels <json>] [--session <id>] [--json] [--wait-ms <n>] -- <program> [args…]
414
444
  start a run under a caller-chosen id; safe to retry (see below)
415
445
  pi-durable-subagents send --request <id> --to <run-id|wid/key> [--to ...] --kind follow-up|answer|steer|notify|model
416
446
  [--call <key>] [--qid <qid> --rev <n>] --message <text|@file> [--model <m>] [--json]
@@ -422,7 +452,7 @@ pi-durable-subagents stop-all pause every existing workflow now; journ
422
452
  pi-durable-subagents prune [wid] [--older-than <days>]
423
453
  delete finished workflows (done, failed, stopped); prints count and bytes freed
424
454
  pi-durable-subagents restart [--force <token> --reason <text>] switch to the installed version (see "Updating Durable Subagents")
425
- pi-durable-subagents hold <resource> [--shared | --slots <n>] [--max-wait <s> | --no-wait] [--note <text>] -- <command…>
455
+ pi-durable-subagents hold <resource> [--shared | --slots <n>] [--priority <n>] [--yield] [--expect <duration>] [--max-wait <s> | --no-wait] [--note <text>] -- <command…>
426
456
  run one command while holding a resource lease (see below)
427
457
  pi-durable-subagents leases [--json] who holds and who waits for each resource
428
458
  pi-durable-subagents doctor [--json] read-only health check; exits 1 when something needs you
@@ -454,6 +484,32 @@ retry from the same place or pass it explicitly. The `spec` file is the
454
484
  `{tasks: […], name?, usageBudget?, maxCalls?}`); `context: "fork"` needs a pi
455
485
  session and is rejected.
456
486
 
487
+ The `run -- …` shorthand submits `{command: [program, ...args], timeoutMs?,
488
+ name?}` through the same normalizer. Arguments after `--` are literal; use
489
+ `-- sh -c 'make && make test'` for shell syntax. `--spec` and `--` are mutually
490
+ exclusive. `--timeout-ms` (positive integer milliseconds) and `--name` require
491
+ the argv form; `--cwd`, labels, session display and request-id exit codes
492
+ work as before.
493
+
494
+ `--wake` takes only `caller` and needs a valid `DSA_CALL`, supplied inside a
495
+ subagent call. Without it, the CLI refuses before submitting anything:
496
+ `--wake caller needs DSA_CALL: run it from inside a subagent call`.
497
+ The caller must be an agent call in an existing, unpruned workflow's current
498
+ revision; invalid callers are rejected with `wake caller: …`, with no new
499
+ workflow. A command call cannot receive a wake; the main-session `subagents`
500
+ tool has no wake option. The stored `RunBody.wake: {to: "<wid>/<key>"}` is
501
+ part of the digest; `RunBody.caller` (the full `DSA_CALL`) is provenance, not
502
+ part of it. Retrying from another generation of the same caller therefore
503
+ keeps the request identity. Requests without wake keep their digests.
504
+
505
+ Caller wakes need a 1.1.0 orchestrator. After upgrading the CLI, restart a
506
+ still-running 1.0.45 orchestrator: a new wake request exits 1 before recording
507
+ anything, with `the running orchestrator 1.0.45 predates run --wake (new in 1.1.0)`
508
+ and restart guidance, not a silently ignored flag. This gate applies
509
+ when the running version predates both 1.1.0 and the loaded CLI; an already
510
+ recorded request retains its first outcome. With no running orchestrator,
511
+ the next one starts on the installed version.
512
+
457
513
  | exit | meaning | `--json` reply |
458
514
  | --- | --- | --- |
459
515
  | 0 | decided and applied (a retry gets the same answer) | run: `{request, wid, created, spec_digest, writerWait?, hint?}` (`writerWait: [{call, heldBy, cwd}]`: calls already queued behind a writer lock); send/stop: `{request, applied, generation?, call?, spec_digest}` |
@@ -506,6 +562,33 @@ is. The reason is a best-effort reading of the journals: `restart-force` when a
506
562
  `orchestrator-crash` when the orchestrator died uncleanly while it ran, else
507
563
  `process-died`.
508
564
 
565
+ A wake run's `describe` adds `wake: {to, state, rev?, generation?, reason?}`:
566
+ `state` is `pending`, `applied`, `skipped` or `rejected`; `rev` counts workflow
567
+ completions and `generation` names the delivery generation when known. A
568
+ stopped caller is skipped (`caller stopped`); a pruned or retired caller or
569
+ broken pins can reject delivery. Skips and rejections are final. A pending
570
+ wake prevents prune (`wake pending`) and lazy settlement; pruning after
571
+ delivery keeps its receipt.
572
+
573
+ Each described caller call, and each call in `status <wid> --json`, can have
574
+ `awaiting: [{request, wid?, state}]`: `pending` means admitted but no workflow
575
+ yet, `running` means not completed, `finished` means completed with the wake
576
+ still undecided. Entries are ordered by admission, limited to the caller's
577
+ current revision and removed once the latest wake is decided; absent when
578
+ empty. Reading this indexes caller addresses in the ledger and reads only
579
+ matching run journals, not every workflow.
580
+ A sealed described call also has `sealedAt`, its latest generation's seal
581
+ timestamp in milliseconds; an unsealed generation omits it.
582
+
583
+ For an agent call, `describe` can show `endedAtSeal: [{pid, command}]`, the
584
+ SIGKILL targets recorded by fences of its latest generation, in journal
585
+ order, at most 20, and `endedAtSealMore` for the rest. Each `ended` journal
586
+ entry lists at most 20 targets plus optional `more`; command lines are
587
+ clipped to 200 characters, empty when unreadable (Linux `/proc`, macOS `ps`).
588
+ The direct pi child is excluded; command calls and gates have no such
589
+ records. These fields are absent when nothing was recorded. They diagnose
590
+ signal targets, not proof of death (see the limits below).
591
+
509
592
  ```sh
510
593
  pi-durable-subagents run --request build-42 --spec build-42.json --json
511
594
  # exit 75: retry later with the same id and bytes
@@ -763,18 +846,24 @@ pi-durable-subagents hold machine -- make bench # exclusive
763
846
  pi-durable-subagents hold machine --shared -- npm test # with other shared holders, never with an exclusive one
764
847
  pi-durable-subagents hold machine --max-wait 600 --note "profile" -- ./measure.sh
765
848
  pi-durable-subagents hold build --slots 4 -- cargo test # at most 4 at a time
849
+ pi-durable-subagents hold machine --priority 50 --expect 25m -- ./measure.sh
850
+ pi-durable-subagents hold machine --shared --yield -- ./advisory-check.sh
766
851
  ```
767
852
 
768
853
  - The lease covers one command, not a whole call: a subagent that thinks
769
854
  or waits for an answer holds nothing.
770
- - Requests are served strictly in order. An exclusive request waits for
771
- everything before it, and keeps later shared requests out (no starvation).
772
- A waiting `hold` prints who holds the resource; `--max-wait` gives up with
773
- exit 75 without running the command.
855
+ - Waiters rank by `--priority N` (integer -100..100, default 0), higher
856
+ first, then sequence. Incompatible granted holders always block. An
857
+ exclusive request waits behind every ranked-ahead waiter; a shared one
858
+ behind exclusive waiters. Higher priorities can overtake lower waiters,
859
+ never incompatible holders; equal priorities keep the existing FIFO
860
+ rules. Low priorities can starve. Every final grant is checked under the
861
+ resource lock. A waiting `hold` prints who holds the resource; `--max-wait`
862
+ gives up with exit 75 without running the command.
774
863
  - `--slots N` (an integer of at least 1; not with `--shared`) makes the
775
864
  resource a counting semaphore: a request runs once fewer than N holders
776
- (slot or shared) hold it, no exclusive request is ahead of it, and no
777
- earlier request of any kind still waits, so it never overtakes a waiter.
865
+ (slot or shared) hold it, no exclusive holder blocks it, and no
866
+ ranked-ahead request of any kind still waits.
778
867
  Shared requests are not limited by slots but occupy them, and they do not
779
868
  queue behind a slot waiter, so a stream of shared requests can keep it
780
869
  waiting; use one mode and one N per resource name. `leases` shows
@@ -786,17 +875,35 @@ pi-durable-subagents hold build --slots 4 -- cargo test # at most 4 at a time
786
875
  written already granted. Otherwise nothing is written, and it exits 75
787
876
  naming who holds or waits, without running the command. It is never
788
877
  listed as a waiter, even for a moment, so it can probe a resource whose
789
- owner treats any queued request as interference. It also leaves the
878
+ owner treats any queued request as interference. It can pass lower-priority
879
+ waiters; equal- or higher-priority waiters block it by the same mode rules
880
+ (a counted request waits behind every such waiter). It also leaves the
790
881
  resource alone: unlike a queued waiter, it does not end processes left
791
882
  by a holder whose `hold` was killed, and is refused while they remain.
883
+ - `--yield` makes a holder stop its command and descendants when a live
884
+ waiter is blocked by it, even a lower-priority one. Compatible waiters
885
+ and no-wait probes do not trigger it. Detection is within the poll
886
+ interval plus one second; cleanup runs before release, then `hold` exits
887
+ 75. The command is not resumed or retried.
888
+ - `--expect` records an estimate, not a timeout or reservation: whole
889
+ seconds, optionally `s`, `m` or `h` (`90`, `90s`, `25m`, `2h`), from one
890
+ second through seven days (`604800s` or `168h`). Holder text shows
891
+ `3m of ~25m`, waiter text `expects 25m` (the first waiter for counted
892
+ listings). `leases --json` includes optional ticket fields `priority`,
893
+ `yield: true` and `expectMs`; unused fields stay absent, old priority is 0.
792
894
  - The command runs without a shell (write `-- sh -c '…'` for one) in its
793
- own process group; signals to `hold` go to it and its exit status is
794
- returned. When it exits, whatever it left in its process group is ended
795
- before the lease passes on.
895
+ own process group, with `DSA_HOLD=<resource>:<seq>`; `DSA_EXEC` and
896
+ `DSA_CALL` are unchanged. Signals to `hold` go to its group, and the exit
897
+ status passes through unless it yields. Before release on command exit,
898
+ yield, a forwarded signal followed by exit, or wrapper cleanup, the group
899
+ and exact-tagged descendants are ended: TERM, grace, KILL and rescans,
900
+ bounded to five seconds. If tags survive, it releases anyway and prints
901
+ `hold: <n> processes tagged <tag> survived; releasing`.
796
902
  - The lease lives as long as the `hold` process or its command lives, so a
797
903
  killed `hold` does not hand the machine over while the command still
798
904
  runs. If `hold` is killed and its command has exited, processes the
799
- command left in its group still hold the lease; the next waiter ends them
905
+ command left in its group or with its tag still hold the lease; the next
906
+ queued waiter ends them before proceeding, with the same cleanup bound
800
907
  (on macOS, a process that took over the command's pid is waited for, not
801
908
  ended). State is one small file per request under
802
909
  `$DSA_HOME/leases/<resource>/`; no orchestrator is needed, and the user's
@@ -811,8 +918,27 @@ pi-durable-subagents hold build --slots 4 -- cargo test # at most 4 at a time
811
918
  `(holds lease machine)` / `(waiting for lease machine 3m)` on call lines.
812
919
  Tell a subagent in its task to run measurements under
813
920
  `pi-durable-subagents hold machine -- …`.
814
- - Leases are cooperative: processes started without `hold` are not held
815
- back, and a daemon that leaves the process group is not covered.
921
+ - Linux finds tags in `/proc/<pid>/environ`, including descendants in new
922
+ groups or sessions. macOS uses `ps` when it exposes the tag, otherwise
923
+ falls back to group-only cleanup. Clearing the tag and leaving the group
924
+ can escape. Tags are not a security boundary; separate DSA homes should
925
+ use distinct resource names to avoid identical tags.
926
+ - Priorities and yield take effect once every hold wrapper for the resource
927
+ runs 1.1.0; upgrading the orchestrator alone does not update wrappers.
928
+ Leases remain cooperative: processes started without `hold` are not held
929
+ back.
930
+
931
+ Programs may treat exit 75 with any of these stable line forms as no check
932
+ verdict (identity and duration text in the middle varies):
933
+
934
+ ```text
935
+ hold: <resource> is not free now (…); not running the command (exit 75)
936
+ hold: <resource> still held by … after …; not running the command (exit 75)
937
+ hold: yielded <resource> to <who> after <age>; the command was stopped (exit 75)
938
+ ```
939
+
940
+ The first two never started the command; the yield line stopped it, so its
941
+ partial output is not a completed result.
816
942
 
817
943
  ## Configuration
818
944
 
@@ -991,8 +1117,9 @@ subagent is a pi process the orchestrator drives over its stdin and stdout, and
991
1117
  those pipes end with the old process. A crash is no different: the successor
992
1118
  fences every execution that still runs (an execution that had already ended is
993
1119
  not counted as interrupted). Work that must survive a forced restart, such as a
994
- long measurement, belongs outside the subagent's processes (for example
995
- `systemd-run --user … pi-durable-subagents hold machine -- …`), with the
1120
+ long measurement, belongs outside the subagent's processes: use a durable
1121
+ command call (`run --wake caller -- …`) or an external launcher such as
1122
+ `systemd-run --user … pi-durable-subagents hold machine -- …`, with the
996
1123
  subagent only watching it.
997
1124
  The restart ledger records the reason and initiator; after the next start,
998
1125
  `status` shows who forced it and why for 24 hours.
@@ -1051,7 +1178,25 @@ loads the old extension; start a new one.
1051
1178
  - After a crash, the model call that was in flight is paid for again.
1052
1179
  - Process containment uses process tags plus a 1-second tracker. A process
1053
1180
  that clears its tag and leaves the process tree within its first second
1054
- cannot be found.
1181
+ cannot be found. Lease tag discovery on macOS depends on `ps` exposing
1182
+ environments; otherwise only the command's group is covered. Even on
1183
+ Linux, lease cleanup releases after five seconds with a warning if tagged
1184
+ processes survive.
1185
+ - Caller wakes use ordinary follow-up delivery, not a stronger guarantee:
1186
+ durable storage and an available orchestrator are needed, a held caller
1187
+ waits for resume, and stop, retired revisions or broken pins can prevent
1188
+ delivery. A wake lists at most 20 calls (then `… N more`), with at most
1189
+ 4000 characters total, dropping earlier output to fit; agent results never get invented exit
1190
+ codes. `describe` and `status` retain the command result's last 16 KiB,
1191
+ not its whole output; read the command's log for the full interleaved text.
1192
+ - Ended-process diagnostics are best effort, with a total 500 ms budget per
1193
+ fence; failed or timed-out recording does not prevent cleanup. A record
1194
+ lists SIGKILL targets, not proof of death: a process may exit or its pid
1195
+ may be reused before signalling, and identity rechecks can skip it.
1196
+ An append already in progress can finish after the budget expires.
1197
+ Recovery without a persisted direct-child identity omits roots (including
1198
+ orphaned descendants) from diagnostics but still fences them. Command
1199
+ lines can contain sensitive arguments, like other workflow diagnostics.
1055
1200
  - Model and tool behaviour belong to the models and tools you use.
1056
1201
 
1057
1202
  ## License
package/dist/cli/hold.js CHANGED
@@ -1,15 +1,13 @@
1
- // `pi-durable-subagents hold <resource> [--shared | --slots <n>] [--max-wait <s>] [--note <text>] -- <command> [args…]`
2
- // Waits for the lease (strict FIFO), runs the command in its own process group, ends what the command left in that
3
- // group, then releases. `--max-wait 0` (or `--no-wait`) takes the lease at once or exits 75 without ever being queued.
4
- // See src/platform/lease.ts for the ticket protocol.
1
+ // Command-scoped leases: priority then FIFO among waiters, with every grant committed under the resource lock.
2
+ // Commands run in their own process group and inherit DSA_HOLD; their group and tagged descendants end before release.
5
3
  import { spawn } from "node:child_process";
6
4
  import { watch } from "node:fs";
7
5
  import { constants } from "node:os";
8
6
  import { dsaHome } from "../paths.js";
9
7
  import { captureStart } from "../platform/proctable.js";
10
- import { blockers, enqueue, groupAlive, tryGrant, leaseDir, liveTickets, orphaned, removeTicket, RESOURCE, who, writeTicket, modeLabel } from "../platform/lease.js";
11
- export const HOLD_USAGE = "usage: pi-durable-subagents hold <resource> [--shared | --slots <n>] [--max-wait <seconds> | --no-wait] [--note <text>] -- <command> [args…]";
12
- /** Exit status when --max-wait expires before the lease is granted (EX_TEMPFAIL). */
8
+ import { blockers, endLeaseProcesses, enqueue, grantQueued, holdDetail, holdTag, tryGrant, leaseDir, liveTickets, orphaned, rank, removeTicket, RESOURCE, who, writeTicket } from "../platform/lease.js";
9
+ export const HOLD_USAGE = "usage: pi-durable-subagents hold <resource> [--shared | --slots <n>] [--priority <n>] [--yield] [--expect <duration>] [--max-wait <seconds> | --no-wait] [--note <text>] -- <command> [args…]";
10
+ /** Exit status when the command did not run or was stopped to yield (EX_TEMPFAIL). */
13
11
  export const WAIT_EXPIRED = 75;
14
12
  export function parseHold(args) {
15
13
  const split = args.indexOf("--");
@@ -17,13 +15,16 @@ export function parseHold(args) {
17
15
  throw new Error(`hold needs -- before the command. ${HOLD_USAGE}`);
18
16
  const opts = args.slice(0, split), argv = args.slice(split + 1);
19
17
  let resource, shared = false, slots, maxWaitMs, note;
18
+ let priority, yielding, expectMs;
20
19
  for (let i = 0; i < opts.length; i++) {
21
20
  const a = opts[i];
22
21
  if (a === "--shared")
23
22
  shared = true;
23
+ else if (a === "--yield")
24
+ yielding = true;
24
25
  else if (a === "--no-wait")
25
26
  maxWaitMs = 0;
26
- else if (a === "--max-wait" || a === "--note" || a === "--slots") {
27
+ else if (["--max-wait", "--note", "--slots", "--priority", "--expect"].includes(a)) {
27
28
  const v = opts[++i];
28
29
  if (v === undefined)
29
30
  throw new Error(`${a} needs a value. ${HOLD_USAGE}`);
@@ -34,6 +35,18 @@ export function parseHold(args) {
34
35
  throw new Error(`--slots must be an integer >= 1. ${HOLD_USAGE}`);
35
36
  slots = Number(v);
36
37
  }
38
+ else if (a === "--priority") {
39
+ if (!/^-?\d+$/.test(v) || !Number.isInteger(Number(v)) || Number(v) < -100 || Number(v) > 100)
40
+ throw new Error(`--priority must be an integer from -100 to 100. ${HOLD_USAGE}`);
41
+ priority = Number(v);
42
+ }
43
+ else if (a === "--expect") {
44
+ const m = /^(\d+)([smh]?)$/.exec(v);
45
+ const duration = m ? Number(m[1]) * (m[2] === "h" ? 3_600_000 : m[2] === "m" ? 60_000 : 1000) : NaN;
46
+ if (!Number.isSafeInteger(duration) || duration < 1000 || duration > 7 * 24 * 3_600_000)
47
+ throw new Error(`--expect must be a duration from 1s to 7d (seconds, s, m or h). ${HOLD_USAGE}`);
48
+ expectMs = duration;
49
+ }
37
50
  else {
38
51
  const s = Number(v);
39
52
  if (!Number.isFinite(s) || s < 0)
@@ -57,31 +70,35 @@ export function parseHold(args) {
57
70
  if (shared && slots !== undefined)
58
71
  throw new Error(`--slots and --shared cannot be combined. ${HOLD_USAGE}`);
59
72
  const mode = slots !== undefined ? "counted" : shared ? "shared" : "exclusive";
60
- return { resource, mode, ...(slots !== undefined ? { slots } : {}), ...(maxWaitMs !== undefined ? { maxWaitMs } : {}), ...(note !== undefined ? { note } : {}), argv };
73
+ return { resource, mode, ...(slots !== undefined ? { slots } : {}), ...(priority !== undefined ? { priority } : {}),
74
+ ...(yielding ? { yield: yielding } : {}), ...(expectMs !== undefined ? { expectMs } : {}),
75
+ ...(maxWaitMs !== undefined ? { maxWaitMs } : {}), ...(note !== undefined ? { note } : {}), argv };
61
76
  }
62
77
  const age = (ms) => ms < 60_000 ? `${Math.max(0, Math.round(ms / 1000))}s` : ms < 3_600_000 ? `${Math.round(ms / 60_000)}m` : `${(ms / 3_600_000).toFixed(1)}h`;
63
78
  const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
64
- /** Run one held command; resolves to the exit status for the process. */
79
+ /** Run one held command; resolves only after its command tree has been ended and its lease released. */
65
80
  export async function hold(args, options = {}) {
66
81
  const env = options.env ?? process.env, home = dsaHome(env), say = options.stderr ?? (l => process.stderr.write(`${l}\n`));
67
82
  const pollMs = options.pollMs ?? 250, graceMs = options.graceMs ?? 2000;
68
83
  const request = {
69
84
  resource: args.resource, mode: args.mode, ...(args.slots !== undefined ? { slots: args.slots } : {}),
85
+ ...(args.priority !== undefined ? { priority: args.priority } : {}), ...(args.yield ? { yield: args.yield } : {}),
86
+ ...(args.expectMs !== undefined ? { expectMs: args.expectMs } : {}),
70
87
  wrapper: { pid: process.pid, start: (await captureStart(process.pid)) || undefined },
71
88
  argv: args.argv.map(a => a.length > 200 ? `${a.slice(0, 199)}…` : a).slice(0, 32), cwd: process.cwd(),
72
89
  ...(args.note ? { note: args.note.slice(0, 300) } : {}), since: Date.now(),
73
90
  ...(env.DSA_EXEC ? { exec: env.DSA_EXEC } : {}), ...(env.DSA_CALL ? { call: env.DSA_CALL } : {}),
74
91
  };
75
- // No wait: granted now, or refused without a ticket — never listed as a waiter, even for a moment.
76
92
  const granted = args.maxWaitMs === 0 ? await tryGrant(home, request) : undefined;
77
93
  if (granted && "busy" in granted) {
78
- const now = Date.now(), by = granted.busy.map(t => `${who(t)} (${modeLabel(t)}${t.grantedAt === undefined ? ", waiting" : ""}, ${age(now - (t.grantedAt ?? t.since))})`).join(", ");
94
+ const now = Date.now(), by = granted.busy.map(t => `${who(t)} (${t.grantedAt === undefined
95
+ ? `${t.mode === "counted" ? "slot" : t.mode}, waiting, ${age(now - t.since)}${t.expectMs !== undefined ? `, expects ${age(t.expectMs)}` : ""}`
96
+ : holdDetail({ ...t, note: undefined }, now, false)})`).join(", ");
79
97
  say(`hold: ${args.resource} is not free now (${by}); not running the command (exit ${WAIT_EXPIRED})`);
80
98
  return WAIT_EXPIRED;
81
99
  }
82
100
  const ticket = granted ?? await enqueue(home, request);
83
- // Signals: while waiting they withdraw the request; while the command runs they go to its process group.
84
- let child, interrupted, wake = () => { };
101
+ let child, interrupted, wake = () => { }, cleaned = false;
85
102
  const onSignal = (signal) => {
86
103
  if (child?.pid) {
87
104
  try {
@@ -97,8 +114,11 @@ export async function hold(args, options = {}) {
97
114
  for (const s of SIGNALS)
98
115
  process.on(s, onSignal);
99
116
  let watcher;
117
+ const pause = () => new Promise(resolve => {
118
+ const timer = setTimeout(resolve, pollMs);
119
+ wake = () => { clearTimeout(timer); resolve(); };
120
+ });
100
121
  try {
101
- // Wait in order.
102
122
  const deadline = args.maxWaitMs !== undefined ? ticket.since + args.maxWaitMs : undefined;
103
123
  try {
104
124
  watcher = watch(leaseDir(home, args.resource), () => wake());
@@ -106,103 +126,88 @@ export async function hold(args, options = {}) {
106
126
  }
107
127
  catch { /* polling suffices */ }
108
128
  let shown;
109
- const ended = new Map();
110
- // A ticket granted under the lock (no wait) runs at once; only a queued one waits.
111
129
  while (ticket.grantedAt === undefined) {
112
- if (interrupted) {
113
- removeTicket(home, ticket);
130
+ if (interrupted)
114
131
  return 128 + (constants.signals[interrupted] ?? 1);
132
+ const all = liveTickets(home, args.resource);
133
+ let ahead = blockers(ticket, all);
134
+ // A lock-free observation is only a hint. Priority can change while the lock is being acquired.
135
+ if (!ahead.length) {
136
+ ahead = await grantQueued(home, ticket);
137
+ if (ticket.grantedAt !== undefined)
138
+ break;
115
139
  }
116
- const all = liveTickets(home, args.resource), ahead = blockers(ticket, all);
117
- if (!ahead.length)
118
- break;
119
- const now = Date.now();
120
- // A holder whose wrapper was killed after its command ended can leave processes in the command's group; the
121
- // wrapper would have ended them before releasing, so a waiter does: TERM, then KILL after the grace period.
122
- for (const t of ahead.filter(orphaned)) {
123
- const first = ended.get(t.seq);
124
- if (first === undefined)
125
- say(`hold: ending processes left by ${who(t)} (its hold process is gone)`);
126
- try {
127
- process.kill(-t.command.pid, first !== undefined && now - first >= graceMs ? "SIGKILL" : "SIGTERM");
128
- }
129
- catch { /* gone */ }
130
- if (first === undefined)
131
- ended.set(t.seq, now);
140
+ const leftovers = ahead.filter(orphaned);
141
+ for (const t of leftovers) {
142
+ say(`hold: ending processes left by ${who(t)} (its hold process is gone)`);
143
+ await endLeaseProcesses(t, graceMs, say);
144
+ removeTicket(home, t);
132
145
  }
146
+ if (leftovers.length)
147
+ continue;
148
+ const now = Date.now();
133
149
  if (deadline !== undefined && now >= deadline) {
134
- removeTicket(home, ticket);
135
150
  say(`hold: ${args.resource} still held by ${ahead.filter(t => t.grantedAt !== undefined).map(who).join(", ") || who(ahead[0])} after ${age(now - ticket.since)}; not running the command (exit ${WAIT_EXPIRED})`);
136
151
  return WAIT_EXPIRED;
137
152
  }
138
- // A counted request names its place among the waiters and how many slots are taken: "position 2, held 4/4".
139
- const counted = args.mode === "counted", granted = (counted ? all : ahead).filter(t => t.grantedAt !== undefined && t.seq !== ticket.seq);
140
- const position = all.filter(t => t.seq < ticket.seq && t.grantedAt === undefined).length + 1;
141
- const key = `${granted.map(t => t.seq).join(",") || `q${ahead[0].seq}`}${counted ? `@${position}` : ""}`;
153
+ const counted = args.mode === "counted", holders = (counted ? all : ahead).filter(t => t.grantedAt !== undefined && t.seq !== ticket.seq);
154
+ const position = all.filter(t => t.grantedAt === undefined && rank(t, ticket) < 0).length + 1;
155
+ const key = `${holders.map(t => t.seq).join(",") || `q${ahead[0].seq}`}${counted ? `@${position}` : ""}`;
142
156
  if (key !== shown) {
143
157
  shown = key;
144
- const by = granted.length ? granted.map(t => `${who(t)} (${modeLabel(t)}, ${age(now - (t.grantedAt ?? t.since))})`).join(", ") : `${who(ahead[0])} (waiting)`;
158
+ const by = holders.length ? holders.map(t => `${who(t)} (${holdDetail({ ...t, note: undefined }, now, false)})`).join(", ") : `${who(ahead[0])} (waiting)`;
145
159
  say(counted
146
- ? `hold: waiting for ${args.resource} (slot, position ${position}, held ${granted.length}/${args.slots}); held by ${by}`
160
+ ? `hold: waiting for ${args.resource} (slot, position ${position}, held ${holders.length}/${args.slots}); held by ${by}`
147
161
  : `hold: waiting for ${args.resource} (${args.mode}) — held by ${by}; ${ahead.length} ahead`);
148
162
  }
149
- await new Promise(resolve => { const timer = setTimeout(resolve, pollMs); wake = () => { clearTimeout(timer); resolve(); }; });
163
+ await pause();
150
164
  }
151
- watcher?.close();
152
- watcher = undefined;
153
- ticket.grantedAt ??= Date.now();
154
- await writeTicket(home, ticket);
155
- if (interrupted) {
156
- removeTicket(home, ticket);
165
+ if (interrupted)
157
166
  return 128 + (constants.signals[interrupted] ?? 1);
158
- }
159
167
  if (shown)
160
168
  say(`hold: ${args.resource} granted after ${age(ticket.grantedAt - ticket.since)}`);
161
- // Run. stdin stays attached only when it is not a terminal: a background process group reading the terminal stops.
162
- const c = spawn(args.argv[0], args.argv.slice(1), { stdio: [process.stdin.isTTY ? "ignore" : "inherit", "inherit", "inherit"], detached: true, env });
169
+ // stdin stays attached only when it is not a terminal: a background group reading the terminal stops.
170
+ const c = spawn(args.argv[0], args.argv.slice(1), { stdio: [process.stdin.isTTY ? "ignore" : "inherit", "inherit", "inherit"], detached: true,
171
+ env: { ...env, DSA_HOLD: holdTag(ticket) } });
163
172
  child = c;
173
+ let status;
164
174
  const exit = new Promise(resolve => {
165
175
  c.once("error", error => { say(`hold: cannot run ${args.argv[0]}: ${error.message}`); resolve(127); });
166
176
  c.once("exit", (code, signal) => resolve(code ?? 128 + (signal ? constants.signals[signal] ?? 1 : 1)));
167
177
  });
178
+ void exit.then(value => { status = value; wake(); });
168
179
  if (c.pid) {
169
- ticket.command = { pid: c.pid, start: (await captureStart(c.pid)) || undefined };
180
+ ticket.command = { pid: c.pid };
181
+ ticket.command.start = (await captureStart(c.pid)) || undefined;
170
182
  await writeTicket(home, ticket).catch(() => { });
171
183
  }
172
- const status = await exit;
173
- // End what the command left behind in its group before the lease goes to the next holder.
174
- if (c.pid && groupAlive(c.pid)) {
175
- try {
176
- process.kill(-c.pid, "SIGTERM");
177
- }
178
- catch { /* gone */ }
179
- const until = Date.now() + graceMs;
180
- while (groupAlive(c.pid) && Date.now() < until)
181
- await new Promise(r => setTimeout(r, 50));
182
- if (groupAlive(c.pid)) {
183
- try {
184
- process.kill(-c.pid, "SIGKILL");
184
+ while (status === undefined) {
185
+ if (args.yield) {
186
+ const all = liveTickets(home, args.resource);
187
+ const waiter = all.filter(t => t.grantedAt === undefined && blockers(t, all).some(b => b.seq === ticket.seq)).sort(rank)[0];
188
+ if (waiter) {
189
+ await endLeaseProcesses(ticket, graceMs, say);
190
+ cleaned = true;
191
+ say(`hold: yielded ${args.resource} to ${who(waiter)} after ${age(Date.now() - ticket.grantedAt)}; the command was stopped (exit ${WAIT_EXPIRED})`);
192
+ return WAIT_EXPIRED;
185
193
  }
186
- catch { /* gone */ }
187
- }
188
- for (let i = 0; i < 40 && groupAlive(c.pid); i++)
189
- await new Promise(r => setTimeout(r, 25));
190
- }
191
- // A /proc listing is not atomic (a member can fork and exit while it is read): a last group signal ends any member
192
- // the checks missed, a newborn included. The group id is still ours while it has members.
193
- if (c.pid) {
194
- try {
195
- process.kill(-c.pid, "SIGKILL");
196
194
  }
197
- catch { /* gone */ }
195
+ await pause();
198
196
  }
199
- removeTicket(home, ticket);
200
197
  return status;
201
198
  }
202
199
  finally {
203
200
  watcher?.close();
204
- for (const s of SIGNALS)
205
- process.off(s, onSignal);
201
+ // Also covers errors during launch/capture/write and forwarded signals followed by command exit.
202
+ try {
203
+ if (child && !cleaned)
204
+ await endLeaseProcesses(ticket, graceMs, say);
205
+ }
206
+ finally {
207
+ removeTicket(home, ticket);
208
+ for (const s of SIGNALS)
209
+ process.off(s, onSignal);
210
+ }
206
211
  }
207
212
  }
208
213
  /** `leases [--json]`. */