@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.
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Reader of a chat turn's UI-message SSE stream.
3
+ *
4
+ * The stream is `text/event-stream` with one JSON frame per `data:` line. The
5
+ * reader keeps only what a driver needs: the assistant's text and the error
6
+ * frame, if the turn carried one. Cards are NOT taken from the stream: the
7
+ * state read after the turn is the single source of what the session waits on.
8
+ */
9
+ function isRecord(value) {
10
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
11
+ }
12
+ /**
13
+ * The ai-agent writes an error frame's `errorText` as a JSON object with
14
+ * `code` and `message`; anything else is kept as plain text.
15
+ */
16
+ function parseStreamError(errorText) {
17
+ const text = typeof errorText === 'string' ? errorText : '';
18
+ try {
19
+ const parsed = JSON.parse(text);
20
+ if (isRecord(parsed) && typeof parsed.message === 'string') {
21
+ return {
22
+ code: typeof parsed.code === 'string' ? parsed.code : 'STREAM_ERROR',
23
+ message: parsed.message,
24
+ ...(typeof parsed.recoverable === 'boolean' ? { recoverable: parsed.recoverable } : {}),
25
+ };
26
+ }
27
+ }
28
+ catch {
29
+ // Plain text, handled below.
30
+ }
31
+ return { code: 'STREAM_ERROR', message: text === '' ? 'The turn ended with an error' : text };
32
+ }
33
+ function applyFrame(raw, state) {
34
+ if (raw === '' || raw === '[DONE]')
35
+ return;
36
+ let frame;
37
+ try {
38
+ frame = JSON.parse(raw);
39
+ }
40
+ catch {
41
+ // A malformed frame is skipped, never fatal: the turn is real work that
42
+ // is already running, and one bad line must not cost the rest of it.
43
+ return;
44
+ }
45
+ if (!isRecord(frame))
46
+ return;
47
+ if (frame.type === 'text-delta' && typeof frame.delta === 'string') {
48
+ state.assistantText += frame.delta;
49
+ return;
50
+ }
51
+ // The first error wins: a later one is usually a consequence of it.
52
+ if (frame.type === 'error' && state.error === null) {
53
+ state.error = parseStreamError(frame.errorText);
54
+ }
55
+ }
56
+ function applyLines(block, state) {
57
+ for (const line of block.split('\n')) {
58
+ // Lines that start with `:` are SSE comments (the keepalive heartbeat).
59
+ if (line.startsWith('data:'))
60
+ applyFrame(line.slice(5).trim(), state);
61
+ }
62
+ }
63
+ /**
64
+ * Starts reading `body` at once and runs to its end on its own. The body is
65
+ * never cancelled: the ai-agent releases the session lock when the response
66
+ * body ends, so dropping the stream would cut the turn short.
67
+ */
68
+ export function readTurnStream(body) {
69
+ const state = { assistantText: '', error: null };
70
+ const drained = (async () => {
71
+ if (body === null)
72
+ return;
73
+ const reader = body.getReader();
74
+ const decoder = new TextDecoder();
75
+ let buffer = '';
76
+ for (;;) {
77
+ const { done, value } = await reader.read();
78
+ if (done)
79
+ break;
80
+ // A proxy may rewrite line endings; frames are split on blank lines.
81
+ buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, '\n');
82
+ let boundary = buffer.indexOf('\n\n');
83
+ while (boundary !== -1) {
84
+ applyLines(buffer.slice(0, boundary), state);
85
+ buffer = buffer.slice(boundary + 2);
86
+ boundary = buffer.indexOf('\n\n');
87
+ }
88
+ }
89
+ // A stream that ends without a trailing blank line still holds a frame.
90
+ applyLines(buffer + decoder.decode(), state);
91
+ })().catch((err) => {
92
+ state.error ??= {
93
+ code: 'STREAM_INTERRUPTED',
94
+ message: err instanceof Error ? err.message : String(err),
95
+ };
96
+ });
97
+ return {
98
+ drained,
99
+ snapshot: () => ({
100
+ assistantText: state.assistantText,
101
+ error: state.error,
102
+ }),
103
+ };
104
+ }
@@ -0,0 +1,339 @@
1
+ /**
2
+ * Wire types of the MySpec session driver.
3
+ *
4
+ * These mirror, structurally, what the ai-agent sends and accepts. They are
5
+ * written out here rather than imported from `@myspec/ai` so the SDK has no
6
+ * runtime dependency. A test in the ai-agent assigns each `@myspec/ai` type to
7
+ * its mirror below, so a renamed or retyped field fails that project's
8
+ * typecheck instead of failing a caller at runtime.
9
+ */
10
+ /** Every kind of card a session can wait on. */
11
+ export declare const PENDING_ACTION_KINDS: readonly ["mcq", "spec-decision", "review-decision", "skill-selection", "user-choice", "edit-decision", "site-plan", "artifact-revision"];
12
+ export type PendingActionKind = (typeof PENDING_ACTION_KINDS)[number];
13
+ /**
14
+ * The `pendingActionId` that says "the session must wait on no card". The
15
+ * server refuses the turn, as for a stale card id, when a card is pending. It
16
+ * cannot be the id of a card: those always hold a colon.
17
+ */
18
+ export declare const NO_PENDING_ACTION_ID = "none";
19
+ export interface McqOption {
20
+ id: string;
21
+ label: string;
22
+ description?: string;
23
+ /** The option the workflow recommends, when it recommends one. */
24
+ recommended?: boolean;
25
+ }
26
+ export interface McqQuestion {
27
+ id: string;
28
+ text: string;
29
+ type: 'single' | 'multiple';
30
+ options: McqOption[];
31
+ required: boolean;
32
+ /** Whether a free-text "Other" answer is accepted. */
33
+ allowOther?: boolean;
34
+ }
35
+ export interface McqFormCard {
36
+ stage: string;
37
+ round: number;
38
+ questions: McqQuestion[];
39
+ }
40
+ export interface SpecFileCard {
41
+ specType: string;
42
+ bundleName: string;
43
+ specFileId: string;
44
+ fileRevisionId: string;
45
+ revisionNumber: number;
46
+ filePath: string;
47
+ }
48
+ export interface ReviewFeedbackItem {
49
+ section: string;
50
+ line: number;
51
+ confidenceScore: number;
52
+ description: string;
53
+ /** What the reviewer proposes to write instead. */
54
+ suggestion: string;
55
+ }
56
+ export interface ReviewFeedbackCard {
57
+ specType: string;
58
+ nextStep: 'pass' | 'needs_revision';
59
+ message: string;
60
+ feedback: {
61
+ mustfix: ReviewFeedbackItem[];
62
+ recommendations: ReviewFeedbackItem[];
63
+ };
64
+ }
65
+ export interface SkillRecommendationCard {
66
+ stage: string;
67
+ skills: {
68
+ id: string;
69
+ }[];
70
+ }
71
+ export interface UserChoiceCard {
72
+ prompt: string;
73
+ reason?: string;
74
+ choices: {
75
+ id: string;
76
+ label: string;
77
+ recommended: boolean;
78
+ }[];
79
+ }
80
+ export interface EditReviewCard {
81
+ turnId: string;
82
+ files: {
83
+ specFileId: string;
84
+ specType: string;
85
+ filePath: string;
86
+ fromRevision: number;
87
+ toRevision: number;
88
+ }[];
89
+ }
90
+ export interface SitePlanCard {
91
+ name: string;
92
+ description?: string;
93
+ files: {
94
+ path: string;
95
+ purpose: string;
96
+ }[];
97
+ libraries: {
98
+ name: string;
99
+ url: string;
100
+ }[];
101
+ planId?: string;
102
+ }
103
+ export interface ArtifactRevisionCard {
104
+ artifactId: string;
105
+ slug: string;
106
+ name: string;
107
+ revisionNumber: number;
108
+ fileCount: number;
109
+ totalBytes: number;
110
+ hosts: string[];
111
+ mode: 'generate' | 'edit';
112
+ }
113
+ /** The card payload of each pending action kind. */
114
+ export interface CardByKind {
115
+ mcq: McqFormCard;
116
+ 'spec-decision': SpecFileCard;
117
+ 'review-decision': ReviewFeedbackCard;
118
+ 'skill-selection': SkillRecommendationCard;
119
+ 'user-choice': UserChoiceCard;
120
+ 'edit-decision': EditReviewCard;
121
+ 'site-plan': SitePlanCard;
122
+ 'artifact-revision': ArtifactRevisionCard;
123
+ }
124
+ /** The data of the decision part that answers each kind. */
125
+ export interface DecisionDataByKind {
126
+ mcq: {
127
+ stage: string;
128
+ round: number;
129
+ answers: Record<string, string | string[]>;
130
+ };
131
+ 'spec-decision': {
132
+ action: 'approve' | 'reject';
133
+ editPrompt?: string;
134
+ };
135
+ 'review-decision': {
136
+ action: 'accept' | 'ignore' | 'update';
137
+ editPrompt?: string;
138
+ /** The review items to fold in, for `accept` and `update`. */
139
+ selectedFeedback?: ReviewFeedbackItem[];
140
+ };
141
+ 'skill-selection': {
142
+ skillId: string | null;
143
+ };
144
+ 'user-choice': {
145
+ choiceId: string;
146
+ };
147
+ 'edit-decision': {
148
+ turnId: string;
149
+ decisions: Record<string, 'accept' | 'discard'>;
150
+ };
151
+ 'site-plan': {
152
+ decision: 'approve' | 'request-changes';
153
+ feedback?: string;
154
+ planId?: string;
155
+ };
156
+ 'artifact-revision': {
157
+ artifactId: string;
158
+ revisionNumber: number;
159
+ decision: 'approve' | 'request-changes' | 'keep' | 'discard';
160
+ feedback?: string;
161
+ };
162
+ }
163
+ /** The decision part type that answers each kind. */
164
+ export declare const DECISION_PART_TYPE: {
165
+ readonly mcq: "data-mcq-answers";
166
+ readonly 'spec-decision': "data-spec-decision";
167
+ readonly 'review-decision': "data-review-decision";
168
+ readonly 'skill-selection': "data-skill-selection";
169
+ readonly 'user-choice': "data-user-choice-response";
170
+ readonly 'edit-decision': "data-edit-decision";
171
+ readonly 'site-plan': "data-site-plan-decision";
172
+ readonly 'artifact-revision': "data-artifact-revision-decision";
173
+ };
174
+ /** A decision for one pending action kind, ready to send. */
175
+ export type Decision = {
176
+ [K in PendingActionKind]: {
177
+ kind: K;
178
+ data: DecisionDataByKind[K];
179
+ };
180
+ }[PendingActionKind];
181
+ /** What a session waits on. `card` is `null` when its content cannot be shown. */
182
+ export type PendingAction = {
183
+ [K in PendingActionKind]: {
184
+ /** Opaque. Echo it back with the decision; never parse it. */
185
+ id: string;
186
+ kind: K;
187
+ accepts: (typeof DECISION_PART_TYPE)[K];
188
+ card: CardByKind[K] | null;
189
+ };
190
+ }[PendingActionKind];
191
+ export type SessionPhase = 'running' | 'awaiting_input' | 'idle' | 'completed';
192
+ export interface SessionStateSpecFile {
193
+ specType: string;
194
+ specFileId: string;
195
+ filePath: string;
196
+ fileRevisionId: string;
197
+ revisionNumber: number;
198
+ }
199
+ /** One answered question of an MCQ round, with option labels resolved. */
200
+ export interface SessionStateMcqAnswer {
201
+ questionId: string;
202
+ /** The question text, or `null` when the form is no longer in the transcript. */
203
+ question: string | null;
204
+ /** Labels of the chosen options. */
205
+ selected: string[];
206
+ /** Free text typed under "Other", when there was any. */
207
+ other?: string;
208
+ }
209
+ /**
210
+ * Who made a decision and when, where the transcript records it. A decision
211
+ * saved before the server recorded the sender has none of these: treat a
212
+ * missing `actorKind` as unknown, not as a person.
213
+ */
214
+ export interface SessionStateDecisionAttribution {
215
+ /** User id of whoever sent the turn: a person, or an org agent identity. */
216
+ answeredBy?: string;
217
+ /** ISO-8601 time the server received the turn. */
218
+ answeredAt?: string;
219
+ /** `ai` when an agent decided, `human` when a person did. */
220
+ actorKind?: 'human' | 'ai';
221
+ }
222
+ /** One entry of the decision log: what was decided on one card, and by whom. */
223
+ export type SessionStateDecision = SessionStateDecisionAttribution & SessionStateDecisionContent;
224
+ type SessionStateDecisionContent = {
225
+ kind: 'mcq';
226
+ stage: string;
227
+ round: number;
228
+ answers: SessionStateMcqAnswer[];
229
+ /** `true` when the workflow derived the answer from a chat reply. */
230
+ onBehalf?: boolean;
231
+ } | {
232
+ kind: 'spec-decision';
233
+ specType: string | null;
234
+ action: string;
235
+ editPrompt?: string;
236
+ } | {
237
+ kind: 'review-decision';
238
+ specType: string | null;
239
+ action: string;
240
+ editPrompt?: string;
241
+ } | {
242
+ kind: 'skill-selection';
243
+ skillId: string | null;
244
+ } | {
245
+ kind: 'user-choice';
246
+ choiceId: string;
247
+ label: string | null;
248
+ } | {
249
+ kind: 'edit-decision';
250
+ turnId: string;
251
+ decisions: Record<string, string>;
252
+ } | {
253
+ kind: 'site-plan';
254
+ decision: string;
255
+ feedback?: string;
256
+ } | {
257
+ kind: 'artifact-revision';
258
+ artifactId: string;
259
+ revisionNumber: number;
260
+ decision: string;
261
+ feedback?: string;
262
+ };
263
+ /** The answer of `GET /api/v1/chat/:id/state`. */
264
+ export interface SessionState {
265
+ sessionId: string;
266
+ projectId: string;
267
+ status: string;
268
+ phase: SessionPhase;
269
+ workflowId: string | null;
270
+ stage: string | null;
271
+ substage: string | null;
272
+ turn: {
273
+ running: boolean;
274
+ heldBy?: string;
275
+ };
276
+ pendingAction: PendingAction | null;
277
+ specFiles: SessionStateSpecFile[];
278
+ decisions: SessionStateDecision[];
279
+ decisionsTruncated?: true;
280
+ /**
281
+ * Agent-driven turns of this session: how many it has run and how many it
282
+ * may run. At `used >= cap` the next agent-driven turn is refused
283
+ * (`AgentTurnCapReachedError`); a person's turn still runs.
284
+ *
285
+ * Absent when the server is older than this field: the state route existed
286
+ * before it. Such a server has no turn cap.
287
+ */
288
+ agentTurns?: {
289
+ used: number;
290
+ cap: number;
291
+ };
292
+ /**
293
+ * Whether the server's kill switch for agent-driven turns is on. Off, an
294
+ * agent may not continue a session (`AgentDrivingDisabledError`).
295
+ *
296
+ * It reports the switch only. It does not say the next turn will run: the
297
+ * cap is in `agentTurns`, a read-only token cannot send a turn at all, and
298
+ * the opening turn of a session runs whatever this says. Absent when the
299
+ * server is older than this field.
300
+ */
301
+ agentDrivingEnabled?: boolean;
302
+ }
303
+ /** An error the turn's stream carried instead of (or after) its content. */
304
+ export interface TurnStreamError {
305
+ /** The ai-agent's error code when the stream named one, else `STREAM_ERROR`. */
306
+ code: string;
307
+ message: string;
308
+ /**
309
+ * Whether the ai-agent says the turn can be tried again. `false` for a
310
+ * refusal that trying again cannot change (a quota, a missing permission);
311
+ * absent when the stream did not say.
312
+ */
313
+ recoverable?: boolean;
314
+ }
315
+ /** What one sent turn produced. */
316
+ export interface TurnResult {
317
+ /** The assistant's text of this turn, deltas joined. */
318
+ assistantText: string;
319
+ /** The stream's error, or `null` when the turn ended normally. */
320
+ error: TurnStreamError | null;
321
+ /**
322
+ * `true` when the wait budget elapsed before the stream ended. The stream is
323
+ * still being read in the background so the turn is not cut short; read the
324
+ * state again (or `waitForTurn`) to learn its outcome.
325
+ */
326
+ turnStillRunning: boolean;
327
+ /**
328
+ * The state read after the turn. `null` while the turn still runs, and when
329
+ * that read failed (see `stateError`).
330
+ */
331
+ state: SessionState | null;
332
+ /**
333
+ * Set when the turn ran but the state could not be read after it. The turn
334
+ * is NOT to be sent again: read the state (`getState`) when the server is
335
+ * reachable again.
336
+ */
337
+ stateError?: unknown;
338
+ }
339
+ export {};
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Wire types of the MySpec session driver.
3
+ *
4
+ * These mirror, structurally, what the ai-agent sends and accepts. They are
5
+ * written out here rather than imported from `@myspec/ai` so the SDK has no
6
+ * runtime dependency. A test in the ai-agent assigns each `@myspec/ai` type to
7
+ * its mirror below, so a renamed or retyped field fails that project's
8
+ * typecheck instead of failing a caller at runtime.
9
+ */
10
+ /** Every kind of card a session can wait on. */
11
+ export const PENDING_ACTION_KINDS = [
12
+ 'mcq',
13
+ 'spec-decision',
14
+ 'review-decision',
15
+ 'skill-selection',
16
+ 'user-choice',
17
+ 'edit-decision',
18
+ 'site-plan',
19
+ 'artifact-revision',
20
+ ];
21
+ /**
22
+ * The `pendingActionId` that says "the session must wait on no card". The
23
+ * server refuses the turn, as for a stale card id, when a card is pending. It
24
+ * cannot be the id of a card: those always hold a colon.
25
+ */
26
+ export const NO_PENDING_ACTION_ID = 'none';
27
+ /** The decision part type that answers each kind. */
28
+ export const DECISION_PART_TYPE = {
29
+ mcq: 'data-mcq-answers',
30
+ 'spec-decision': 'data-spec-decision',
31
+ 'review-decision': 'data-review-decision',
32
+ 'skill-selection': 'data-skill-selection',
33
+ 'user-choice': 'data-user-choice-response',
34
+ 'edit-decision': 'data-edit-decision',
35
+ 'site-plan': 'data-site-plan-decision',
36
+ 'artifact-revision': 'data-artifact-revision-decision',
37
+ };
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "@myspec/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "MySpec session driver: read what a chat session waits on and answer it, from a script, a test or an agent",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "default": "./dist/index.js"
12
+ }
13
+ },
14
+ "keywords": [
15
+ "myspec",
16
+ "sdk",
17
+ "spec-session",
18
+ "agent"
19
+ ],
20
+ "author": "MySpec Team",
21
+ "license": "MIT",
22
+ "engines": {
23
+ "node": ">=22"
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "README.md",
28
+ "LICENSE"
29
+ ],
30
+ "sideEffects": false,
31
+ "publishConfig": {
32
+ "access": "public"
33
+ }
34
+ }