@myspec/sdk 0.1.0 → 0.1.2

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 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 (the MCP servers default to 'interview').
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
  ```
@@ -51,20 +51,23 @@ A turn that ends with a stream error ends the run with `turn_error`. Pass `turnE
51
51
 
52
52
  ## API
53
53
 
54
- | Export | Purpose |
55
- | ---------------------------------------------- | ------------------------------------------------------------------------- |
56
- | `apiTokenAuth({ apiToken, authUrl? })` | A `getToken` that trades an API token for short-lived access tokens. |
57
- | `createClient(options)` → `attach(sessionId)` | A handle on one session. Sends nothing. |
58
- | `session.getState()` | Phase, stage, pending action, spec files, decision log, agent turn count. |
59
- | `session.respond(pending, decision, options?)` | Answers a card and reads the turn to its end. |
60
- | `session.send(text, options?)` | Sends a free-text turn. |
61
- | `session.waitForTurn()` | Polls until no turn is running. |
62
- | `decide.*`, `validateDecision` | Builds and checks a decision for each card kind. |
63
- | `recommendedPolicy()`, `scriptedPolicy(steps)` | Ready-made policies. |
64
- | `runToCompletion(session, policy, options?)` | The read, decide, send loop, with a run report. |
54
+ | Export | Purpose |
55
+ | ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
56
+ | `apiTokenAuth({ apiToken, authUrl? })` | A `getToken` that trades an API token for short-lived access tokens. |
57
+ | `createClient(options)` → `attach(sessionId)` | A handle on one session. Sends nothing. |
58
+ | `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
+ | `session.listMessages({ after?, limit? })` | The saved transcript, oldest first, one page at a time. |
60
+ | `session.respond(pending, decision, options?)` | Answers a card and reads the turn to its end. |
61
+ | `session.send(text, options?)` | Sends a free-text turn. |
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
+ | `decide.*`, `validateDecision` | Builds and checks a decision for each card kind. |
64
+ | `recommendedPolicy()`, `scriptedPolicy(steps)` | Ready-made policies. |
65
+ | `runToCompletion(session, policy, options?)` | The read, decide, send loop, with a run report. |
65
66
 
66
67
  `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.
