@pugi/cli 0.1.0-alpha.17 → 0.1.0-alpha.19

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.
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Cancellation token — Sprint α6.9 Phase 1 (agent loop FSM + cancellation).
3
+ *
4
+ * A pure-JS one-shot signal that fans out to N listeners. One token is
5
+ * minted per dispatch turn (fresh on each operator brief); when the
6
+ * operator hits Ctrl+C, the REPL calls `abort()` which:
7
+ *
8
+ * 1. Latches `aborted = true` so any future `isAborted` check returns
9
+ * true (a tool that observes the flag mid-execution can short-circuit
10
+ * its loop without waiting for an explicit signal-handler callback).
11
+ * 2. Drains the listener set, firing each callback exactly once. The
12
+ * set is cleared after the drain so a late `onAbort` listener
13
+ * attached AFTER abort does NOT fire — that is the documented
14
+ * contract; late listeners are expected to check `isAborted`
15
+ * explicitly at registration time if they need to know whether the
16
+ * token already tripped.
17
+ *
18
+ * Design choices:
19
+ *
20
+ * - No coupling to `AbortController` / `AbortSignal`. The session +
21
+ * tool path are wrapped around this token; where a Web platform
22
+ * primitive is needed (fetch signal, MCP call), the wrapper bridges
23
+ * `onAbort` → `controller.abort()` at the seam.
24
+ * - Idempotent `abort()`. Calling twice is safe and the second call is
25
+ * a no-op (the listener set is already empty). This matters because
26
+ * two code paths can race to cancel — the Ctrl+C handler and a
27
+ * downstream tool that observed `isAborted` and threw — and both
28
+ * end up calling `dispatch.cancel()` which transitively calls
29
+ * `token.abort()`.
30
+ * - Listener errors do NOT block the drain. A throwing listener
31
+ * stops itself but the next listener still fires. The error is
32
+ * swallowed because the cancellation path is best-effort and
33
+ * surfacing the error mid-drain would leak through the abort
34
+ * pathway into the REPL state (a UI rerender on a half-aborted
35
+ * session is worse than a silent listener crash).
36
+ *
37
+ * Brand voice: no forbidden words. ASCII only. No emoji.
38
+ */
39
+ export class CancellationToken {
40
+ aborted = false;
41
+ listeners = new Set();
42
+ /**
43
+ * Latch the token to aborted and fire every currently-attached
44
+ * listener exactly once. Subsequent `abort()` calls are no-ops
45
+ * (idempotent — the listener set was already cleared on first abort).
46
+ * Listener callbacks that throw are swallowed; the next listener
47
+ * still fires.
48
+ */
49
+ abort() {
50
+ if (this.aborted)
51
+ return;
52
+ this.aborted = true;
53
+ // Snapshot the listener set so a listener that mutates the set
54
+ // (e.g. detaches itself via the returned unsubscribe handle while
55
+ // its own callback is running) does not corrupt the iteration.
56
+ const snapshot = Array.from(this.listeners);
57
+ this.listeners.clear();
58
+ for (const listener of snapshot) {
59
+ try {
60
+ listener();
61
+ }
62
+ catch {
63
+ // Swallow listener errors — see header comment for rationale.
64
+ }
65
+ }
66
+ }
67
+ /**
68
+ * True after `abort()` has been called. Mutation observers and tool
69
+ * inner loops should read this BEFORE each potentially-expensive
70
+ * iteration so they can short-circuit on cancel.
71
+ */
72
+ get isAborted() {
73
+ return this.aborted;
74
+ }
75
+ /**
76
+ * Register a callback that fires on the FIRST `abort()` call. If the
77
+ * token has already aborted at registration time, the callback is
78
+ * NOT auto-fired — the caller is responsible for checking
79
+ * `isAborted` first.
80
+ *
81
+ * Returns an unsubscribe handle. Calling it before abort detaches the
82
+ * listener so it never fires; calling it after abort is a no-op (the
83
+ * set was already drained).
84
+ */
85
+ onAbort(listener) {
86
+ if (this.aborted) {
87
+ // Document the contract by returning a no-op unsubscribe handle.
88
+ // The listener does NOT fire — late subscribers must check
89
+ // isAborted at registration time.
90
+ return () => undefined;
91
+ }
92
+ this.listeners.add(listener);
93
+ return () => {
94
+ this.listeners.delete(listener);
95
+ };
96
+ }
97
+ }
98
+ //# sourceMappingURL=cancellation.js.map
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Dispatch FSM — Sprint α6.9 Phase 1 (agent loop FSM + cancellation).
3
+ *
4
+ * Tracks the lifecycle of a single operator-issued brief from the moment
5
+ * `POST /api/pugi/sessions/:id/brief` fires until the persona returns a
6
+ * final reply (or the operator aborts). The Ctrl+C handler and the
7
+ * status-bar surface both subscribe to state transitions so the UX is
8
+ * predictable: the operator can always tell where the dispatch is in
9
+ * its lifecycle and the abort signal lands at a deterministic seam.
10
+ *
11
+ * State graph:
12
+ *
13
+ * idle
14
+ * │ (brief posted)
15
+ * ▼
16
+ * awaiting_response ←──────────┐
17
+ * │ │ (next turn)
18
+ * ▼ │
19
+ * tool_running ────────────────┘
20
+ * │
21
+ * ▼
22
+ * completed
23
+ *
24
+ * Terminal states: `completed`, `failed`, `aborted`. The FSM does not
25
+ * transition out of a terminal state; a fresh brief mints a new FSM
26
+ * instance. `aborting` is transient — any non-terminal state can
27
+ * transition to `aborting`, which then transitions to `aborted` once
28
+ * the SSE stream + in-flight tool acknowledge the abort.
29
+ *
30
+ * Illegal transitions are rejected by throwing a typed error. This is
31
+ * load-bearing: a bug that tries to walk `completed → tool_running`
32
+ * would otherwise silently corrupt the agent tree. Throwing fails
33
+ * loud at the call site so the integration bug surfaces immediately.
34
+ *
35
+ * onEnter listeners fire AFTER the state transition is committed.
36
+ * Subscribers can call `transition()` from inside a listener; the FSM
37
+ * uses a small re-entrancy guard so nested transitions are processed
38
+ * in order (the inner transition fires its own listeners before the
39
+ * outer transition returns).
40
+ *
41
+ * Brand voice: no forbidden words. ASCII only. No emoji.
42
+ */
43
+ /**
44
+ * Legal transitions per state. Building the matrix at module scope
45
+ * keeps the FSM declarative and exhaustive — adding a new state forces
46
+ * the matrix update at typecheck time.
47
+ *
48
+ * `idle` is the start state. Posting a brief moves to
49
+ * `awaiting_response`. The model's first turn either returns a final
50
+ * text (`completed`), requests tools (`tool_running`), or fails
51
+ * (`failed`). After tools execute the model gets another turn
52
+ * (`awaiting_response`); the cycle repeats until a final text or a
53
+ * terminal outcome.
54
+ *
55
+ * `aborting` is reachable from every non-terminal state. From
56
+ * `aborting` we always end at `aborted` (no rollback — once the
57
+ * operator aborts, the dispatch is dead). Terminal states have no
58
+ * outgoing transitions.
59
+ */
60
+ const LEGAL_TRANSITIONS = {
61
+ idle: new Set(['awaiting_response', 'aborting']),
62
+ awaiting_response: new Set([
63
+ 'tool_running',
64
+ 'completed',
65
+ 'failed',
66
+ 'aborting',
67
+ ]),
68
+ tool_running: new Set([
69
+ 'awaiting_response',
70
+ 'completed',
71
+ 'failed',
72
+ 'aborting',
73
+ ]),
74
+ aborting: new Set(['aborted']),
75
+ aborted: new Set(),
76
+ completed: new Set(),
77
+ failed: new Set(),
78
+ };
79
+ /**
80
+ * Thrown when `transition()` is called with a state that is not in the
81
+ * current state's legal outgoing set. Carries enough context that a log
82
+ * line can be reconstructed at the call site.
83
+ */
84
+ export class IllegalDispatchTransitionError extends Error {
85
+ from;
86
+ to;
87
+ constructor(from, to) {
88
+ super(`Illegal dispatch FSM transition: ${from} -> ${to}`);
89
+ this.name = 'IllegalDispatchTransitionError';
90
+ this.from = from;
91
+ this.to = to;
92
+ }
93
+ }
94
+ export class DispatchFSM {
95
+ state = 'idle';
96
+ listeners = new Map();
97
+ /**
98
+ * Re-entrancy guard. While `firing === true` we are draining the
99
+ * listener fan-out for an in-progress transition. A nested
100
+ * `transition()` call from inside a listener queues into `pending`
101
+ * instead of recursing, so the legality check + state mutation +
102
+ * listener drain happen sequentially in commit order. Without this,
103
+ * a listener that immediately fired another transition would mutate
104
+ * `this.state` mid-iteration of the outer listener snapshot, which
105
+ * (a) could turn a legal outer transition into a thrown illegal
106
+ * inner one (the legality check reads `this.state` already mutated),
107
+ * (b) could ship `onEnter(B)` reasons under state A's snapshot.
108
+ * Queueing keeps the transition log linear.
109
+ */
110
+ firing = false;
111
+ pending = [];
112
+ /**
113
+ * Current state. Read-only — mutate via `transition()`.
114
+ */
115
+ get current() {
116
+ return this.state;
117
+ }
118
+ /**
119
+ * True when the current state is one of `completed`, `failed`,
120
+ * `aborted`. Terminal states cannot transition further.
121
+ */
122
+ get isTerminal() {
123
+ return this.state === 'completed' || this.state === 'failed' || this.state === 'aborted';
124
+ }
125
+ /**
126
+ * Transition the FSM to `next`, optionally carrying a `reason` string
127
+ * that is forwarded to `onEnter` listeners. Throws
128
+ * `IllegalDispatchTransitionError` when the transition is not in the
129
+ * current state's legal outgoing set.
130
+ *
131
+ * Listener errors do NOT block the transition. A throwing listener
132
+ * stops itself but the transition is already committed; the next
133
+ * listener still fires.
134
+ *
135
+ * Re-entrant calls (a listener calls `transition()` again) are
136
+ * queued — the inner transition runs after the outer listener drain
137
+ * completes, in FIFO order. See `firing` field comment.
138
+ */
139
+ transition(next, reason) {
140
+ if (this.firing) {
141
+ this.pending.push({ next, reason });
142
+ return;
143
+ }
144
+ this.firing = true;
145
+ try {
146
+ this.commit(next, reason);
147
+ while (this.pending.length > 0) {
148
+ const queued = this.pending.shift();
149
+ if (!queued)
150
+ break;
151
+ this.commit(queued.next, queued.reason);
152
+ }
153
+ }
154
+ finally {
155
+ this.firing = false;
156
+ }
157
+ }
158
+ /**
159
+ * Inner commit step — legality check + state mutation + listener
160
+ * drain. Called by `transition()` directly for the first move and
161
+ * for every queued nested move thereafter. Errors propagate to the
162
+ * outer `transition()` caller (illegal transitions still throw).
163
+ */
164
+ commit(next, reason) {
165
+ const legal = LEGAL_TRANSITIONS[this.state];
166
+ if (!legal.has(next)) {
167
+ throw new IllegalDispatchTransitionError(this.state, next);
168
+ }
169
+ this.state = next;
170
+ const set = this.listeners.get(next);
171
+ if (!set || set.size === 0)
172
+ return;
173
+ // Snapshot the listener set so a listener that detaches itself
174
+ // (via the returned unsubscribe handle) does not corrupt iteration.
175
+ const snapshot = Array.from(set);
176
+ for (const listener of snapshot) {
177
+ try {
178
+ listener(reason);
179
+ }
180
+ catch {
181
+ // Swallow listener errors — see header comment for rationale.
182
+ }
183
+ }
184
+ }
185
+ /**
186
+ * Register a listener that fires whenever the FSM ENTERS `state`. The
187
+ * listener does NOT fire if the FSM is already in `state` at
188
+ * registration time — onEnter is edge-triggered, not level-triggered.
189
+ *
190
+ * Returns an unsubscribe handle.
191
+ */
192
+ onEnter(state, listener) {
193
+ let set = this.listeners.get(state);
194
+ if (!set) {
195
+ set = new Set();
196
+ this.listeners.set(state, set);
197
+ }
198
+ set.add(listener);
199
+ return () => {
200
+ set?.delete(listener);
201
+ };
202
+ }
203
+ }
204
+ //# sourceMappingURL=dispatch-fsm.js.map
@@ -1,14 +1,14 @@
1
1
  /**
2
- * Privacy mode REPL surface α6.13 (Phase 1).
2
+ * Privacy mode REPL surface - alpha 6.13 (Phase 1).
3
3
  *
4
4
  * Two surfaces:
5
5
  *
6
- * 1. `renderPrivacyBanner(mode)` one-line banner shown on REPL
6
+ * 1. `renderPrivacyBanner(mode)` - one-line banner shown on REPL
7
7
  * bootstrap (mirrors `apps/admin-api/src/privacy/privacy-mode.ts`
8
- * `PRIVACY_MODE_BANNER` verbatim keep in sync, the unit spec
8
+ * `PRIVACY_MODE_BANNER` verbatim - keep in sync, the unit spec
9
9
  * asserts they match).
10
10
  *
11
- * 2. `renderPrivacyContractDoc(mode)` multi-line contract doc the
11
+ * 2. `renderPrivacyContractDoc(mode)` - multi-line contract doc the
12
12
  * `/privacy` slash command prints. Shows the active mode header
13
13
  * + the full 3-mode contract so the operator can compare their
14
14
  * current posture to the alternatives without leaving the REPL.