@skrr-ai/cli 0.1.202 → 0.1.204

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/base-command.js +1 -1
  2. package/dist/commands/agent/message/context.d.ts +3 -0
  3. package/dist/commands/agent/message/context.js +33 -1
  4. package/dist/commands/agent/message/no-reply.d.ts +17 -0
  5. package/dist/commands/agent/message/no-reply.js +54 -0
  6. package/dist/commands/agent/message/retract.d.ts +24 -0
  7. package/dist/commands/agent/message/retract.js +167 -0
  8. package/dist/commands/agent/message/send.d.ts +47 -3
  9. package/dist/commands/agent/message/send.js +135 -4
  10. package/dist/commands/agents/chat.d.ts +12 -0
  11. package/dist/commands/agents/chat.js +258 -25
  12. package/dist/commands/agents/manager/status.d.ts +9 -0
  13. package/dist/commands/agents/manager/status.js +84 -0
  14. package/dist/commands/agents/queue/clear.d.ts +13 -0
  15. package/dist/commands/agents/queue/clear.js +31 -0
  16. package/dist/commands/agents/queue/list.d.ts +10 -0
  17. package/dist/commands/agents/queue/list.js +34 -0
  18. package/dist/commands/agents/queue/move.d.ts +16 -0
  19. package/dist/commands/agents/queue/move.js +33 -0
  20. package/dist/commands/agents/queue/pause.d.ts +7 -0
  21. package/dist/commands/agents/queue/pause.js +24 -0
  22. package/dist/commands/agents/queue/resume.d.ts +7 -0
  23. package/dist/commands/agents/queue/resume.js +24 -0
  24. package/dist/commands/agents/queue/steer.d.ts +14 -0
  25. package/dist/commands/agents/queue/steer.js +38 -0
  26. package/dist/commands/agents/queue/withdraw.d.ts +10 -0
  27. package/dist/commands/agents/queue/withdraw.js +27 -0
  28. package/dist/commands/agents/supervision.d.ts +1 -0
  29. package/dist/commands/agents/supervision.js +28 -9
  30. package/dist/commands/duties/advance-next.d.ts +17 -0
  31. package/dist/commands/duties/advance-next.js +122 -0
  32. package/dist/commands/duties/pack/plan.js +45 -0
  33. package/dist/commands/duties/preflight.d.ts +1 -0
  34. package/dist/commands/duties/preflight.js +18 -2
  35. package/dist/commands/spaces/auto-executor/preview.js +6 -2
  36. package/dist/commands/spaces/charter/revise.d.ts +16 -0
  37. package/dist/commands/spaces/charter/revise.js +84 -0
  38. package/dist/commands/spaces/skills/propose.d.ts +1 -0
  39. package/dist/commands/spaces/skills/propose.js +5 -0
  40. package/dist/commands/tasks/create.js +16 -1
  41. package/dist/commands/tasks/result/show.js +6 -3
  42. package/dist/commands/tasks/start.d.ts +3 -0
  43. package/dist/commands/tasks/start.js +12 -1
  44. package/dist/commands/triggers/capabilities.js +14 -4
  45. package/dist/generated/agent-guides.json +258 -24
  46. package/dist/lib/agent-chat-queue-command.d.ts +29 -0
  47. package/dist/lib/agent-chat-queue-command.js +75 -0
  48. package/dist/lib/agent-chat-queue.d.ts +77 -0
  49. package/dist/lib/agent-chat-queue.js +245 -0
  50. package/dist/lib/agent-chat-start.d.ts +101 -0
  51. package/dist/lib/agent-chat-start.js +151 -6
  52. package/dist/lib/duties.d.ts +5 -1
  53. package/dist/lib/duties.js +16 -5
  54. package/dist/lib/duty-product.js +6 -0
  55. package/dist/lib/input-queue.d.ts +18 -0
  56. package/dist/lib/input-queue.js +59 -0
  57. package/dist/lib/message-intent.d.ts +26 -3
  58. package/dist/lib/message-intent.js +7 -1
  59. package/dist/lib/task-runtime-headers.d.ts +5 -0
  60. package/dist/lib/task-runtime-headers.js +28 -8
  61. package/dist/node_modules/@skrr-ai/data-provider/index.js +10464 -10221
  62. package/oclif.manifest.json +1956 -765
  63. package/package.json +6 -3