67
68
 
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`.
70
+
68
71
  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.
69
72
 
70
73
  ## Agent-driven turns
@@ -91,7 +94,7 @@ A turn result with `state: null` and a `stateError` means the turn ran but its s
91
94
  ## What works today
92
95
 
93
96
  - Against the ai-agent directly, and in-process (`createInProcessAgent` in the ai-agent's test support): everything above.
94
- - Through the webapp's chat proxy: everything above. The proxy forwards the chat turn and `/state`.
97
+ - Through the webapp's chat proxy: everything above. The proxy forwards the chat turn, `/state` (with `waitMs`) and `/messages` (with `after` and `limit`).
95
98
  - 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.
96
99
 
97
100
  ## Rules
package/dist/index.d.ts CHANGED
@@ -5,10 +5,10 @@
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, TURN_SETTLE_POLL_MS, TURN_SETTLE_TIMEOUT_MS, createClient, type ClientOptions, type SessionClient, 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 ListMessagesOptions, type SessionClient, type StateReadOptions, type SendOptions, type SessionHandle, type SessionLanguage, type TurnOptions, type WaitOptions, } from './src/client.js';
9
9
  export { MCQ_OTHER_PREFIX, decide, validateDecision, type PendingOf } from './src/decisions.js';
10
10
  export { AgentDrivingDisabledError, AgentTurnCapReachedError, InvalidDecisionError, PendingActionMismatchError, ReadOnlyTokenError, SessionBusyError, SessionRequestError, TurnSettleTimeoutError, TurnTimeoutError, } from './src/errors.js';
11
11
  export { isSay, recommendedPolicy, sayWhenIdle, scriptedPolicy, type Policy, type PolicyInfo, type PolicyResult, type Say, type ScriptStep, } from './src/policies.js';
12
12
  export { DRIVER_MAX_TURNS, INTERVIEW_AUTONOMY_KINDS, runToCompletion, type AutonomyLevel, type RunEndReason, type RunOptions, type RunReport, type RunTurnRecord, } from './src/run.js';
13
13
  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 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';
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';
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@
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, 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, createClient, } from "./src/client.js";
9
9
  export { MCQ_OTHER_PREFIX, decide, validateDecision } from "./src/decisions.js";
10
10
  export { AgentDrivingDisabledError, AgentTurnCapReachedError, InvalidDecisionError, PendingActionMismatchError, ReadOnlyTokenError, SessionBusyError, SessionRequestError, TurnSettleTimeoutError, TurnTimeoutError, } from "./src/errors.js";
11
11
  export { isSay, recommendedPolicy, sayWhenIdle, scriptedPolicy, } from "./src/policies.js";
@@ -10,7 +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 Decision, type PendingAction, type SessionState, type TurnResult } from './types.js';
13
+ import { type Decision, type PendingAction, type SessionMessagesPage, type SessionState, type TurnResult } from './types.js';
14
14
  /** Client type the ai-agent segments analytics on, unless the caller sets one. */
15
15
  export declare const DEFAULT_CLIENT_TYPE = "sdk";
16
16
  /** Default wait between two state polls of {@link SessionHandle.waitForTurn}. */
@@ -25,6 +25,11 @@ export declare const DEFAULT_WAIT_TIMEOUT_MS: number;
25
25
  export declare const TURN_SETTLE_TIMEOUT_MS = 30000;
26
26
  /** Wait between polls while a finished turn settles. */
27
27
  export declare const TURN_SETTLE_POLL_MS = 500;
28
+ /**
29
+ * Longest long-poll one state read asks the server for. The server holds the
30
+ * answer while a turn runs, up to this, and answers as soon as it ends.
31
+ */
32
+ export declare const MAX_STATE_LONG_POLL_MS = 25000;
28
33
  /** Languages a session can be started in. */
29
34
  export type SessionLanguage = 'en' | 'zh' | 'ja' | 'vi';
30
35
  export interface ClientOptions {
@@ -93,11 +98,42 @@ export interface SendOptions extends TurnOptions {
93
98
  export interface WaitOptions {
94
99
  pollMs?: number;
95
100
  timeoutMs?: number;
101
+ /**
102
+ * Ask the server to hold each state read up to this long while a turn runs
103
+ * (at most {@link MAX_STATE_LONG_POLL_MS}). The read then answers as soon as
104
+ * the turn ends, so the wait needs a few requests instead of one per
105
+ * `pollMs`. A server older than the long-poll answers at once, and the wait
106
+ * falls back to polling. Omit for plain polling.
107
+ */
108
+ longPollMs?: number;
109
+ }
110
+ /** Choices of a state read. */
111
+ export interface StateReadOptions {
112
+ /**
113
+ * While a turn runs, let the server hold the answer up to this long (at
114
+ * most {@link MAX_STATE_LONG_POLL_MS}) and answer when the turn ends. The
115
+ * answer can still say `running` when the time runs out first.
116
+ */
117
+ waitMs?: number;
118
+ }
119
+ /** Choices of a transcript read. */
120
+ export interface ListMessagesOptions {
121
+ /** The `nextCursor` of the last page you read: the page starts after it. */
122
+ after?: string;
123
+ /** Page size, 1 to 50. The server's default is 20. */
124
+ limit?: number;
96
125
  }
97
126
  export interface SessionHandle {
98
127
  readonly sessionId: string;
99
128
  /** Reads what the session is doing and what it waits on. */
100
- getState(): Promise<SessionState>;
129
+ getState(options?: StateReadOptions): Promise<SessionState>;
130
+ /**
131
+ * Reads the saved transcript, oldest first, one page at a time. Pass the
132
+ * page's `nextCursor` as `after` for the next one. A cursor the transcript
133
+ * no longer holds is refused with a `SessionRequestError` whose code is
134
+ * `CURSOR_NOT_FOUND`: read again from the start.
135
+ */
136
+ listMessages(options?: ListMessagesOptions): Promise<SessionMessagesPage>;
101
137
  /**
102
138
  * Answers `pending` with `decision`. The pending action's id is sent along,
103
139
  * so the server refuses the turn (`PendingActionMismatchError`) when the
@@ -28,6 +28,11 @@ export const DEFAULT_WAIT_TIMEOUT_MS = 20 * 60_000;
28
28
  export const TURN_SETTLE_TIMEOUT_MS = 30_000;
29
29
  /** Wait between polls while a finished turn settles. */
30
30
  export const TURN_SETTLE_POLL_MS = 500;
31
+ /**
32
+ * Longest long-poll one state read asks the server for. The server holds the
33
+ * answer while a turn runs, up to this, and answers as soon as it ends.
34
+ */
35
+ export const MAX_STATE_LONG_POLL_MS = 25_000;
31
36
  const defaultSleep = (ms) => new Promise((resolve) => {
32
37
  setTimeout(resolve, ms);
33
38
  });
@@ -82,21 +87,49 @@ export function createClient(options) {
82
87
  }
83
88
  function attach(sessionId) {
84
89
  const chatPath = `/api/v1/chat/${encodeURIComponent(sessionId)}`;
85
- const readState = async (signal) => {
86
- const response = await request(`${chatPath}/state`, { method: 'GET', signal });
90
+ const readState = async (signal, waitMs) => {
91
+ const wait = waitMs === undefined || waitMs <= 0
92
+ ? ''
93
+ : `?waitMs=${String(Math.min(Math.floor(waitMs), MAX_STATE_LONG_POLL_MS))}`;
94
+ const response = await request(`${chatPath}/state${wait}`, { method: 'GET', signal });
95
+ return (await response.json());
96
+ };
97
+ const getState = (read = {}) => readState(undefined, read.waitMs);
98
+ const listMessages = async (list = {}) => {
99
+ const query = new URLSearchParams();
100
+ if (list.after !== undefined)
101
+ query.set('after', list.after);
102
+ if (list.limit !== undefined)
103
+ query.set('limit', String(list.limit));
104
+ const search = query.toString();
105
+ const response = await request(`${chatPath}/messages${search === '' ? '' : `?${search}`}`, {
106
+ method: 'GET',
107
+ });
87
108
  return (await response.json());
88
109
  };
89
- const getState = () => readState();
90
110
  const waitForTurn = async (wait = {}) => {
91
111
  const pollMs = wait.pollMs ?? DEFAULT_POLL_MS;
92
112
  const timeoutMs = wait.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS;
113
+ const longPollMs = wait.longPollMs ?? 0;
93
114
  let waited = 0;
115
+ let first = true;
94
116
  for (;;) {
95
- const state = await getState();
117
+ // The first read never waits: a session with no turn running answers
118
+ // at once either way, and one with a turn is waited on from the next.
119
+ const holdMs = first ? 0 : Math.min(longPollMs, Math.max(timeoutMs - waited, 0));
120
+ first = false;
121
+ const startedAt = Date.now();
122
+ const state = await readState(undefined, holdMs);
96
123
  if (state.phase !== 'running')
97
124
  return state;
125
+ // A read the server held already waited: it counts toward the timeout,
126
+ // and needs no pause after it.
127
+ const held = holdMs > 0 ? Date.now() - startedAt : 0;
128
+ waited += held;
98
129
  if (waited >= timeoutMs)
99
130
  throw new TurnTimeoutError(sessionId, timeoutMs);
131
+ if (held >= pollMs)
132
+ continue;
100
133
  await sleep(pollMs);
101
134
  waited += pollMs;
102
135
  }
@@ -200,6 +233,7 @@ export function createClient(options) {
200
233
  return {
201
234
  sessionId,
202
235
  getState,
236
+ listMessages,
203
237
  waitForTurn,
204
238
  respond(pending, decision, turn) {
205
239
  validateDecision(pending, decision);
@@ -186,8 +186,28 @@ 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;
189
194
  };
190
195
  }[PendingActionKind];
196
+ /** A short preview of the spec file a `spec-decision` card asks about. */
197
+ export interface SpecFilePreview {
198
+ specFileId: string;
199
+ revisionNumber: number;
200
+ /** The revision the diff is against; absent for a first revision. */
201
+ previousRevisionNumber?: number;
202
+ linesAdded: number;
203
+ linesRemoved: number;
204
+ /** Unified-style diff: `+`, `-` and ` ` lines, `@@` between hunks. */
205
+ diff?: string;
206
+ /** The start of the file, for a first revision. */
207
+ excerpt?: string;
208
+ /** Present (and `true`) when the diff or the excerpt was cut. */
209
+ truncated?: true;
210
+ }
191
211
  export type SessionPhase = 'running' | 'awaiting_input' | 'idle' | 'completed';
192
212
  export interface SessionStateSpecFile {
193
213
  specType: string;
@@ -299,6 +319,93 @@ export interface SessionState {
299
319
  * server is older than this field.
300
320
  */
301
321
  agentDrivingEnabled?: boolean;
322
+ /**
323
+ * The newest assistant message, `null` when the session has none yet. Read
324
+ * the reply of a turn that outlasted your wait here, and a question the
325
+ * session asked as text instead of a card. Absent when the server is older
326
+ * than this field.
327
+ */
328
+ lastAssistantMessage?: LastAssistantMessage | null;
329
+ /**
330
+ * How many saved messages the transcript holds (see
331
+ * `SessionHandle.listMessages`). Absent when the server is older than this
332
+ * field.
333
+ */
334
+ messageCount?: number;
335
+ /**
336
+ * Your own `reverse` bridge: a brownfield turn reads local files through
337
+ * the bridge of the account that sends it. Absent when the server cannot
338
+ * tell, or is older than this field.
339
+ */
340
+ localBridge?: SessionStateLocalBridge;
341
+ }
342
+ /** Whether your `reverse` bridge is connected to MySpec. */
343
+ export interface SessionStateLocalBridge {
344
+ connected: boolean;
345
+ /** When the connected bridge connected (ISO-8601). */
346
+ connectedSince?: string;
347
+ /** When MySpec last heard from it (ISO-8601). */
348
+ lastSeenAt?: string;
349
+ }
350
+ /** The newest assistant message of a session, as the state read reports it. */
351
+ export interface LastAssistantMessage {
352
+ messageId: string;
353
+ /** Zero-based position in the transcript. */
354
+ index: number;
355
+ /** Its text parts joined. May be empty: a message can hold only cards. */
356
+ text: string;
357
+ /** Present (and `true`) when the server cut a very long text. */
358
+ textTruncated?: true;
359
+ /** The types of its cards, without the `data-` prefix (`mcq-form`, ...). */
360
+ cardTypes: string[];
361
+ }
362
+ /** A tool call of an assistant message. */
363
+ export interface SessionMessageToolCall {
364
+ name: string;
365
+ /** How far it got (`output-available`, `output-error`, ...), when known. */
366
+ state?: string;
367
+ /** `key=value` pairs of its main arguments (a path, a query), when recorded. */
368
+ summary?: string;
369
+ /** `true` when its result was an error. */
370
+ failed?: true;
371
+ }
372
+ /** A card or a decision of a message. */
373
+ export interface SessionMessageCard {
374
+ /** The part type without its `data-` prefix: `mcq-form`, `spec-file`, ... */
375
+ type: string;
376
+ /** The card's data. Absent when it was too large: see `dataTruncated`. */
377
+ data?: unknown;
378
+ dataTruncated?: true;
379
+ }
380
+ /** One saved message of a session's transcript. */
381
+ export interface SessionMessage {
382
+ /** The message id. */
383
+ id: string;
384
+ /** Zero-based position among the messages the server shows (`< total`). */
385
+ index: number;
386
+ role: 'user' | 'assistant';
387
+ /** Its text parts joined. */
388
+ text: string;
389
+ /** Present (and `true`) when the server cut a very long text. */
390
+ textTruncated?: true;
391
+ /** Who sent a user message, when the server recorded it. */
392
+ actorKind?: 'human' | 'ai';
393
+ /** User id of the sender, when recorded. */
394
+ senderId?: string;
395
+ /** When the server received a user message (ISO-8601), when recorded. */
396
+ receivedAt?: string;
397
+ toolCalls: SessionMessageToolCall[];
398
+ cards: SessionMessageCard[];
399
+ }
400
+ /** The answer of `GET /api/v1/chat/:id/messages`: one page, oldest first. */
401
+ export interface SessionMessagesPage {
402
+ sessionId: string;
403
+ messages: SessionMessage[];
404
+ /** How many messages the transcript holds in all. */
405
+ total: number;
406
+ hasMore: boolean;
407
+ /** The `after` of the next page (opaque); `null` when `hasMore` is false. */
408
+ nextCursor: string | null;
302
409
  }
303
410
  /** An error the turn's stream carried instead of (or after) its content. */
304
411
  export interface TurnStreamError {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myspec/sdk",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "MySpec session driver: read what a chat session waits on and answer it, from a script, a test or an agent",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",