@myspec/sdk 0.0.0-stage → 0.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/LICENSE +21 -0
- package/README.md +130 -2
- package/dist/index.d.ts +14 -0
- package/dist/index.js +14 -0
- package/dist/src/auth.d.ts +73 -0
- package/dist/src/auth.js +169 -0
- package/dist/src/client.d.ts +124 -0
- package/dist/src/client.js +219 -0
- package/dist/src/decisions.d.ts +51 -0
- package/dist/src/decisions.js +219 -0
- package/dist/src/errors.d.ts +93 -0
- package/dist/src/errors.js +170 -0
- package/dist/src/policies.d.ts +62 -0
- package/dist/src/policies.js +124 -0
- package/dist/src/run.d.ts +101 -0
- package/dist/src/run.js +131 -0
- package/dist/src/stream.d.ts +29 -0
- package/dist/src/stream.js +104 -0
- package/dist/src/types.d.ts +339 -0
- package/dist/src/types.js +37 -0
- package/package.json +32 -4
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The session driver client.
|
|
3
|
+
*
|
|
4
|
+
* `createClient(...).attach(sessionId)` returns a handle on one chat session,
|
|
5
|
+
* whoever started it. The handle reads what the session waits on and sends
|
|
6
|
+
* turns; it holds no state of its own, so two handles on one session behave
|
|
7
|
+
* the same.
|
|
8
|
+
*
|
|
9
|
+
* The transport is a `fetch` function and `baseUrl` is the origin that serves
|
|
10
|
+
* `/api/v1/chat/...`: the ai-agent, or a proxy in front of it. In a test it can
|
|
11
|
+
* be the `fetch` of an in-process ai-agent app, with no network at all.
|
|
12
|
+
*/
|
|
13
|
+
import { validateDecision } from "./decisions.js";
|
|
14
|
+
import { InvalidDecisionError, TurnSettleTimeoutError, TurnTimeoutError, errorFromResponse, } from "./errors.js";
|
|
15
|
+
import { readTurnStream } from "./stream.js";
|
|
16
|
+
import { DECISION_PART_TYPE, NO_PENDING_ACTION_ID, } from "./types.js";
|
|
17
|
+
/** Client type the ai-agent segments analytics on, unless the caller sets one. */
|
|
18
|
+
export const DEFAULT_CLIENT_TYPE = 'sdk';
|
|
19
|
+
/** Default wait between two state polls of {@link SessionHandle.waitForTurn}. */
|
|
20
|
+
export const DEFAULT_POLL_MS = 2_000;
|
|
21
|
+
/** Default longest wait of {@link SessionHandle.waitForTurn}. */
|
|
22
|
+
export const DEFAULT_WAIT_TIMEOUT_MS = 20 * 60_000;
|
|
23
|
+
/**
|
|
24
|
+
* Longest wait for the server to stop reporting a turn as running AFTER its
|
|
25
|
+
* stream ended. The stream's end is what releases the turn on the server, but
|
|
26
|
+
* the release is not instant and another replica can lag behind it.
|
|
27
|
+
*/
|
|
28
|
+
export const TURN_SETTLE_TIMEOUT_MS = 30_000;
|
|
29
|
+
/** Wait between polls while a finished turn settles. */
|
|
30
|
+
export const TURN_SETTLE_POLL_MS = 500;
|
|
31
|
+
const defaultSleep = (ms) => new Promise((resolve) => {
|
|
32
|
+
setTimeout(resolve, ms);
|
|
33
|
+
});
|
|
34
|
+
/**
|
|
35
|
+
* Resolves with `promise`'s value when it settles within `waitMs`, or with
|
|
36
|
+
* `undefined` when the time runs out first. A rejection inside the time is
|
|
37
|
+
* passed on; one after it is the caller's to handle on `promise` itself.
|
|
38
|
+
*/
|
|
39
|
+
function withinBudget(promise, waitMs) {
|
|
40
|
+
return new Promise((resolve, reject) => {
|
|
41
|
+
const timer = setTimeout(() => {
|
|
42
|
+
resolve(undefined);
|
|
43
|
+
}, waitMs);
|
|
44
|
+
promise.then((value) => {
|
|
45
|
+
clearTimeout(timer);
|
|
46
|
+
resolve(value);
|
|
47
|
+
}, (error) => {
|
|
48
|
+
clearTimeout(timer);
|
|
49
|
+
reject(error instanceof Error ? error : new Error(String(error)));
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
export function createClient(options) {
|
|
54
|
+
const baseUrl = options.baseUrl.replace(/\/+$/, '');
|
|
55
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
56
|
+
const sleep = options.sleep ?? defaultSleep;
|
|
57
|
+
const clientType = options.clientType ?? DEFAULT_CLIENT_TYPE;
|
|
58
|
+
/** Sends a request with the bearer token; one refresh and one retry on 401. */
|
|
59
|
+
async function request(path, init) {
|
|
60
|
+
const send = async (forceRefresh) => {
|
|
61
|
+
const token = await options.getToken({ forceRefresh });
|
|
62
|
+
return fetchImpl(`${baseUrl}${path}`, {
|
|
63
|
+
method: init.method,
|
|
64
|
+
headers: {
|
|
65
|
+
authorization: `Bearer ${token}`,
|
|
66
|
+
'x-client-type': clientType,
|
|
67
|
+
...(init.body === undefined ? {} : { 'content-type': 'application/json' }),
|
|
68
|
+
},
|
|
69
|
+
...(init.body === undefined ? {} : { body: init.body }),
|
|
70
|
+
...(init.signal === undefined ? {} : { signal: init.signal }),
|
|
71
|
+
});
|
|
72
|
+
};
|
|
73
|
+
let response = await send(false);
|
|
74
|
+
if (response.status === 401) {
|
|
75
|
+
// Let the connection go before retrying; the body is not needed.
|
|
76
|
+
await response.body?.cancel().catch(() => undefined);
|
|
77
|
+
response = await send(true);
|
|
78
|
+
}
|
|
79
|
+
if (!response.ok)
|
|
80
|
+
throw await errorFromResponse(response);
|
|
81
|
+
return response;
|
|
82
|
+
}
|
|
83
|
+
function attach(sessionId) {
|
|
84
|
+
const chatPath = `/api/v1/chat/${encodeURIComponent(sessionId)}`;
|
|
85
|
+
const readState = async (signal) => {
|
|
86
|
+
const response = await request(`${chatPath}/state`, { method: 'GET', signal });
|
|
87
|
+
return (await response.json());
|
|
88
|
+
};
|
|
89
|
+
const getState = () => readState();
|
|
90
|
+
const waitForTurn = async (wait = {}) => {
|
|
91
|
+
const pollMs = wait.pollMs ?? DEFAULT_POLL_MS;
|
|
92
|
+
const timeoutMs = wait.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
|
|
93
|
+
let waited = 0;
|
|
94
|
+
for (;;) {
|
|
95
|
+
const state = await getState();
|
|
96
|
+
if (state.phase !== 'running')
|
|
97
|
+
return state;
|
|
98
|
+
if (waited >= timeoutMs)
|
|
99
|
+
throw new TurnTimeoutError(sessionId, timeoutMs);
|
|
100
|
+
await sleep(pollMs);
|
|
101
|
+
waited += pollMs;
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
/**
|
|
105
|
+
* The state after a turn whose stream has ended. The turn RAN, so a failure
|
|
106
|
+
* to read the state must not look like a failed turn: a caller that sent
|
|
107
|
+
* the turn again would run the model twice. The failure is returned.
|
|
108
|
+
*/
|
|
109
|
+
const stateAfterTurn = async (settleMs) => {
|
|
110
|
+
try {
|
|
111
|
+
if (settleMs !== undefined)
|
|
112
|
+
return await settledStateWithin(settleMs);
|
|
113
|
+
return {
|
|
114
|
+
state: await waitForTurn({
|
|
115
|
+
pollMs: TURN_SETTLE_POLL_MS,
|
|
116
|
+
timeoutMs: TURN_SETTLE_TIMEOUT_MS,
|
|
117
|
+
}),
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
return { state: null, stateError: error };
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
/**
|
|
125
|
+
* The settled state, read within `settleMs` in total. The bound covers
|
|
126
|
+
* every read (a read that does not answer is given up and aborted) and
|
|
127
|
+
* every wait between two reads. Out of time, the answer is no state and a
|
|
128
|
+
* `TurnSettleTimeoutError`.
|
|
129
|
+
*/
|
|
130
|
+
const settledStateWithin = async (settleMs) => {
|
|
131
|
+
const startedAt = Date.now();
|
|
132
|
+
// Counted as well as the clock, so a `sleep` that returns at once (a
|
|
133
|
+
// test's) still uses the time up.
|
|
134
|
+
let slept = 0;
|
|
135
|
+
const left = () => settleMs - Math.max(Date.now() - startedAt, slept);
|
|
136
|
+
const outOfTime = () => ({
|
|
137
|
+
state: null,
|
|
138
|
+
stateError: new TurnSettleTimeoutError(sessionId, settleMs),
|
|
139
|
+
});
|
|
140
|
+
for (;;) {
|
|
141
|
+
if (left() <= 0)
|
|
142
|
+
return outOfTime();
|
|
143
|
+
const abort = new AbortController();
|
|
144
|
+
const read = readState(abort.signal);
|
|
145
|
+
const state = await withinBudget(read, left());
|
|
146
|
+
if (state === undefined) {
|
|
147
|
+
// Nobody waits for this read any more: let the request go.
|
|
148
|
+
read.catch(() => undefined);
|
|
149
|
+
abort.abort();
|
|
150
|
+
return outOfTime();
|
|
151
|
+
}
|
|
152
|
+
if (state.phase !== 'running')
|
|
153
|
+
return { state };
|
|
154
|
+
const pause = Math.min(TURN_SETTLE_POLL_MS, left());
|
|
155
|
+
if (pause <= 0)
|
|
156
|
+
return outOfTime();
|
|
157
|
+
await sleep(pause);
|
|
158
|
+
slept += pause;
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
const sendTurn = async (parts, pendingActionId, turn = {}) => {
|
|
162
|
+
// The request and the read of its stream, as one promise: the wait
|
|
163
|
+
// budget covers both, since the server sends headers only after it has
|
|
164
|
+
// loaded the session.
|
|
165
|
+
let stream;
|
|
166
|
+
const ended = (async () => {
|
|
167
|
+
const response = await request(chatPath, {
|
|
168
|
+
method: 'POST',
|
|
169
|
+
body: JSON.stringify({
|
|
170
|
+
parts,
|
|
171
|
+
version: 1,
|
|
172
|
+
...(pendingActionId === undefined ? {} : { pendingActionId }),
|
|
173
|
+
...(options.actorKind === undefined ? {} : { actorKind: options.actorKind }),
|
|
174
|
+
...(turn.modelId === undefined ? {} : { modelId: turn.modelId }),
|
|
175
|
+
...(turn.specDepth === undefined ? {} : { specDepth: turn.specDepth }),
|
|
176
|
+
...(turn.language === undefined ? {} : { language: turn.language }),
|
|
177
|
+
}),
|
|
178
|
+
});
|
|
179
|
+
stream = readTurnStream(response.body);
|
|
180
|
+
await stream.drained;
|
|
181
|
+
return true;
|
|
182
|
+
})();
|
|
183
|
+
const finished = turn.waitMs === undefined ? await ended : await withinBudget(ended, turn.waitMs);
|
|
184
|
+
const { assistantText, error } = stream?.snapshot() ?? { assistantText: '', error: null };
|
|
185
|
+
if (finished === undefined) {
|
|
186
|
+
// Left to finish in the background. The stream is never dropped (that
|
|
187
|
+
// would end the turn early on the server), and a refusal that arrives
|
|
188
|
+
// after the budget has no caller left to tell: the next state read
|
|
189
|
+
// shows what the session did.
|
|
190
|
+
ended.catch(() => undefined);
|
|
191
|
+
return { assistantText, error, turnStillRunning: true, state: null };
|
|
192
|
+
}
|
|
193
|
+
return {
|
|
194
|
+
assistantText,
|
|
195
|
+
error,
|
|
196
|
+
turnStillRunning: false,
|
|
197
|
+
...(await stateAfterTurn(turn.settleMs)),
|
|
198
|
+
};
|
|
199
|
+
};
|
|
200
|
+
return {
|
|
201
|
+
sessionId,
|
|
202
|
+
getState,
|
|
203
|
+
waitForTurn,
|
|
204
|
+
respond(pending, decision, turn) {
|
|
205
|
+
validateDecision(pending, decision);
|
|
206
|
+
const part = { type: DECISION_PART_TYPE[decision.kind], data: decision.data };
|
|
207
|
+
return sendTurn([part], pending.id, turn);
|
|
208
|
+
},
|
|
209
|
+
send(text, turn) {
|
|
210
|
+
if (turn?.expectNoPending === true && turn.pending !== undefined) {
|
|
211
|
+
throw new InvalidDecisionError('send: `pending` and `expectNoPending` cannot be combined');
|
|
212
|
+
}
|
|
213
|
+
const pendingActionId = turn?.expectNoPending === true ? NO_PENDING_ACTION_ID : turn?.pending?.id;
|
|
214
|
+
return sendTurn([{ type: 'text', text }], pendingActionId, turn);
|
|
215
|
+
},
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
return { attach };
|
|
219
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Decision builders and validation.
|
|
3
|
+
*
|
|
4
|
+
* A builder takes the pending action it answers, so the identity fields a
|
|
5
|
+
* decision must echo (an MCQ's stage and round, an edit review's turn id, a
|
|
6
|
+
* revision's number) are copied from the card and cannot be mistyped.
|
|
7
|
+
* {@link validateDecision} runs before every send: a decision the server would
|
|
8
|
+
* misread is refused here, with no request made.
|
|
9
|
+
*/
|
|
10
|
+
import type { Decision, PendingAction, PendingActionKind, ReviewFeedbackItem } from './types.js';
|
|
11
|
+
/** Prefix of a free-text "Other" answer inside an MCQ answer value. */
|
|
12
|
+
export declare const MCQ_OTHER_PREFIX = "other:";
|
|
13
|
+
/** The pending action narrowed to one kind. */
|
|
14
|
+
export type PendingOf<K extends PendingActionKind> = Extract<PendingAction, {
|
|
15
|
+
kind: K;
|
|
16
|
+
}>;
|
|
17
|
+
type DecisionOf<K extends PendingActionKind> = Extract<Decision, {
|
|
18
|
+
kind: K;
|
|
19
|
+
}>;
|
|
20
|
+
/** Builders for each pending action kind. */
|
|
21
|
+
export declare const decide: {
|
|
22
|
+
/** Answers an MCQ form. `answers` maps question id to option id(s) or `other:<text>`. */
|
|
23
|
+
mcq(pending: PendingOf<"mcq">, answers: Record<string, string | string[]>): DecisionOf<"mcq">;
|
|
24
|
+
approveSpec(): DecisionOf<"spec-decision">;
|
|
25
|
+
/** Rejects the spec file and asks for `editPrompt` to be applied. */
|
|
26
|
+
rejectSpec(editPrompt: string): DecisionOf<"spec-decision">;
|
|
27
|
+
/**
|
|
28
|
+
* Answers a review board. `ignore` moves on without changes. `accept` folds
|
|
29
|
+
* review items into the file, and `update` does so together with
|
|
30
|
+
* `editPrompt`. Both carry the items to fold in: every item of the board
|
|
31
|
+
* unless `selectedFeedback` narrows them, as ticking boxes does in the webapp.
|
|
32
|
+
*/
|
|
33
|
+
review(pending: PendingOf<"review-decision">, action: "accept" | "ignore" | "update", options?: {
|
|
34
|
+
editPrompt?: string;
|
|
35
|
+
selectedFeedback?: ReviewFeedbackItem[];
|
|
36
|
+
}): DecisionOf<"review-decision">;
|
|
37
|
+
/** Picks a recommended skill, or `null` to skip. */
|
|
38
|
+
selectSkill(skillId: string | null): DecisionOf<"skill-selection">;
|
|
39
|
+
choose(choiceId: string): DecisionOf<"user-choice">;
|
|
40
|
+
/** Accepts or discards each edited file; `'accept-all'` accepts every file. */
|
|
41
|
+
editReview(pending: PendingOf<"edit-decision">, decisions: Record<string, "accept" | "discard"> | "accept-all"): DecisionOf<"edit-decision">;
|
|
42
|
+
sitePlan(pending: PendingOf<"site-plan">, decision: "approve" | "request-changes", feedback?: string): DecisionOf<"site-plan">;
|
|
43
|
+
artifactRevision(pending: PendingOf<"artifact-revision">, decision: "approve" | "request-changes" | "keep" | "discard", feedback?: string): DecisionOf<"artifact-revision">;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Throws {@link InvalidDecisionError} when `decision` cannot answer `pending`.
|
|
47
|
+
* Checks the kind always, and the content against the card when the card is
|
|
48
|
+
* available.
|
|
49
|
+
*/
|
|
50
|
+
export declare function validateDecision(pending: PendingAction, decision: Decision): void;
|
|
51
|
+
export {};
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Decision builders and validation.
|
|
3
|
+
*
|
|
4
|
+
* A builder takes the pending action it answers, so the identity fields a
|
|
5
|
+
* decision must echo (an MCQ's stage and round, an edit review's turn id, a
|
|
6
|
+
* revision's number) are copied from the card and cannot be mistyped.
|
|
7
|
+
* {@link validateDecision} runs before every send: a decision the server would
|
|
8
|
+
* misread is refused here, with no request made.
|
|
9
|
+
*/
|
|
10
|
+
import { InvalidDecisionError } from "./errors.js";
|
|
11
|
+
/** Prefix of a free-text "Other" answer inside an MCQ answer value. */
|
|
12
|
+
export const MCQ_OTHER_PREFIX = 'other:';
|
|
13
|
+
function requireCard(pending) {
|
|
14
|
+
if (pending.card === null) {
|
|
15
|
+
throw new InvalidDecisionError(`The ${pending.kind} card is not available, so it cannot be answered from its content.`);
|
|
16
|
+
}
|
|
17
|
+
return pending.card;
|
|
18
|
+
}
|
|
19
|
+
/** Builders for each pending action kind. */
|
|
20
|
+
export const decide = {
|
|
21
|
+
/** Answers an MCQ form. `answers` maps question id to option id(s) or `other:<text>`. */
|
|
22
|
+
mcq(pending, answers) {
|
|
23
|
+
const card = requireCard(pending);
|
|
24
|
+
return { kind: 'mcq', data: { stage: card.stage, round: card.round, answers } };
|
|
25
|
+
},
|
|
26
|
+
approveSpec() {
|
|
27
|
+
return { kind: 'spec-decision', data: { action: 'approve' } };
|
|
28
|
+
},
|
|
29
|
+
/** Rejects the spec file and asks for `editPrompt` to be applied. */
|
|
30
|
+
rejectSpec(editPrompt) {
|
|
31
|
+
return { kind: 'spec-decision', data: { action: 'reject', editPrompt } };
|
|
32
|
+
},
|
|
33
|
+
/**
|
|
34
|
+
* Answers a review board. `ignore` moves on without changes. `accept` folds
|
|
35
|
+
* review items into the file, and `update` does so together with
|
|
36
|
+
* `editPrompt`. Both carry the items to fold in: every item of the board
|
|
37
|
+
* unless `selectedFeedback` narrows them, as ticking boxes does in the webapp.
|
|
38
|
+
*/
|
|
39
|
+
review(pending, action, options = {}) {
|
|
40
|
+
const feedback = pending.card?.feedback;
|
|
41
|
+
const selectedFeedback = action === 'ignore'
|
|
42
|
+
? undefined
|
|
43
|
+
: (options.selectedFeedback ??
|
|
44
|
+
(feedback === undefined
|
|
45
|
+
? undefined
|
|
46
|
+
: [...feedback.mustfix, ...feedback.recommendations]));
|
|
47
|
+
return {
|
|
48
|
+
kind: 'review-decision',
|
|
49
|
+
data: {
|
|
50
|
+
action,
|
|
51
|
+
...(options.editPrompt === undefined ? {} : { editPrompt: options.editPrompt }),
|
|
52
|
+
...(selectedFeedback === undefined ? {} : { selectedFeedback }),
|
|
53
|
+
},
|
|
54
|
+
};
|
|
55
|
+
},
|
|
56
|
+
/** Picks a recommended skill, or `null` to skip. */
|
|
57
|
+
selectSkill(skillId) {
|
|
58
|
+
return { kind: 'skill-selection', data: { skillId } };
|
|
59
|
+
},
|
|
60
|
+
choose(choiceId) {
|
|
61
|
+
return { kind: 'user-choice', data: { choiceId } };
|
|
62
|
+
},
|
|
63
|
+
/** Accepts or discards each edited file; `'accept-all'` accepts every file. */
|
|
64
|
+
editReview(pending, decisions) {
|
|
65
|
+
const card = requireCard(pending);
|
|
66
|
+
const perFile = decisions === 'accept-all'
|
|
67
|
+
? Object.fromEntries(card.files.map((f) => [f.specFileId, 'accept']))
|
|
68
|
+
: decisions;
|
|
69
|
+
return { kind: 'edit-decision', data: { turnId: card.turnId, decisions: perFile } };
|
|
70
|
+
},
|
|
71
|
+
sitePlan(pending, decision, feedback) {
|
|
72
|
+
const planId = pending.card?.planId;
|
|
73
|
+
return {
|
|
74
|
+
kind: 'site-plan',
|
|
75
|
+
data: {
|
|
76
|
+
decision,
|
|
77
|
+
...(feedback === undefined ? {} : { feedback }),
|
|
78
|
+
...(planId === undefined ? {} : { planId }),
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
},
|
|
82
|
+
artifactRevision(pending, decision, feedback) {
|
|
83
|
+
const card = requireCard(pending);
|
|
84
|
+
return {
|
|
85
|
+
kind: 'artifact-revision',
|
|
86
|
+
data: {
|
|
87
|
+
artifactId: card.artifactId,
|
|
88
|
+
revisionNumber: card.revisionNumber,
|
|
89
|
+
decision,
|
|
90
|
+
...(feedback === undefined ? {} : { feedback }),
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
function fail(message) {
|
|
96
|
+
throw new InvalidDecisionError(message);
|
|
97
|
+
}
|
|
98
|
+
function isBlank(text) {
|
|
99
|
+
return text === undefined || text.trim() === '';
|
|
100
|
+
}
|
|
101
|
+
function validateMcqAnswer(question, value) {
|
|
102
|
+
const values = value === undefined ? [] : Array.isArray(value) ? value : [value];
|
|
103
|
+
if (values.length === 0) {
|
|
104
|
+
if (question.required)
|
|
105
|
+
fail(`Question "${question.id}" is required and has no answer.`);
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
if (question.type === 'single' && values.length > 1) {
|
|
109
|
+
fail(`Question "${question.id}" takes one option; ${String(values.length)} were given.`);
|
|
110
|
+
}
|
|
111
|
+
const optionIds = new Set(question.options.map((o) => o.id));
|
|
112
|
+
for (const optionId of values) {
|
|
113
|
+
if (optionId.startsWith(MCQ_OTHER_PREFIX)) {
|
|
114
|
+
if (question.allowOther !== true) {
|
|
115
|
+
fail(`Question "${question.id}" does not accept a free-text answer.`);
|
|
116
|
+
}
|
|
117
|
+
if (isBlank(optionId.slice(MCQ_OTHER_PREFIX.length))) {
|
|
118
|
+
fail(`Question "${question.id}" has an empty free-text answer.`);
|
|
119
|
+
}
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
if (!optionIds.has(optionId)) {
|
|
123
|
+
fail(`Question "${question.id}" has no option "${optionId}".`);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
function validateMcq(pending, data) {
|
|
128
|
+
const card = pending.card;
|
|
129
|
+
if (card === null)
|
|
130
|
+
return;
|
|
131
|
+
if (data.stage !== card.stage || data.round !== card.round) {
|
|
132
|
+
fail(`The answers are for ${data.stage} round ${String(data.round)}, ` +
|
|
133
|
+
`but the form is ${card.stage} round ${String(card.round)}.`);
|
|
134
|
+
}
|
|
135
|
+
const questionIds = new Set(card.questions.map((q) => q.id));
|
|
136
|
+
for (const answered of Object.keys(data.answers)) {
|
|
137
|
+
if (!questionIds.has(answered))
|
|
138
|
+
fail(`The form has no question "${answered}".`);
|
|
139
|
+
}
|
|
140
|
+
for (const question of card.questions) {
|
|
141
|
+
validateMcqAnswer(question, data.answers[question.id]);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
function validateEditReview(pending, data) {
|
|
145
|
+
const card = pending.card;
|
|
146
|
+
if (card === null)
|
|
147
|
+
return;
|
|
148
|
+
if (data.turnId !== card.turnId) {
|
|
149
|
+
fail(`The decision is for edit turn "${data.turnId}", but the card is "${card.turnId}".`);
|
|
150
|
+
}
|
|
151
|
+
for (const file of card.files) {
|
|
152
|
+
if (data.decisions[file.specFileId] === undefined) {
|
|
153
|
+
fail(`The edited file "${file.filePath}" has no accept or discard choice.`);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
/**
|
|
158
|
+
* Throws {@link InvalidDecisionError} when `decision` cannot answer `pending`.
|
|
159
|
+
* Checks the kind always, and the content against the card when the card is
|
|
160
|
+
* available.
|
|
161
|
+
*/
|
|
162
|
+
export function validateDecision(pending, decision) {
|
|
163
|
+
if (decision.kind !== pending.kind) {
|
|
164
|
+
fail(`The session waits on "${pending.kind}", but the decision is "${decision.kind}".`);
|
|
165
|
+
}
|
|
166
|
+
switch (decision.kind) {
|
|
167
|
+
case 'mcq':
|
|
168
|
+
validateMcq(pending, decision.data);
|
|
169
|
+
return;
|
|
170
|
+
case 'spec-decision':
|
|
171
|
+
if (decision.data.action === 'reject' && isBlank(decision.data.editPrompt)) {
|
|
172
|
+
fail('A "reject" decision needs an editPrompt that says what to change.');
|
|
173
|
+
}
|
|
174
|
+
return;
|
|
175
|
+
case 'review-decision':
|
|
176
|
+
if (decision.data.action === 'update' && isBlank(decision.data.editPrompt)) {
|
|
177
|
+
fail('An "update" decision needs an editPrompt that says what to change.');
|
|
178
|
+
}
|
|
179
|
+
return;
|
|
180
|
+
case 'skill-selection': {
|
|
181
|
+
const card = pending.card;
|
|
182
|
+
const { skillId } = decision.data;
|
|
183
|
+
if (card !== null && skillId !== null && !card.skills.some((s) => s.id === skillId)) {
|
|
184
|
+
fail(`The card does not recommend a skill "${skillId}".`);
|
|
185
|
+
}
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
case 'user-choice': {
|
|
189
|
+
const card = pending.card;
|
|
190
|
+
const { choiceId } = decision.data;
|
|
191
|
+
if (card !== null && !card.choices.some((c) => c.id === choiceId)) {
|
|
192
|
+
fail(`The card has no choice "${choiceId}".`);
|
|
193
|
+
}
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
case 'edit-decision':
|
|
197
|
+
validateEditReview(pending, decision.data);
|
|
198
|
+
return;
|
|
199
|
+
case 'site-plan':
|
|
200
|
+
return;
|
|
201
|
+
case 'artifact-revision': {
|
|
202
|
+
const card = pending.card;
|
|
203
|
+
if (card === null)
|
|
204
|
+
return;
|
|
205
|
+
const { artifactId, revisionNumber, decision: choice } = decision.data;
|
|
206
|
+
if (card.artifactId !== artifactId || card.revisionNumber !== revisionNumber) {
|
|
207
|
+
fail('The decision names a different artifact revision than the card.');
|
|
208
|
+
}
|
|
209
|
+
// A Generate card is approved; an Edit card's change is kept or discarded.
|
|
210
|
+
if (card.mode === 'generate' && (choice === 'keep' || choice === 'discard')) {
|
|
211
|
+
fail(`A generated revision is approved, not "${choice}".`);
|
|
212
|
+
}
|
|
213
|
+
if (card.mode === 'edit' && choice === 'approve') {
|
|
214
|
+
fail('An edited revision is kept or discarded, not "approve".');
|
|
215
|
+
}
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Typed errors of the session driver.
|
|
3
|
+
*
|
|
4
|
+
* {@link SessionRequestError} is any refused HTTP request. The five subclasses
|
|
5
|
+
* are the refusals a driver is expected to handle in code; everything else is
|
|
6
|
+
* reported with its status and body and left to the caller.
|
|
7
|
+
*
|
|
8
|
+
* The server refuses a turn from a read-only token first (403), whoever
|
|
9
|
+
* drives. It then checks an agent-driven turn in a fixed order: agent driving
|
|
10
|
+
* turned off (403), then the turn cap (429), then a stale pending action
|
|
11
|
+
* (409). A person's turn is only checked for the last one.
|
|
12
|
+
*/
|
|
13
|
+
/** A request the server answered with a non-2xx status. */
|
|
14
|
+
export declare class SessionRequestError extends Error {
|
|
15
|
+
/** HTTP status of the answer. */
|
|
16
|
+
readonly status: number;
|
|
17
|
+
/** The server's error code (`error` in the body), or `HTTP_<status>`. */
|
|
18
|
+
readonly code: string;
|
|
19
|
+
/** The parsed JSON body, or the raw text when it was not JSON. */
|
|
20
|
+
readonly body: unknown;
|
|
21
|
+
constructor(status: number, code: string, message: string, body: unknown);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The decision named a pending action the session no longer waits on: another
|
|
25
|
+
* participant answered it, or the transcript moved on. Nothing was run. Read
|
|
26
|
+
* the state again and decide again.
|
|
27
|
+
*/
|
|
28
|
+
export declare class PendingActionMismatchError extends SessionRequestError {
|
|
29
|
+
/** What the session waits on now, or `null` for nothing. */
|
|
30
|
+
readonly current: {
|
|
31
|
+
id: string;
|
|
32
|
+
kind: string;
|
|
33
|
+
} | null;
|
|
34
|
+
constructor(status: number, message: string, body: unknown);
|
|
35
|
+
}
|
|
36
|
+
/** Another turn is running on the session. Wait for it, then read the state. */
|
|
37
|
+
export declare class SessionBusyError extends SessionRequestError {
|
|
38
|
+
/** User id of whoever runs the turn, when the server may say. */
|
|
39
|
+
readonly heldBy: string | undefined;
|
|
40
|
+
constructor(status: number, message: string, body: unknown);
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The session has run as many agent-driven turns as it allows (HTTP 429).
|
|
44
|
+
* Nothing was run. A person must continue: a person's turn is never refused
|
|
45
|
+
* by the cap. Trying again as an agent gets the same answer.
|
|
46
|
+
*/
|
|
47
|
+
export declare class AgentTurnCapReachedError extends SessionRequestError {
|
|
48
|
+
/** Agent-driven turns the session has run, when the server says. */
|
|
49
|
+
readonly used: number | undefined;
|
|
50
|
+
/** Most agent-driven turns the session accepts, when the server says. */
|
|
51
|
+
readonly cap: number | undefined;
|
|
52
|
+
constructor(status: number, message: string, body: unknown);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Agent driving is turned off for this environment, and this turn would
|
|
56
|
+
* continue a session (HTTP 403). The opening turn of a session is not refused
|
|
57
|
+
* this way. Nothing was run. A person can still continue the session, and the
|
|
58
|
+
* state can still be read.
|
|
59
|
+
*/
|
|
60
|
+
export declare class AgentDrivingDisabledError extends SessionRequestError {
|
|
61
|
+
constructor(status: number, message: string, body: unknown);
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* The token is read-only (its `access` claim is `read`), and a turn was sent
|
|
65
|
+
* with it (HTTP 403). Nothing was run. Trying again with the same token gets
|
|
66
|
+
* the same answer: send turns with a read-write token. The state can still be
|
|
67
|
+
* read with this one.
|
|
68
|
+
*/
|
|
69
|
+
export declare class ReadOnlyTokenError extends SessionRequestError {
|
|
70
|
+
constructor(status: number, message: string, body: unknown);
|
|
71
|
+
}
|
|
72
|
+
/** A turn was still running when `waitForTurn` gave up waiting for it. */
|
|
73
|
+
export declare class TurnTimeoutError extends Error {
|
|
74
|
+
readonly sessionId: string;
|
|
75
|
+
readonly timeoutMs: number;
|
|
76
|
+
constructor(sessionId: string, timeoutMs: number);
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* The state could not be read within `settleMs` after a turn's stream ended:
|
|
80
|
+
* the server still reported the turn as running, or a read did not answer. The
|
|
81
|
+
* turn itself RAN. Do not send it again; read the state later.
|
|
82
|
+
*/
|
|
83
|
+
export declare class TurnSettleTimeoutError extends Error {
|
|
84
|
+
readonly sessionId: string;
|
|
85
|
+
readonly settleMs: number;
|
|
86
|
+
constructor(sessionId: string, settleMs: number);
|
|
87
|
+
}
|
|
88
|
+
/** A decision that cannot be sent as given. Thrown before any request. */
|
|
89
|
+
export declare class InvalidDecisionError extends Error {
|
|
90
|
+
constructor(message: string);
|
|
91
|
+
}
|
|
92
|
+
/** Builds the typed error for a refused response. Reads the body once. */
|
|
93
|
+
export declare function errorFromResponse(response: Response): Promise<SessionRequestError>;
|