@@ -0,0 +1,77 @@
1
+ import { dataService, type TConversationInputQueueCard, type TConversationInputQueueRead, type TConversationInputQueueSnapshot, type TConversationInputQueueSteerResponse, type TConversationInputQueueSubmitResponse } from '@skrr-ai/data-provider';
2
+ type AgenticChatParams = Parameters<typeof dataService.startAgenticChat>[0];
3
+ export declare const WHEN_BUSY_MODES: readonly ["fail", "queue", "steer"];
4
+ export type WhenBusyMode = (typeof WHEN_BUSY_MODES)[number];
5
+ /** How long `agents chat --when-busy queue` follows a queued message by default. */
6
+ export declare const DEFAULT_QUEUE_WAIT_SECONDS: number;
7
+ export interface QueuedTurn {
8
+ conversationId: string;
9
+ clientInputId: string;
10
+ sessionId: string;
11
+ responseMessageId: string;
12
+ submitted: TConversationInputQueueSubmitResponse;
13
+ }
14
+ /**
15
+ * Queue the turn `startAgenticChat(params)` would have started. The CLI chooses the turn's session
16
+ * and reply ids, so once the card is sent it attaches to that turn exactly as after a direct start.
17
+ * `clientInputId` is the start key: a retry of the same command finds the same card.
18
+ */
19
+ export declare function queueAgentChatTurn(params: AgenticChatParams & {
20
+ conversationId: string;
21
+ }, { clientInputId, deps, }: {
22
+ clientInputId: string;
23
+ deps?: {
24
+ submit?: typeof dataService.submitConversationInput;
25
+ };
26
+ }): Promise<QueuedTurn>;
27
+ export type QueuedTurnWait = {
28
+ outcome: 'sent';
29
+ } | {
30
+ outcome: 'held';
31
+ card: TConversationInputQueueCard;
32
+ reason: string;
33
+ } | {
34
+ outcome: 'not_sent';
35
+ } | {
36
+ outcome: 'timeout';
37
+ card: TConversationInputQueueCard | null;
38
+ };
39
+ export interface QueueWaitDeps {
40
+ read?: (conversationId: string) => Promise<TConversationInputQueueRead>;
41
+ messages?: (conversationId: string) => Promise<Array<Record<string, unknown>> | undefined>;
42
+ sleep?: (ms: number) => Promise<void>;
43
+ now?: () => number;
44
+ }
45
+ /**
46
+ * Follow a queued card until it is sent, held, gone without being sent, or the wait runs out.
47
+ * A pause is reported once through `onPaused` and waited through: a person may resume it elsewhere.
48
+ * So is a hold the queue clears by itself (`SELF_CLEARING_HOLD_REASONS`).
49
+ */
50
+ export declare function waitForQueuedTurn(turn: Pick<QueuedTurn, 'conversationId' | 'clientInputId' | 'sessionId' | 'responseMessageId'>, { timeoutMs, onPaused, onPosition, deps, }: {
51
+ timeoutMs: number;
52
+ onPaused?: (sentence: string) => void;
53
+ onPosition?: (position: number, of: number) => void;
54
+ deps?: QueueWaitDeps;
55
+ }): Promise<QueuedTurnWait>;
56
+ /** A refusal from the input queue, in the CLI's words, or `null` for any other failure. */
57
+ export declare function queueErrorOf(err: unknown): {
58
+ code: string;
59
+ message: string;
60
+ status?: number;
61
+ retryable: boolean;
62
+ } | null;
63
+ export declare function readQueue(conversationId: string): Promise<TConversationInputQueueRead>;
64
+ export declare function withdrawCard(conversationId: string, cardId: string): Promise<TConversationInputQueueSnapshot>;
65
+ export declare function moveCard(conversationId: string, cardId: string, toIndex: number, expectedVersion?: number): Promise<TConversationInputQueueSnapshot>;
66
+ export declare function steerCard(conversationId: string, cardId: string, expectedVersion?: number): Promise<TConversationInputQueueSteerResponse>;
67
+ export declare function setQueuePaused(conversationId: string, paused: boolean): Promise<TConversationInputQueueSnapshot>;
68
+ export declare function clearQueue(conversationId: string): Promise<TConversationInputQueueSnapshot>;
69
+ /**
70
+ * A card named by id, by `#<n>` (1-based position) or by a unique id prefix of at least 6
71
+ * characters.
72
+ */
73
+ export declare function resolveCard(snapshot: TConversationInputQueueSnapshot, ref: string): TConversationInputQueueCard | null;
74
+ export declare function steerOutcomeSentence(outcome: TConversationInputQueueSteerResponse['outcome']): string;
75
+ /** The queue as lines of text: the pause, what the running turn takes, then the cards in order. */
76
+ export declare function renderQueue(read: TConversationInputQueueRead): string[];
77
+ export {};
@@ -0,0 +1,245 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_QUEUE_WAIT_SECONDS = exports.WHEN_BUSY_MODES = void 0;
4
+ exports.queueAgentChatTurn = queueAgentChatTurn;
5
+ exports.waitForQueuedTurn = waitForQueuedTurn;
6
+ exports.queueErrorOf = queueErrorOf;
7
+ exports.readQueue = readQueue;
8
+ exports.withdrawCard = withdrawCard;
9
+ exports.moveCard = moveCard;
10
+ exports.steerCard = steerCard;
11
+ exports.setQueuePaused = setQueuePaused;
12
+ exports.clearQueue = clearQueue;
13
+ exports.resolveCard = resolveCard;
14
+ exports.steerOutcomeSentence = steerOutcomeSentence;
15
+ exports.renderQueue = renderQueue;
16
+ /**
17
+ * The conversation input queue from the CLI (G7): queue a turn on a busy conversation, follow it
18
+ * until it is sent, and act on the queue's cards.
19
+ *
20
+ * Every call goes through `dataService` (the CLI ↔ API parity rule); the vocabularies are
21
+ * `@skrr-ai/data-provider`'s, and the sentences are in `./input-queue`.
22
+ */
23
+ const node_crypto_1 = require("node:crypto");
24
+ const data_provider_1 = require("@skrr-ai/data-provider");
25
+ const agent_chat_start_1 = require("./agent-chat-start");
26
+ const http_error_1 = require("./http-error");
27
+ const input_queue_1 = require("./input-queue");
28
+ exports.WHEN_BUSY_MODES = ['fail', 'queue', 'steer'];
29
+ /** How long `agents chat --when-busy queue` follows a queued message by default. */
30
+ exports.DEFAULT_QUEUE_WAIT_SECONDS = 30 * 60;
31
+ const POLL_MS = 2_000;
32
+ /** Polls after a card leaves the queue before it is reported as not sent (withdrawn elsewhere). */
33
+ const SETTLE_POLLS = 3;
34
+ /**
35
+ * Queue the turn `startAgenticChat(params)` would have started. The CLI chooses the turn's session
36
+ * and reply ids, so once the card is sent it attaches to that turn exactly as after a direct start.
37
+ * `clientInputId` is the start key: a retry of the same command finds the same card.
38
+ */
39
+ async function queueAgentChatTurn(params, { clientInputId, deps = {}, }) {
40
+ const sessionId = (0, node_crypto_1.randomUUID)();
41
+ const responseMessageId = (0, node_crypto_1.randomUUID)();
42
+ const { clientRequestId: _key, ...body } = data_provider_1.dataService.buildAgenticChatBody(params);
43
+ void _key;
44
+ const submit = deps.submit ?? data_provider_1.dataService.submitConversationInput;
45
+ const submitted = await submit(params.conversationId, {
46
+ capability: data_provider_1.CONVERSATION_INPUT_QUEUE_CAPABILITY,
47
+ clientInputId,
48
+ source: 'cli',
49
+ deliveryMode: 'queue',
50
+ submission: { ...body, sessionId, responseMessageId },
51
+ });
52
+ return {
53
+ conversationId: params.conversationId,
54
+ clientInputId,
55
+ sessionId,
56
+ responseMessageId,
57
+ submitted,
58
+ };
59
+ }
60
+ /**
61
+ * Follow a queued card until it is sent, held, gone without being sent, or the wait runs out.
62
+ * A pause is reported once through `onPaused` and waited through: a person may resume it elsewhere.
63
+ * So is a hold the queue clears by itself (`SELF_CLEARING_HOLD_REASONS`).
64
+ */
65
+ async function waitForQueuedTurn(turn, { timeoutMs, onPaused, onPosition, deps = {}, }) {
66
+ const read = deps.read ?? data_provider_1.dataService.getConversationInputQueue;
67
+ const messages = deps.messages ??
68
+ ((id) => data_provider_1.dataService.getMessagesByConvoId(id));
69
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
70
+ const now = deps.now ?? Date.now;
71
+ const deadline = now() + timeoutMs;
72
+ let lastCard = null;
73
+ let pausedSaid = null;
74
+ let lastPosition = -1;
75
+ let goneFor = 0;
76
+ for (;;) {
77
+ const snapshot = await read(turn.conversationId);
78
+ const ordered = [...snapshot.cards].sort((a, b) => a.position - b.position);
79
+ const index = ordered.findIndex((c) => c.clientInputId === turn.clientInputId);
80
+ const card = index >= 0 ? ordered[index] : null;
81
+ if (card) {
82
+ lastCard = card;
83
+ goneFor = 0;
84
+ const selfClearing = card.state === 'held' &&
85
+ !!card.holdReason &&
86
+ input_queue_1.SELF_CLEARING_HOLD_REASONS.has(card.holdReason);
87
+ if (card.state === 'held' && !selfClearing) {
88
+ return {
89
+ outcome: 'held',
90
+ card,
91
+ reason: card.holdReason
92
+ ? input_queue_1.HOLD_REASON_COPY[card.holdReason]
93
+ : 'The message could not be sent.',
94
+ };
95
+ }
96
+ const sentence = waitingSentence(card, snapshot);
97
+ if (sentence) {
98
+ if (sentence !== pausedSaid)
99
+ onPaused?.(sentence);
100
+ pausedSaid = sentence;
101
+ }
102
+ else {
103
+ pausedSaid = null;
104
+ }
105
+ if (index !== lastPosition)
106
+ onPosition?.(index, ordered.length);
107
+ lastPosition = index;
108
+ }
109
+ else {
110
+ if (snapshot.turn?.sessionId === turn.sessionId)
111
+ return { outcome: 'sent' };
112
+ const rows = await messages(turn.conversationId);
113
+ if (Array.isArray(rows) && rows.some((m) => m.messageId === turn.responseMessageId)) {
114
+ return { outcome: 'sent' };
115
+ }
116
+ goneFor += 1;
117
+ if (goneFor >= SETTLE_POLLS)
118
+ return { outcome: 'not_sent' };
119
+ }
120
+ if (now() >= deadline)
121
+ return { outcome: 'timeout', card: lastCard };
122
+ await sleep(POLL_MS);
123
+ }
124
+ }
125
+ /** What a followed card is waiting on, or null when it is simply in line. */
126
+ function waitingSentence(card, snapshot) {
127
+ if (card.state === 'held' && card.holdReason)
128
+ return input_queue_1.HOLD_REASON_COPY[card.holdReason];
129
+ const paused = snapshot.paused;
130
+ if (!paused)
131
+ return null;
132
+ // Behind another card's hold: name it when it clears by itself, else the pause itself.
133
+ const code = paused.code;
134
+ if (paused.reason === 'card_held' && code && input_queue_1.SELF_CLEARING_HOLD_REASONS.has(code)) {
135
+ return input_queue_1.HOLD_REASON_COPY[code];
136
+ }
137
+ return input_queue_1.PAUSE_REASON_COPY[paused.reason];
138
+ }
139
+ /** A refusal from the input queue, in the CLI's words, or `null` for any other failure. */
140
+ function queueErrorOf(err) {
141
+ const response = err?.response?.data;
142
+ const body = (0, agent_chat_start_1.bodyOf)(err) ??
143
+ (response && typeof response === 'object'
144
+ ? response
145
+ : undefined);
146
+ const code = typeof body?.code === 'string' ? body.code : null;
147
+ if (!code || !code.startsWith('INPUT_QUEUE_'))
148
+ return null;
149
+ const serverMessage = typeof body?.message === 'string' ? body.message : null;
150
+ return {
151
+ code,
152
+ message: (0, input_queue_1.describeInputQueueError)(code) ?? serverMessage ?? 'The input queue refused this.',
153
+ status: (0, http_error_1.httpStatusOf)(err),
154
+ retryable: [
155
+ 'INPUT_QUEUE_CONTENDED',
156
+ 'INPUT_QUEUE_UNAVAILABLE',
157
+ 'INPUT_QUEUE_STEER_UNAVAILABLE',
158
+ ].includes(code),
159
+ };
160
+ }
161
+ /* ── Queue actions ─────────────────────────────────────────────────────── */
162
+ function readQueue(conversationId) {
163
+ return data_provider_1.dataService.getConversationInputQueue(conversationId);
164
+ }
165
+ function withdrawCard(conversationId, cardId) {
166
+ return data_provider_1.dataService.withdrawConversationInput(conversationId, cardId);
167
+ }
168
+ function moveCard(conversationId, cardId, toIndex, expectedVersion) {
169
+ return data_provider_1.dataService.moveConversationInput(conversationId, cardId, {
170
+ toIndex,
171
+ ...(expectedVersion != null ? { expectedVersion } : {}),
172
+ });
173
+ }
174
+ function steerCard(conversationId, cardId, expectedVersion) {
175
+ return data_provider_1.dataService.steerConversationInput(conversationId, cardId, expectedVersion != null ? { expectedVersion } : {});
176
+ }
177
+ function setQueuePaused(conversationId, paused) {
178
+ return data_provider_1.dataService.setConversationInputQueuePaused(conversationId, paused);
179
+ }
180
+ function clearQueue(conversationId) {
181
+ return data_provider_1.dataService.clearConversationInputQueue(conversationId);
182
+ }
183
+ /**
184
+ * A card named by id, by `#<n>` (1-based position) or by a unique id prefix of at least 6
185
+ * characters.
186
+ */
187
+ function resolveCard(snapshot, ref) {
188
+ const ordered = [...snapshot.cards].sort((a, b) => a.position - b.position);
189
+ const positional = /^#(\d+)$/.exec(ref);
190
+ if (positional)
191
+ return ordered[Number(positional[1]) - 1] ?? null;
192
+ const exact = ordered.find((c) => c.cardId === ref);
193
+ if (exact)
194
+ return exact;
195
+ if (ref.length < 6)
196
+ return null;
197
+ const matches = ordered.filter((c) => c.cardId.startsWith(ref));
198
+ return matches.length === 1 ? matches[0] : null;
199
+ }
200
+ function steerOutcomeSentence(outcome) {
201
+ return input_queue_1.STEER_OUTCOME_COPY[outcome];
202
+ }
203
+ const STATE_LABEL = {
204
+ waiting: 'waiting',
205
+ dispatching: 'sending',
206
+ held: 'held',
207
+ editing: 'editing',
208
+ };
209
+ /** The queue as lines of text: the pause, what the running turn takes, then the cards in order. */
210
+ function renderQueue(read) {
211
+ const lines = [];
212
+ if (read.paused)
213
+ lines.push(input_queue_1.PAUSE_REASON_COPY[read.paused.reason]);
214
+ if (read.turn) {
215
+ if (read.turn.acceptsSteer === true)
216
+ lines.push('A turn is running and takes messages (steer).');
217
+ else if (read.turn.acceptsSteer === false)
218
+ lines.push(`A turn is running and takes no messages: ${read.turn.reason
219
+ ? input_queue_1.NO_STEER_REASON_COPY[read.turn.reason]
220
+ : 'it reads no input until it ends.'}`);
221
+ else
222
+ lines.push('A turn is running.');
223
+ }
224
+ const ordered = [...read.cards].sort((a, b) => a.position - b.position);
225
+ if (ordered.length === 0) {
226
+ lines.push('The queue is empty.');
227
+ return lines;
228
+ }
229
+ ordered.forEach((card, i) => {
230
+ const flags = [
231
+ STATE_LABEL[card.state],
232
+ card.kind === 'command' ? 'command' : null,
233
+ card.deliveryMode === 'steer' ? 'asks to steer' : null,
234
+ card.files.length ? `${card.files.length} file${card.files.length === 1 ? '' : 's'}` : null,
235
+ ].filter(Boolean);
236
+ const text = card.text.replace(/\s+/g, ' ').trim();
237
+ lines.push(`#${i + 1} ${card.cardId} [${flags.join(', ')}] ${text.length > 72 ? `${text.slice(0, 71)}…` : text}`);
238
+ if (card.state === 'held') {
239
+ lines.push(` ${card.holdReason ? input_queue_1.HOLD_REASON_COPY[card.holdReason] : 'Could not be sent.'}`);
240
+ if (card.holdMessage)
241
+ lines.push(` ${card.holdMessage}`);
242
+ }
243
+ });
244
+ return lines;
245
+ }
@@ -22,6 +22,12 @@
22
22
  * unconfirmed previous admission, a changed release), any 4xx, and anything that is not
