@myspec/sdk 0.1.2 → 0.2.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/README.md +39 -3
- package/dist/index.d.ts +5 -4
- package/dist/index.js +4 -3
- package/dist/src/client.d.ts +75 -0
- package/dist/src/client.js +146 -2
- package/dist/src/commands.d.ts +50 -0
- package/dist/src/commands.js +50 -0
- package/dist/src/errors.d.ts +18 -0
- package/dist/src/errors.js +25 -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/dist/src/types.d.ts +41 -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,21 +57,55 @@ 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. |
|
|
61
64
|
| `session.send(text, options?)` | Sends a free-text turn. |
|
|
62
65
|
| `session.waitForTurn({ longPollMs? })` | Waits until no turn is running. With `longPollMs` each read is held by the server, so it needs a few requests instead of one per `pollMs`. |
|
|
66
|
+
| `session.runCommand(name, args?, options?)` | Runs a slash command the session offers (`complete`, `goback`, `btw`), as the webapp runs it. |
|
|
63
67
|
| `decide.*`, `validateDecision` | Builds and checks a decision for each card kind. |
|
|
64
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. |
|
|
65
70
|
| `runToCompletion(session, policy, options?)` | The read, decide, send loop, with a run report. |
|
|
66
71
|
|
|
67
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.
|
|
68
73
|
|
|
69
|
-
A `spec-decision` pending action can carry `preview` (the diff against the previous revision, or the start of a first one), and `state.localBridge` says whether your `reverse` bridge is connected, which a brownfield turn needs. `state.lastAssistantMessage` is the newest reply (`messageId`, `index`, `text`, `cardTypes`), `null` before the first. Read it when a turn outlasted your `waitMs`, and when the session waits on no card: it may have asked a question as text. `listMessages()` pages the whole transcript: pass `nextCursor` as `after`. A cursor the transcript no longer holds is a `SessionRequestError` with code `CURSOR_NOT_FOUND`.
|
|
74
|
+
A `spec-decision` pending action can carry `preview` (the diff against the previous revision, or the start of a first one), an `edit-decision` one `previews` (one diff per edited file, against the revision before the edit, at most 5, with `previewsOmitted` for the rest), and `state.localBridge` says whether your `reverse` bridge is connected, which a brownfield turn needs. `state.lastAssistantMessage` is the newest reply (`messageId`, `index`, `text`, `cardTypes`), `null` before the first. Read it when a turn outlasted your `waitMs`, and when the session waits on no card: it may have asked a question as text. `listMessages()` pages the whole transcript: pass `nextCursor` as `after`. A cursor the transcript no longer holds is a `SessionRequestError` with code `CURSOR_NOT_FOUND`.
|
|
70
75
|
|
|
71
76
|
Refusals a driver should handle are typed errors: `PendingActionMismatchError` (read the state again), `SessionBusyError` (wait for the running turn), `AgentTurnCapReachedError` and `AgentDrivingDisabledError` (a person must continue), `ReadOnlyTokenError` (use a read-write token). `runToCompletion` handles the first two itself and ends with `agent_refused` on the other three.
|
|
72
77
|
|
|
78
|
+
**Slash commands.** `state.availableCommands` lists the commands the session offers now, from the registry the webapp's palette uses: `name`, `args` (with `optional` and, for some, the accepted `values`), `readOnly`, `runsAs` and `blockedReason` when one cannot run yet. `session.runCommand(name, args)` checks the call against that list and throws `CommandNotAvailableError` (with `code`) before sending anything when it does not fit. Then it runs the command as `runsAs` says:
|
|
79
|
+
|
|
80
|
+
- `action` (`complete` of a spec session): `POST /api/v1/chat/:id/commands`. No model runs. The result is `{ kind: 'action', state }`, the state read after it. An edit session ends only this way.
|
|
81
|
+
- `turn` (`goback`, and `complete` of a website session): a chat turn whose one part is `data-slash-command`, with the pending action's id (or `none`). The result is `{ kind: 'turn', turn }`. `goback` takes `text`, or `explicitStage` to skip the question about which stage.
|
|
82
|
+
- `side-question` (`btw`): `POST /api/v1/chat/:id/btw`. The result is `{ kind: 'answer', text }`. Nothing is saved, and the pending action does not change.
|
|
83
|
+
|
|
84
|
+
Pass `options.state` when you have just read the state, to skip the first read.
|
|
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
|
+
|
|
73
109
|
## Agent-driven turns
|
|
74
110
|
|
|
75
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.
|
|
@@ -94,7 +130,7 @@ A turn result with `state: null` and a `stateError` means the turn ran but its s
|
|
|
94
130
|
## What works today
|
|
95
131
|
|
|
96
132
|
- Against the ai-agent directly, and in-process (`createInProcessAgent` in the ai-agent's test support): everything above.
|
|
97
|
-
- Through the webapp's chat proxy: everything above. The proxy forwards the chat turn, `/state` (with `waitMs`) and `/messages` (with `after` and `limit`).
|
|
133
|
+
- Through the webapp's chat proxy: everything above. The proxy forwards the chat turn, `/btw`, `/commands`, `/state` (with `waitMs`) and `/messages` (with `after` and `limit`).
|
|
98
134
|
- An agent-driven turn (`actorKind: 'ai'`, or an org agent token) that continues a session is refused until the `ai-agent-driven-sessions` flag is on in the environment. It ships off. The opening turn of a session runs either way.
|
|
99
135
|
|
|
100
136
|
## Rules
|
package/dist/index.d.ts
CHANGED
|
@@ -5,10 +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 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
|
+
export { checkCommand, type CommandArgs, type CommandResult } from './src/commands.js';
|
|
9
10
|
export { MCQ_OTHER_PREFIX, decide, validateDecision, type PendingOf } from './src/decisions.js';
|
|
10
|
-
export { AgentDrivingDisabledError, AgentTurnCapReachedError, InvalidDecisionError, PendingActionMismatchError, ReadOnlyTokenError, SessionBusyError, SessionRequestError, TurnSettleTimeoutError, TurnTimeoutError, } from './src/errors.js';
|
|
11
|
-
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';
|
|
12
13
|
export { DRIVER_MAX_TURNS, INTERVIEW_AUTONOMY_KINDS, runToCompletion, type AutonomyLevel, type RunEndReason, type RunOptions, type RunReport, type RunTurnRecord, } from './src/run.js';
|
|
13
14
|
export { readTurnStream, type TurnStream, type TurnStreamSnapshot } from './src/stream.js';
|
|
14
|
-
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 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';
|
|
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,10 +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
|
+
export { checkCommand } from "./src/commands.js";
|
|
9
10
|
export { MCQ_OTHER_PREFIX, decide, validateDecision } from "./src/decisions.js";
|
|
10
|
-
export { AgentDrivingDisabledError, AgentTurnCapReachedError, InvalidDecisionError, PendingActionMismatchError, ReadOnlyTokenError, SessionBusyError, SessionRequestError, TurnSettleTimeoutError, TurnTimeoutError, } from "./src/errors.js";
|
|
11
|
-
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";
|
|
12
13
|
export { DRIVER_MAX_TURNS, INTERVIEW_AUTONOMY_KINDS, runToCompletion, } from "./src/run.js";
|
|
13
14
|
export { readTurnStream } from "./src/stream.js";
|
|
14
15
|
export { DECISION_PART_TYPE, NO_PENDING_ACTION_ID, PENDING_ACTION_KINDS, } from "./src/types.js";
|
package/dist/src/client.d.ts
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
* `/api/v1/chat/...`: the ai-agent, or a proxy in front of it. In a test it can
|
|
11
11
|
* be the `fetch` of an in-process ai-agent app, with no network at all.
|
|
12
12
|
*/
|
|
13
|
+
import { type CommandArgs, type CommandResult } from './commands.js';
|
|
13
14
|
import { type Decision, type PendingAction, type SessionMessagesPage, type SessionState, type TurnResult } from './types.js';
|
|
14
15
|
/** Client type the ai-agent segments analytics on, unless the caller sets one. */
|
|
15
16
|
export declare const DEFAULT_CLIENT_TYPE = "sdk";
|
|
@@ -83,6 +84,15 @@ export interface TurnOptions {
|
|
|
83
84
|
*/
|
|
84
85
|
settleMs?: number;
|
|
85
86
|
}
|
|
87
|
+
/** Choices of `runCommand`. */
|
|
88
|
+
export interface CommandOptions extends TurnOptions {
|
|
89
|
+
/**
|
|
90
|
+
* The state you just read, to check the command against instead of reading
|
|
91
|
+
* it again. Pass it only when it is fresh: a stale one can name a card the
|
|
92
|
+
* session no longer waits on, and the server then refuses the turn.
|
|
93
|
+
*/
|
|
94
|
+
state?: SessionState;
|
|
95
|
+
}
|
|
86
96
|
/** Choices of a free-text turn. */
|
|
87
97
|
export interface SendOptions extends TurnOptions {
|
|
88
98
|
/** The card on screen, so the stale-answer guard applies to the reply. */
|
|
@@ -152,9 +162,74 @@ export interface SessionHandle {
|
|
|
152
162
|
* `TurnTimeoutError` when a turn outlasts `timeoutMs`.
|
|
153
163
|
*/
|
|
154
164
|
waitForTurn(options?: WaitOptions): Promise<SessionState>;
|
|
165
|
+
/**
|
|
166
|
+
* Runs a slash command the session offers (`state.availableCommands`), the
|
|
167
|
+
* way the webapp runs it: `complete`, `goback`, `btw`, and any the server
|
|
168
|
+
* adds. Reads the state first and checks `name` and `args` against it, so
|
|
169
|
+
* a command the session does not offer throws `CommandNotAvailableError`
|
|
170
|
+
* before anything is sent.
|
|
171
|
+
*
|
|
172
|
+
* - `action` (`complete` of a spec session): no model runs; the result has
|
|
173
|
+
* the state read after it.
|
|
174
|
+
* - `turn` (`goback`): a chat turn, with the pending action's id (or the
|
|
175
|
+
* reserved "none") so the stale-answer guard applies. `options` work as
|
|
176
|
+
* for `send`.
|
|
177
|
+
* - `side-question` (`btw`): the answer's text. Nothing is saved, and the
|
|
178
|
+
* pending action does not change. `options.waitMs` bounds the wait.
|
|
179
|
+
*
|
|
180
|
+
* Pass `options.state` to skip the first state read.
|
|
181
|
+
*/
|
|
182
|
+
runCommand(name: string, args?: CommandArgs, options?: CommandOptions): Promise<CommandResult>;
|
|
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;
|
|
155
222
|
}
|
|
156
223
|
export interface SessionClient {
|
|
157
224
|
/** A handle on an existing session. Sends nothing. */
|
|
158
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>;
|
|
159
234
|
}
|
|
160
235
|
export declare function createClient(options: ClientOptions): SessionClient;
|
package/dist/src/client.js
CHANGED
|
@@ -10,8 +10,9 @@
|
|
|
10
10
|
* `/api/v1/chat/...`: the ai-agent, or a proxy in front of it. In a test it can
|
|
11
11
|
* be the `fetch` of an in-process ai-agent app, with no network at all.
|
|
12
12
|
*/
|
|
13
|
+
import { checkCommand } from "./commands.js";
|
|
13
14
|
import { validateDecision } from "./decisions.js";
|
|
14
|
-
import { InvalidDecisionError, TurnSettleTimeoutError, TurnTimeoutError, errorFromResponse, } from "./errors.js";
|
|
15
|
+
import { InvalidDecisionError, InvalidStartOptionsError, SessionRequestError, TurnSettleTimeoutError, TurnTimeoutError, errorFromResponse, } from "./errors.js";
|
|
15
16
|
import { readTurnStream } from "./stream.js";
|
|
16
17
|
import { DECISION_PART_TYPE, NO_PENDING_ACTION_ID, } from "./types.js";
|
|
17
18
|
/** Client type the ai-agent segments analytics on, unless the caller sets one. */
|
|
@@ -33,6 +34,8 @@ export const TURN_SETTLE_POLL_MS = 500;
|
|
|
33
34
|
* answer while a turn runs, up to this, and answers as soon as it ends.
|
|
34
35
|
*/
|
|
35
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';
|
|
36
39
|
const defaultSleep = (ms) => new Promise((resolve) => {
|
|
37
40
|
setTimeout(resolve, ms);
|
|
38
41
|
});
|
|
@@ -230,11 +233,76 @@ export function createClient(options) {
|
|
|
230
233
|
...(await stateAfterTurn(turn.settleMs)),
|
|
231
234
|
};
|
|
232
235
|
};
|
|
236
|
+
/** Asks a side question; reads its answer within `waitMs`, if given. */
|
|
237
|
+
const askSideQuestion = async (name, parts, turn) => {
|
|
238
|
+
let stream;
|
|
239
|
+
const ended = (async () => {
|
|
240
|
+
const response = await request(`${chatPath}/btw`, {
|
|
241
|
+
method: 'POST',
|
|
242
|
+
body: JSON.stringify({
|
|
243
|
+
parts,
|
|
244
|
+
...(turn.modelId === undefined ? {} : { modelId: turn.modelId }),
|
|
245
|
+
}),
|
|
246
|
+
});
|
|
247
|
+
stream = readTurnStream(response.body);
|
|
248
|
+
await stream.drained;
|
|
249
|
+
return true;
|
|
250
|
+
})();
|
|
251
|
+
const finished = turn.waitMs === undefined ? await ended : await withinBudget(ended, turn.waitMs);
|
|
252
|
+
if (finished === undefined)
|
|
253
|
+
ended.catch(() => undefined);
|
|
254
|
+
const { assistantText, error } = stream?.snapshot() ?? { assistantText: '', error: null };
|
|
255
|
+
return {
|
|
256
|
+
kind: 'answer',
|
|
257
|
+
command: name,
|
|
258
|
+
text: assistantText,
|
|
259
|
+
error,
|
|
260
|
+
stillRunning: finished === undefined,
|
|
261
|
+
};
|
|
262
|
+
};
|
|
263
|
+
const runCommand = async (name, args = {}, turn = {}) => {
|
|
264
|
+
const state = turn.state ?? (await readState());
|
|
265
|
+
const command = checkCommand(state, name, args);
|
|
266
|
+
const part = { type: 'data-slash-command', data: { command: name, ...args } };
|
|
267
|
+
switch (command.runsAs) {
|
|
268
|
+
case 'action': {
|
|
269
|
+
const sent = request(`${chatPath}/commands`, {
|
|
270
|
+
method: 'POST',
|
|
271
|
+
body: JSON.stringify({
|
|
272
|
+
command: name,
|
|
273
|
+
args,
|
|
274
|
+
...(options.actorKind === undefined ? {} : { actorKind: options.actorKind }),
|
|
275
|
+
}),
|
|
276
|
+
});
|
|
277
|
+
const answered = turn.waitMs === undefined ? await sent : await withinBudget(sent, turn.waitMs);
|
|
278
|
+
if (answered === undefined) {
|
|
279
|
+
sent.catch(() => undefined);
|
|
280
|
+
return { kind: 'action', command: name, state: null, unconfirmed: true };
|
|
281
|
+
}
|
|
282
|
+
// The command ran: a failed read after it must not look like a failed command.
|
|
283
|
+
try {
|
|
284
|
+
return { kind: 'action', command: name, state: await readState() };
|
|
285
|
+
}
|
|
286
|
+
catch (stateError) {
|
|
287
|
+
return { kind: 'action', command: name, state: null, stateError };
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
case 'side-question':
|
|
291
|
+
return askSideQuestion(name, [part], turn);
|
|
292
|
+
case 'turn':
|
|
293
|
+
return {
|
|
294
|
+
kind: 'turn',
|
|
295
|
+
command: name,
|
|
296
|
+
turn: await sendTurn([part], state.pendingAction?.id ?? NO_PENDING_ACTION_ID, turn),
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
};
|
|
233
300
|
return {
|
|
234
301
|
sessionId,
|
|
235
302
|
getState,
|
|
236
303
|
listMessages,
|
|
237
304
|
waitForTurn,
|
|
305
|
+
runCommand,
|
|
238
306
|
respond(pending, decision, turn) {
|
|
239
307
|
validateDecision(pending, decision);
|
|
240
308
|
const part = { type: DECISION_PART_TYPE[decision.kind], data: decision.data };
|
|
@@ -249,5 +317,81 @@ export function createClient(options) {
|
|
|
249
317
|
},
|
|
250
318
|
};
|
|
251
319
|
}
|
|
252
|
-
|
|
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
|
+
};
|
|
253
397
|
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Slash commands, as a session offers them (`SessionState.availableCommands`).
|
|
3
|
+
*
|
|
4
|
+
* The server lists the commands from the registry the webapp's palette uses,
|
|
5
|
+
* with how each runs. This file only checks a call against that list before
|
|
6
|
+
* anything is sent, so the SDK keeps no list of its own and a command the
|
|
7
|
+
* server adds works without an SDK change.
|
|
8
|
+
*/
|
|
9
|
+
import type { SessionCommand, SessionState, TurnResult, TurnStreamError } from './types.js';
|
|
10
|
+
/** Arguments of a command, by the names `SessionCommand.args` lists. */
|
|
11
|
+
export type CommandArgs = Readonly<Record<string, string>>;
|
|
12
|
+
/** What `SessionHandle.runCommand` did. */
|
|
13
|
+
export type CommandResult =
|
|
14
|
+
/**
|
|
15
|
+
* An `action` command was sent. `state` is read after it; `null` with
|
|
16
|
+
* `stateError` when that read failed (the command still ran: do not run it
|
|
17
|
+
* again). `unconfirmed` is `true` when `waitMs` ran out before the server
|
|
18
|
+
* answered: it may still take effect, so read the state before trying again.
|
|
19
|
+
*/
|
|
20
|
+
{
|
|
21
|
+
kind: 'action';
|
|
22
|
+
command: string;
|
|
23
|
+
state: SessionState | null;
|
|
24
|
+
stateError?: unknown;
|
|
25
|
+
unconfirmed?: true;
|
|
26
|
+
}
|
|
27
|
+
/** A `turn` command ran as a chat turn, like `send`. */
|
|
28
|
+
| {
|
|
29
|
+
kind: 'turn';
|
|
30
|
+
command: string;
|
|
31
|
+
turn: TurnResult;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* A `side-question` command was answered. Nothing was saved: the session's
|
|
35
|
+
* turn and its pending action are as they were.
|
|
36
|
+
*/
|
|
37
|
+
| {
|
|
38
|
+
kind: 'answer';
|
|
39
|
+
command: string;
|
|
40
|
+
text: string;
|
|
41
|
+
error: TurnStreamError | null;
|
|
42
|
+
/** `true` when the wait ended before the answer did; `text` is what came. */
|
|
43
|
+
stillRunning: boolean;
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* The command `name` of `state`, checked with `args`. Throws
|
|
47
|
+
* {@link CommandNotAvailableError} when the session does not offer it now or
|
|
48
|
+
* the arguments do not fit. Sends nothing.
|
|
49
|
+
*/
|
|
50
|
+
export declare function checkCommand(state: SessionState, name: string, args: CommandArgs): SessionCommand;
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Slash commands, as a session offers them (`SessionState.availableCommands`).
|
|
3
|
+
*
|
|
4
|
+
* The server lists the commands from the registry the webapp's palette uses,
|
|
5
|
+
* with how each runs. This file only checks a call against that list before
|
|
6
|
+
* anything is sent, so the SDK keeps no list of its own and a command the
|
|
7
|
+
* server adds works without an SDK change.
|
|
8
|
+
*/
|
|
9
|
+
import { CommandNotAvailableError } from "./errors.js";
|
|
10
|
+
/**
|
|
11
|
+
* The command `name` of `state`, checked with `args`. Throws
|
|
12
|
+
* {@link CommandNotAvailableError} when the session does not offer it now or
|
|
13
|
+
* the arguments do not fit. Sends nothing.
|
|
14
|
+
*/
|
|
15
|
+
export function checkCommand(state, name, args) {
|
|
16
|
+
const commands = state.availableCommands;
|
|
17
|
+
if (commands === undefined) {
|
|
18
|
+
throw new CommandNotAvailableError('COMMANDS_NOT_LISTED', 'This MySpec server does not list session commands yet, so none can be run.');
|
|
19
|
+
}
|
|
20
|
+
const command = commands.find((c) => c.name === name);
|
|
21
|
+
if (command === undefined) {
|
|
22
|
+
const offered = commands.map((c) => c.name).join(', ') || 'none';
|
|
23
|
+
throw new CommandNotAvailableError('COMMAND_NOT_AVAILABLE', `This session does not offer the command "${name}" now. It offers: ${offered}.`);
|
|
24
|
+
}
|
|
25
|
+
if (command.blockedReason !== undefined) {
|
|
26
|
+
throw new CommandNotAvailableError('COMMAND_BLOCKED', `"${name}" cannot run now: ${command.blockedReason}`);
|
|
27
|
+
}
|
|
28
|
+
const allowed = new Set(command.args.map((a) => a.name));
|
|
29
|
+
const unknown = Object.keys(args).filter((key) => !allowed.has(key));
|
|
30
|
+
if (unknown.length > 0) {
|
|
31
|
+
throw new CommandNotAvailableError('INVALID_COMMAND_ARGS', `"${name}" takes no argument ${unknown.map((k) => `"${k}"`).join(', ')}. ` +
|
|
32
|
+
`Its arguments: ${command.args.map((a) => a.name).join(', ') || 'none'}.`);
|
|
33
|
+
}
|
|
34
|
+
for (const arg of command.args) {
|
|
35
|
+
const value = args[arg.name];
|
|
36
|
+
if (value === undefined) {
|
|
37
|
+
if (!arg.optional) {
|
|
38
|
+
throw new CommandNotAvailableError('INVALID_COMMAND_ARGS', `"${name}" needs the argument "${arg.name}": ${arg.description}`);
|
|
39
|
+
}
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
if (value.trim() === '') {
|
|
43
|
+
throw new CommandNotAvailableError('INVALID_COMMAND_ARGS', `The argument "${arg.name}" of "${name}" must be non-empty text.`);
|
|
44
|
+
}
|
|
45
|
+
if (arg.values !== undefined && !arg.values.includes(value)) {
|
|
46
|
+
throw new CommandNotAvailableError('INVALID_COMMAND_ARGS', `The argument "${arg.name}" of "${name}" must be one of: ${arg.values.join(', ') || 'none'}.`);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return command;
|
|
50
|
+
}
|
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. */
|
|
@@ -85,6 +92,17 @@ export declare class TurnSettleTimeoutError extends Error {
|
|
|
85
92
|
readonly settleMs: number;
|
|
86
93
|
constructor(sessionId: string, settleMs: number);
|
|
87
94
|
}
|
|
95
|
+
/**
|
|
96
|
+
* A command the session does not offer now, or arguments it does not take.
|
|
97
|
+
* Thrown before any request is sent. `code` says which:
|
|
98
|
+
* `UNKNOWN_COMMAND`, `COMMAND_NOT_AVAILABLE`, `COMMAND_BLOCKED`,
|
|
99
|
+
* `INVALID_COMMAND_ARGS`, or `COMMANDS_NOT_LISTED` (a server older than
|
|
100
|
+
* `availableCommands`).
|
|
101
|
+
*/
|
|
102
|
+
export declare class CommandNotAvailableError extends Error {
|
|
103
|
+
readonly code: string;
|
|
104
|
+
constructor(code: string, message: string);
|
|
105
|
+
}
|
|
88
106
|
/** A decision that cannot be sent as given. Thrown before any request. */
|
|
89
107
|
export declare class InvalidDecisionError extends Error {
|
|
90
108
|
constructor(message: string);
|
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. */
|
|
@@ -119,6 +129,21 @@ export class TurnSettleTimeoutError extends Error {
|
|
|
119
129
|
this.settleMs = settleMs;
|
|
120
130
|
}
|
|
121
131
|
}
|
|
132
|
+
/**
|
|
133
|
+
* A command the session does not offer now, or arguments it does not take.
|
|
134
|
+
* Thrown before any request is sent. `code` says which:
|
|
135
|
+
* `UNKNOWN_COMMAND`, `COMMAND_NOT_AVAILABLE`, `COMMAND_BLOCKED`,
|
|
136
|
+
* `INVALID_COMMAND_ARGS`, or `COMMANDS_NOT_LISTED` (a server older than
|
|
137
|
+
* `availableCommands`).
|
|
138
|
+
*/
|
|
139
|
+
export class CommandNotAvailableError extends Error {
|
|
140
|
+
code;
|
|
141
|
+
constructor(code, message) {
|
|
142
|
+
super(message);
|
|
143
|
+
this.name = 'CommandNotAvailableError';
|
|
144
|
+
this.code = code;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
122
147
|
/** A decision that cannot be sent as given. Thrown before any request. */
|
|
123
148
|
export class InvalidDecisionError extends Error {
|
|
124
149
|
constructor(message) {
|
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/dist/src/types.d.ts
CHANGED
|
@@ -191,9 +191,17 @@ export type PendingAction = {
|
|
|
191
191
|
* or the start of a first revision, when the server could read the file.
|
|
192
192
|
*/
|
|
193
193
|
preview?: SpecFilePreview;
|
|
194
|
+
/**
|
|
195
|
+
* For an `edit-decision` card: one preview per edited file, the change
|
|
196
|
+
* against the revision before the turn's edit, when the server could
|
|
197
|
+
* read the files.
|
|
198
|
+
*/
|
|
199
|
+
previews?: SpecFilePreview[];
|
|
200
|
+
/** For an `edit-decision` card: how many files got no preview (only when some did not). */
|
|
201
|
+
previewsOmitted?: number;
|
|
194
202
|
};
|
|
195
203
|
}[PendingActionKind];
|
|
196
|
-
/** A short preview of
|
|
204
|
+
/** A short preview of a spec file a `spec-decision` or `edit-decision` card asks about. */
|
|
197
205
|
export interface SpecFilePreview {
|
|
198
206
|
specFileId: string;
|
|
199
207
|
revisionNumber: number;
|
|
@@ -280,6 +288,32 @@ type SessionStateDecisionContent = {
|
|
|
280
288
|
decision: string;
|
|
281
289
|
feedback?: string;
|
|
282
290
|
};
|
|
291
|
+
/** How a command runs. See `SessionHandle.runCommand`. */
|
|
292
|
+
export type SessionCommandRunsAs = 'action' | 'turn' | 'side-question';
|
|
293
|
+
/** One argument of a session command. `name` is its key in `args`. */
|
|
294
|
+
export interface SessionCommandArg {
|
|
295
|
+
name: string;
|
|
296
|
+
optional: boolean;
|
|
297
|
+
description: string;
|
|
298
|
+
/** The values it accepts, when it accepts only some. */
|
|
299
|
+
values?: string[];
|
|
300
|
+
}
|
|
301
|
+
/** A slash command the session offers now, as the webapp's palette shows it. */
|
|
302
|
+
export interface SessionCommand {
|
|
303
|
+
name: string;
|
|
304
|
+
description: string;
|
|
305
|
+
args: SessionCommandArg[];
|
|
306
|
+
/** `true` when running it changes nothing in the session (`btw`). */
|
|
307
|
+
readOnly: boolean;
|
|
308
|
+
/**
|
|
309
|
+
* - `action`: no model runs and no turn is saved (`complete` of a spec session).
|
|
310
|
+
* - `turn`: a chat turn, like a message (`goback`, `complete` of a website session).
|
|
311
|
+
* - `side-question`: answered from the session and never saved (`btw`).
|
|
312
|
+
*/
|
|
313
|
+
runsAs: SessionCommandRunsAs;
|
|
314
|
+
/** Why it cannot run now, when it cannot. */
|
|
315
|
+
blockedReason?: string;
|
|
316
|
+
}
|
|
283
317
|
/** The answer of `GET /api/v1/chat/:id/state`. */
|
|
284
318
|
export interface SessionState {
|
|
285
319
|
sessionId: string;
|
|
@@ -338,6 +372,12 @@ export interface SessionState {
|
|
|
338
372
|
* tell, or is older than this field.
|
|
339
373
|
*/
|
|
340
374
|
localBridge?: SessionStateLocalBridge;
|
|
375
|
+
/**
|
|
376
|
+
* The slash commands the session offers now (see
|
|
377
|
+
* `SessionHandle.runCommand`). Empty once the session is completed. Absent
|
|
378
|
+
* when the server is older than this field.
|
|
379
|
+
*/
|
|
380
|
+
availableCommands?: SessionCommand[];
|
|
341
381
|
}
|
|
342
382
|
/** Whether your `reverse` bridge is connected to MySpec. */
|
|
343
383
|
export interface SessionStateLocalBridge {
|
package/package.json
CHANGED