@myspec/sdk 0.0.0-stage → 0.1.1
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 +133 -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 +160 -0
- package/dist/src/client.js +253 -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 +408 -0
- package/dist/src/types.js +37 -0
- package/package.json +32 -4
|
@@ -0,0 +1,170 @@
|
|
|
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 class SessionRequestError extends Error {
|
|
15
|
+
/** HTTP status of the answer. */
|
|
16
|
+
status;
|
|
17
|
+
/** The server's error code (`error` in the body), or `HTTP_<status>`. */
|
|
18
|
+
code;
|
|
19
|
+
/** The parsed JSON body, or the raw text when it was not JSON. */
|
|
20
|
+
body;
|
|
21
|
+
constructor(status, code, message, body) {
|
|
22
|
+
super(message);
|
|
23
|
+
this.name = 'SessionRequestError';
|
|
24
|
+
this.status = status;
|
|
25
|
+
this.code = code;
|
|
26
|
+
this.body = body;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* The decision named a pending action the session no longer waits on: another
|
|
31
|
+
* participant answered it, or the transcript moved on. Nothing was run. Read
|
|
32
|
+
* the state again and decide again.
|
|
33
|
+
*/
|
|
34
|
+
export class PendingActionMismatchError extends SessionRequestError {
|
|
35
|
+
/** What the session waits on now, or `null` for nothing. */
|
|
36
|
+
current;
|
|
37
|
+
constructor(status, message, body) {
|
|
38
|
+
super(status, 'PENDING_ACTION_MISMATCH', message, body);
|
|
39
|
+
this.name = 'PendingActionMismatchError';
|
|
40
|
+
this.current = readCurrent(body);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** Another turn is running on the session. Wait for it, then read the state. */
|
|
44
|
+
export class SessionBusyError extends SessionRequestError {
|
|
45
|
+
/** User id of whoever runs the turn, when the server may say. */
|
|
46
|
+
heldBy;
|
|
47
|
+
constructor(status, message, body) {
|
|
48
|
+
super(status, 'SESSION_BUSY', message, body);
|
|
49
|
+
this.name = 'SessionBusyError';
|
|
50
|
+
const details = isRecord(body) && isRecord(body.details) ? body.details : undefined;
|
|
51
|
+
this.heldBy = typeof details?.heldBy === 'string' ? details.heldBy : undefined;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* The session has run as many agent-driven turns as it allows (HTTP 429).
|
|
56
|
+
* Nothing was run. A person must continue: a person's turn is never refused
|
|
57
|
+
* by the cap. Trying again as an agent gets the same answer.
|
|
58
|
+
*/
|
|
59
|
+
export class AgentTurnCapReachedError extends SessionRequestError {
|
|
60
|
+
/** Agent-driven turns the session has run, when the server says. */
|
|
61
|
+
used;
|
|
62
|
+
/** Most agent-driven turns the session accepts, when the server says. */
|
|
63
|
+
cap;
|
|
64
|
+
constructor(status, message, body) {
|
|
65
|
+
super(status, 'AGENT_TURN_CAP_REACHED', message, body);
|
|
66
|
+
this.name = 'AgentTurnCapReachedError';
|
|
67
|
+
const details = isRecord(body) && isRecord(body.details) ? body.details : undefined;
|
|
68
|
+
this.used = typeof details?.used === 'number' ? details.used : undefined;
|
|
69
|
+
this.cap = typeof details?.cap === 'number' ? details.cap : undefined;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Agent driving is turned off for this environment, and this turn would
|
|
74
|
+
* continue a session (HTTP 403). The opening turn of a session is not refused
|
|
75
|
+
* this way. Nothing was run. A person can still continue the session, and the
|
|
76
|
+
* state can still be read.
|
|
77
|
+
*/
|
|
78
|
+
export class AgentDrivingDisabledError extends SessionRequestError {
|
|
79
|
+
constructor(status, message, body) {
|
|
80
|
+
super(status, 'AGENT_DRIVING_DISABLED', message, body);
|
|
81
|
+
this.name = 'AgentDrivingDisabledError';
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* The token is read-only (its `access` claim is `read`), and a turn was sent
|
|
86
|
+
* with it (HTTP 403). Nothing was run. Trying again with the same token gets
|
|
87
|
+
* the same answer: send turns with a read-write token. The state can still be
|
|
88
|
+
* read with this one.
|
|
89
|
+
*/
|
|
90
|
+
export class ReadOnlyTokenError extends SessionRequestError {
|
|
91
|
+
constructor(status, message, body) {
|
|
92
|
+
super(status, 'READ_ONLY_TOKEN', message, body);
|
|
93
|
+
this.name = 'ReadOnlyTokenError';
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
/** A turn was still running when `waitForTurn` gave up waiting for it. */
|
|
97
|
+
export class TurnTimeoutError extends Error {
|
|
98
|
+
sessionId;
|
|
99
|
+
timeoutMs;
|
|
100
|
+
constructor(sessionId, timeoutMs) {
|
|
101
|
+
super(`Session ${sessionId} still has a turn running after ${String(timeoutMs)} ms`);
|
|
102
|
+
this.name = 'TurnTimeoutError';
|
|
103
|
+
this.sessionId = sessionId;
|
|
104
|
+
this.timeoutMs = timeoutMs;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* The state could not be read within `settleMs` after a turn's stream ended:
|
|
109
|
+
* the server still reported the turn as running, or a read did not answer. The
|
|
110
|
+
* turn itself RAN. Do not send it again; read the state later.
|
|
111
|
+
*/
|
|
112
|
+
export class TurnSettleTimeoutError extends Error {
|
|
113
|
+
sessionId;
|
|
114
|
+
settleMs;
|
|
115
|
+
constructor(sessionId, settleMs) {
|
|
116
|
+
super(`The state of session ${sessionId} could not be read within ${String(settleMs)} ms after the turn`);
|
|
117
|
+
this.name = 'TurnSettleTimeoutError';
|
|
118
|
+
this.sessionId = sessionId;
|
|
119
|
+
this.settleMs = settleMs;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/** A decision that cannot be sent as given. Thrown before any request. */
|
|
123
|
+
export class InvalidDecisionError extends Error {
|
|
124
|
+
constructor(message) {
|
|
125
|
+
super(message);
|
|
126
|
+
this.name = 'InvalidDecisionError';
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
function isRecord(value) {
|
|
130
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
131
|
+
}
|
|
132
|
+
function readCurrent(body) {
|
|
133
|
+
const details = isRecord(body) && isRecord(body.details) ? body.details : undefined;
|
|
134
|
+
const current = details?.current;
|
|
135
|
+
if (!isRecord(current))
|
|
136
|
+
return null;
|
|
137
|
+
return typeof current.id === 'string' && typeof current.kind === 'string'
|
|
138
|
+
? { id: current.id, kind: current.kind }
|
|
139
|
+
: null;
|
|
140
|
+
}
|
|
141
|
+
/** Builds the typed error for a refused response. Reads the body once. */
|
|
142
|
+
export async function errorFromResponse(response) {
|
|
143
|
+
const text = await response.text().catch(() => '');
|
|
144
|
+
let body = text;
|
|
145
|
+
try {
|
|
146
|
+
body = text === '' ? null : JSON.parse(text);
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
// Not JSON (a proxy's HTML error page, say): keep the raw text.
|
|
150
|
+
}
|
|
151
|
+
const status = response.status;
|
|
152
|
+
const code = isRecord(body) && typeof body.error === 'string' ? body.error : `HTTP_${String(status)}`;
|
|
153
|
+
const message = isRecord(body) && typeof body.message === 'string'
|
|
154
|
+
? body.message
|
|
155
|
+
: `Request failed with HTTP ${String(status)}`;
|
|
156
|
+
switch (code) {
|
|
157
|
+
case 'PENDING_ACTION_MISMATCH':
|
|
158
|
+
return new PendingActionMismatchError(status, message, body);
|
|
159
|
+
case 'SESSION_BUSY':
|
|
160
|
+
return new SessionBusyError(status, message, body);
|
|
161
|
+
case 'AGENT_TURN_CAP_REACHED':
|
|
162
|
+
return new AgentTurnCapReachedError(status, message, body);
|
|
163
|
+
case 'AGENT_DRIVING_DISABLED':
|
|
164
|
+
return new AgentDrivingDisabledError(status, message, body);
|
|
165
|
+
case 'READ_ONLY_TOKEN':
|
|
166
|
+
return new ReadOnlyTokenError(status, message, body);
|
|
167
|
+
default:
|
|
168
|
+
return new SessionRequestError(status, code, message, body);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Policies: the part of a driver that decides.
|
|
3
|
+
*
|
|
4
|
+
* A policy sees the session state and returns what to do next. It does not
|
|
5
|
+
* send anything; `runToCompletion` (or the caller's own loop) does.
|
|
6
|
+
*/
|
|
7
|
+
import type { Decision, SessionState, TurnStreamError } from './types.js';
|
|
8
|
+
/** Free text to send as a chat message. */
|
|
9
|
+
export interface Say {
|
|
10
|
+
say: string;
|
|
11
|
+
}
|
|
12
|
+
/** What a policy wants done: a decision, a chat message, or stop here. */
|
|
13
|
+
export type PolicyResult = Decision | Say | 'stop';
|
|
14
|
+
/** What the driver loop tells a policy about the turn before this call. */
|
|
15
|
+
export interface PolicyInfo {
|
|
16
|
+
/**
|
|
17
|
+
* Set when the previous answer of this policy was refused and did NOT run:
|
|
18
|
+
* the session had moved on (`mismatch`) or another turn was running
|
|
19
|
+
* (`busy`). `null` on the first call and after a turn that ran.
|
|
20
|
+
*/
|
|
21
|
+
lastTurnRefused: 'mismatch' | 'busy' | null;
|
|
22
|
+
/**
|
|
23
|
+
* The stream error of the previous turn, when it ended with one and the run
|
|
24
|
+
* went on (`turnErrorRetries`). `null` otherwise. The ai-agent usually saves
|
|
25
|
+
* a turn before it reports its error, so the session may have moved on:
|
|
26
|
+
* read the state, do not assume the last answer was lost.
|
|
27
|
+
*/
|
|
28
|
+
lastTurnError?: TurnStreamError | null;
|
|
29
|
+
}
|
|
30
|
+
export type Policy = (state: SessionState, info?: PolicyInfo) => PolicyResult | Promise<PolicyResult>;
|
|
31
|
+
export declare function isSay(result: PolicyResult): result is Say;
|
|
32
|
+
/**
|
|
33
|
+
* Takes the path the workflow itself recommends, with no judgement: the
|
|
34
|
+
* recommended option of every question, approve every spec file, plan and
|
|
35
|
+
* revision, ignore every review board (also one that asks for a revision),
|
|
36
|
+
* skip optional skills.
|
|
37
|
+
*
|
|
38
|
+
* It answers cards only. When the session waits on nothing (`idle`), or shows
|
|
39
|
+
* a card it cannot answer from its content, it stops: there is nothing it can
|
|
40
|
+
* recommend.
|
|
41
|
+
*/
|
|
42
|
+
export declare function recommendedPolicy(): Policy;
|
|
43
|
+
/**
|
|
44
|
+
* Wraps `policy` so the run does not stop where the session waits on no card:
|
|
45
|
+
* `text` is sent instead, as a person would type to open a session or to say
|
|
46
|
+
* "go on". Cards are still answered by `policy`.
|
|
47
|
+
*/
|
|
48
|
+
export declare function sayWhenIdle(text: string, policy: Policy): Policy;
|
|
49
|
+
/** One step of a script: a fixed decision or message, or a function of the state. */
|
|
50
|
+
export type ScriptStep = Decision | Say | ((state: SessionState) => Decision | Say);
|
|
51
|
+
/**
|
|
52
|
+
* Plays `steps` in order, one per turn that runs. Stops when the steps are
|
|
53
|
+
* used up, or when a step's decision is for a different card kind than the one
|
|
54
|
+
* pending: the session is not where the script expects it to be, and guessing
|
|
55
|
+
* would only hide that.
|
|
56
|
+
*
|
|
57
|
+
* A step whose turn was refused (`info.lastTurnRefused`) did not happen, so it
|
|
58
|
+
* is played again rather than skipped. So is a step whose turn failed
|
|
59
|
+
* (`info.lastTurnError`) while the card it answered is still the pending one:
|
|
60
|
+
* the answer was lost with the turn.
|
|
61
|
+
*/
|
|
62
|
+
export declare function scriptedPolicy(steps: readonly ScriptStep[]): Policy;
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Policies: the part of a driver that decides.
|
|
3
|
+
*
|
|
4
|
+
* A policy sees the session state and returns what to do next. It does not
|
|
5
|
+
* send anything; `runToCompletion` (or the caller's own loop) does.
|
|
6
|
+
*/
|
|
7
|
+
import { decide } from "./decisions.js";
|
|
8
|
+
export function isSay(result) {
|
|
9
|
+
return typeof result === 'object' && 'say' in result;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* The option ids the `recommended` policy picks for one question: the options
|
|
13
|
+
* marked recommended (the first one only, for a single-select question), or
|
|
14
|
+
* else the first option. `[]` means the question is left unanswered, which is
|
|
15
|
+
* only acceptable when it is optional.
|
|
16
|
+
*/
|
|
17
|
+
function recommendedOptionIds(question) {
|
|
18
|
+
const marked = question.options.filter((o) => o.recommended === true).map((o) => o.id);
|
|
19
|
+
const first = question.options[0]?.id;
|
|
20
|
+
const picked = marked.length > 0 ? marked : first === undefined ? [] : [first];
|
|
21
|
+
if (picked.length === 0) {
|
|
22
|
+
return question.allowOther === true && question.required ? ['other:No preference'] : [];
|
|
23
|
+
}
|
|
24
|
+
return question.type === 'single' ? picked.slice(0, 1) : picked;
|
|
25
|
+
}
|
|
26
|
+
function recommendedMcq(pending) {
|
|
27
|
+
if (pending.card === null)
|
|
28
|
+
return 'stop';
|
|
29
|
+
const answers = {};
|
|
30
|
+
for (const question of pending.card.questions) {
|
|
31
|
+
const ids = recommendedOptionIds(question);
|
|
32
|
+
const [only] = ids;
|
|
33
|
+
if (only === undefined) {
|
|
34
|
+
// A required question with nothing to pick: there is no recommended
|
|
35
|
+
// path through this form.
|
|
36
|
+
if (question.required)
|
|
37
|
+
return 'stop';
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
answers[question.id] = question.type === 'single' ? only : ids;
|
|
41
|
+
}
|
|
42
|
+
return decide.mcq(pending, answers);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Takes the path the workflow itself recommends, with no judgement: the
|
|
46
|
+
* recommended option of every question, approve every spec file, plan and
|
|
47
|
+
* revision, ignore every review board (also one that asks for a revision),
|
|
48
|
+
* skip optional skills.
|
|
49
|
+
*
|
|
50
|
+
* It answers cards only. When the session waits on nothing (`idle`), or shows
|
|
51
|
+
* a card it cannot answer from its content, it stops: there is nothing it can
|
|
52
|
+
* recommend.
|
|
53
|
+
*/
|
|
54
|
+
export function recommendedPolicy() {
|
|
55
|
+
return (state) => {
|
|
56
|
+
const pending = state.pendingAction;
|
|
57
|
+
if (pending === null)
|
|
58
|
+
return 'stop';
|
|
59
|
+
switch (pending.kind) {
|
|
60
|
+
case 'mcq':
|
|
61
|
+
return recommendedMcq(pending);
|
|
62
|
+
case 'spec-decision':
|
|
63
|
+
return decide.approveSpec();
|
|
64
|
+
case 'review-decision':
|
|
65
|
+
return decide.review(pending, 'ignore');
|
|
66
|
+
case 'skill-selection':
|
|
67
|
+
return decide.selectSkill(null);
|
|
68
|
+
case 'user-choice': {
|
|
69
|
+
const choices = pending.card?.choices ?? [];
|
|
70
|
+
const choice = choices.find((c) => c.recommended) ?? choices[0];
|
|
71
|
+
return choice === undefined ? 'stop' : decide.choose(choice.id);
|
|
72
|
+
}
|
|
73
|
+
case 'edit-decision':
|
|
74
|
+
return pending.card === null ? 'stop' : decide.editReview(pending, 'accept-all');
|
|
75
|
+
case 'site-plan':
|
|
76
|
+
return decide.sitePlan(pending, 'approve');
|
|
77
|
+
case 'artifact-revision':
|
|
78
|
+
if (pending.card === null)
|
|
79
|
+
return 'stop';
|
|
80
|
+
// A Generate card is approved; an Edit card's change is kept.
|
|
81
|
+
return decide.artifactRevision(pending, pending.card.mode === 'edit' ? 'keep' : 'approve');
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Wraps `policy` so the run does not stop where the session waits on no card:
|
|
87
|
+
* `text` is sent instead, as a person would type to open a session or to say
|
|
88
|
+
* "go on". Cards are still answered by `policy`.
|
|
89
|
+
*/
|
|
90
|
+
export function sayWhenIdle(text, policy) {
|
|
91
|
+
return (state, info) => (state.pendingAction === null ? { say: text } : policy(state, info));
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Plays `steps` in order, one per turn that runs. Stops when the steps are
|
|
95
|
+
* used up, or when a step's decision is for a different card kind than the one
|
|
96
|
+
* pending: the session is not where the script expects it to be, and guessing
|
|
97
|
+
* would only hide that.
|
|
98
|
+
*
|
|
99
|
+
* A step whose turn was refused (`info.lastTurnRefused`) did not happen, so it
|
|
100
|
+
* is played again rather than skipped. So is a step whose turn failed
|
|
101
|
+
* (`info.lastTurnError`) while the card it answered is still the pending one:
|
|
102
|
+
* the answer was lost with the turn.
|
|
103
|
+
*/
|
|
104
|
+
export function scriptedPolicy(steps) {
|
|
105
|
+
let next = 0;
|
|
106
|
+
/** Id of the card the last step answered; `null` for a message. */
|
|
107
|
+
let lastAnswered = null;
|
|
108
|
+
return (state, info) => {
|
|
109
|
+
const pendingId = state.pendingAction?.id ?? null;
|
|
110
|
+
const refused = info?.lastTurnRefused != null;
|
|
111
|
+
const lostWithFailedTurn = info?.lastTurnError != null && lastAnswered !== null && lastAnswered === pendingId;
|
|
112
|
+
if ((refused || lostWithFailedTurn) && next > 0)
|
|
113
|
+
next -= 1;
|
|
114
|
+
const step = steps[next];
|
|
115
|
+
if (step === undefined)
|
|
116
|
+
return 'stop';
|
|
117
|
+
const result = typeof step === 'function' ? step(state) : step;
|
|
118
|
+
if (!isSay(result) && result.kind !== state.pendingAction?.kind)
|
|
119
|
+
return 'stop';
|
|
120
|
+
next += 1;
|
|
121
|
+
lastAnswered = isSay(result) ? null : pendingId;
|
|
122
|
+
return result;
|
|
123
|
+
};
|
|
124
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The driver loop: read state, ask the policy, send, repeat.
|
|
3
|
+
*/
|
|
4
|
+
import { type SessionHandle, type TurnOptions } from './client.js';
|
|
5
|
+
import { type Policy, type Say } from './policies.js';
|
|
6
|
+
import type { Decision, PendingActionKind, SessionState, TurnStreamError } from './types.js';
|
|
7
|
+
/** Most turns `runToCompletion` sends before it stops, unless told otherwise. */
|
|
8
|
+
export declare const DRIVER_MAX_TURNS = 80;
|
|
9
|
+
/**
|
|
10
|
+
* Which cards a driver may answer without a person.
|
|
11
|
+
* - `interview`: question cards only; the run hands over at approval cards.
|
|
12
|
+
* - `full`: every card.
|
|
13
|
+
*/
|
|
14
|
+
export type AutonomyLevel = 'interview' | 'full';
|
|
15
|
+
/** The kinds a driver at `interview` autonomy may answer. */
|
|
16
|
+
export declare const INTERVIEW_AUTONOMY_KINDS: ReadonlySet<PendingActionKind>;
|
|
17
|
+
export type RunEndReason =
|
|
18
|
+
/** The session reached `completed`. */
|
|
19
|
+
'completed'
|
|
20
|
+
/** The policy returned `stop`. */
|
|
21
|
+
| 'policy_stop'
|
|
22
|
+
/** The turn limit was reached. */
|
|
23
|
+
| 'max_turns'
|
|
24
|
+
/** `interview` autonomy met a card that needs a person. */
|
|
25
|
+
| 'handover'
|
|
26
|
+
/** A turn ended with a stream error. */
|
|
27
|
+
| 'turn_error'
|
|
28
|
+
/**
|
|
29
|
+
* The server will not take more turns from this driver on this session.
|
|
30
|
+
* The turn cap, or agent driving turned off: a person must continue. A
|
|
31
|
+
* read-only token: a read-write token is needed. See `report.error`.
|
|
32
|
+
*/
|
|
33
|
+
| 'agent_refused'
|
|
34
|
+
/** Something else failed; the run could not go on. See `report.error`. */
|
|
35
|
+
| 'error';
|
|
36
|
+
export interface RunTurnRecord {
|
|
37
|
+
/** 1-based position of the turn in the run. */
|
|
38
|
+
index: number;
|
|
39
|
+
/** The card the turn answered, or `null` for a turn sent with none pending. */
|
|
40
|
+
pendingKind: PendingActionKind | null;
|
|
41
|
+
pendingActionId: string | null;
|
|
42
|
+
/** What the policy chose. */
|
|
43
|
+
action: Decision | Say;
|
|
44
|
+
/** What the agent said in the turn. Empty for a refused turn. */
|
|
45
|
+
assistantText: string;
|
|
46
|
+
durationMs: number;
|
|
47
|
+
/** The stream's error, when the turn ended with one. */
|
|
48
|
+
error: TurnStreamError | null;
|
|
49
|
+
/**
|
|
50
|
+
* Set when the turn was refused and not run: the session had moved on
|
|
51
|
+
* (`mismatch`) or another turn was running (`busy`).
|
|
52
|
+
*/
|
|
53
|
+
refused?: 'mismatch' | 'busy';
|
|
54
|
+
}
|
|
55
|
+
export interface RunReport {
|
|
56
|
+
endReason: RunEndReason;
|
|
57
|
+
turns: RunTurnRecord[];
|
|
58
|
+
/** The last state the run read. */
|
|
59
|
+
finalState: SessionState;
|
|
60
|
+
/** What stopped the run, for `agent_refused` and `error`. */
|
|
61
|
+
error?: unknown;
|
|
62
|
+
}
|
|
63
|
+
export interface RunOptions {
|
|
64
|
+
/** Defaults to {@link DRIVER_MAX_TURNS}. A refused turn counts. */
|
|
65
|
+
maxTurns?: number;
|
|
66
|
+
/** Defaults to `full`. */
|
|
67
|
+
autonomy?: AutonomyLevel;
|
|
68
|
+
/** Model, depth and language for every turn of the run. `waitMs` is not used. */
|
|
69
|
+
turn?: Omit<TurnOptions, 'waitMs'>;
|
|
70
|
+
/**
|
|
71
|
+
* How many turns that end with a stream error the run goes on from, as a
|
|
72
|
+
* person would press "try again": the state is read again and the policy is
|
|
73
|
+
* asked again, with the error in `info.lastTurnError`. Defaults to 0, so the
|
|
74
|
+
* first such turn ends the run with `turn_error`. One budget for the whole
|
|
75
|
+
* run, not per turn. An error the ai-agent marks as not recoverable ends the
|
|
76
|
+
* run whatever is left. A turn that failed is in the report either way.
|
|
77
|
+
*/
|
|
78
|
+
turnErrorRetries?: number;
|
|
79
|
+
/** Called after every turn, refused ones included. */
|
|
80
|
+
onTurn?: (record: RunTurnRecord) => void;
|
|
81
|
+
/** Wait before trying again after `SESSION_BUSY`. Defaults to the poll interval. */
|
|
82
|
+
busyBackoffMs?: number;
|
|
83
|
+
/** Waits. Replaceable so tests need no real timers. */
|
|
84
|
+
sleep?: (ms: number) => Promise<void>;
|
|
85
|
+
/** Clock, replaceable in tests. */
|
|
86
|
+
now?: () => number;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Drives `session` with `policy` until the session completes, the policy
|
|
90
|
+
* stops, the autonomy level hands over, a turn fails, or the turn limit is
|
|
91
|
+
* reached.
|
|
92
|
+
*
|
|
93
|
+
* A refused turn (the session moved on, or someone else's turn is running) is
|
|
94
|
+
* not an error: the state is read again and the policy is asked again, so a
|
|
95
|
+
* person and a driver can work on the same session.
|
|
96
|
+
*
|
|
97
|
+
* Once the first state is read the run always ends with a report: a failure on
|
|
98
|
+
* the way is the report's `error`, never a throw that would lose the turns
|
|
99
|
+
* already made.
|
|
100
|
+
*/
|
|
101
|
+
export declare function runToCompletion(session: SessionHandle, policy: Policy, options?: RunOptions): Promise<RunReport>;
|
package/dist/src/run.js
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The driver loop: read state, ask the policy, send, repeat.
|
|
3
|
+
*/
|
|
4
|
+
import { DEFAULT_POLL_MS } from "./client.js";
|
|
5
|
+
import { AgentDrivingDisabledError, AgentTurnCapReachedError, InvalidDecisionError, PendingActionMismatchError, ReadOnlyTokenError, SessionBusyError, } from "./errors.js";
|
|
6
|
+
import { isSay } from "./policies.js";
|
|
7
|
+
/** Most turns `runToCompletion` sends before it stops, unless told otherwise. */
|
|
8
|
+
export const DRIVER_MAX_TURNS = 80;
|
|
9
|
+
/** The kinds a driver at `interview` autonomy may answer. */
|
|
10
|
+
export const INTERVIEW_AUTONOMY_KINDS = new Set([
|
|
11
|
+
'mcq',
|
|
12
|
+
'user-choice',
|
|
13
|
+
'skill-selection',
|
|
14
|
+
]);
|
|
15
|
+
const defaultSleep = (ms) => new Promise((resolve) => {
|
|
16
|
+
setTimeout(resolve, ms);
|
|
17
|
+
});
|
|
18
|
+
/**
|
|
19
|
+
* Drives `session` with `policy` until the session completes, the policy
|
|
20
|
+
* stops, the autonomy level hands over, a turn fails, or the turn limit is
|
|
21
|
+
* reached.
|
|
22
|
+
*
|
|
23
|
+
* A refused turn (the session moved on, or someone else's turn is running) is
|
|
24
|
+
* not an error: the state is read again and the policy is asked again, so a
|
|
25
|
+
* person and a driver can work on the same session.
|
|
26
|
+
*
|
|
27
|
+
* Once the first state is read the run always ends with a report: a failure on
|
|
28
|
+
* the way is the report's `error`, never a throw that would lose the turns
|
|
29
|
+
* already made.
|
|
30
|
+
*/
|
|
31
|
+
export async function runToCompletion(session, policy, options = {}) {
|
|
32
|
+
const maxTurns = options.maxTurns ?? DRIVER_MAX_TURNS;
|
|
33
|
+
const autonomy = options.autonomy ?? 'full';
|
|
34
|
+
const now = options.now ?? Date.now;
|
|
35
|
+
const sleep = options.sleep ?? defaultSleep;
|
|
36
|
+
const busyBackoffMs = options.busyBackoffMs ?? DEFAULT_POLL_MS;
|
|
37
|
+
const turns = [];
|
|
38
|
+
// Anything that is not a whole number of at least 1 means no retry.
|
|
39
|
+
const asked = options.turnErrorRetries ?? 0;
|
|
40
|
+
let retriesLeft = Number.isInteger(asked) && asked > 0 ? asked : 0;
|
|
41
|
+
let state = await session.waitForTurn();
|
|
42
|
+
const end = (endReason, error) => ({
|
|
43
|
+
endReason,
|
|
44
|
+
turns,
|
|
45
|
+
finalState: state,
|
|
46
|
+
...(error === undefined ? {} : { error }),
|
|
47
|
+
});
|
|
48
|
+
const info = { lastTurnRefused: null, lastTurnError: null };
|
|
49
|
+
try {
|
|
50
|
+
while (turns.length < maxTurns) {
|
|
51
|
+
if (state.phase === 'completed')
|
|
52
|
+
return end('completed');
|
|
53
|
+
if (state.phase === 'running') {
|
|
54
|
+
// Never decide on a state that is about to change.
|
|
55
|
+
state = await session.waitForTurn();
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
const pending = state.pendingAction;
|
|
59
|
+
if (autonomy === 'interview' &&
|
|
60
|
+
pending !== null &&
|
|
61
|
+
!INTERVIEW_AUTONOMY_KINDS.has(pending.kind)) {
|
|
62
|
+
return end('handover');
|
|
63
|
+
}
|
|
64
|
+
const action = await policy(state, { ...info });
|
|
65
|
+
if (action === 'stop')
|
|
66
|
+
return end('policy_stop');
|
|
67
|
+
const record = {
|
|
68
|
+
index: turns.length + 1,
|
|
69
|
+
pendingKind: pending?.kind ?? null,
|
|
70
|
+
pendingActionId: pending?.id ?? null,
|
|
71
|
+
action,
|
|
72
|
+
assistantText: '',
|
|
73
|
+
durationMs: 0,
|
|
74
|
+
error: null,
|
|
75
|
+
};
|
|
76
|
+
const startedAt = now();
|
|
77
|
+
let result;
|
|
78
|
+
try {
|
|
79
|
+
if (isSay(action)) {
|
|
80
|
+
result = await session.send(action.say, {
|
|
81
|
+
...options.turn,
|
|
82
|
+
pending: pending ?? undefined,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
if (pending === null) {
|
|
87
|
+
throw new InvalidDecisionError(`The policy returned a "${action.kind}" decision, but the session waits on no card.`);
|
|
88
|
+
}
|
|
89
|
+
result = await session.respond(pending, action, options.turn);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
if (error instanceof PendingActionMismatchError)
|
|
94
|
+
record.refused = 'mismatch';
|
|
95
|
+
else if (error instanceof SessionBusyError)
|
|
96
|
+
record.refused = 'busy';
|
|
97
|
+
else
|
|
98
|
+
throw error;
|
|
99
|
+
}
|
|
100
|
+
record.durationMs = now() - startedAt;
|
|
101
|
+
record.assistantText = result?.assistantText ?? '';
|
|
102
|
+
record.error = result?.error ?? null;
|
|
103
|
+
info.lastTurnRefused = record.refused ?? null;
|
|
104
|
+
info.lastTurnError = record.error;
|
|
105
|
+
turns.push(record);
|
|
106
|
+
options.onTurn?.(record);
|
|
107
|
+
if (result === undefined) {
|
|
108
|
+
// Refused, nothing ran. The lock that refused a busy turn can outlive
|
|
109
|
+
// the "running" flag by a moment, so give it time before looking again.
|
|
110
|
+
if (record.refused === 'busy')
|
|
111
|
+
await sleep(busyBackoffMs);
|
|
112
|
+
state = await session.waitForTurn();
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
// `state` is null when the turn ran but its state could not be read yet.
|
|
116
|
+
state = result.state ?? (await session.waitForTurn());
|
|
117
|
+
if (result.error !== null) {
|
|
118
|
+
if (retriesLeft <= 0 || result.error.recoverable === false)
|
|
119
|
+
return end('turn_error');
|
|
120
|
+
retriesLeft -= 1;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
const agentRefused = error instanceof AgentTurnCapReachedError ||
|
|
126
|
+
error instanceof AgentDrivingDisabledError ||
|
|
127
|
+
error instanceof ReadOnlyTokenError;
|
|
128
|
+
return end(agentRefused ? 'agent_refused' : 'error', error);
|
|
129
|
+
}
|
|
130
|
+
return end(state.phase === 'completed' ? 'completed' : 'max_turns');
|
|
131
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Reader of a chat turn's UI-message SSE stream.
|
|
3
|
+
*
|
|
4
|
+
* The stream is `text/event-stream` with one JSON frame per `data:` line. The
|
|
5
|
+
* reader keeps only what a driver needs: the assistant's text and the error
|
|
6
|
+
* frame, if the turn carried one. Cards are NOT taken from the stream: the
|
|
7
|
+
* state read after the turn is the single source of what the session waits on.
|
|
8
|
+
*/
|
|
9
|
+
import type { TurnStreamError } from './types.js';
|
|
10
|
+
export interface TurnStreamSnapshot {
|
|
11
|
+
assistantText: string;
|
|
12
|
+
error: TurnStreamError | null;
|
|
13
|
+
}
|
|
14
|
+
export interface TurnStream {
|
|
15
|
+
/**
|
|
16
|
+
* Resolves when the stream has been read to its end, or failed. NEVER
|
|
17
|
+
* rejects: a transport failure lands in `snapshot().error`, so a read that
|
|
18
|
+
* outlives its caller cannot become an unhandled rejection.
|
|
19
|
+
*/
|
|
20
|
+
readonly drained: Promise<void>;
|
|
21
|
+
/** Everything read so far. Safe to call at any time. */
|
|
22
|
+
snapshot: () => TurnStreamSnapshot;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Starts reading `body` at once and runs to its end on its own. The body is
|
|
26
|
+
* never cancelled: the ai-agent releases the session lock when the response
|
|
27
|
+
* body ends, so dropping the stream would cut the turn short.
|
|
28
|
+
*/
|
|
29
|
+
export declare function readTurnStream(body: ReadableStream<Uint8Array> | null): TurnStream;
|