23
23
  * an HTTP failure of the transport. Those describe a state the caller has to change
24
24
  * first, and replaying them only repeats the refusal.
25
+ *
26
+ * One 4xx is a state that changes by itself: `429 conversation_busy`, the conversation
27
+ * already has a turn running (OSK-32920). It is refused before anything is admitted or
28
+ * reserved, and the replay check comes before it on the server, so asking again under
29
+ * the same key is safe. It is still not replayed by default, because a turn sent later
30
+ * than the caller meant is a different turn; `waitForIdle` opts in, with a deadline.
25
31
  */
26
32
  export declare const START_KEY_RULE = "1-128 characters: letters, numbers, dot, underscore, colon, hyphen";
27
33
  /**
@@ -35,6 +41,16 @@ export declare function newStartKey(): string;
35
41
  /** Whether a caller-supplied key is one the server will accept. */
36
42
  export declare function isValidStartKey(value: string): boolean;
37
43
  export type StartVerdict = 'replay' | 'surface';
44
+ interface ErrorBody {
45
+ errorType?: unknown;
46
+ retryable?: unknown;
47
+ code?: unknown;
48
+ message?: unknown;
49
+ }
50
+ /** The server's answer when the conversation already has a turn running. */
51
+ export declare const CONVERSATION_BUSY = "conversation_busy";
52
+ /** The JSON body of a failed response, when the transport kept it as text or as an object. */
53
+ export declare function bodyOf(err: unknown): ErrorBody | undefined;
38
54
  /**
39
55
  * Whether a failed start may be sent again under the same key.
40
56
  *
@@ -42,6 +58,26 @@ export type StartVerdict = 'replay' | 'surface';
42
58
  * said "still being admitted"; `surface` is everything the caller has to act on.
43
59
  */
