@myspec/sdk 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MySpec
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,131 @@
1
- # Temporary Holding Version
1
+ # @myspec/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The MySpec session driver. It reads what a chat session waits on and answers it, from a script, a test or an agent.
4
+
5
+ ```bash
6
+ npm install @myspec/sdk
7
+ ```
8
+
9
+ Node 22 or later (it uses the built-in `fetch`). ESM only. No runtime dependency. MIT license.
10
+
11
+ ## Model
12
+
13
+ - A session waits on at most one **pending action**: a card such as an MCQ form, a spec file to approve or a review board.
14
+ - A **decision** answers it. Every decision carries the pending action's `id`, so the server refuses an answer to a card the session no longer waits on.
15
+ - A **driver** is a policy plus a transport. The policy decides. The transport is a `fetch` function, so the same code runs against a deployed stack or an in-process ai-agent app.
16
+
17
+ ## Use
18
+
19
+ ```ts
20
+ import {
21
+ apiTokenAuth,
22
+ createClient,
23
+ decide,
24
+ recommendedPolicy,
25
+ runToCompletion,
26
+ } from '@myspec/sdk';
27
+
28
+ const client = createClient({
29
+ baseUrl: 'https://app.myspec.dev', // the web app; it serves /api/v1/chat/...
30
+ getToken: apiTokenAuth({ apiToken: process.env.MYSPEC_API_TOKEN! }),
31
+ actorKind: 'ai', // an agent decides; leave out for a person or a test script
32
+ });
33
+
34
+ // A session someone already started, or one you created through the platform API.
35
+ const session = client.attach(sessionId);
36
+
37
+ // One step at a time.
38
+ const state = await session.getState();
39
+ if (state.pendingAction?.kind === 'spec-decision') {
40
+ await session.respond(state.pendingAction, decide.approveSpec());
41
+ }
42
+
43
+ // Or let a policy drive it.
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').
46
+ console.log(report.endReason);
47
+ // completed | policy_stop | max_turns | handover | turn_error | agent_refused | error
48
+ ```
49
+
50
+ A turn that ends with a stream error ends the run with `turn_error`. Pass `turnErrorRetries: n` to go on from up to `n` such turns in a run instead: the state is read again and the policy is asked again, with the error in `info.lastTurnError`, as a person would press "try again". An error the ai-agent marks as not recoverable still ends the run. The ai-agent usually saves a turn before it reports its error, so a policy must read the state and not assume its last answer was lost; `scriptedPolicy` plays a step again only when the card it answered is still pending. Each turn record carries `assistantText` (what the agent said) and `error`.
51
+
52
+ ## API
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. |
65
+
66
+ `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
+ 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
+
70
+ ## Agent-driven turns
71
+
72
+ 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.
73
+
74
+ - The server records who sent each turn. The state's `decisions` entries carry `answeredBy`, `answeredAt` and `actorKind` (`human` or `ai`). An entry saved before this was recorded has none of them: treat a missing `actorKind` as unknown.
75
+ - `state.agentTurns` is `{ used, cap }`: the agent-driven turns the session has run and the most it accepts (`AGENT_DRIVEN_TURN_CAP` on the server, default 60). At `used >= cap` the next agent-driven turn is refused with `AgentTurnCapReachedError` (HTTP 429). A person's turn is never refused by the cap. The field is optional in the type: an older server, from before the cap, does not send it.
76
+ - Every agent-driven turn the server accepts is counted, also one that fails or saves nothing (a `/btw` part).
77
+ - An org agent token cannot use the `/btw` side channel or the human-edit route (HTTP 403).
78
+ - While the server's `ai-agent-driven-sessions` flag is off, an agent may start a session but not continue one: an agent-driven turn on a session that already has a saved message is refused with `AgentDrivingDisabledError` (HTTP 403). The opening turn of a session runs. `getState()` still works, and so does a person's turn.
79
+ - `state.agentDrivingEnabled` says whether that flag is on. It reports the switch only: not the cap, not what the token may do, and not the opening turn, which runs either way. It is optional in the type: an older server does not send it.
80
+ - The server checks an agent-driven turn in this order: flag off (403), cap reached (429), stale pending action (409).
81
+ - A read-only token (`access: 'read'`) cannot send a turn, whoever drives: the server refuses it first with `ReadOnlyTokenError` (HTTP 403 `READ_ONLY_TOKEN`), and nothing runs. `getState()` still works with that token.
82
+
83
+ `runToCompletion` does not throw once it has read the first state: whatever stops it is the report's `endReason` and `error`, so the turns already made are never lost.
84
+
85
+ A turn result with `state: null` and a `stateError` means the turn ran but its state could not be read afterwards. Do not send the turn again; call `getState()` later.
86
+
87
+ **Free text when nothing is pending.** `session.send(text, { expectNoPending: true })` sends the reserved id `NO_PENDING_ACTION_ID` (`'none'`): "the session must wait on no card". If another participant's turn left a card since you read the state, the server refuses the turn with `PendingActionMismatchError` (its `current` names the card) and your text is not read as an answer to that card. Without the option a free-text turn carries no id and is not checked. `expectNoPending` cannot be combined with `pending`. It needs an ai-agent that knows the `none` id; an older one refuses every such turn with the same 409.
88
+
89
+ **A bound on the wait after a turn.** When a turn's stream ends, the SDK reads the state until the server stops reporting the turn as running. By default that is up to 30 seconds of waits, and a single read has no time limit. Pass `settleMs` in the turn options (`respond`, `send`) to bound the whole of it: the reads and the waits together. When the time runs out the result has `state: null` and a `TurnSettleTimeoutError` as `stateError`; a read that did not answer is aborted. It never throws and never sends the turn again. `waitMs` bounds the turn itself, `settleMs` the time after it, so a caller with a budget sets both.
90
+
91
+ ## What works today
92
+
93
+ - 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`.
95
+ - 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
+
97
+ ## Rules
98
+
99
+ - The pending action `id` is opaque. Send it back; never parse it.
100
+ - Every turn spends model tokens of the token owner's organization.
101
+ - `autonomy: 'interview'` answers question cards only (`mcq`, `user-choice`, `skill-selection`) and stops with `handover` at any other card.
102
+ - `recommendedPolicy()` takes the workflow's own recommended path with no judgement. It ignores review boards, also one that asks for a revision. Write your own policy to act on a review.
103
+
104
+ ## Develop
105
+
106
+ ```bash
107
+ npm install
108
+ npm run format:check # npm run format to fix
109
+ npm run typecheck
110
+ npm test
111
+ ```
112
+
113
+ The wire types in `src/types.ts` mirror `@myspec/ai` by hand, so the package has no runtime dependency. A test in `projects/ai-agent` fails when the two drift.
114
+
115
+ ## Release
116
+
117
+ Every merge to `main` that changes what this package ships (tests and test config aside) publishes it to npm: `.github/workflows/sdk-push-main.yml`. Its `build` job checks, builds and packs the package with no secret; its `publish` job holds the npm token and only publishes that tarball.
118
+
119
+ - **Version:** the release takes the `version` in `package.json`, or the next patch after the highest one on npm, whichever is higher. So a merge publishes a new patch with no commit. Bump `package.json` by hand only for a minor or major release (`0.2.0`, `1.0.0`). Never lower it.
120
+ - **What ships:** the compiled `dist/`, this README and the LICENSE. In the monorepo `package.json` points at the TypeScript source; `scripts/release.mjs write-manifest` rewrites it for npm in the CI checkout only. `npm run build` empties `dist/`, compiles, and points the `.d.ts` imports at `.js` files.
121
+ - **Checks:** the pull request builds and packs the package and installs it into an empty project (`scripts/smoke-test-tarball.sh`). The release `build` job does the same before it uploads the tarball.
122
+ - **Try it locally:**
123
+
124
+ ```bash
125
+ npm run build
126
+ node scripts/release.mjs write-manifest 0.0.0 # rewrites package.json: put it back after
127
+ TGZ="$(npm pack --silent)"
128
+ bash scripts/smoke-test-tarball.sh "$TGZ" 0.0.0
129
+ rm "$TGZ"
130
+ git checkout -- package.json
131
+ ```
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @myspec/sdk — the MySpec session driver.
3
+ *
4
+ * Read what a chat session waits on and answer it, from a script, a test or an
5
+ * agent. See `README.md`.
6
+ */
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';
9
+ 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';
12
+ export { DRIVER_MAX_TURNS, INTERVIEW_AUTONOMY_KINDS, runToCompletion, type AutonomyLevel, type RunEndReason, type RunOptions, type RunReport, type RunTurnRecord, } from './src/run.js';
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';
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @myspec/sdk — the MySpec session driver.
3
+ *
4
+ * Read what a chat session waits on and answer it, from a script, a test or an
5
+ * agent. See `README.md`.
6
+ */
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";
9
+ 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";
12
+ export { DRIVER_MAX_TURNS, INTERVIEW_AUTONOMY_KINDS, runToCompletion, } from "./src/run.js";
13
+ export { readTurnStream } from "./src/stream.js";
14
+ export { DECISION_PART_TYPE, NO_PENDING_ACTION_ID, PENDING_ACTION_KINDS, } from "./src/types.js";
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Sign-in with a MySpec API token.
3
+ *
4
+ * The chat routes take a short-lived access token, not the API token itself.
5
+ * `apiTokenAuth` trades the API token for an access token at the MySpec auth
6
+ * host, keeps it until shortly before it expires, and trades again after that
7
+ * or when the client asks for a fresh one (after a 401). The result is a
8
+ * `getToken` for {@link createClient}.
9
+ */
10
+ import { SessionRequestError } from './errors.js';
11
+ /** The auth host of MySpec's hosted service. */
12
+ export declare const DEFAULT_AUTH_URL = "https://auth.myspec.dev";
13
+ /**
14
+ * An access token is traded again this long before it expires (or after half
15
+ * its lifetime, for a token that lives less than twice this long).
16
+ */
17
+ export declare const ACCESS_TOKEN_REFRESH_MARGIN_MS = 60000;
18
+ /** Longest wait for one trade before it fails. */
19
+ export declare const TOKEN_EXCHANGE_TIMEOUT_MS = 10000;
20
+ export interface ApiTokenAuthOptions {
21
+ /** A MySpec API token (`msp_pat_…`) of a person or an organization agent. */
22
+ apiToken: string;
23
+ /**
24
+ * Origin of the auth host the token was created on. Defaults to
25
+ * {@link DEFAULT_AUTH_URL}. A token works only on the environment it was
26
+ * created in.
27
+ */
28
+ authUrl?: string;
29
+ /** Longest wait for one trade. Defaults to {@link TOKEN_EXCHANGE_TIMEOUT_MS}. */
30
+ timeoutMs?: number;
31
+ /** Transport. Defaults to the global `fetch`. */
32
+ fetch?: typeof fetch;
33
+ /** Clock, for tests. Defaults to `Date.now`. */
34
+ now?: () => number;
35
+ }
36
+ /**
37
+ * The auth host refused the API token (HTTP 401 or 403): it is invalid,
38
+ * disabled or expired, was created on another environment, or its owner lost
39
+ * access to its organization. Trying again gets the same answer, so every
40
+ * later call of the same `getToken` throws this error again without asking
41
+ * the host: create a new token, or point `authUrl` at the environment the
42
+ * token belongs to.
43
+ */
44
+ export declare class ApiTokenRejectedError extends SessionRequestError {
45
+ constructor(status: number, message: string, body: unknown);
46
+ }
47
+ /**
48
+ * Signing in did not work this time (not a refused token): the auth host
49
+ * failed, rate limited the trade, did not answer in time or could not be
50
+ * reached. The next call tries again.
51
+ */
52
+ export declare class TokenExchangeError extends SessionRequestError {
53
+ /** Seconds to wait before trying again, when the host said (`Retry-After`). */
54
+ readonly retryAfterSeconds: number | undefined;
55
+ constructor(status: number, code: string, message: string, body: unknown, retryAfterSeconds?: number);
56
+ }
57
+ /**
58
+ * A `getToken` that signs in with an API token.
59
+ *
60
+ * ```ts
61
+ * const client = createClient({
62
+ * baseUrl: 'https://app.myspec.dev',
63
+ * getToken: apiTokenAuth({ apiToken: process.env.MYSPEC_API_TOKEN ?? '' }),
64
+ * });
65
+ * ```
66
+ *
67
+ * Calls that arrive while a trade is in flight share it. A failed trade is not
68
+ * kept, so the next call tries again, except a refused API token
69
+ * ({@link ApiTokenRejectedError}), which is final.
70
+ */
71
+ export declare function apiTokenAuth(options: ApiTokenAuthOptions): (request?: {
72
+ forceRefresh?: boolean;
73
+ }) => Promise<string>;
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Sign-in with a MySpec API token.
3
+ *
4
+ * The chat routes take a short-lived access token, not the API token itself.
5
+ * `apiTokenAuth` trades the API token for an access token at the MySpec auth
6
+ * host, keeps it until shortly before it expires, and trades again after that
7
+ * or when the client asks for a fresh one (after a 401). The result is a
8
+ * `getToken` for {@link createClient}.
9
+ */
10
+ import { SessionRequestError } from "./errors.js";
11
+ /** The auth host of MySpec's hosted service. */
12
+ export const DEFAULT_AUTH_URL = 'https://auth.myspec.dev';
13
+ /**
14
+ * An access token is traded again this long before it expires (or after half
15
+ * its lifetime, for a token that lives less than twice this long).
16
+ */
17
+ export const ACCESS_TOKEN_REFRESH_MARGIN_MS = 60_000;
18
+ /** Longest wait for one trade before it fails. */
19
+ export const TOKEN_EXCHANGE_TIMEOUT_MS = 10_000;
20
+ /**
21
+ * The auth host refused the API token (HTTP 401 or 403): it is invalid,
22
+ * disabled or expired, was created on another environment, or its owner lost
23
+ * access to its organization. Trying again gets the same answer, so every
24
+ * later call of the same `getToken` throws this error again without asking
25
+ * the host: create a new token, or point `authUrl` at the environment the
26
+ * token belongs to.
27
+ */
28
+ export class ApiTokenRejectedError extends SessionRequestError {
29
+ constructor(status, message, body) {
30
+ super(status, 'API_TOKEN_REJECTED', message, body);
31
+ this.name = 'ApiTokenRejectedError';
32
+ }
33
+ }
34
+ /**
35
+ * Signing in did not work this time (not a refused token): the auth host
36
+ * failed, rate limited the trade, did not answer in time or could not be
37
+ * reached. The next call tries again.
38
+ */
39
+ export class TokenExchangeError extends SessionRequestError {
40
+ /** Seconds to wait before trying again, when the host said (`Retry-After`). */
41
+ retryAfterSeconds;
42
+ constructor(status, code, message, body, retryAfterSeconds) {
43
+ super(status, code, message, body);
44
+ this.name = 'TokenExchangeError';
45
+ this.retryAfterSeconds = retryAfterSeconds;
46
+ }
47
+ }
48
+ async function readBody(response) {
49
+ const text = await response.text().catch(() => '');
50
+ try {
51
+ return JSON.parse(text);
52
+ }
53
+ catch {
54
+ return text;
55
+ }
56
+ }
57
+ function isRecord(value) {
58
+ return typeof value === 'object' && value !== null;
59
+ }
60
+ /** `error.code` of the auth host's error body, when it has one. */
61
+ function errorCodeOf(body) {
62
+ if (!isRecord(body))
63
+ return undefined;
64
+ const error = body.error;
65
+ if (isRecord(error) && typeof error.code === 'string' && error.code !== '')
66
+ return error.code;
67
+ return typeof error === 'string' && error !== '' ? error : undefined;
68
+ }
69
+ function retryAfterOf(response) {
70
+ const header = response.headers.get('retry-after');
71
+ if (header === null || header.trim() === '')
72
+ return undefined;
73
+ const value = Number(header);
74
+ return Number.isFinite(value) && value >= 0 ? value : undefined;
75
+ }
76
+ function parseExchange(body) {
77
+ if (!isRecord(body))
78
+ return null;
79
+ const { accessToken, expiresIn } = body;
80
+ if (typeof accessToken !== 'string' || accessToken === '')
81
+ return null;
82
+ if (typeof expiresIn !== 'number' || !Number.isFinite(expiresIn) || expiresIn <= 0)
83
+ return null;
84
+ return { accessToken, expiresIn };
85
+ }
86
+ /**
87
+ * A `getToken` that signs in with an API token.
88
+ *
89
+ * ```ts
90
+ * const client = createClient({
91
+ * baseUrl: 'https://app.myspec.dev',
92
+ * getToken: apiTokenAuth({ apiToken: process.env.MYSPEC_API_TOKEN ?? '' }),
93
+ * });
94
+ * ```
95
+ *
96
+ * Calls that arrive while a trade is in flight share it. A failed trade is not
97
+ * kept, so the next call tries again, except a refused API token
98
+ * ({@link ApiTokenRejectedError}), which is final.
99
+ */
100
+ export function apiTokenAuth(options) {
101
+ const apiToken = options.apiToken.trim();
102
+ if (apiToken === '')
103
+ throw new TypeError('apiTokenAuth: apiToken is empty');
104
+ const authUrl = (options.authUrl ?? DEFAULT_AUTH_URL).replace(/\/+$/, '');
105
+ const timeoutMs = options.timeoutMs ?? TOKEN_EXCHANGE_TIMEOUT_MS;
106
+ const now = options.now ?? Date.now;
107
+ const fetchImpl = options.fetch ?? ((input, init) => fetch(input, init));
108
+ let current;
109
+ let inFlight;
110
+ let rejection;
111
+ const trade = async () => {
112
+ const url = `${authUrl}/api/auth/token/exchange`;
113
+ let response;
114
+ try {
115
+ response = await fetchImpl(url, {
116
+ method: 'POST',
117
+ headers: { 'x-api-key': apiToken },
118
+ signal: AbortSignal.timeout(timeoutMs),
119
+ });
120
+ }
121
+ catch (err) {
122
+ const timedOut = err instanceof Error && err.name === 'TimeoutError';
123
+ throw new TokenExchangeError(0, timedOut ? 'TOKEN_EXCHANGE_TIMEOUT' : 'TOKEN_EXCHANGE_UNREACHABLE', timedOut
124
+ ? `${authUrl} did not answer the sign-in within ${String(timeoutMs)} ms`
125
+ : `Could not reach ${authUrl} to sign in with the API token`, undefined);
126
+ }
127
+ const body = await readBody(response);
128
+ if (response.status === 401 || response.status === 403) {
129
+ throw new ApiTokenRejectedError(response.status, `${authUrl} refused the API token (HTTP ${String(response.status)}). Check that ` +
130
+ 'authUrl names the environment the token was created in, or create a new token.', body);
131
+ }
132
+ if (!response.ok) {
133
+ const code = errorCodeOf(body) ?? `HTTP_${String(response.status)}`;
134
+ throw new TokenExchangeError(response.status, code, `Could not sign in with the API token: HTTP ${String(response.status)} (${code}) from ${authUrl}`, body, retryAfterOf(response));
135
+ }
136
+ const parsed = parseExchange(body);
137
+ if (!parsed) {
138
+ throw new TokenExchangeError(response.status, 'MALFORMED_TOKEN_RESPONSE', `${authUrl} answered the sign-in without an access token`, body);
139
+ }
140
+ const lifetimeMs = parsed.expiresIn * 1000;
141
+ const margin = Math.min(ACCESS_TOKEN_REFRESH_MARGIN_MS, lifetimeMs / 2);
142
+ return { token: parsed.accessToken, renewAt: now() + lifetimeMs - margin };
143
+ };
144
+ return async (request) => {
145
+ if (rejection)
146
+ throw rejection;
147
+ if (current && request?.forceRefresh !== true && now() < current.renewAt) {
148
+ return current.token;
149
+ }
150
+ if (!inFlight) {
151
+ inFlight = trade()
152
+ .then((next) => {
153
+ current = next;
154
+ return next;
155
+ })
156
+ .catch((err) => {
157
+ if (err instanceof ApiTokenRejectedError) {
158
+ rejection = err;
159
+ current = undefined;
160
+ }
161
+ throw err;
162
+ })
163
+ .finally(() => {
164
+ inFlight = undefined;
165
+ });
166
+ }
167
+ return (await inFlight).token;
168
+ };
169
+ }
@@ -0,0 +1,124 @@
1
+ /**
2
+ * The session driver client.
3
+ *
4
+ * `createClient(...).attach(sessionId)` returns a handle on one chat session,
5
+ * whoever started it. The handle reads what the session waits on and sends
6
+ * turns; it holds no state of its own, so two handles on one session behave
7
+ * the same.
8
+ *
9
+ * The transport is a `fetch` function and `baseUrl` is the origin that serves
10
+ * `/api/v1/chat/...`: the ai-agent, or a proxy in front of it. In a test it can
11
+ * be the `fetch` of an in-process ai-agent app, with no network at all.
12
+ */
13
+ import { type Decision, type PendingAction, type SessionState, type TurnResult } from './types.js';
14
+ /** Client type the ai-agent segments analytics on, unless the caller sets one. */
15
+ export declare const DEFAULT_CLIENT_TYPE = "sdk";
16
+ /** Default wait between two state polls of {@link SessionHandle.waitForTurn}. */
17
+ export declare const DEFAULT_POLL_MS = 2000;
18
+ /** Default longest wait of {@link SessionHandle.waitForTurn}. */
19
+ export declare const DEFAULT_WAIT_TIMEOUT_MS: number;
20
+ /**
21
+ * Longest wait for the server to stop reporting a turn as running AFTER its
22
+ * stream ended. The stream's end is what releases the turn on the server, but
23
+ * the release is not instant and another replica can lag behind it.
24
+ */
25
+ export declare const TURN_SETTLE_TIMEOUT_MS = 30000;
26
+ /** Wait between polls while a finished turn settles. */
27
+ export declare const TURN_SETTLE_POLL_MS = 500;
28
+ /** Languages a session can be started in. */
29
+ export type SessionLanguage = 'en' | 'zh' | 'ja' | 'vi';
30
+ export interface ClientOptions {
31
+ /** Origin that serves `/api/v1/chat/...`. */
32
+ baseUrl: string;
33
+ /**
34
+ * Supplies the bearer token. Called with `forceRefresh: true` once after a
35
+ * 401, to get a token that is not the one just refused.
36
+ */
37
+ getToken: (options: {
38
+ forceRefresh: boolean;
39
+ }) => string | Promise<string>;
40
+ /** Transport. Defaults to the global `fetch`. */
41
+ fetch?: typeof fetch;
42
+ /** Sent as `X-Client-Type`. Defaults to {@link DEFAULT_CLIENT_TYPE}. */
43
+ clientType?: string;
44
+ /**
45
+ * Who is acting. Set `'ai'` when an agent decides; omit for a person or a
46
+ * test script. When set it is sent with every turn.
47
+ *
48
+ * The server records it on the turn and treats an `'ai'` turn as
49
+ * agent-driven: it counts toward the session's turn cap
50
+ * (`AgentTurnCapReachedError` once the cap is reached) and, unless it opens
51
+ * the session, is refused while agent driving is turned off
52
+ * (`AgentDrivingDisabledError`). An org agent token is always `'ai'`,
53
+ * whatever is set here.
54
+ */
55
+ actorKind?: 'human' | 'ai';
56
+ /** Waits between polls. Replaceable so tests need no real timers. */
57
+ sleep?: (ms: number) => Promise<void>;
58
+ }
59
+ /** Per-turn choices, like the webapp's model and depth pickers. */
60
+ export interface TurnOptions {
61
+ modelId?: string;
62
+ specDepth?: 'lite' | 'full' | 'ultra';
63
+ /** Only read on the first turn of a session; a session's language is fixed. */
64
+ language?: SessionLanguage;
65
+ /**
66
+ * Longest time to wait for the turn, from the request to the end of its
67
+ * stream. When it elapses the call returns with `turnStillRunning: true` and
68
+ * the turn is left to finish in the background. Omit to wait for its end.
69
+ */
70
+ waitMs?: number;
71
+ /**
72
+ * Longest time, in total, to spend AFTER the turn's stream has ended on
73
+ * reading a settled state: the reads themselves and the waits between them.
74
+ * When it runs out the call returns the turn with `state: null` and a
75
+ * `TurnSettleTimeoutError` as `stateError`. It never throws and never sends
76
+ * the turn again. Omit for the default: up to
77
+ * {@link TURN_SETTLE_TIMEOUT_MS} of waits, with no limit on a single read.
78
+ */
79
+ settleMs?: number;
80
+ }
81
+ /** Choices of a free-text turn. */
82
+ export interface SendOptions extends TurnOptions {
83
+ /** The card on screen, so the stale-answer guard applies to the reply. */
84
+ pending?: PendingAction;
85
+ /**
86
+ * Say that the session must wait on NO card. The server then refuses the
87
+ * turn (`PendingActionMismatchError`) when a card is pending: another
88
+ * participant's turn left one since the state was read, and this text must
89
+ * not be read as its answer. Cannot be combined with `pending`.
90
+ */
91
+ expectNoPending?: boolean;
92
+ }
93
+ export interface WaitOptions {
94
+ pollMs?: number;
95
+ timeoutMs?: number;
96
+ }
97
+ export interface SessionHandle {
98
+ readonly sessionId: string;
99
+ /** Reads what the session is doing and what it waits on. */
100
+ getState(): Promise<SessionState>;
101
+ /**
102
+ * Answers `pending` with `decision`. The pending action's id is sent along,
103
+ * so the server refuses the turn (`PendingActionMismatchError`) when the
104
+ * session has moved on since `pending` was read.
105
+ */
106
+ respond(pending: PendingAction, decision: Decision, options?: TurnOptions): Promise<TurnResult>;
107
+ /**
108
+ * Sends a free-text turn. Pass the pending action when one is on screen, so
109
+ * the same stale-answer guard applies to the reply; pass `expectNoPending`
110
+ * when none is, so the text cannot answer a card that appeared since.
111
+ * Throws `InvalidDecisionError`, before any request, when both are given.
112
+ */
113
+ send(text: string, options?: SendOptions): Promise<TurnResult>;
114
+ /**
115
+ * Polls the state until no turn is running, and returns that state. Throws
116
+ * `TurnTimeoutError` when a turn outlasts `timeoutMs`.
117
+ */
118
+ waitForTurn(options?: WaitOptions): Promise<SessionState>;
119
+ }
120
+ export interface SessionClient {
121
+ /** A handle on an existing session. Sends nothing. */
122
+ attach(sessionId: string): SessionHandle;
123
+ }
124
+ export declare function createClient(options: ClientOptions): SessionClient;