@myspec/sdk 0.1.1 → 0.1.3
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 +12 -3
- package/dist/index.d.ts +4 -3
- package/dist/index.js +2 -1
- package/dist/src/client.d.ts +28 -0
- package/dist/src/client.js +66 -0
- package/dist/src/commands.d.ts +50 -0
- package/dist/src/commands.js +50 -0
- package/dist/src/errors.d.ts +11 -0
- package/dist/src/errors.js +15 -0
- package/dist/src/types.d.ts +78 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -42,7 +42,7 @@ if (state.pendingAction?.kind === 'spec-decision') {
|
|
|
42
42
|
|
|
43
43
|
// Or let a policy drive it.
|
|
44
44
|
const report = await runToCompletion(session, recommendedPolicy(), { autonomy: 'interview' });
|
|
45
|
-
// Without `autonomy` the run is at 'full' and approves cards too
|
|
45
|
+
// Without `autonomy` the run is at 'full' and approves cards too, like the MCP servers' default.
|
|
46
46
|
console.log(report.endReason);
|
|
47
47
|
// completed | policy_stop | max_turns | handover | turn_error | agent_refused | error
|
|
48
48
|
```
|
|
@@ -60,16 +60,25 @@ A turn that ends with a stream error ends the run with `turn_error`. Pass `turnE
|
|
|
60
60
|
| `session.respond(pending, decision, options?)` | Answers a card and reads the turn to its end. |
|
|
61
61
|
| `session.send(text, options?)` | Sends a free-text turn. |
|
|
62
62
|
| `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`. |
|
|
63
|
+
| `session.runCommand(name, args?, options?)` | Runs a slash command the session offers (`complete`, `goback`, `btw`), as the webapp runs it. |
|
|
63
64
|
| `decide.*`, `validateDecision` | Builds and checks a decision for each card kind. |
|
|
64
65
|
| `recommendedPolicy()`, `scriptedPolicy(steps)` | Ready-made policies. |
|
|
65
66
|
| `runToCompletion(session, policy, options?)` | The read, decide, send loop, with a run report. |
|
|
66
67
|
|
|
67
68
|
`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
69
|
|
|
69
|
-
`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
|
+
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
71
|
|
|
71
72
|
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
73
|
|
|
74
|
+
**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:
|
|
75
|
+
|
|
76
|
+
- `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.
|
|
77
|
+
- `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.
|
|
78
|
+
- `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.
|
|
79
|
+
|
|
80
|
+
Pass `options.state` when you have just read the state, to skip the first read.
|
|
81
|
+
|
|
73
82
|
## Agent-driven turns
|
|
74
83
|
|
|
75
84
|
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 +103,7 @@ A turn result with `state: null` and a `stateError` means the turn ran but its s
|
|
|
94
103
|
## What works today
|
|
95
104
|
|
|
96
105
|
- 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`).
|
|
106
|
+
- 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
107
|
- 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
108
|
|
|
100
109
|
## 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, 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';
|
|
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 { AgentDrivingDisabledError, AgentTurnCapReachedError, CommandNotAvailableError, InvalidDecisionError, PendingActionMismatchError, ReadOnlyTokenError, SessionBusyError, SessionRequestError, TurnSettleTimeoutError, TurnTimeoutError, } from './src/errors.js';
|
|
11
12
|
export { isSay, recommendedPolicy, sayWhenIdle, scriptedPolicy, type Policy, type PolicyInfo, type PolicyResult, 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 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
|
@@ -6,8 +6,9 @@
|
|
|
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
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";
|
|
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 { AgentDrivingDisabledError, AgentTurnCapReachedError, CommandNotAvailableError, InvalidDecisionError, PendingActionMismatchError, ReadOnlyTokenError, SessionBusyError, SessionRequestError, TurnSettleTimeoutError, TurnTimeoutError, } from "./src/errors.js";
|
|
11
12
|
export { 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";
|
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,6 +162,24 @@ 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>;
|
|
155
183
|
}
|
|
156
184
|
export interface SessionClient {
|
|
157
185
|
/** A handle on an existing session. Sends nothing. */
|
package/dist/src/client.js
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 { checkCommand } from "./commands.js";
|
|
13
14
|
import { validateDecision } from "./decisions.js";
|
|
14
15
|
import { InvalidDecisionError, TurnSettleTimeoutError, TurnTimeoutError, errorFromResponse, } from "./errors.js";
|
|
15
16
|
import { readTurnStream } from "./stream.js";
|
|
@@ -230,11 +231,76 @@ export function createClient(options) {
|
|
|
230
231
|
...(await stateAfterTurn(turn.settleMs)),
|
|
231
232
|
};
|
|
232
233
|
};
|
|
234
|
+
/** Asks a side question; reads its answer within `waitMs`, if given. */
|
|
235
|
+
const askSideQuestion = async (name, parts, turn) => {
|
|
236
|
+
let stream;
|
|
237
|
+
const ended = (async () => {
|
|
238
|
+
const response = await request(`${chatPath}/btw`, {
|
|
239
|
+
method: 'POST',
|
|
240
|
+
body: JSON.stringify({
|
|
241
|
+
parts,
|
|
242
|
+
...(turn.modelId === undefined ? {} : { modelId: turn.modelId }),
|
|
243
|
+
}),
|
|
244
|
+
});
|
|
245
|
+
stream = readTurnStream(response.body);
|
|
246
|
+
await stream.drained;
|
|
247
|
+
return true;
|
|
248
|
+
})();
|
|
249
|
+
const finished = turn.waitMs === undefined ? await ended : await withinBudget(ended, turn.waitMs);
|
|
250
|
+
if (finished === undefined)
|
|
251
|
+
ended.catch(() => undefined);
|
|
252
|
+
const { assistantText, error } = stream?.snapshot() ?? { assistantText: '', error: null };
|
|
253
|
+
return {
|
|
254
|
+
kind: 'answer',
|
|
255
|
+
command: name,
|
|
256
|
+
text: assistantText,
|
|
257
|
+
error,
|
|
258
|
+
stillRunning: finished === undefined,
|
|
259
|
+
};
|
|
260
|
+
};
|
|
261
|
+
const runCommand = async (name, args = {}, turn = {}) => {
|
|
262
|
+
const state = turn.state ?? (await readState());
|
|
263
|
+
const command = checkCommand(state, name, args);
|
|
264
|
+
const part = { type: 'data-slash-command', data: { command: name, ...args } };
|
|
265
|
+
switch (command.runsAs) {
|
|
266
|
+
case 'action': {
|
|
267
|
+
const sent = request(`${chatPath}/commands`, {
|
|
268
|
+
method: 'POST',
|
|
269
|
+
body: JSON.stringify({
|
|
270
|
+
command: name,
|
|
271
|
+
args,
|
|
272
|
+
...(options.actorKind === undefined ? {} : { actorKind: options.actorKind }),
|
|
273
|
+
}),
|
|
274
|
+
});
|
|
275
|
+
const answered = turn.waitMs === undefined ? await sent : await withinBudget(sent, turn.waitMs);
|
|
276
|
+
if (answered === undefined) {
|
|
277
|
+
sent.catch(() => undefined);
|
|
278
|
+
return { kind: 'action', command: name, state: null, unconfirmed: true };
|
|
279
|
+
}
|
|
280
|
+
// The command ran: a failed read after it must not look like a failed command.
|
|
281
|
+
try {
|
|
282
|
+
return { kind: 'action', command: name, state: await readState() };
|
|
283
|
+
}
|
|
284
|
+
catch (stateError) {
|
|
285
|
+
return { kind: 'action', command: name, state: null, stateError };
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
case 'side-question':
|
|
289
|
+
return askSideQuestion(name, [part], turn);
|
|
290
|
+
case 'turn':
|
|
291
|
+
return {
|
|
292
|
+
kind: 'turn',
|
|
293
|
+
command: name,
|
|
294
|
+
turn: await sendTurn([part], state.pendingAction?.id ?? NO_PENDING_ACTION_ID, turn),
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
};
|
|
233
298
|
return {
|
|
234
299
|
sessionId,
|
|
235
300
|
getState,
|
|
236
301
|
listMessages,
|
|
237
302
|
waitForTurn,
|
|
303
|
+
runCommand,
|
|
238
304
|
respond(pending, decision, turn) {
|
|
239
305
|
validateDecision(pending, decision);
|
|
240
306
|
const part = { type: DECISION_PART_TYPE[decision.kind], data: decision.data };
|
|
@@ -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
|
@@ -85,6 +85,17 @@ export declare class TurnSettleTimeoutError extends Error {
|
|
|
85
85
|
readonly settleMs: number;
|
|
86
86
|
constructor(sessionId: string, settleMs: number);
|
|
87
87
|
}
|
|
88
|
+
/**
|
|
89
|
+
* A command the session does not offer now, or arguments it does not take.
|
|
90
|
+
* Thrown before any request is sent. `code` says which:
|
|
91
|
+
* `UNKNOWN_COMMAND`, `COMMAND_NOT_AVAILABLE`, `COMMAND_BLOCKED`,
|
|
92
|
+
* `INVALID_COMMAND_ARGS`, or `COMMANDS_NOT_LISTED` (a server older than
|
|
93
|
+
* `availableCommands`).
|
|
94
|
+
*/
|
|
95
|
+
export declare class CommandNotAvailableError extends Error {
|
|
96
|
+
readonly code: string;
|
|
97
|
+
constructor(code: string, message: string);
|
|
98
|
+
}
|
|
88
99
|
/** A decision that cannot be sent as given. Thrown before any request. */
|
|
89
100
|
export declare class InvalidDecisionError extends Error {
|
|
90
101
|
constructor(message: string);
|
package/dist/src/errors.js
CHANGED
|
@@ -119,6 +119,21 @@ export class TurnSettleTimeoutError extends Error {
|
|
|
119
119
|
this.settleMs = settleMs;
|
|
120
120
|
}
|
|
121
121
|
}
|
|
122
|
+
/**
|
|
123
|
+
* A command the session does not offer now, or arguments it does not take.
|
|
124
|
+
* Thrown before any request is sent. `code` says which:
|
|
125
|
+
* `UNKNOWN_COMMAND`, `COMMAND_NOT_AVAILABLE`, `COMMAND_BLOCKED`,
|
|
126
|
+
* `INVALID_COMMAND_ARGS`, or `COMMANDS_NOT_LISTED` (a server older than
|
|
127
|
+
* `availableCommands`).
|
|
128
|
+
*/
|
|
129
|
+
export class CommandNotAvailableError extends Error {
|
|
130
|
+
code;
|
|
131
|
+
constructor(code, message) {
|
|
132
|
+
super(message);
|
|
133
|
+
this.name = 'CommandNotAvailableError';
|
|
134
|
+
this.code = code;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
122
137
|
/** A decision that cannot be sent as given. Thrown before any request. */
|
|
123
138
|
export class InvalidDecisionError extends Error {
|
|
124
139
|
constructor(message) {
|
package/dist/src/types.d.ts
CHANGED
|
@@ -186,8 +186,36 @@ export type PendingAction = {
|
|
|
186
186
|
kind: K;
|
|
187
187
|
accepts: (typeof DECISION_PART_TYPE)[K];
|
|
188
188
|
card: CardByKind[K] | null;
|
|
189
|
+
/**
|
|
190
|
+
* For a `spec-decision` card: the change against the previous revision,
|
|
191
|
+
* or the start of a first revision, when the server could read the file.
|
|
192
|
+
*/
|
|
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;
|
|
189
202
|
};
|
|
190
203
|
}[PendingActionKind];
|
|
204
|
+
/** A short preview of a spec file a `spec-decision` or `edit-decision` card asks about. */
|
|
205
|
+
export interface SpecFilePreview {
|
|
206
|
+
specFileId: string;
|
|
207
|
+
revisionNumber: number;
|
|
208
|
+
/** The revision the diff is against; absent for a first revision. */
|
|
209
|
+
previousRevisionNumber?: number;
|
|
210
|
+
linesAdded: number;
|
|
211
|
+
linesRemoved: number;
|
|
212
|
+
/** Unified-style diff: `+`, `-` and ` ` lines, `@@` between hunks. */
|
|
213
|
+
diff?: string;
|
|
214
|
+
/** The start of the file, for a first revision. */
|
|
215
|
+
excerpt?: string;
|
|
216
|
+
/** Present (and `true`) when the diff or the excerpt was cut. */
|
|
217
|
+
truncated?: true;
|
|
218
|
+
}
|
|
191
219
|
export type SessionPhase = 'running' | 'awaiting_input' | 'idle' | 'completed';
|
|
192
220
|
export interface SessionStateSpecFile {
|
|
193
221
|
specType: string;
|
|
@@ -260,6 +288,32 @@ type SessionStateDecisionContent = {
|
|
|
260
288
|
decision: string;
|
|
261
289
|
feedback?: string;
|
|
262
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
|
+
}
|
|
263
317
|
/** The answer of `GET /api/v1/chat/:id/state`. */
|
|
264
318
|
export interface SessionState {
|
|
265
319
|
sessionId: string;
|
|
@@ -312,6 +366,26 @@ export interface SessionState {
|
|
|
312
366
|
* field.
|
|
313
367
|
*/
|
|
314
368
|
messageCount?: number;
|
|
369
|
+
/**
|
|
370
|
+
* Your own `reverse` bridge: a brownfield turn reads local files through
|
|
371
|
+
* the bridge of the account that sends it. Absent when the server cannot
|
|
372
|
+
* tell, or is older than this field.
|
|
373
|
+
*/
|
|
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[];
|
|
381
|
+
}
|
|
382
|
+
/** Whether your `reverse` bridge is connected to MySpec. */
|
|
383
|
+
export interface SessionStateLocalBridge {
|
|
384
|
+
connected: boolean;
|
|
385
|
+
/** When the connected bridge connected (ISO-8601). */
|
|
386
|
+
connectedSince?: string;
|
|
387
|
+
/** When MySpec last heard from it (ISO-8601). */
|
|
388
|
+
lastSeenAt?: string;
|
|
315
389
|
}
|
|
316
390
|
/** The newest assistant message of a session, as the state read reports it. */
|
|
317
391
|
export interface LastAssistantMessage {
|
|
@@ -330,6 +404,10 @@ export interface SessionMessageToolCall {
|
|
|
330
404
|
name: string;
|
|
331
405
|
/** How far it got (`output-available`, `output-error`, ...), when known. */
|
|
332
406
|
state?: string;
|
|
407
|
+
/** `key=value` pairs of its main arguments (a path, a query), when recorded. */
|
|
408
|
+
summary?: string;
|
|
409
|
+
/** `true` when its result was an error. */
|
|
410
|
+
failed?: true;
|
|
333
411
|
}
|
|
334
412
|
/** A card or a decision of a message. */
|
|
335
413
|
export interface SessionMessageCard {
|
package/package.json
CHANGED