44
60
  export declare function classifyStartFailure(err: unknown): StartVerdict;
61
+ /**
62
+ * Whether a failed start was refused because the conversation already has a turn running
63
+ * (`429 conversation_busy`). Nothing was admitted: no turn, no balance hold.
64
+ */
65
+ export declare function isConversationBusy(err: unknown): boolean;
66
+ /** How long `--wait-for-idle` waits for a busy conversation by default: 5 minutes. */
67
+ export declare const DEFAULT_WAIT_FOR_IDLE_TIMEOUT_MS: number;
68
+ /**
69
+ * Waits between asks while the conversation is busy; the last one repeats. The first is
70
+ * short because a turn that was just stopped or is finishing frees the conversation soon;
71
+ * after that, asking every 15 seconds is plenty.
72
+ */
73
+ export declare const DEFAULT_BUSY_WAIT_DELAYS_MS: readonly number[];
74
+ /** Raised when a busy conversation was still busy when the wait for it ran out. */
75
+ export declare class ConversationStillBusy extends Error {
76
+ readonly attempts: number;
77
+ readonly waitedMs: number;
78
+ readonly lastError: unknown;
79
+ constructor(lastError: unknown, attempts: number, waitedMs: number);
80
+ }
45
81
  /** Raised when every replay of a start ended without the server confirming the outcome. */
