@myspec/sdk 0.1.3 → 0.2.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/README.md +28 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +3 -3
- package/dist/src/client.d.ts +47 -0
- package/dist/src/client.js +80 -2
- package/dist/src/errors.d.ts +7 -0
- package/dist/src/errors.js +10 -0
- package/dist/src/policies.d.ts +30 -4
- package/dist/src/policies.js +46 -2
- package/dist/src/run.d.ts +3 -3
- package/dist/src/run.js +39 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -31,8 +31,10 @@ const client = createClient({
|
|
|
31
31
|
actorKind: 'ai', // an agent decides; leave out for a person or a test script
|
|
32
32
|
});
|
|
33
33
|
|
|
34
|
-
// A session someone already started
|
|
34
|
+
// A session someone already started.
|
|
35
35
|
const session = client.attach(sessionId);
|
|
36
|
+
// Or start one: create it and send the opening message.
|
|
37
|
+
// const { session, turn } = await client.start({ projectId, workflowId: 'generate-artifact-website', prompt });
|
|
36
38
|
|
|
37
39
|
// One step at a time.
|
|
38
40
|
const state = await session.getState();
|
|
@@ -55,6 +57,7 @@ A turn that ends with a stream error ends the run with `turn_error`. Pass `turnE
|
|
|
55
57
|
| ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
56
58
|
| `apiTokenAuth({ apiToken, authUrl? })` | A `getToken` that trades an API token for short-lived access tokens. |
|
|
57
59
|
| `createClient(options)` → `attach(sessionId)` | A handle on one session. Sends nothing. |
|
|
60
|
+
| `client.start(options)` | Creates a session and sends `prompt` as its first turn. See [Start a session](#start-a-session). |
|
|
58
61
|
| `session.getState({ waitMs? })` | Phase, stage, pending action, spec files, decision log, agent turn count, last assistant reply. With `waitMs` the server holds the answer while a turn runs (at most 25 s). |
|
|
59
62
|
| `session.listMessages({ after?, limit? })` | The saved transcript, oldest first, one page at a time. |
|
|
60
63
|
| `session.respond(pending, decision, options?)` | Answers a card and reads the turn to its end. |
|
|
@@ -63,6 +66,7 @@ A turn that ends with a stream error ends the run with `turn_error`. Pass `turnE
|
|
|
63
66
|
| `session.runCommand(name, args?, options?)` | Runs a slash command the session offers (`complete`, `goback`, `btw`), as the webapp runs it. |
|
|
64
67
|
| `decide.*`, `validateDecision` | Builds and checks a decision for each card kind. |
|
|
65
68
|
| `recommendedPolicy()`, `scriptedPolicy(steps)` | Ready-made policies. |
|
|
69
|
+
| `completeWhenIdle(policy)`, `sayWhenIdle(…)` | Wrappers: complete an Edit session once it has kept a change; send text when no card waits. |
|
|
66
70
|
| `runToCompletion(session, policy, options?)` | The read, decide, send loop, with a run report. |
|
|
67
71
|
|
|
68
72
|
`apiTokenAuth` signs in at `https://auth.myspec.dev` unless `authUrl` names another environment; a token works only where it was created. It keeps the access token until a minute before it expires, and trades again after a 401. A refused API token throws `ApiTokenRejectedError`, and every later call of that `getToken` throws it again without asking the host. Any other failed sign-in (a timeout, after 10 s by default; rate limiting, with `retryAfterSeconds`; a 5xx) throws `TokenExchangeError`, and the next call tries again. In tests and in-process runs, pass any `getToken` that returns a valid access token.
|
|
@@ -79,6 +83,29 @@ Refusals a driver should handle are typed errors: `PendingActionMismatchError` (
|
|
|
79
83
|
|
|
80
84
|
Pass `options.state` when you have just read the state, to skip the first read.
|
|
81
85
|
|
|
86
|
+
## Start a session
|
|
87
|
+
|
|
88
|
+
`client.start({ projectId, workflowId, prompt, target?, title?, ...turnOptions })` creates a session through the webapp (`POST /api/v1/projects/:id/sessions`) with its workflow in the create call, then sends `prompt` as the first turn. It returns `{ session, turn }`.
|
|
89
|
+
|
|
90
|
+
- `workflowId` is the workflow as `state.workflowId` names it: `generate-greenfield-myspec`, `edit-greenfield-myspec`, `generate-artifact-website` (build a website artifact), `edit-artifact-website` (edit one), and the rest. The server refuses a workflow its feature flags do not allow (`SessionRequestError`, HTTP 400), but not an unknown one, so `start` refuses a value that is not shaped like a workflow (it must start with `generate-` or `edit-`) and a picker id such as the MCP servers' `website-artifact-v1`.
|
|
91
|
+
- `edit-artifact-website` needs `target: { artifactId, baseRevision }`: the website artifact and its head revision (`revisionCount`). `target` is refused with every other workflow. Bad options throw `InvalidStartOptionsError` before any request.
|
|
92
|
+
- The session exists whatever happens to the first turn: when it is refused or fails, `turn` is `null` and `turnError` says why. Do not start again; drive `session`.
|
|
93
|
+
- Every start spends model tokens. Start once per intent.
|
|
94
|
+
|
|
95
|
+
**Driving a website session to the end.** A Generate website session ends by itself when its final revision is approved. An Edit session (spec or website artifact) ends only with `complete`: wrap the policy in `completeWhenIdle`, which runs `complete` when an Edit session waits on no card, offers `complete` and has kept a change (an edit review with a file accepted, or an artifact revision kept). At `autonomy: 'interview'` the run ends with `handover` instead: a command that changes the session (`complete`, `goback`) is the user's. A read-only one (`btw`) still runs.
|
|
96
|
+
|
|
97
|
+
```ts
|
|
98
|
+
const { session } = await client.start({
|
|
99
|
+
projectId,
|
|
100
|
+
workflowId: 'edit-artifact-website',
|
|
101
|
+
target: { artifactId, baseRevision: 4 },
|
|
102
|
+
prompt: 'Make the header blue.',
|
|
103
|
+
});
|
|
104
|
+
const report = await runToCompletion(session, completeWhenIdle(recommendedPolicy()));
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
A policy may also return `{ command, args? }` to run any command the session offers, and a `scriptedPolicy` step may be one, for example `{ command: 'complete' }` after the steps that answer the cards.
|
|
108
|
+
|
|
82
109
|
## Agent-driven turns
|
|
83
110
|
|
|
84
111
|
A turn is agent-driven when its token belongs to an org agent, or when the client was created with `actorKind: 'ai'`. Set `actorKind: 'ai'` whenever an agent decides with a person's token. Leave it out for a person and for a test or evaluation script that plays a user.
|
package/dist/index.d.ts
CHANGED
|
@@ -5,11 +5,11 @@
|
|
|
5
5
|
* agent. See `README.md`.
|
|
6
6
|
*/
|
|
7
7
|
export { ACCESS_TOKEN_REFRESH_MARGIN_MS, ApiTokenRejectedError, DEFAULT_AUTH_URL, TOKEN_EXCHANGE_TIMEOUT_MS, TokenExchangeError, apiTokenAuth, type ApiTokenAuthOptions, } from './src/auth.js';
|
|
8
|
-
export { DEFAULT_CLIENT_TYPE, DEFAULT_POLL_MS, DEFAULT_WAIT_TIMEOUT_MS, MAX_STATE_LONG_POLL_MS, TURN_SETTLE_POLL_MS, TURN_SETTLE_TIMEOUT_MS, createClient, type ClientOptions, type CommandOptions, type ListMessagesOptions, type SessionClient, type StateReadOptions, type SendOptions, type SessionHandle, type SessionLanguage, type TurnOptions, type WaitOptions, } from './src/client.js';
|
|
8
|
+
export { DEFAULT_CLIENT_TYPE, DEFAULT_POLL_MS, DEFAULT_WAIT_TIMEOUT_MS, MAX_STATE_LONG_POLL_MS, TURN_SETTLE_POLL_MS, TURN_SETTLE_TIMEOUT_MS, EDIT_ARTIFACT_WEBSITE_WORKFLOW_ID, createClient, type ArtifactEditTarget, type ClientOptions, type CommandOptions, type ListMessagesOptions, type SessionClient, type StateReadOptions, type SendOptions, type SessionHandle, type SessionLanguage, type StartSessionOptions, type StartedSession, type TurnOptions, type WaitOptions, } from './src/client.js';
|
|
9
9
|
export { checkCommand, type CommandArgs, type CommandResult } from './src/commands.js';
|
|
10
10
|
export { MCQ_OTHER_PREFIX, decide, validateDecision, type PendingOf } from './src/decisions.js';
|
|
11
|
-
export { AgentDrivingDisabledError, AgentTurnCapReachedError, CommandNotAvailableError, InvalidDecisionError, PendingActionMismatchError, ReadOnlyTokenError, SessionBusyError, SessionRequestError, TurnSettleTimeoutError, TurnTimeoutError, } from './src/errors.js';
|
|
12
|
-
export { isSay, recommendedPolicy, sayWhenIdle, scriptedPolicy, type Policy, type PolicyInfo, type PolicyResult, type Say, type ScriptStep, } from './src/policies.js';
|
|
11
|
+
export { AgentDrivingDisabledError, AgentTurnCapReachedError, CommandNotAvailableError, InvalidDecisionError, InvalidStartOptionsError, PendingActionMismatchError, ReadOnlyTokenError, SessionBusyError, SessionRequestError, TurnSettleTimeoutError, TurnTimeoutError, } from './src/errors.js';
|
|
12
|
+
export { completeWhenIdle, isRunCommand, isSay, recommendedPolicy, sayWhenIdle, scriptedPolicy, type Policy, type PolicyInfo, type PolicyResult, type RunCommand, type Say, type ScriptStep, } from './src/policies.js';
|
|
13
13
|
export { DRIVER_MAX_TURNS, INTERVIEW_AUTONOMY_KINDS, runToCompletion, type AutonomyLevel, type RunEndReason, type RunOptions, type RunReport, type RunTurnRecord, } from './src/run.js';
|
|
14
14
|
export { readTurnStream, type TurnStream, type TurnStreamSnapshot } from './src/stream.js';
|
|
15
15
|
export { DECISION_PART_TYPE, NO_PENDING_ACTION_ID, PENDING_ACTION_KINDS, type ArtifactRevisionCard, type CardByKind, type Decision, type DecisionDataByKind, type EditReviewCard, type McqFormCard, type McqOption, type McqQuestion, type PendingAction, type PendingActionKind, type ReviewFeedbackCard, type ReviewFeedbackItem, type SessionCommand, type SessionCommandArg, type SessionCommandRunsAs, type SessionPhase, type LastAssistantMessage, type SessionMessage, type SessionMessageCard, type SessionMessagesPage, type SessionMessageToolCall, type SessionState, type SessionStateLocalBridge, type SpecFilePreview, type SessionStateDecision, type SessionStateDecisionAttribution, type SessionStateMcqAnswer, type SessionStateSpecFile, type SitePlanCard, type SkillRecommendationCard, type SpecFileCard, type TurnResult, type TurnStreamError, type UserChoiceCard, } from './src/types.js';
|
package/dist/index.js
CHANGED
|
@@ -5,11 +5,11 @@
|
|
|
5
5
|
* agent. See `README.md`.
|
|
6
6
|
*/
|
|
7
7
|
export { ACCESS_TOKEN_REFRESH_MARGIN_MS, ApiTokenRejectedError, DEFAULT_AUTH_URL, TOKEN_EXCHANGE_TIMEOUT_MS, TokenExchangeError, apiTokenAuth, } from "./src/auth.js";
|
|
8
|
-
export { DEFAULT_CLIENT_TYPE, DEFAULT_POLL_MS, DEFAULT_WAIT_TIMEOUT_MS, MAX_STATE_LONG_POLL_MS, TURN_SETTLE_POLL_MS, TURN_SETTLE_TIMEOUT_MS, createClient, } from "./src/client.js";
|
|
8
|
+
export { DEFAULT_CLIENT_TYPE, DEFAULT_POLL_MS, DEFAULT_WAIT_TIMEOUT_MS, MAX_STATE_LONG_POLL_MS, TURN_SETTLE_POLL_MS, TURN_SETTLE_TIMEOUT_MS, EDIT_ARTIFACT_WEBSITE_WORKFLOW_ID, createClient, } from "./src/client.js";
|
|
9
9
|
export { checkCommand } from "./src/commands.js";
|
|
10
10
|
export { MCQ_OTHER_PREFIX, decide, validateDecision } from "./src/decisions.js";
|
|
11
|
-
export { AgentDrivingDisabledError, AgentTurnCapReachedError, CommandNotAvailableError, InvalidDecisionError, PendingActionMismatchError, ReadOnlyTokenError, SessionBusyError, SessionRequestError, TurnSettleTimeoutError, TurnTimeoutError, } from "./src/errors.js";
|
|
12
|
-
export { isSay, recommendedPolicy, sayWhenIdle, scriptedPolicy, } from "./src/policies.js";
|
|
11
|
+
export { AgentDrivingDisabledError, AgentTurnCapReachedError, CommandNotAvailableError, InvalidDecisionError, InvalidStartOptionsError, PendingActionMismatchError, ReadOnlyTokenError, SessionBusyError, SessionRequestError, TurnSettleTimeoutError, TurnTimeoutError, } from "./src/errors.js";
|
|
12
|
+
export { completeWhenIdle, isRunCommand, isSay, recommendedPolicy, sayWhenIdle, scriptedPolicy, } from "./src/policies.js";
|
|
13
13
|
export { DRIVER_MAX_TURNS, INTERVIEW_AUTONOMY_KINDS, runToCompletion, } from "./src/run.js";
|
|
14
14
|
export { readTurnStream } from "./src/stream.js";
|
|
15
15
|
export { DECISION_PART_TYPE, NO_PENDING_ACTION_ID, PENDING_ACTION_KINDS, } from "./src/types.js";
|
package/dist/src/client.d.ts
CHANGED
|
@@ -181,8 +181,55 @@ export interface SessionHandle {
|
|
|
181
181
|
*/
|
|
182
182
|
runCommand(name: string, args?: CommandArgs, options?: CommandOptions): Promise<CommandResult>;
|
|
183
183
|
}
|
|
184
|
+
/** The workflow that edits one website artifact: the one that needs `target`. */
|
|
185
|
+
export declare const EDIT_ARTIFACT_WEBSITE_WORKFLOW_ID = "edit-artifact-website";
|
|
186
|
+
/** The website artifact an artifact Edit session edits. */
|
|
187
|
+
export interface ArtifactEditTarget {
|
|
188
|
+
artifactId: string;
|
|
189
|
+
/**
|
|
190
|
+
* The revision the session starts from: the artifact's head
|
|
191
|
+
* (`revisionCount`) when you start. A newer head is used instead, and the
|
|
192
|
+
* session says so in its first reply.
|
|
193
|
+
*/
|
|
194
|
+
baseRevision: number;
|
|
195
|
+
}
|
|
196
|
+
/** What `client.start` creates. */
|
|
197
|
+
export interface StartSessionOptions extends TurnOptions {
|
|
198
|
+
projectId: string;
|
|
199
|
+
/**
|
|
200
|
+
* The workflow, as `state.workflowId` names it: for example
|
|
201
|
+
* `generate-greenfield-myspec`, `generate-artifact-website` (build a
|
|
202
|
+
* website artifact) or `edit-artifact-website` (edit one, with `target`).
|
|
203
|
+
* The server refuses a workflow its feature flags do not allow.
|
|
204
|
+
*/
|
|
205
|
+
workflowId: string;
|
|
206
|
+
/** The opening message, sent as the session's first turn. */
|
|
207
|
+
prompt: string;
|
|
208
|
+
/** Required with {@link EDIT_ARTIFACT_WEBSITE_WORKFLOW_ID}, refused with every other workflow. */
|
|
209
|
+
target?: ArtifactEditTarget;
|
|
210
|
+
/** The session's title. A workflow that names the session itself overwrites it. */
|
|
211
|
+
title?: string;
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* A session `client.start` created. It exists whatever happened to the
|
|
215
|
+
* opening turn: `turn` is its result, or `null` with `turnError` when it was
|
|
216
|
+
* refused or failed. Do not start again then; drive `session`.
|
|
217
|
+
*/
|
|
218
|
+
export interface StartedSession {
|
|
219
|
+
session: SessionHandle;
|
|
220
|
+
turn: TurnResult | null;
|
|
221
|
+
turnError?: unknown;
|
|
222
|
+
}
|
|
184
223
|
export interface SessionClient {
|
|
185
224
|
/** A handle on an existing session. Sends nothing. */
|
|
186
225
|
attach(sessionId: string): SessionHandle;
|
|
226
|
+
/**
|
|
227
|
+
* Creates a session in a project and sends `prompt` as its first turn, as
|
|
228
|
+
* the webapp's composer does. Throws {@link InvalidStartOptionsError}
|
|
229
|
+
* before any request when the options cannot start one, and a
|
|
230
|
+
* `SessionRequestError` when the server refuses to create it. Every start
|
|
231
|
+
* spends model tokens: start once per intent.
|
|
232
|
+
*/
|
|
233
|
+
start(options: StartSessionOptions): Promise<StartedSession>;
|
|
187
234
|
}
|
|
188
235
|
export declare function createClient(options: ClientOptions): SessionClient;
|
package/dist/src/client.js
CHANGED
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
*/
|
|
13
13
|
import { checkCommand } from "./commands.js";
|
|
14
14
|
import { validateDecision } from "./decisions.js";
|
|
15
|
-
import { InvalidDecisionError, TurnSettleTimeoutError, TurnTimeoutError, errorFromResponse, } from "./errors.js";
|
|
15
|
+
import { InvalidDecisionError, InvalidStartOptionsError, SessionRequestError, TurnSettleTimeoutError, TurnTimeoutError, errorFromResponse, } from "./errors.js";
|
|
16
16
|
import { readTurnStream } from "./stream.js";
|
|
17
17
|
import { DECISION_PART_TYPE, NO_PENDING_ACTION_ID, } from "./types.js";
|
|
18
18
|
/** Client type the ai-agent segments analytics on, unless the caller sets one. */
|
|
@@ -34,6 +34,8 @@ export const TURN_SETTLE_POLL_MS = 500;
|
|
|
34
34
|
* answer while a turn runs, up to this, and answers as soon as it ends.
|
|
35
35
|
*/
|
|
36
36
|
export const MAX_STATE_LONG_POLL_MS = 25_000;
|
|
37
|
+
/** The workflow that edits one website artifact: the one that needs `target`. */
|
|
38
|
+
export const EDIT_ARTIFACT_WEBSITE_WORKFLOW_ID = 'edit-artifact-website';
|
|
37
39
|
const defaultSleep = (ms) => new Promise((resolve) => {
|
|
38
40
|
setTimeout(resolve, ms);
|
|
39
41
|
});
|
|
@@ -315,5 +317,81 @@ export function createClient(options) {
|
|
|
315
317
|
},
|
|
316
318
|
};
|
|
317
319
|
}
|
|
318
|
-
|
|
320
|
+
async function start(start) {
|
|
321
|
+
const context = startContext(start);
|
|
322
|
+
const response = await request(`/api/v1/projects/${encodeURIComponent(start.projectId)}/sessions`, { method: 'POST', body: JSON.stringify({ context }) });
|
|
323
|
+
const created = (await response.json().catch(() => null));
|
|
324
|
+
if (typeof created?.id !== 'string' || created.id === '') {
|
|
325
|
+
throw new SessionRequestError(response.status, 'INVALID_RESPONSE', 'The server created a session but did not return its id.', created);
|
|
326
|
+
}
|
|
327
|
+
const session = attach(created.id);
|
|
328
|
+
// Everything that is not about the session itself is a turn option.
|
|
329
|
+
const { projectId, workflowId, prompt, target, title, ...turn } = start;
|
|
330
|
+
try {
|
|
331
|
+
return { session, turn: await session.send(prompt, turn) };
|
|
332
|
+
}
|
|
333
|
+
catch (turnError) {
|
|
334
|
+
return { session, turn: null, turnError };
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
return { attach, start };
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* Refuses a `workflowId` that cannot be a workflow's dispatch key. The
|
|
341
|
+
* platform does not refuse an unknown key, and the ai-agent runs the spec Edit
|
|
342
|
+
* workflow for one, so a typo would spend tokens on the wrong workflow. The
|
|
343
|
+
* check is by shape only, so a workflow the server adds needs no SDK change:
|
|
344
|
+
* a key starts with `generate-` or `edit-`, and a picker id such as the MCP
|
|
345
|
+
* servers' `website-artifact-v1` ends with a version.
|
|
346
|
+
*/
|
|
347
|
+
function checkDispatchKey(workflowId) {
|
|
348
|
+
if (/-v\d+$/.test(workflowId)) {
|
|
349
|
+
throw new InvalidStartOptionsError(`start: "${workflowId}" is a picker id. Pass the workflow as state.workflowId names it, ` +
|
|
350
|
+
'for example generate-artifact-website or edit-artifact-website.');
|
|
351
|
+
}
|
|
352
|
+
if (!/^(generate|edit)-[a-z0-9-]+$/.test(workflowId)) {
|
|
353
|
+
throw new InvalidStartOptionsError(`start: "${workflowId}" is not a workflow. A workflow starts with "generate-" or ` +
|
|
354
|
+
'"edit-", for example generate-greenfield-myspec or edit-artifact-website.');
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* The context a session is created with: the workflow (and an artifact Edit
|
|
359
|
+
* session's target) is written at create time, so the first turn already runs
|
|
360
|
+
* the chosen workflow. Throws {@link InvalidStartOptionsError} for options
|
|
361
|
+
* that cannot start a session.
|
|
362
|
+
*/
|
|
363
|
+
function startContext(start) {
|
|
364
|
+
if (start.projectId === '')
|
|
365
|
+
throw new InvalidStartOptionsError('start: projectId is empty.');
|
|
366
|
+
if (start.workflowId === '')
|
|
367
|
+
throw new InvalidStartOptionsError('start: workflowId is empty.');
|
|
368
|
+
checkDispatchKey(start.workflowId);
|
|
369
|
+
if (start.prompt === '')
|
|
370
|
+
throw new InvalidStartOptionsError('start: prompt is empty.');
|
|
371
|
+
const editsArtifact = start.workflowId === EDIT_ARTIFACT_WEBSITE_WORKFLOW_ID;
|
|
372
|
+
const { target } = start;
|
|
373
|
+
if (editsArtifact && target === undefined) {
|
|
374
|
+
throw new InvalidStartOptionsError(`start: workflow "${EDIT_ARTIFACT_WEBSITE_WORKFLOW_ID}" edits one website artifact, so it ` +
|
|
375
|
+
'needs target: { artifactId, baseRevision }.');
|
|
376
|
+
}
|
|
377
|
+
if (!editsArtifact && target !== undefined) {
|
|
378
|
+
throw new InvalidStartOptionsError(`start: target names an artifact to edit, which only workflow ` +
|
|
379
|
+
`"${EDIT_ARTIFACT_WEBSITE_WORKFLOW_ID}" does, not "${start.workflowId}".`);
|
|
380
|
+
}
|
|
381
|
+
if (target !== undefined &&
|
|
382
|
+
(target.artifactId === '' ||
|
|
383
|
+
!Number.isSafeInteger(target.baseRevision) ||
|
|
384
|
+
target.baseRevision < 1)) {
|
|
385
|
+
throw new InvalidStartOptionsError('start: target needs an artifactId and a baseRevision of at least 1.');
|
|
386
|
+
}
|
|
387
|
+
return {
|
|
388
|
+
workflow: {
|
|
389
|
+
version: 1,
|
|
390
|
+
workflowId: start.workflowId,
|
|
391
|
+
...(target === undefined
|
|
392
|
+
? {}
|
|
393
|
+
: { target: { artifactId: target.artifactId, baseRevision: target.baseRevision } }),
|
|
394
|
+
},
|
|
395
|
+
...(start.title === undefined || start.title === '' ? {} : { sessionSummary: start.title }),
|
|
396
|
+
};
|
|
319
397
|
}
|
package/dist/src/errors.d.ts
CHANGED
|
@@ -10,6 +10,13 @@
|
|
|
10
10
|
* turned off (403), then the turn cap (429), then a stale pending action
|
|
11
11
|
* (409). A person's turn is only checked for the last one.
|
|
12
12
|
*/
|
|
13
|
+
/**
|
|
14
|
+
* `client.start` was called with options that cannot start a session, for
|
|
15
|
+
* example an artifact Edit workflow without its `target`. Nothing was sent.
|
|
16
|
+
*/
|
|
17
|
+
export declare class InvalidStartOptionsError extends Error {
|
|
18
|
+
constructor(message: string);
|
|
19
|
+
}
|
|
13
20
|
/** A request the server answered with a non-2xx status. */
|
|
14
21
|
export declare class SessionRequestError extends Error {
|
|
15
22
|
/** HTTP status of the answer. */
|
package/dist/src/errors.js
CHANGED
|
@@ -10,6 +10,16 @@
|
|
|
10
10
|
* turned off (403), then the turn cap (429), then a stale pending action
|
|
11
11
|
* (409). A person's turn is only checked for the last one.
|
|
12
12
|
*/
|
|
13
|
+
/**
|
|
14
|
+
* `client.start` was called with options that cannot start a session, for
|
|
15
|
+
* example an artifact Edit workflow without its `target`. Nothing was sent.
|
|
16
|
+
*/
|
|
17
|
+
export class InvalidStartOptionsError extends Error {
|
|
18
|
+
constructor(message) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.name = 'InvalidStartOptionsError';
|
|
21
|
+
}
|
|
22
|
+
}
|
|
13
23
|
/** A request the server answered with a non-2xx status. */
|
|
14
24
|
export class SessionRequestError extends Error {
|
|
15
25
|
/** HTTP status of the answer. */
|
package/dist/src/policies.d.ts
CHANGED
|
@@ -4,13 +4,22 @@
|
|
|
4
4
|
* A policy sees the session state and returns what to do next. It does not
|
|
5
5
|
* send anything; `runToCompletion` (or the caller's own loop) does.
|
|
6
6
|
*/
|
|
7
|
+
import type { CommandArgs } from './commands.js';
|
|
7
8
|
import type { Decision, SessionState, TurnStreamError } from './types.js';
|
|
8
9
|
/** Free text to send as a chat message. */
|
|
9
10
|
export interface Say {
|
|
10
11
|
say: string;
|
|
11
12
|
}
|
|
12
|
-
/**
|
|
13
|
-
|
|
13
|
+
/**
|
|
14
|
+
* A slash command to run, one the session offers (`state.availableCommands`),
|
|
15
|
+
* as `session.runCommand` runs it: for example `{ command: 'complete' }`.
|
|
16
|
+
*/
|
|
17
|
+
export interface RunCommand {
|
|
18
|
+
command: string;
|
|
19
|
+
args?: CommandArgs;
|
|
20
|
+
}
|
|
21
|
+
/** What a policy wants done: a decision, a chat message, a command, or stop here. */
|
|
22
|
+
export type PolicyResult = Decision | Say | RunCommand | 'stop';
|
|
14
23
|
/** What the driver loop tells a policy about the turn before this call. */
|
|
15
24
|
export interface PolicyInfo {
|
|
16
25
|
/**
|
|
@@ -29,6 +38,7 @@ export interface PolicyInfo {
|
|
|
29
38
|
}
|
|
30
39
|
export type Policy = (state: SessionState, info?: PolicyInfo) => PolicyResult | Promise<PolicyResult>;
|
|
31
40
|
export declare function isSay(result: PolicyResult): result is Say;
|
|
41
|
+
export declare function isRunCommand(result: PolicyResult): result is RunCommand;
|
|
32
42
|
/**
|
|
33
43
|
* Takes the path the workflow itself recommends, with no judgement: the
|
|
34
44
|
* recommended option of every question, approve every spec file, plan and
|
|
@@ -46,8 +56,24 @@ export declare function recommendedPolicy(): Policy;
|
|
|
46
56
|
* "go on". Cards are still answered by `policy`.
|
|
47
57
|
*/
|
|
48
58
|
export declare function sayWhenIdle(text: string, policy: Policy): Policy;
|
|
49
|
-
/**
|
|
50
|
-
|
|
59
|
+
/**
|
|
60
|
+
* Wraps `policy` so the run ends an Edit session once it is done: an Edit
|
|
61
|
+
* session (spec or website artifact) never ends on its own, only when someone
|
|
62
|
+
* runs `complete`. When an Edit session waits on no card, offers `complete`
|
|
63
|
+
* and can run it now, and has kept a change (an edit review with a file
|
|
64
|
+
* accepted, or an artifact revision kept), `complete` is run. Anything else
|
|
65
|
+
* goes to `policy`. At `interview` autonomy `runToCompletion` hands over
|
|
66
|
+
* instead of running it: completing is the user's decision.
|
|
67
|
+
*
|
|
68
|
+
* Generate sessions are left to `policy`: they end on their own at their last
|
|
69
|
+
* approval, and completing one that is idle mid-way would cut it short. The
|
|
70
|
+
* kept-change guard keeps it from completing an Edit session that has changed
|
|
71
|
+
* nothing yet, for example one that answered a question and then asked
|
|
72
|
+
* another in text.
|
|
73
|
+
*/
|
|
74
|
+
export declare function completeWhenIdle(policy: Policy): Policy;
|
|
75
|
+
/** One step of a script: a fixed decision, message or command, or a function of the state. */
|
|
76
|
+
export type ScriptStep = Decision | Say | RunCommand | ((state: SessionState) => Decision | Say | RunCommand);
|
|
51
77
|
/**
|
|
52
78
|
* Plays `steps` in order, one per turn that runs. Stops when the steps are
|
|
53
79
|
* used up, or when a step's decision is for a different card kind than the one
|
package/dist/src/policies.js
CHANGED
|
@@ -8,6 +8,9 @@ import { decide } from "./decisions.js";
|
|
|
8
8
|
export function isSay(result) {
|
|
9
9
|
return typeof result === 'object' && 'say' in result;
|
|
10
10
|
}
|
|
11
|
+
export function isRunCommand(result) {
|
|
12
|
+
return typeof result === 'object' && 'command' in result;
|
|
13
|
+
}
|
|
11
14
|
/**
|
|
12
15
|
* The option ids the `recommended` policy picks for one question: the options
|
|
13
16
|
* marked recommended (the first one only, for a single-select question), or
|
|
@@ -90,6 +93,46 @@ export function recommendedPolicy() {
|
|
|
90
93
|
export function sayWhenIdle(text, policy) {
|
|
91
94
|
return (state, info) => (state.pendingAction === null ? { say: text } : policy(state, info));
|
|
92
95
|
}
|
|
96
|
+
/**
|
|
97
|
+
* Wraps `policy` so the run ends an Edit session once it is done: an Edit
|
|
98
|
+
* session (spec or website artifact) never ends on its own, only when someone
|
|
99
|
+
* runs `complete`. When an Edit session waits on no card, offers `complete`
|
|
100
|
+
* and can run it now, and has kept a change (an edit review with a file
|
|
101
|
+
* accepted, or an artifact revision kept), `complete` is run. Anything else
|
|
102
|
+
* goes to `policy`. At `interview` autonomy `runToCompletion` hands over
|
|
103
|
+
* instead of running it: completing is the user's decision.
|
|
104
|
+
*
|
|
105
|
+
* Generate sessions are left to `policy`: they end on their own at their last
|
|
106
|
+
* approval, and completing one that is idle mid-way would cut it short. The
|
|
107
|
+
* kept-change guard keeps it from completing an Edit session that has changed
|
|
108
|
+
* nothing yet, for example one that answered a question and then asked
|
|
109
|
+
* another in text.
|
|
110
|
+
*/
|
|
111
|
+
export function completeWhenIdle(policy) {
|
|
112
|
+
return (state, info) => {
|
|
113
|
+
const complete = state.availableCommands?.find((c) => c.name === 'complete');
|
|
114
|
+
const canComplete = state.workflowId?.startsWith('edit-') === true &&
|
|
115
|
+
state.phase === 'idle' &&
|
|
116
|
+
state.pendingAction === null &&
|
|
117
|
+
complete !== undefined &&
|
|
118
|
+
complete.blockedReason === undefined &&
|
|
119
|
+
state.decisions.some(keptAChange);
|
|
120
|
+
return canComplete ? { command: 'complete' } : policy(state, info);
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Whether a decision kept a change: an edit review with at least one file
|
|
125
|
+
* accepted, or an artifact revision kept (`keep`, or `approve`). A question's answer, a discarded
|
|
126
|
+
* edit and a discarded revision change nothing.
|
|
127
|
+
*/
|
|
128
|
+
function keptAChange(decision) {
|
|
129
|
+
if (decision.kind === 'edit-decision') {
|
|
130
|
+
return Object.values(decision.decisions).includes('accept');
|
|
131
|
+
}
|
|
132
|
+
// The Edit workflow also keeps a revision on `approve`, the Generate wording.
|
|
133
|
+
return (decision.kind === 'artifact-revision' &&
|
|
134
|
+
(decision.decision === 'keep' || decision.decision === 'approve'));
|
|
135
|
+
}
|
|
93
136
|
/**
|
|
94
137
|
* Plays `steps` in order, one per turn that runs. Stops when the steps are
|
|
95
138
|
* used up, or when a step's decision is for a different card kind than the one
|
|
@@ -115,10 +158,11 @@ export function scriptedPolicy(steps) {
|
|
|
115
158
|
if (step === undefined)
|
|
116
159
|
return 'stop';
|
|
117
160
|
const result = typeof step === 'function' ? step(state) : step;
|
|
118
|
-
|
|
161
|
+
const answersCard = !isSay(result) && !isRunCommand(result);
|
|
162
|
+
if (answersCard && result.kind !== state.pendingAction?.kind)
|
|
119
163
|
return 'stop';
|
|
120
164
|
next += 1;
|
|
121
|
-
lastAnswered =
|
|
165
|
+
lastAnswered = answersCard ? pendingId : null;
|
|
122
166
|
return result;
|
|
123
167
|
};
|
|
124
168
|
}
|
package/dist/src/run.d.ts
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* The driver loop: read state, ask the policy, send, repeat.
|
|
3
3
|
*/
|
|
4
4
|
import { type SessionHandle, type TurnOptions } from './client.js';
|
|
5
|
-
import { type Policy, type Say } from './policies.js';
|
|
5
|
+
import { type Policy, type RunCommand, type Say } from './policies.js';
|
|
6
6
|
import type { Decision, PendingActionKind, SessionState, TurnStreamError } from './types.js';
|
|
7
7
|
/** Most turns `runToCompletion` sends before it stops, unless told otherwise. */
|
|
8
8
|
export declare const DRIVER_MAX_TURNS = 80;
|
|
@@ -21,7 +21,7 @@ export type RunEndReason =
|
|
|
21
21
|
| 'policy_stop'
|
|
22
22
|
/** The turn limit was reached. */
|
|
23
23
|
| 'max_turns'
|
|
24
|
-
/** `interview` autonomy met a card that needs a person. */
|
|
24
|
+
/** `interview` autonomy met a card, or a command, that needs a person. */
|
|
25
25
|
| 'handover'
|
|
26
26
|
/** A turn ended with a stream error. */
|
|
27
27
|
| 'turn_error'
|
|
@@ -40,7 +40,7 @@ export interface RunTurnRecord {
|
|
|
40
40
|
pendingKind: PendingActionKind | null;
|
|
41
41
|
pendingActionId: string | null;
|
|
42
42
|
/** What the policy chose. */
|
|
43
|
-
action: Decision | Say;
|
|
43
|
+
action: Decision | Say | RunCommand;
|
|
44
44
|
/** What the agent said in the turn. Empty for a refused turn. */
|
|
45
45
|
assistantText: string;
|
|
46
46
|
durationMs: number;
|
package/dist/src/run.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import { DEFAULT_POLL_MS } from "./client.js";
|
|
5
5
|
import { AgentDrivingDisabledError, AgentTurnCapReachedError, InvalidDecisionError, PendingActionMismatchError, ReadOnlyTokenError, SessionBusyError, } from "./errors.js";
|
|
6
|
-
import { isSay } from "./policies.js";
|
|
6
|
+
import { isRunCommand, isSay, } from "./policies.js";
|
|
7
7
|
/** Most turns `runToCompletion` sends before it stops, unless told otherwise. */
|
|
8
8
|
export const DRIVER_MAX_TURNS = 80;
|
|
9
9
|
/** The kinds a driver at `interview` autonomy may answer. */
|
|
@@ -15,6 +15,36 @@ export const INTERVIEW_AUTONOMY_KINDS = new Set([
|
|
|
15
15
|
const defaultSleep = (ms) => new Promise((resolve) => {
|
|
16
16
|
setTimeout(resolve, ms);
|
|
17
17
|
});
|
|
18
|
+
/** Whether the session lists `action`'s command as one that changes nothing (`btw`). */
|
|
19
|
+
function isReadOnlyCommand(state, action) {
|
|
20
|
+
return state.availableCommands?.find((c) => c.name === action.command)?.readOnly === true;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* A command's result as a turn of the run. An `action` command (`complete`
|
|
24
|
+
* of a spec session) and a side question run no saved turn: their result has
|
|
25
|
+
* no stream text, or the answer's, and the state read after them, if any.
|
|
26
|
+
*/
|
|
27
|
+
function commandTurn(result) {
|
|
28
|
+
switch (result.kind) {
|
|
29
|
+
case 'turn':
|
|
30
|
+
return result.turn;
|
|
31
|
+
case 'action':
|
|
32
|
+
return {
|
|
33
|
+
assistantText: '',
|
|
34
|
+
error: null,
|
|
35
|
+
turnStillRunning: false,
|
|
36
|
+
state: result.state,
|
|
37
|
+
...(result.stateError === undefined ? {} : { stateError: result.stateError }),
|
|
38
|
+
};
|
|
39
|
+
case 'answer':
|
|
40
|
+
return {
|
|
41
|
+
assistantText: result.text,
|
|
42
|
+
error: result.error,
|
|
43
|
+
turnStillRunning: false,
|
|
44
|
+
state: null,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
}
|
|
18
48
|
/**
|
|
19
49
|
* Drives `session` with `policy` until the session completes, the policy
|
|
20
50
|
* stops, the autonomy level hands over, a turn fails, or the turn limit is
|
|
@@ -64,6 +94,11 @@ export async function runToCompletion(session, policy, options = {}) {
|
|
|
64
94
|
const action = await policy(state, { ...info });
|
|
65
95
|
if (action === 'stop')
|
|
66
96
|
return end('policy_stop');
|
|
97
|
+
// A command that changes the session (complete, goback) is an approval:
|
|
98
|
+
// at `interview` it is the user's, as it is for the MCP servers.
|
|
99
|
+
if (autonomy === 'interview' && isRunCommand(action) && !isReadOnlyCommand(state, action)) {
|
|
100
|
+
return end('handover');
|
|
101
|
+
}
|
|
67
102
|
const record = {
|
|
68
103
|
index: turns.length + 1,
|
|
69
104
|
pendingKind: pending?.kind ?? null,
|
|
@@ -82,6 +117,9 @@ export async function runToCompletion(session, policy, options = {}) {
|
|
|
82
117
|
pending: pending ?? undefined,
|
|
83
118
|
});
|
|
84
119
|
}
|
|
120
|
+
else if (isRunCommand(action)) {
|
|
121
|
+
result = commandTurn(await session.runCommand(action.command, action.args, { ...options.turn, state }));
|
|
122
|
+
}
|
|
85
123
|
else {
|
|
86
124
|
if (pending === null) {
|
|
87
125
|
throw new InvalidDecisionError(`The policy returned a "${action.kind}" decision, but the session waits on no card.`);
|
package/package.json
CHANGED