@myspec/sdk 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -12
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/src/client.d.ts +38 -2
- package/dist/src/client.js +38 -4
- package/dist/src/types.d.ts +69 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -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()`
|
|
59
|
-
| `session.
|
|
60
|
-
| `session.
|
|
61
|
-
| `session.
|
|
62
|
-
| `
|
|
63
|
-
| `
|
|
64
|
-
| `
|
|
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
|
+
`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 `/
|
|
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 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";
|
package/dist/src/client.d.ts
CHANGED
|
@@ -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
|
package/dist/src/client.js
CHANGED
|
@@ -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
|
|
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
|
-
|
|
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);
|
package/dist/src/types.d.ts
CHANGED
|
@@ -299,6 +299,75 @@ export interface SessionState {
|
|
|
299
299
|
* server is older than this field.
|
|
300
300
|
*/
|
|
301
301
|
agentDrivingEnabled?: boolean;
|
|
302
|
+
/**
|
|
303
|
+
* The newest assistant message, `null` when the session has none yet. Read
|
|
304
|
+
* the reply of a turn that outlasted your wait here, and a question the
|
|
305
|
+
* session asked as text instead of a card. Absent when the server is older
|
|
306
|
+
* than this field.
|
|
307
|
+
*/
|
|
308
|
+
lastAssistantMessage?: LastAssistantMessage | null;
|
|
309
|
+
/**
|
|
310
|
+
* How many saved messages the transcript holds (see
|
|
311
|
+
* `SessionHandle.listMessages`). Absent when the server is older than this
|
|
312
|
+
* field.
|
|
313
|
+
*/
|
|
314
|
+
messageCount?: number;
|
|
315
|
+
}
|
|
316
|
+
/** The newest assistant message of a session, as the state read reports it. */
|
|
317
|
+
export interface LastAssistantMessage {
|
|
318
|
+
messageId: string;
|
|
319
|
+
/** Zero-based position in the transcript. */
|
|
320
|
+
index: number;
|
|
321
|
+
/** Its text parts joined. May be empty: a message can hold only cards. */
|
|
322
|
+
text: string;
|
|
323
|
+
/** Present (and `true`) when the server cut a very long text. */
|
|
324
|
+
textTruncated?: true;
|
|
325
|
+
/** The types of its cards, without the `data-` prefix (`mcq-form`, ...). */
|
|
326
|
+
cardTypes: string[];
|
|
327
|
+
}
|
|
328
|
+
/** A tool call of an assistant message. */
|
|
329
|
+
export interface SessionMessageToolCall {
|
|
330
|
+
name: string;
|
|
331
|
+
/** How far it got (`output-available`, `output-error`, ...), when known. */
|
|
332
|
+
state?: string;
|
|
333
|
+
}
|
|
334
|
+
/** A card or a decision of a message. */
|
|
335
|
+
export interface SessionMessageCard {
|
|
336
|
+
/** The part type without its `data-` prefix: `mcq-form`, `spec-file`, ... */
|
|
337
|
+
type: string;
|
|
338
|
+
/** The card's data. Absent when it was too large: see `dataTruncated`. */
|
|
339
|
+
data?: unknown;
|
|
340
|
+
dataTruncated?: true;
|
|
341
|
+
}
|
|
342
|
+
/** One saved message of a session's transcript. */
|
|
343
|
+
export interface SessionMessage {
|
|
344
|
+
/** The message id. */
|
|
345
|
+
id: string;
|
|
346
|
+
/** Zero-based position among the messages the server shows (`< total`). */
|
|
347
|
+
index: number;
|
|
348
|
+
role: 'user' | 'assistant';
|
|
349
|
+
/** Its text parts joined. */
|
|
350
|
+
text: string;
|
|
351
|
+
/** Present (and `true`) when the server cut a very long text. */
|
|
352
|
+
textTruncated?: true;
|
|
353
|
+
/** Who sent a user message, when the server recorded it. */
|
|
354
|
+
actorKind?: 'human' | 'ai';
|
|
355
|
+
/** User id of the sender, when recorded. */
|
|
356
|
+
senderId?: string;
|
|
357
|
+
/** When the server received a user message (ISO-8601), when recorded. */
|
|
358
|
+
receivedAt?: string;
|
|
359
|
+
toolCalls: SessionMessageToolCall[];
|
|
360
|
+
cards: SessionMessageCard[];
|
|
361
|
+
}
|
|
362
|
+
/** The answer of `GET /api/v1/chat/:id/messages`: one page, oldest first. */
|
|
363
|
+
export interface SessionMessagesPage {
|
|
364
|
+
sessionId: string;
|
|
365
|
+
messages: SessionMessage[];
|
|
366
|
+
/** How many messages the transcript holds in all. */
|
|
367
|
+
total: number;
|
|
368
|
+
hasMore: boolean;
|
|
369
|
+
/** The `after` of the next page (opaque); `null` when `hasMore` is false. */
|
|
370
|
+
nextCursor: string | null;
|
|
302
371
|
}
|
|
303
372
|
/** An error the turn's stream carried instead of (or after) its content. */
|
|
304
373
|
export interface TurnStreamError {
|
package/package.json
CHANGED