46
82
  export declare class StartNotConfirmed extends Error {
47
83
  readonly attempts: number;
@@ -56,10 +92,38 @@ export interface ReplayInfo {
56
92
  waitMs: number;
57
93
  error: unknown;
58
94
  }
95
+ export interface BusyWaitInfo {
96
+ /** The ask about to be sent again, 1-based. */
97
+ attempt: number;
98
+ waitMs: number;
99
+ /** How long this start has waited for the conversation so far. */
100
+ waitedMs: number;
101
+ timeoutMs: number;
102
+ /**
103
+ * An earlier attempt's answer was lost, so the running turn may be that attempt and
104
+ * "nothing was sent" is not known.
105
+ */
106
+ earlierAttemptUnconfirmed: boolean;
107
+ }
108
+ export interface WaitForIdleOptions {
109
+ /** Give up once this much time has passed since the first refusal. */
110
+ timeoutMs: number;
111
+ /** Waits between asks; the last one repeats. */
112
+ delaysMs?: readonly number[];
113
+ onBusy?: (info: BusyWaitInfo) => void;
114
+ }
59
115
  export interface StartReplayOptions {
60
116
  delaysMs?: readonly number[];
61
117
  sleep?: (ms: number) => Promise<void>;
62
118
  onReplay?: (info: ReplayInfo) => void;
119
+ /**
120
+ * Ask again, under the same key, while the conversation is busy, until it is free or
121
+ * `timeoutMs` has passed (then `ConversationStillBusy`). Without it a busy refusal is
122
+ * thrown untouched, like every other refusal.
123
+ */
124
+ waitForIdle?: WaitForIdleOptions;
125
+ /** The clock the busy wait reads; tests pass their own. */
126
+ now?: () => number;
63
127
  }
64
128
  /**
65
129
  * Run `start`; when it fails with an unknown outcome, run it again — the SAME call, so the
@@ -68,10 +132,47 @@ export interface StartReplayOptions {
68
132
  * A failure that is not replayable is thrown untouched on whichever attempt it happens, so
69
133
  * existing error handling (and its message) is unchanged. Only running out of replays turns
70
134
  * into `StartNotConfirmed`, which carries the last transport error for the caller to render.
135
+ *
136
+ * A busy conversation (`429 conversation_busy`) is thrown untouched too, unless an earlier
137
+ * attempt is unconfirmed (then it is replayed like any unknown outcome) or `waitForIdle`
138
+ * asks to wait: then the same call is sent again until the conversation is free, and a
139
+ * conversation still busy at `timeoutMs` becomes `ConversationStillBusy`.
71
140
  */
72
141
  export declare function startWithReplay<T>(start: () => Promise<T>, options?: StartReplayOptions): Promise<T>;
142
+ /**
143
+ * What to tell a person whose start was refused because the conversation already has a
144
+ * turn running. Nothing was sent, so they can simply send it again; the advice names the
145
+ * flag that waits for them.
146
+ */
147
+ export declare function conversationBusyMessage(input: {
148
+ conversationId?: string | null;
149
+ /** Set when `--wait-for-idle` waited and the conversation never came free. */
150
+ waitedMs?: number;
151
+ }): string;
152
+ /** A start refused because the conversation was busy, ready for the command to report. */
153
+ export interface BusyStartFailure {
154
+ message: string;
155
+ code: typeof CONVERSATION_BUSY;
156
+ status: 429;
157
+ /** Waiting can help: the refusal ends when the running turn does. */
158
+ retryable: true;
159
+ details: {
160
+ conversationId?: string;
161
+ waitedMs?: number;
162
+ attempts?: number;
163
+ };
164
+ }
165
+ /**
166
+ * The report for a start that failed because the conversation was busy: refused once
167
+ * (`isConversationBusy`), or still busy when `--wait-for-idle` ran out
168
+ * (`ConversationStillBusy`). Null for every other failure, which keeps its own handling.
169
+ */
170
+ export declare function busyStartFailure(err: unknown, conversationId?: string | null): BusyStartFailure | null;
171
+ /** The line printed (to stderr) each time `--wait-for-idle` waits for a busy conversation. */
172
+ export declare function busyWaitNotice(info: BusyWaitInfo, conversationId?: string | null): string;
73
173
  /**
74
174
  * What to tell a person when the server never confirmed the start. The turn may be running,
75
175
  * so the advice is to re-attach with the same key rather than start a second turn.
76
176
  */
77
177
  export declare function startNotConfirmedHint(key: string, attempts: number): string;
178
+ export {};
@@ -23,13 +23,24 @@
23
23
  * unconfirmed previous admission, a changed release), any 4xx, and anything that is not
24
24
  * an HTTP failure of the transport. Those describe a state the caller has to change
25
25
  * first, and replaying them only repeats the refusal.
26
+ *
27
+ * One 4xx is a state that changes by itself: `429 conversation_busy`, the conversation
28
+ * already has a turn running (OSK-32920). It is refused before anything is admitted or
29
+ * reserved, and the replay check comes before it on the server, so asking again under
30
+ * the same key is safe. It is still not replayed by default, because a turn sent later
31
+ * than the caller meant is a different turn; `waitForIdle` opts in, with a deadline.
26
32
  */
27
33
  Object.defineProperty(exports, "__esModule", { value: true });
28
- exports.StartNotConfirmed = exports.DEFAULT_REPLAY_DELAYS_MS = exports.START_KEY_RULE = void 0;
34
+ exports.StartNotConfirmed = exports.ConversationStillBusy = exports.DEFAULT_BUSY_WAIT_DELAYS_MS = exports.DEFAULT_WAIT_FOR_IDLE_TIMEOUT_MS = exports.CONVERSATION_BUSY = exports.DEFAULT_REPLAY_DELAYS_MS = exports.START_KEY_RULE = void 0;
29
35
  exports.newStartKey = newStartKey;
30
36
  exports.isValidStartKey = isValidStartKey;
37
+ exports.bodyOf = bodyOf;
31
38
  exports.classifyStartFailure = classifyStartFailure;
39
+ exports.isConversationBusy = isConversationBusy;
32
40
  exports.startWithReplay = startWithReplay;
41
+ exports.conversationBusyMessage = conversationBusyMessage;
42
+ exports.busyStartFailure = busyStartFailure;
43
+ exports.busyWaitNotice = busyWaitNotice;
33
44
  exports.startNotConfirmedHint = startNotConfirmedHint;
34
45
  const node_crypto_1 = require("node:crypto");
35
46
  const http_error_1 = require("./http-error");
@@ -51,6 +62,8 @@ function newStartKey() {
51
62
  function isValidStartKey(value) {
52
63
  return START_KEY_PATTERN.test(value);
53
64
  }
65
+ /** The server's answer when the conversation already has a turn running. */
66
+ exports.CONVERSATION_BUSY = 'conversation_busy';
54
67
  /** The JSON body of a failed response, when the transport kept it as text or as an object. */
55
68
  function bodyOf(err) {
56
69
  if (typeof err !== 'object' || err === null)
@@ -116,6 +129,39 @@ function classifyStartFailure(err) {
116
129
  return 'replay';
117
130
  return 'surface';
118
131
  }
132
+ /**
133
+ * Whether a failed start was refused because the conversation already has a turn running
134
+ * (`429 conversation_busy`). Nothing was admitted: no turn, no balance hold.
135
+ */
136
+ function isConversationBusy(err) {
137
+ return (0, http_error_1.httpStatusOf)(err) === 429 && bodyOf(err)?.errorType === exports.CONVERSATION_BUSY;
138
+ }
139
+ /** How long `--wait-for-idle` waits for a busy conversation by default: 5 minutes. */
140
+ exports.DEFAULT_WAIT_FOR_IDLE_TIMEOUT_MS = 5 * 60_000;
141
+ /**
142
+ * Waits between asks while the conversation is busy; the last one repeats. The first is
143
+ * short because a turn that was just stopped or is finishing frees the conversation soon;
144
+ * after that, asking every 15 seconds is plenty.
145
+ */
146
+ exports.DEFAULT_BUSY_WAIT_DELAYS_MS = [2_000, 4_000, 8_000, 15_000];
147
+ /** Raised when a busy conversation was still busy when the wait for it ran out. */
148
+ class ConversationStillBusy extends Error {
149
+ attempts;
150
+ waitedMs;
151
+ lastError;
152
+ constructor(lastError, attempts, waitedMs) {
153
+ super(`The conversation still had a turn running after waiting ${formatSeconds(waitedMs)}.`);
154
+ this.name = 'ConversationStillBusy';
155
+ this.attempts = attempts;
156
+ this.waitedMs = waitedMs;
157
+ this.lastError = lastError;
158
+ }
159
+ }
160
+ exports.ConversationStillBusy = ConversationStillBusy;
161
+ function formatSeconds(ms) {
162
+ const seconds = Math.max(0, Math.round(ms / 1000));
163
+ return `${seconds} second${seconds === 1 ? '' : 's'}`;
164
+ }
119
165
  /** Raised when every replay of a start ended without the server confirming the outcome. */
120
166
  class StartNotConfirmed extends Error {
121
167
  attempts;
@@ -136,28 +182,127 @@ const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
136
182
  * A failure that is not replayable is thrown untouched on whichever attempt it happens, so
137
183
  * existing error handling (and its message) is unchanged. Only running out of replays turns
138
184
  * into `StartNotConfirmed`, which carries the last transport error for the caller to render.
185
+ *
186
+ * A busy conversation (`429 conversation_busy`) is thrown untouched too, unless an earlier
187
+ * attempt is unconfirmed (then it is replayed like any unknown outcome) or `waitForIdle`
188
+ * asks to wait: then the same call is sent again until the conversation is free, and a
189
+ * conversation still busy at `timeoutMs` becomes `ConversationStillBusy`.
139
190
  */
140
191
  async function startWithReplay(start, options = {}) {
141
192
  const delays = options.delaysMs ?? exports.DEFAULT_REPLAY_DELAYS_MS;
142
193
  const sleep = options.sleep ?? defaultSleep;
194
+ const now = options.now ?? Date.now;
195
+ const waitForIdle = options.waitForIdle;
196
+ const busyDelays = waitForIdle?.delaysMs && waitForIdle.delaysMs.length > 0
197
+ ? waitForIdle.delaysMs
198
+ : exports.DEFAULT_BUSY_WAIT_DELAYS_MS;
143
199
  let attempts = 0;
200
+ // Two separate budgets: replays of an unknown outcome are counted, the busy wait is timed.
201
+ let replays = 0;
202
+ let busyWaits = 0;
203
+ let busySince = null;
144
204
  for (;;) {
145
205
  attempts += 1;
146
206
  try {
147
207
  return await start();
148
208
  }
149
209
  catch (error) {
150
- if (classifyStartFailure(error) !== 'replay')
210
+ const busy = isConversationBusy(error);
211
+ if (busy && waitForIdle) {
212
+ busySince ??= now();
213
+ const waitedMs = now() - busySince;
214
+ const remainingMs = waitForIdle.timeoutMs - waitedMs;
215
+ if (remainingMs <= 0) {
216
+ // After an unconfirmed attempt the running turn may be that attempt, so
217
+ // "nothing was sent" would not be known.
218
+ if (replays > 0)
219
+ throw new StartNotConfirmed(error, attempts);
220
+ throw new ConversationStillBusy(error, attempts, waitedMs);
221
+ }
222
+ const waitMs = Math.min(busyDelays[Math.min(busyWaits, busyDelays.length - 1)], remainingMs);
223
+ busyWaits += 1;
224
+ waitForIdle.onBusy?.({
225
+ attempt: busyWaits,
226
+ waitMs,
227
+ waitedMs,
228
+ timeoutMs: waitForIdle.timeoutMs,
229
+ earlierAttemptUnconfirmed: replays > 0,
230
+ });
231
+ await sleep(waitMs);
232
+ continue;
233
+ }
234
+ // A busy answer to a REPLAY confirms nothing: the server takes the conversation's
235
+ // lock before it records the admission the replay check reads, so the turn holding
236
+ // the conversation may be the attempt whose answer was lost. Keep replaying; the
237
+ // same key returns that turn once its admission is recorded.
238
+ const replayable = busy ? replays > 0 : classifyStartFailure(error) === 'replay';
239
+ if (!replayable)
151
240
  throw error;
152
- const replayIndex = attempts - 1;
153
- if (replayIndex >= delays.length)
241
+ if (replays >= delays.length)
154
242
  throw new StartNotConfirmed(error, attempts);
155
- const waitMs = delays[replayIndex];
156
- options.onReplay?.({ attempt: replayIndex + 1, of: delays.length, waitMs, error });
243
+ const waitMs = delays[replays];
244
+ replays += 1;
245
+ options.onReplay?.({ attempt: replays, of: delays.length, waitMs, error });
157
246
  await sleep(waitMs);
158
247
  }
159
248
  }
160
249
  }
250
+ function conversationPhrase(conversationId) {
251
+ return conversationId ? `Conversation ${conversationId}` : 'This conversation';
252
+ }
253
+ /**
254
+ * What to tell a person whose start was refused because the conversation already has a
255
+ * turn running. Nothing was sent, so they can simply send it again; the advice names the
256
+ * flag that waits for them.
257
+ */
258
+ function conversationBusyMessage(input) {
259
+ const which = conversationPhrase(input.conversationId);
260
+ if (input.waitedMs !== undefined) {
261
+ return (`${which} still had a turn running after waiting ${formatSeconds(input.waitedMs)}, ` +
262
+ 'so Skrr did not start this one and nothing was sent. Run the command again with a ' +
263
+ 'longer --wait-timeout, or stop the running turn first.');
264
+ }
265
+ return (`${which} already has a turn running, so Skrr did not start this one and nothing was ` +
266
+ 'sent. Send it again when that turn ends, add --wait-for-idle to wait for it and ' +
267
+ 'send this turn then, or add --when-busy queue to queue it on the server.');
268
+ }
269
+ /**
270
+ * The report for a start that failed because the conversation was busy: refused once
271
+ * (`isConversationBusy`), or still busy when `--wait-for-idle` ran out
272
+ * (`ConversationStillBusy`). Null for every other failure, which keeps its own handling.
273
+ */
274
+ function busyStartFailure(err, conversationId) {
275
+ const conversation = conversationId ? { conversationId } : {};
276
+ if (err instanceof ConversationStillBusy) {
277
+ return {
278
+ message: conversationBusyMessage({ conversationId, waitedMs: err.waitedMs }),
279
+ code: exports.CONVERSATION_BUSY,
280
+ status: 429,
281
+ retryable: true,
282
+ details: { ...conversation, waitedMs: err.waitedMs, attempts: err.attempts },
283
+ };
284
+ }
285
+ if (!isConversationBusy(err))
286
+ return null;
287
+ return {
288
+ message: conversationBusyMessage({ conversationId }),
289
+ code: exports.CONVERSATION_BUSY,
290
+ status: 429,
291
+ retryable: true,
292
+ details: conversation,
293
+ };
294
+ }
295
+ /** The line printed (to stderr) each time `--wait-for-idle` waits for a busy conversation. */
296
+ function busyWaitNotice(info, conversationId) {
297
+ const left = Math.max(0, info.timeoutMs - info.waitedMs);
298
+ return (`${conversationPhrase(conversationId)} has a turn running. Asking again in ` +
299
+ `${formatSeconds(info.waitMs)}; this start waits ${formatSeconds(left)} more before ` +
300
+ 'giving up.' +
301
+ (info.earlierAttemptUnconfirmed
302
+ ? ' An earlier attempt was not confirmed, so that turn may be this one; asking again ' +
303
+ 'with the same key returns it rather than starting a second.'
304
+ : ' Nothing has been sent yet.'));
305
+ }
161
306
  /**
162
307
  * What to tell a person when the server never confirmed the start. The turn may be running,
163
308
  * so the advice is to re-attach with the same key rather than start a second turn.