@agent-compose/sdk 0.7.0 → 0.8.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.
Files changed (116) hide show
  1. package/README.md +66 -39
  2. package/dist/agent/__tests__/runtime-json-schema.test.d.ts +10 -0
  3. package/dist/agent/agent-context.d.ts +21 -1
  4. package/dist/agent/agent-loop.d.ts +24 -1
  5. package/dist/client.d.ts +338 -534
  6. package/dist/directives.d.ts +112 -0
  7. package/dist/display.d.ts +242 -0
  8. package/dist/errors.d.ts +24 -1
  9. package/dist/index.d.ts +24 -12
  10. package/dist/index.js +3545 -1667
  11. package/dist/pause/wrappers.d.ts +31 -9
  12. package/dist/runtimes/_acp-client.d.ts +46 -1
  13. package/dist/runtimes/_cli-agent.d.ts +49 -4
  14. package/dist/runtimes/_jsonl-guard.d.ts +103 -0
  15. package/dist/runtimes/amp.d.ts +2 -2
  16. package/dist/runtimes/claude-code.d.ts +59 -0
  17. package/dist/runtimes/claude-code.test.d.ts +14 -0
  18. package/dist/runtimes/claude.d.ts +16 -0
  19. package/dist/runtimes/claude.test.d.ts +8 -0
  20. package/dist/runtimes/codex.d.ts +9 -3
  21. package/dist/runtimes/cursor.d.ts +2 -2
  22. package/dist/runtimes/droid.d.ts +2 -2
  23. package/dist/runtimes/jsonl-guard.test.d.ts +19 -0
  24. package/dist/runtimes/openai-desktop.js +2691 -864
  25. package/dist/runtimes/opencode.d.ts +2 -2
  26. package/dist/runtimes/vercel.js +12 -1
  27. package/dist/sandbox/devbox.d.ts +42 -0
  28. package/dist/sandbox/exec-stream.d.ts +14 -0
  29. package/dist/sandbox/network-policy.d.ts +100 -0
  30. package/dist/sandbox/provider-def.d.ts +79 -0
  31. package/dist/sandbox/providers/desktop.d.ts +10 -0
  32. package/dist/sandbox/providers/e2b.d.ts +17 -0
  33. package/dist/sandbox/providers/local.d.ts +11 -0
  34. package/dist/sandbox/providers/vercel.d.ts +18 -0
  35. package/dist/sandbox/registry.d.ts +45 -0
  36. package/dist/sandbox/sizes.d.ts +68 -0
  37. package/dist/sandbox.d.ts +24 -299
  38. package/dist/step-invocation/__tests__/foreground-recovery.test.d.ts +1 -0
  39. package/dist/step-invocation/invoker.d.ts +10 -0
  40. package/dist/step-invocation/protocol.d.ts +5 -0
  41. package/dist/types/api-compliance.d.ts +71 -0
  42. package/dist/types/api-conversations.d.ts +492 -0
  43. package/dist/types/api-factory.d.ts +309 -0
  44. package/dist/types/api-projects.d.ts +131 -0
  45. package/dist/types/api-runs.d.ts +377 -0
  46. package/dist/types/api-scopes.d.ts +102 -0
  47. package/dist/types/conversation-stream.d.ts +191 -0
  48. package/dist/types/execution-context.d.ts +12 -2
  49. package/dist/types/protocol.d.ts +30 -1
  50. package/dist/types/sandbox-environment.d.ts +8 -5
  51. package/dist/types/sandbox.d.ts +74 -4
  52. package/dist/types/workflow-metadata.d.ts +33 -8
  53. package/dist/types/workflow-plan.d.ts +10 -0
  54. package/dist/types/workflow.d.ts +18 -205
  55. package/dist/utils/bundler.d.ts +12 -1
  56. package/dist/workflow-steps/index.d.ts +1 -1
  57. package/dist/workflow-steps/observability.d.ts +8 -1
  58. package/dist/workflow-steps/runner.d.ts +3 -3
  59. package/dist/workflow-steps/step.d.ts +15 -1
  60. package/dist/workflow-steps/types.d.ts +19 -5
  61. package/dist/workflow-steps/workflow.d.ts +22 -1
  62. package/dist/workflows/engine.d.ts +3 -2
  63. package/dist/workflows/invoke-child.d.ts +2 -2
  64. package/package.json +1 -1
  65. package/src/agent/agent-context.ts +186 -3
  66. package/src/agent/agent-loop.ts +31 -2
  67. package/src/client.ts +909 -621
  68. package/src/directives.ts +184 -0
  69. package/src/display.ts +788 -0
  70. package/src/errors.ts +39 -0
  71. package/src/index.ts +104 -10
  72. package/src/pause/wrappers.ts +44 -9
  73. package/src/runtimes/_acp-client.ts +72 -3
  74. package/src/runtimes/_cli-agent.ts +159 -36
  75. package/src/runtimes/_jsonl-guard.ts +219 -0
  76. package/src/runtimes/claude-code.ts +246 -0
  77. package/src/runtimes/claude.ts +32 -2
  78. package/src/runtimes/codex.ts +55 -3
  79. package/src/runtimes/openai-desktop.ts +59 -14
  80. package/src/sandbox/devbox.ts +48 -0
  81. package/src/sandbox/exec-stream.ts +48 -0
  82. package/src/sandbox/network-policy.ts +181 -0
  83. package/src/sandbox/provider-def.ts +94 -0
  84. package/src/sandbox/providers/desktop.ts +57 -0
  85. package/src/sandbox/providers/e2b.ts +354 -0
  86. package/src/sandbox/providers/local.ts +106 -0
  87. package/src/sandbox/providers/vercel.ts +331 -0
  88. package/src/sandbox/registry.ts +198 -0
  89. package/src/sandbox/sizes.ts +95 -0
  90. package/src/sandbox.ts +59 -1275
  91. package/src/step-invocation/invoker.ts +151 -28
  92. package/src/step-invocation/protocol.ts +8 -0
  93. package/src/types/api-compliance.ts +79 -0
  94. package/src/types/api-conversations.ts +522 -0
  95. package/src/types/api-factory.ts +336 -0
  96. package/src/types/api-projects.ts +140 -0
  97. package/src/types/api-runs.ts +412 -0
  98. package/src/types/api-scopes.ts +102 -0
  99. package/src/types/conversation-stream.ts +231 -0
  100. package/src/types/execution-context.ts +10 -2
  101. package/src/types/protocol.ts +33 -0
  102. package/src/types/sandbox-environment.ts +28 -9
  103. package/src/types/sandbox.ts +73 -4
  104. package/src/types/workflow-metadata.ts +35 -8
  105. package/src/types/workflow-plan.ts +11 -0
  106. package/src/types/workflow.ts +25 -292
  107. package/src/utils/bundler.ts +32 -5
  108. package/src/utils/errors.ts +16 -1
  109. package/src/workflow-steps/index.ts +1 -0
  110. package/src/workflow-steps/observability.ts +19 -8
  111. package/src/workflow-steps/runner.ts +4 -4
  112. package/src/workflow-steps/step.ts +49 -1
  113. package/src/workflow-steps/types.ts +20 -5
  114. package/src/workflow-steps/workflow.ts +22 -1
  115. package/src/workflows/engine.ts +3 -2
  116. package/src/workflows/invoke-child.ts +2 -2
package/src/client.ts CHANGED
@@ -12,13 +12,108 @@
12
12
  */
13
13
 
14
14
  import { ofetch } from "ofetch";
15
- import { AgentComposeError } from "./errors.js";
15
+ import { AgentComposeError, parseRetryAfterMs } from "./errors.js";
16
16
  import { parseSseStream } from "./sse.js";
17
- import type { SandboxNetworkPolicy, SandboxSize } from "./sandbox.js";
18
17
  import type { RunEvent } from "./types/events.js";
19
- import type { WorkflowPlan } from "./types/workflow-plan.js";
20
- import type { SnapshotConfig, IOSchema, ConnectorRequirements, ConnectorOperationTag, InvokePolicy, SandboxResources } from "./types/workflow-metadata.js";
21
- import type { WorkflowManifest } from "./utils/bundler.js";
18
+ import type { ConversationStreamEvent } from "./types/conversation-stream.js";
19
+ import { normalizeConversationStreamEvent } from "./types/conversation-stream.js";
20
+ import type {
21
+ InvokeWorkflowOptions, InvokeAndWaitOptions, InvokeResult, StreamRunLogsOptions,
22
+ RunStatus, ResumePauseOptions, ResumePauseResponse, AnswerSteerOptions,
23
+ RequestAgentPauseOptions, RequestAgentPauseResponse,
24
+ SendAgentMessageOptions, SendAgentMessageResponse,
25
+ RunDetail, RunListEntry, ListRunsOptions, TimelineEvent, RunFundingResponse, EventRow, ReportEventInput,
26
+ ListEventsOptions, ListEventsResult, RunArtifactRow, RunLogLine, ListRunLogsOptions,
27
+ CancelRunResponse, ListSnapshotsOptions, SnapshotListResponse, SnapshotListEntry, RunSnapshotEntry,
28
+ } from "./types/api-runs.js";
29
+ import type {
30
+ TeamMember, Mention, CreateMentionsInput,
31
+ ConversationsPage, SessionsPage, ConversationDetail, ConversationThread,
32
+ CreateCloudSessionInput, CloudSessionCreated,
33
+ SessionPreview, PreviewOpened, OpenPreviewInput, SessionForked,
34
+ SessionChangeSet, SessionMergeReport, SessionDiscardReport,
35
+ SendConversationMessageInput, SendConversationMessageResult,
36
+ ChannelSessionRow, ChannelSessionsResponse, SessionChannelMessagePosted,
37
+ ConversationPresenceSnapshot, StreamConversationOptions, AgentListRow,
38
+ } from "./types/api-conversations.js";
39
+ import type {
40
+ ConversationMemberRole, ConversationMember, ArtifactScope,
41
+ SetScopeGrantsInput, SetTemplateScopeInput,
42
+ } from "./types/api-scopes.js";
43
+ import type {
44
+ Project, ProjectsPage, ProjectRole, ProjectMember,
45
+ ProjectObjectsPage, ProjectAddPreview,
46
+ AddProjectObjectInput, AddProjectObjectResult, RefreshProjectObjectResult,
47
+ } from "./types/api-projects.js";
48
+ import type {
49
+ RegisterResult, RegisterWorkflowInput, TemplateRow, TemplateDetail, ListTemplatesOptions,
50
+ SearchFactoryFilesOptions, FactoryFileSearchResult, FactoryFileWriteResult,
51
+ FactoryRow, CreateFactoryInput, UpdateFactoryInput,
52
+ ScheduleRow, CreateScheduleInput,
53
+ SecretOptions, SetSecretResult, SecretListEntry,
54
+ CreateApiKeyInput, ApiKey, ApiKeyCreated, UsageResponse,
55
+ DriveRepoLink, CreateDriveRepoLinkInput,
56
+ } from "./types/api-factory.js";
57
+ import type {
58
+ ComplianceSession, RequestComplianceSessionInput, ListComplianceSessionsOptions,
59
+ ComplianceSessionsPage, ListComplianceAccessesOptions, ComplianceAccessesPage,
60
+ } from "./types/api-compliance.js";
61
+
62
+ // The client's request/response wire types live in
63
+ // `./types/api-{runs,conversations,scopes,factory}.ts`. They are re-exported
64
+ // here so `client.js` stays the single import surface for the client and its
65
+ // shapes (index.ts re-exports from here).
66
+ export type {
67
+ RunState, InvokeWorkflowOptions, InvokeAndWaitOptions, InvokeResult, StreamRunLogsOptions,
68
+ RunStatus, ResumePauseActor, ResumePauseSuccess, ResumePausePending, ResumePauseResponse,
69
+ ResumePauseOptions, RequestAgentPauseOptions, AnswerSteerOptions, RequestAgentPauseResponse,
70
+ SendAgentMessageOptions, SendAgentMessageResponse,
71
+ RunDetail, RunListEntry, ListRunsOptions, TimelineEvent,
72
+ FundingLane, RunFundingStamp, RunFundingUsageRow, RunFundingResponse,
73
+ EventSubjectType, EventRow, RunArtifactRow, ReportEventInput, ListEventsOptions, ListEventsResult,
74
+ RunLogLine, ListRunLogsOptions, CancelRunResponse,
75
+ ListSnapshotsOptions, SnapshotListEntry, SnapshotListResponse, RunSnapshotEntry,
76
+ } from "./types/api-runs.js";
77
+ export type {
78
+ TeamMember, Mention, CreateMentionsInput,
79
+ ConversationMessagePart, ConversationRow, ConversationMessageRow,
80
+ ConversationsPage, SessionsPage, ConversationDetail,
81
+ CreateCloudSessionInput, CloudSessionCreated, ConversationThread,
82
+ SessionPreview, PreviewOpened, OpenPreviewInput, SessionForked,
83
+ SessionFileChange, SessionChangeSet,
84
+ SessionMergeReportDetail, SessionMergeReport, SessionDiscardReport,
85
+ ConversationPageContext, SendConversationMessageInput, ConversationTurnState,
86
+ SendConversationMessageResult, ConversationPresenceSnapshot, AgentListRow, StreamConversationOptions,
87
+ ChannelSessionStatus, ChannelSessionRow, ChannelSessionsResponse, SessionChannelMessagePosted,
88
+ } from "./types/api-conversations.js";
89
+ export type {
90
+ ConversationMemberRole, ConversationMember,
91
+ DocumentCapability, TemplateCapability, ScopeGrant, ArtifactScope,
92
+ RunContext, SetScopeGrantsInput, SetTemplateScopeInput,
93
+ } from "./types/api-scopes.js";
94
+ export type {
95
+ Project, ProjectsPage, ProjectRole, ProjectMember,
96
+ ProjectObject, ProjectObjectsPage, ProjectSkippedFile, ProjectPreviewFile,
97
+ ProjectAddPreview, AddProjectObjectInput, AddProjectObjectResult,
98
+ RefreshProjectObjectResult,
99
+ } from "./types/api-projects.js";
100
+ export type {
101
+ RegisterResult, RegisteredRuntime, RuntimeSourceInput, TemplateSourceRef, RegisterWorkflowInput,
102
+ TemplateRow, TemplateDetail, ListTemplatesOptions,
103
+ FactoryFileSearchRow, FactoryFolderSearchRow, SearchFactoryFilesOptions, FactoryFileSearchResult, FactoryFileWriteResult,
104
+ PublicFileLinkState,
105
+ FactoryRow, CreateFactoryInput, UpdateFactoryInput,
106
+ ScheduleRow, CreateScheduleInput,
107
+ SecretOptions, SetSecretResult, SecretListEntry,
108
+ CreateApiKeyInput, ApiKey, ApiKeyCreated,
109
+ UsageRollupRow, UsageResponse,
110
+ DriveRepoLink, CreateDriveRepoLinkInput,
111
+ } from "./types/api-factory.js";
112
+ export type {
113
+ ComplianceScopeKind, ComplianceStatus, ComplianceSession, ComplianceAccess,
114
+ RequestComplianceSessionInput, ListComplianceSessionsOptions, ComplianceSessionsPage,
115
+ ListComplianceAccessesOptions, ComplianceAccessesPage,
116
+ } from "./types/api-compliance.js";
22
117
 
23
118
  /** UUID-v4-ish — matches the server-side predicate. Used to auto-detect
24
119
  * that `process.env.RUN_ID` was injected by the runner sandbox (rather
@@ -47,436 +142,9 @@ function templatePath(factorySlug: string, ...rest: string[]): string {
47
142
  return `/api/v1/factories/${encodeURIComponent(factorySlug)}/templates${tail}`;
48
143
  }
49
144
 
50
- export interface RegisterResult {
51
- id: string;
52
- name: string;
53
- version: string;
54
- runtimes?: RegisteredRuntime[];
55
- }
56
-
57
- export interface RegisteredRuntime {
58
- id: string;
59
- name: string;
60
- version: string;
61
- }
62
-
63
- export interface RuntimeSourceInput {
64
- name: string;
65
- source: string;
66
- }
67
-
68
- /** GitHub provenance for a registered template's source file — stored as
69
- * `metadata.source` on the registration. `cloud-build` stamps the built
70
- * commit's sha; the dashboard's manual link path writes `sha: "manual"`. */
71
- export interface TemplateSourceRef {
72
- owner: string;
73
- repo: string;
74
- branch: string;
75
- /** Repo-relative file path, e.g. `.agentc/workflows/workflow-deploy.ts`. */
76
- path: string;
77
- /** Commit sha the version was built from, or `"manual"` for hand-links. */
78
- sha: string;
79
- }
80
-
81
- export interface RegisterWorkflowInput {
82
- name: string;
83
- source: string;
84
- /** Structured attestation produced by `bundleWorkflow`. The server
85
- * requires this on every registration; it proves the source was
86
- * bundled by a `defineWorkflow`-aware toolchain. The server validates
87
- * the manifest's shape and verifies `manifest.sourceHash` matches
88
- * sha256(source) — the source bytes themselves are never parsed or
89
- * executed on the server. */
90
- manifest: WorkflowManifest;
91
- version?: string;
92
- /** Where the source file lives on GitHub — stored as `metadata.source`.
93
- * Named `sourceRef` because `source` is the bundled code itself. */
94
- sourceRef?: TemplateSourceRef;
95
- schedule?: string;
96
- runtimes?: RuntimeSourceInput[];
97
- /** Human-readable description declared via
98
- * `defineWorkflow({ description })`. Stored in template metadata and
99
- * surfaced on the dashboard template card. */
100
- description?: string;
101
- networkPolicy?: unknown;
102
- placeholders?: Record<string, string>;
103
- /** All snapshot config — `bootFrom` (where to restore at run start),
104
- * `save`, `retain`. See `WorkflowMetadata.snapshots`. */
105
- snapshots?: SnapshotConfig;
106
- /** Sandbox machine resources — size + provider (template defaults).
107
- * See `WorkflowMetadata.resources`. */
108
- resources?: SandboxResources;
109
- /** Provider-neutral execution plan detected by the CLI bundler. */
110
- workflowPlan?: WorkflowPlan;
111
- /** Connector requirements declared via `defineWorkflow({ connectors })`
112
- * (ADR-0007). Validated against the server's provider registry at
113
- * registration; tokens are injected at the network layer at dispatch. */
114
- connectors?: ConnectorRequirements;
115
- /** Connector-catalogue operation tag — see `ConnectorOperationTag`. */
116
- connectorOperation?: ConnectorOperationTag;
117
- /** Tier-1 invoke ACL declared via `defineWorkflow({ invokePolicy })`.
118
- * Only meaningful when the workflow also declares `connectors` — the
119
- * server gates dispatch on it before binding any grant. */
120
- invokePolicy?: InvokePolicy;
121
- /** Input schema extracted from the workflow's `input` zod schema. */
122
- inputSchema?: IOSchema;
123
- /** Output schema extracted from the workflow's `output` zod schema. */
124
- outputSchema?: IOSchema;
125
- /** Set by `defineSandboxEnvironment` — marks an environment build so the
126
- * server skips the /factory mount for its runs (#13). See
127
- * `WorkflowMetadata.environmentBuild`. */
128
- environmentBuild?: boolean;
129
- /** Factory slug. Defaults to `"default"`. */
130
- factorySlug?: string;
131
- }
132
-
133
- export type RunState = "running" | "success" | "failed" | "abandoned" | "canceled";
134
-
135
- export interface InvokeWorkflowOptions {
136
- /** Per-invocation snapshot config override. `snapshots.bootFrom`
137
- * replaces the template's boot source; `snapshots.saveLatest` and
138
- * `snapshots.retainSteps` override capture mode. Anything omitted
139
- * falls back to the template's registered default. */
140
- snapshots?: SnapshotConfig;
141
- /** Per-invocation network policy override. Replaces the template-level
142
- * policy for this run only — registered metadata is not mutated. */
143
- networkPolicy?: SandboxNetworkPolicy;
144
- /** Per-invocation placeholder override. Maps secret names referenced in
145
- * `networkPolicy` ($VAR) to the values the runner should see for env
146
- * vars after brokering. Replaces the template-level placeholders for
147
- * this run only — registered metadata is not mutated. */
148
- placeholders?: Record<string, string>;
149
- /** Per-invocation machine-size override of the template's `resources.size`.
150
- * `small` (default) | `medium` | `large`; omit → the template default,
151
- * else `small`. Honoured on Vercel (→ vCPUs); E2B ignores it. */
152
- size?: SandboxSize;
153
- /** Explicit parent run id. Pass `null` to suppress ambient RUN_ID auto-detection. */
154
- parentRunId?: string | null;
155
- /** Agent loop inside the parent run that caused this invoke, when applicable. */
156
- agentId?: string | null;
157
- /** Factory slug. Defaults to `"default"`. */
158
- factorySlug?: string;
159
- /** Idempotency key — sent as the `Idempotency-Key` header. A repeat invoke
160
- * with the same key inside the server's dedup window returns the original
161
- * run instead of starting a new one (matches `resumePause`'s pattern). */
162
- idempotencyKey?: string;
163
- }
164
-
165
- export interface InvokeAndWaitOptions extends InvokeWorkflowOptions {
166
- timeoutMs?: number;
167
- pollIntervalMs?: number;
168
- }
169
-
170
- export interface InvokeResult {
171
- id: string;
172
- }
173
-
174
- export interface ListSnapshotsOptions {
175
- /** Factory slug. Defaults to `"default"`. */
176
- factorySlug?: string;
177
- workflow?: string;
178
- limit?: number;
179
- /** Cursor returned as `next_cursor` from `listSnapshotsPage`. */
180
- before?: string;
181
- }
182
-
183
- export interface TemplateRow {
184
- name: string;
185
- version: string;
186
- factorySlug: string;
187
- }
188
-
189
- export interface ListTemplatesOptions {
190
- factorySlug?: string;
191
- }
192
-
193
- /** A human member of your team — the people an agent (or you) can @-flag. */
194
- export interface TeamMember {
195
- /** Membership row id. */
196
- id: string;
197
- /** The user id — what you pass to `createMentions({ mentionedUserIds })`. */
198
- userId: string;
199
- role: string;
200
- email: string;
201
- name: string;
202
- joinedAt: string;
203
- }
204
-
205
- /** A "you were flagged" ping, persisted server-side so it reaches the
206
- * mentioned teammate in their Workbench. */
207
- export interface Mention {
208
- id: string;
209
- factoryId: string;
210
- mentionedUserId: string;
211
- /** Who flagged: 'user' | 'api_key' | 'run' | 'system'. */
212
- actorKind: string;
213
- actorId: string | null;
214
- actorLabel: string | null;
215
- /** Where it lives: 'doc' | 'comment' | 'plan' | 'run'. */
216
- contextKind: string;
217
- contextPath: string | null;
218
- /** Ready-made relative dashboard URL the Workbench card links to. */
219
- contextUrl: string | null;
220
- text: string;
221
- runId: string | null;
222
- seenAt: string | null;
223
- resolvedAt: string | null;
224
- createdAt: string;
225
- }
226
-
227
- export interface CreateMentionsInput {
228
- /** Team-member user ids to flag (1–20). Discover them via `listMembers()`.
229
- * Non-members are dropped server-side. */
230
- mentionedUserIds: string[];
231
- /** The flag message shown in the teammate's Workbench. */
232
- text: string;
233
- contextKind: "doc" | "comment" | "plan" | "run";
234
- /** Factory-relative file path or comment thread id, when applicable. */
235
- contextPath?: string;
236
- /** Ready-made relative dashboard URL the Workbench card links to (e.g.
237
- * `/factories/<slug>/files/view?path=<plan>`). */
238
- contextUrl?: string;
239
- runId?: string;
240
- factorySlug?: string;
241
- }
242
-
243
- export interface CreateFactoryInput {
244
- slug: string;
245
- name: string;
246
- description?: string;
247
- }
248
-
249
- export interface UpdateFactoryInput {
250
- name?: string;
251
- description?: string;
252
- }
253
-
254
- export interface ScheduleRow {
255
- id: string;
256
- name: string;
257
- workflowName: string;
258
- cron: string;
259
- createdAt: string;
260
- updatedAt: string;
261
- nextFireAt: string | null;
262
- lastFireAt: string | null;
263
- }
264
-
265
- export interface CreateScheduleInput {
266
- /** Human-friendly schedule name. Unique within the factory. */
267
- name: string;
268
- /** The workflow this schedule should fire. Must already be registered
269
- * in the same factory. */
270
- workflow: string;
271
- /** Cron expression (UTC). */
272
- cron: string;
273
- /** Factory to attach the schedule to. Defaults to `"default"`. */
274
- factorySlug?: string;
275
- }
276
-
277
- export interface SecretOptions {
278
- factorySlug?: string;
279
- }
280
-
281
- export interface SetSecretResult {
282
- key: string;
283
- }
284
-
285
- export interface SecretListEntry {
286
- key: string;
287
- createdAt: string;
288
- updatedAt: string;
289
- }
290
-
291
- export interface CreateApiKeyInput {
292
- name?: string;
293
- scopes?: string[];
294
- expiresAt?: string;
295
- factorySlug?: string;
296
- }
297
-
298
- export interface StreamRunLogsOptions {
299
- lastEventId?: number;
300
- signal?: AbortSignal;
301
- }
302
-
303
- export interface RunStatus<TOutput = unknown> {
304
- id: string;
305
- status: RunState;
306
- output?: TOutput;
307
- /** The run's latest (`saveLatest`) snapshot id, populated once the run has
308
- * succeeded — the boot source to fork this run's evolved filesystem from
309
- * (pass as `snapshots.bootFrom` on a follow-up invoke). `null` while the run
310
- * is still in flight or when it captured no snapshot. Lets an orchestrator
311
- * fork a child straight off the `invokeChild` result without a separate
312
- * `listRunSnapshots` call. */
313
- latestSnapshotId?: string | null;
314
- }
315
-
316
- /** ADR-0006 step 10 — actor record returned on a successful resume.
317
- * Shape mirrors the server's `PauseResumeActor` type after the row
318
- * has been stamped. Audit FKs (`userId` / `keyId` / `runId`) may be
319
- * null when the referenced row was deleted between resume and the
320
- * response render — the immutable `label` survives. */
321
- export interface ResumePauseActor {
322
- kind: "session_user" | "api_key" | "agent";
323
- /** Better Auth user id when kind='session_user'. */
324
- userId?: string | null;
325
- /** api_keys.id when kind='api_key'. */
326
- keyId?: string | null;
327
- /** Caller-run id when kind='agent' (NOT the run being resumed). */
328
- runId?: string | null;
329
- /** Agent-instance within `runId` when kind='agent'. */
330
- agentId?: string | null;
331
- label: string;
332
- }
333
-
334
- /** Success branch of the resume HTTP response. The pause has reached
335
- * a terminal state — `resolved` (workflow signal arrived), `expired`
336
- * (TTL fired first), or `cancelled` (workflow terminated mid-pause).
337
- * Only `resolved` carries the resume payload the user supplied. */
338
- export interface ResumePauseSuccess {
339
- status: "resolved" | "expired" | "cancelled";
340
- pauseId: string;
341
- resolvedAt: string | null;
342
- resumePayload: unknown;
343
- actor: ResumePauseActor | null;
344
- }
345
-
346
- /** Pending branch — the workflow accepted the signal but the row
347
- * flip didn't observe within the route's 5s wait window. The
348
- * operation is in-flight; retry with the same `Idempotency-Key`
349
- * and the cache collapses the duplicate to a single canonical
350
- * response. */
351
- export interface ResumePausePending {
352
- status: "pending";
353
- pauseId: string;
354
- timedOut: true;
355
- }
356
-
357
- export type ResumePauseResponse = ResumePauseSuccess | ResumePausePending;
358
-
359
- export interface ResumePauseOptions {
360
- /** Stripe-style retry-dedup key — same syntax as the workflow-invoke
361
- * route: 1..255 chars of `[A-Za-z0-9_\-:.]`, no embedded CR/LF.
362
- * Sent as the `Idempotency-Key` request header. (The server reads the
363
- * header first, falling back to a body field for callers behind a
364
- * header-stripping proxy; this client only sends the header.) */
365
- idempotencyKey?: string;
366
- /** Abort the HTTP request mid-wait (e.g. from a UI cancel button).
367
- * The server's LISTEN tears down via the request's AbortSignal. */
368
- signal?: AbortSignal;
369
- }
370
-
371
- export interface RequestAgentPauseOptions {
372
- /** Human-readable note surfaced to the agent as the pause reason. */
373
- reason?: string;
374
- /** Your handle for answering this pause without the minted pauseId:
375
- * pass the same value to `resumePauseByKey`. */
376
- correlationKey?: string;
377
- /** Abort the HTTP request. */
378
- signal?: AbortSignal;
379
- }
380
-
381
- export interface AnswerSteerOptions extends ResumePauseOptions {
382
- /** Who answered — surfaced to the agent as `[human steer from <actor>]`. */
383
- actor?: string;
384
- }
385
-
386
- /** 202 envelope from a steer-pause request. The request is best-effort and
387
- * fire-and-forget: it publishes a transient control message and returns
388
- * immediately — the agent parks at its next iteration boundary (if it is
389
- * `mode: "hitl"` and still running). Answer it via `answerSteerByKey`
390
- * (pass the `correlationKey` you set here) or `answerSteer` (by pauseId). */
391
- export interface RequestAgentPauseResponse {
392
- status: "steer_requested";
393
- runId: string;
394
- agentId: string;
395
- }
396
-
397
- export interface SendAgentMessageOptions {
398
- /** Transcript attribution. For non-session callers (API key, orchestrator)
399
- * this names the sender; defaults to the caller's identity server-side. */
400
- senderName?: string;
401
- /** Abort the HTTP request. */
402
- signal?: AbortSignal;
403
- }
404
-
405
- /** 202 envelope from a message-to-running-agent request. The message is queued
406
- * durably and delivered mid-stream as the agent's next user turn — the workflow
407
- * is NOT paused. `seq` is the message's per-run ordinal. */
408
- export interface SendAgentMessageResponse {
409
- status: "message_enqueued";
410
- runId: string;
411
- agentId: string;
412
- seq: number;
413
- }
414
-
415
- export interface RunDetail<TOutput = unknown> {
416
- runId: string;
417
- title: string;
418
- metadata: Record<string, unknown>;
419
- outcome: string;
420
- startedAt: string;
421
- endedAt: string | null;
422
- durationMs: number | null;
423
- failureReason: string | null;
424
- input: unknown;
425
- output: TOutput | null;
426
- lifecycleEvents: Array<{ at: string; type: string; payload: unknown }>;
427
- children?: RunDetail[];
428
- }
429
-
430
- export interface TimelineEvent {
431
- kind: string;
432
- at: string;
433
- seq: number;
434
- type: string;
435
- payload: Record<string, unknown>;
436
- }
437
-
438
- export type EventSubjectType = "run" | "agent" | "workflow" | "factory";
439
-
440
- export interface EventRow {
441
- id: string;
442
- teamId: string;
443
- subjectType: EventSubjectType | string;
444
- subjectId: string;
445
- runId: string | null;
446
- agentId: string | null;
447
- workflowId: string | null;
448
- factoryId: string | null;
449
- name: string;
450
- body: unknown;
451
- summary: string | null;
452
- confidence: string | null;
453
- timestamp: string;
454
- attributes: Record<string, unknown>;
455
- propagate: boolean;
456
- idempotencyKey: string | null;
457
- createdAt: string;
458
- }
459
-
460
- // The server emits these rows in snake_case; the client maps them to
461
- // camelCase at the fetch boundary so the SDK surface stays uniform
462
- // (`EventRow.createdAt`, `RunStatus.latestSnapshotId`, …).
463
- export interface RunArtifactRow {
464
- path: string;
465
- factorySlug: string | null;
466
- sizeBytes: number | null;
467
- lastWriteAt: string;
468
- /** Opening text of the file (≤320 chars) — null for binary/empty. */
469
- preview: string | null;
470
- }
471
-
472
- export interface FactoryFileWriteResult {
473
- path: string;
474
- contentHash: string;
475
- sizeBytes: number;
476
- created: boolean;
477
- }
478
-
479
- /** Wire shapes — what the server actually emits (snake_case). */
145
+ /** Wire shapes — what the server actually emits (snake_case); the client
146
+ * maps them to camelCase at the fetch boundary so the SDK surface stays
147
+ * uniform (`RunArtifactRow.sizeBytes`, `FactoryFileWriteResult.contentHash`). */
480
148
  interface RunArtifactWire {
481
149
  path: string;
482
150
  factory_slug: string | null;
@@ -492,141 +160,6 @@ interface FactoryFileWriteWire {
492
160
  created: boolean;
493
161
  }
494
162
 
495
- export interface ReportEventInput {
496
- name: string;
497
- body: unknown;
498
- summary?: string;
499
- confidence?: number;
500
- timestamp?: string | Date;
501
- attributes?: Record<string, unknown>;
502
- propagate?: boolean;
503
- idempotencyKey?: string;
504
- }
505
-
506
- export interface ListEventsOptions {
507
- factorySlug?: string;
508
- limit?: number;
509
- /** Case-insensitive substring match. Server uses `ILIKE %name%`, so
510
- * `"site"` matches `site.created`, `site.failed`, etc. Pass the
511
- * full event name for an effectively-exact filter (any string is a
512
- * substring of itself). */
513
- name?: string;
514
- /** Date-range lower bound: only include events at or after this
515
- * timestamp. Used by the dashboard's range toggle (1h / 24h / 7d
516
- * / 30d). Same semantics as `from` on the runs list endpoint. */
517
- from?: string;
518
- /** Timestamp cursor for "load older" pagination. Pass the
519
- * `timestamp` of the last row from the previous page; the server
520
- * returns rows strictly older than that. Distinct from `from`:
521
- * `from` filters a date range, `before` walks the page boundary.
522
- * Both can be supplied together for a paginated range-query. */
523
- before?: string;
524
- }
525
-
526
- export interface ListEventsResult {
527
- events: EventRow[];
528
- has_more: boolean;
529
- }
530
-
531
- /** One captured stdout or stderr line from a run's sandbox subprocess.
532
- * `id` is per-run monotonically increasing — pass the highest `id`
533
- * you've seen as `afterId` to paginate forward. */
534
- export interface RunLogLine {
535
- id: number;
536
- at: string;
537
- stream: "stdout" | "stderr";
538
- line: string;
539
- }
540
-
541
- export interface ListRunLogsOptions {
542
- /** Return only lines with `id > afterId` (forward pagination). */
543
- afterId?: number;
544
- /** Max lines (server clamps to [1, 1000], defaults to 200). */
545
- limit?: number;
546
- /** Stream direction. `"asc"` (default) returns the oldest lines first
547
- * — use with `afterId` to paginate forward. `"desc"` returns the newest
548
- * lines first — use to fetch the last N lines of a finished run. */
549
- direction?: "asc" | "desc";
550
- }
551
-
552
- /** Row shape returned by `GET /api-keys`. */
553
- export interface ApiKey {
554
- object: "api_key";
555
- id: string;
556
- name: string | null;
557
- last4: string | null;
558
- scopes: string[];
559
- teamId: string;
560
- createdByUserId: string | null;
561
- /** Non-null when the key is restricted to a single factory. */
562
- factoryId: string | null;
563
- createdAt: string;
564
- expiresAt: string | null;
565
- lastUsedAt: string | null;
566
- revokedAt: string | null;
567
- }
568
-
569
- /** Response from `POST /api-keys`. The `key` field is the plaintext token —
570
- * shown once at creation, never retrievable again. */
571
- export interface ApiKeyCreated extends ApiKey { key: string }
572
-
573
- /** Single rollup row from `GET /api/v1/usage`. */
574
- export interface UsageRollupRow {
575
- eventType: string;
576
- unit: string;
577
- total: number;
578
- tags: Record<string, unknown>;
579
- }
580
-
581
- /** Response from `GET /api/v1/usage`. */
582
- export interface UsageResponse {
583
- object: "list";
584
- data: UsageRollupRow[];
585
- has_more: boolean;
586
- from: string | null;
587
- to: string | null;
588
- }
589
-
590
- /** Response from `POST /api/v1/workflows/:id/cancel`. The endpoint is
591
- * idempotent: cancelling a run that's already terminal returns its current
592
- * outcome verbatim (rather than throwing or pretending it just canceled),
593
- * so `status` widens to every terminal value the server might surface. */
594
- export interface CancelRunResponse {
595
- runId: string;
596
- status: "canceled" | "success" | "failed" | "abandoned";
597
- canceledAt: string;
598
- }
599
-
600
- export interface SnapshotListEntry {
601
- snapshotId: string;
602
- kind: "latest" | "step";
603
- stepIndex: number | null;
604
- runId: string;
605
- workflow: string | null;
606
- version: string | null;
607
- createdAt: string | null;
608
- /** Provider-reported on-disk size, or null when unavailable. */
609
- sizeBytes: number | null;
610
- }
611
-
612
- export interface SnapshotListResponse {
613
- object: "list";
614
- data: SnapshotListEntry[];
615
- has_more: boolean;
616
- next_cursor: string | null;
617
- }
618
-
619
- export interface RunSnapshotEntry {
620
- snapshotId: string;
621
- /** `"latest"` = current/last pointer on the run.
622
- * `"step"` = retained per-step snapshot. */
623
- kind: "latest" | "step";
624
- stepIndex: number | null;
625
- createdAt: string | null;
626
- /** Provider-reported on-disk size, or null when unavailable. */
627
- sizeBytes: number | null;
628
- }
629
-
630
163
  export interface AgentComposeClientOptions {
631
164
  /** Your team's API key — minted from the dashboard or `agentc keys create`.
632
165
  * Required. Resolved from `process.env.AGENT_COMPOSE_API_KEY` when omitted. */
@@ -675,12 +208,50 @@ export class AgentComposeClient {
675
208
  baseURL: this.baseUrl,
676
209
  headers: { Authorization: `Bearer ${apiKey}` },
677
210
  async onResponseError({ response }) {
678
- const body = response._data as { error?: string } | undefined;
679
- throw new AgentComposeError(response.status, body?.error ?? response.statusText);
211
+ const body = response._data as { error?: string; code?: string; capability?: string } | undefined;
212
+ throw new AgentComposeError(response.status, body?.error ?? response.statusText, {
213
+ retryAfterMs: parseRetryAfterMs(response.headers.get("retry-after")),
214
+ ...(body?.code ? { code: body.code } : {}),
215
+ ...(body?.capability ? { capability: body.capability } : {}),
216
+ });
680
217
  },
681
218
  });
682
219
  }
683
220
 
221
+ /** Open an authenticated SSE stream and yield its parsed frames. Uses raw
222
+ * `fetch` (not ofetch) because SSE requires access to the response's
223
+ * `ReadableStream`, which ofetch consumes when parsing. Auth + base URL
224
+ * come from the same constructor inputs, and non-2xx responses throw the
225
+ * same `AgentComposeError`. Shared by `streamRunLogs` / `streamConversation`
226
+ * — per-event mapping stays at each call site. */
227
+ private async *openSseStream(
228
+ path: string,
229
+ opts?: { lastEventId?: number; signal?: AbortSignal },
230
+ ): AsyncGenerator<{ id: number; event: string; data: Record<string, unknown> }> {
231
+ const headers: Record<string, string> = {
232
+ Authorization: `Bearer ${this.apiKey}`,
233
+ Accept: "text/event-stream",
234
+ };
235
+ if (opts?.lastEventId && opts.lastEventId > 0) {
236
+ headers["Last-Event-ID"] = String(opts.lastEventId);
237
+ }
238
+ const res = await fetch(`${this.baseUrl}${path}`, {
239
+ headers,
240
+ ...(opts?.signal ? { signal: opts.signal } : {}),
241
+ });
242
+ if (!res.ok || !res.body) {
243
+ let message = res.statusText;
244
+ try {
245
+ const body = await res.json() as { error?: string };
246
+ if (body.error) message = body.error;
247
+ } catch { /* non-JSON error body — fall back to statusText */ }
248
+ throw new AgentComposeError(res.status, message, {
249
+ retryAfterMs: parseRetryAfterMs(res.headers.get("retry-after")),
250
+ });
251
+ }
252
+ yield* parseSseStream(res.body);
253
+ }
254
+
684
255
  /** Register (or update) a workflow template inside a factory. Defaults to
685
256
  * the team's `default` factory when `factorySlug` is omitted. */
686
257
  register(payload: RegisterWorkflowInput): Promise<RegisterResult> {
@@ -979,6 +550,23 @@ export class AgentComposeClient {
979
550
  return this.fetch(`/api/v1/workflows/${encodeURIComponent(runId)}`);
980
551
  }
981
552
 
553
+ /** Recent runs in one factory, newest first by default. Bounded at the
554
+ * server (limit ≤ 200). `workflow` filters by the registered workflow
555
+ * name (substring) — `listRuns({ workflow: "report", limit: 1 })` is
556
+ * "the latest report run". */
557
+ async listRuns(opts: ListRunsOptions = {}): Promise<RunListEntry[]> {
558
+ const q = new URLSearchParams();
559
+ if (opts.workflow) q.set("workflow", opts.workflow);
560
+ if (opts.search) q.set("search", opts.search);
561
+ if (opts.outcome) q.set("outcome", opts.outcome);
562
+ if (opts.sort) q.set("sort", opts.sort);
563
+ if (opts.limit !== undefined) q.set("limit", String(opts.limit));
564
+ const slug = encodeURIComponent(opts.factorySlug ?? "default");
565
+ const body = await this.fetch<{ workflows: RunListEntry[] }>(
566
+ `/api/v1/factories/${slug}/runs${q.toString() ? `?${q}` : ""}`);
567
+ return body.workflows;
568
+ }
569
+
982
570
  /** Ordered lifecycle timeline for one run. */
983
571
  async getRunTimeline(runId: string, opts?: { limit?: number; offset?: number }): Promise<TimelineEvent[]> {
984
572
  const q = new URLSearchParams();
@@ -990,6 +578,16 @@ export class AgentComposeClient {
990
578
  return body.events;
991
579
  }
992
580
 
581
+ /** One run's funding-lane surface (ADR-0048): per-step credential stamps
582
+ * recorded at resolution, plus the gateway-attested platform dollars —
583
+ * the only usage the ledger records (non-platform lanes are attribution,
584
+ * never metered). */
585
+ async getRunFunding(runId: string): Promise<RunFundingResponse> {
586
+ return this.fetch<RunFundingResponse>(
587
+ `/api/v1/workflows/${encodeURIComponent(runId)}/funding`,
588
+ );
589
+ }
590
+
993
591
  /** Report a durable event against a run. Events are late-binding facts
994
592
  * like quality.accepted, defect.regression, or intervention.override. */
995
593
  async reportEvent(runId: string, input: ReportEventInput): Promise<EventRow> {
@@ -1060,19 +658,415 @@ export class AgentComposeClient {
1060
658
  };
1061
659
  }
1062
660
 
1063
- /** Read one file's current content (or a specific revision) as text. */
1064
- async getFactoryFile(
661
+ /** Read one file's current content (or a specific revision) as RAW BYTES —
662
+ * byte-exact for any content type. This is the wire truth; `getFactoryFile`
663
+ * is a UTF-8 decode over it. Binaries (images, archives) MUST come through
664
+ * here: a text decode is lossy (every non-UTF-8 sequence collapses to
665
+ * U+FFFD and the original bytes are unrecoverable). */
666
+ async getFactoryFileBytes(
1065
667
  path: string,
1066
668
  opts?: { factorySlug?: string; revision?: number },
1067
- ): Promise<string> {
669
+ ): Promise<Uint8Array> {
1068
670
  const factorySlug = opts?.factorySlug
1069
671
  ?? (typeof process !== "undefined" ? process.env?.AGENT_COMPOSE_FACTORY : undefined)
1070
672
  ?? DEFAULT_FACTORY;
1071
673
  const q = new URLSearchParams({ path });
1072
674
  if (opts?.revision !== undefined) q.set("revision", String(opts.revision));
1073
- return this.fetch(
675
+ const buf = await this.fetch<ArrayBuffer, "arrayBuffer">(
1074
676
  `/api/v1/factories/${encodeURIComponent(factorySlug)}/files/content?${q}`,
1075
- { responseType: "text" },
677
+ { responseType: "arrayBuffer" },
678
+ );
679
+ return new Uint8Array(buf);
680
+ }
681
+
682
+ /** Read one file's current content (or a specific revision) as text
683
+ * (UTF-8). For binary files use `getFactoryFileBytes` — decoding them to
684
+ * text corrupts the bytes irreversibly. */
685
+ async getFactoryFile(
686
+ path: string,
687
+ opts?: { factorySlug?: string; revision?: number },
688
+ ): Promise<string> {
689
+ return new TextDecoder().decode(await this.getFactoryFileBytes(path, opts));
690
+ }
691
+
692
+ // ── Conversations ──────────────────────────────────────────────────────────
693
+ // The chat surfaces (channels / solo chats / sessions) the caller can
694
+ // access. Key callers see what their sender scope allows; the server is the
695
+ // sole authority — these are thin typed wrappers.
696
+
697
+ /** List conversations the caller can access, newest-activity first.
698
+ * Cursor-paginated: pass the previous page's `next_cursor`. */
699
+ listConversations(opts?: { cursor?: string }): Promise<ConversationsPage> {
700
+ const q = new URLSearchParams();
701
+ if (opts?.cursor) q.set("cursor", opts.cursor);
702
+ return this.fetch<ConversationsPage>(`/api/v1/conversations${q.toString() ? `?${q}` : ""}`);
703
+ }
704
+
705
+ /** List the sessions the caller can ACCESS in one factory (their own +
706
+ * shared/project-reachable ones), newest first (kind='session' rows are
707
+ * excluded from listConversations by design). Session or user-bound driver credential only. */
708
+ listSessions(factoryId: string, opts?: { cursor?: string }): Promise<SessionsPage> {
709
+ const q = new URLSearchParams({ factoryId });
710
+ if (opts?.cursor) q.set("cursor", opts.cursor);
711
+ return this.fetch<SessionsPage>(`/api/v1/sessions?${q}`);
712
+ }
713
+
714
+ /** One conversation with its latest page of messages. */
715
+ getConversation(id: string): Promise<ConversationDetail> {
716
+ return this.fetch<ConversationDetail>(`/api/v1/conversations/${encodeURIComponent(id)}`);
717
+ }
718
+
719
+ /** Provision a CLOUD-native session (ADR-0037 Phase 3b / ADR-0055 §9): a
720
+ * persistent server-side sandbox on the factory drive that keeps working
721
+ * after the caller's terminal (and laptop) closes. The session's TYPE is
722
+ * fixed at creation: `chat` hosts a coding runtime driven via ACP (open →
723
+ * the transcript, drive it like any conversation); `terminal`/`custom`
724
+ * are raw machine surfaces with no chat pane (open → the PTY). Omitting
725
+ * `type` lets the server derive it from `runtime` (the older-caller
726
+ * grandfather); send it explicitly. Requires the `invoke` scope and a
727
+ * user-bound credential. */
728
+ createCloudSession(input: CreateCloudSessionInput): Promise<CloudSessionCreated> {
729
+ return this.fetch<CloudSessionCreated>(`/api/v1/sessions/cloud`, {
730
+ method: "POST",
731
+ body: {
732
+ ...(input.type ? { type: input.type } : {}),
733
+ ...(input.runtime ? { runtime: input.runtime } : {}),
734
+ factoryId: input.factoryId,
735
+ ...(input.presetId ? { presetId: input.presetId } : {}),
736
+ ...(input.preStart ? { preStart: input.preStart } : {}),
737
+ ...(input.title ? { title: input.title } : {}),
738
+ ...(input.repoUrl ? { repoUrl: input.repoUrl } : {}),
739
+ ...(input.repoBranch ? { repoBranch: input.repoBranch } : {}),
740
+ ...(input.channelId ? { channelId: input.channelId } : {}),
741
+ ...(input.templateId ? { templateId: input.templateId } : {}),
742
+ ...(input.sandboxSize ? { sandboxSize: input.sandboxSize } : {}),
743
+ ...(input.networkPolicy !== undefined ? { networkPolicy: input.networkPolicy } : {}),
744
+ ...(input.connectorProfileId !== undefined ? { connectorProfileId: input.connectorProfileId } : {}),
745
+ },
746
+ });
747
+ }
748
+
749
+ /** One thread (root + replies, oldest→newest) inside a channel. */
750
+ getConversationThread(conversationId: string, rootId: string): Promise<ConversationThread> {
751
+ return this.fetch<ConversationThread>(
752
+ `/api/v1/conversations/${encodeURIComponent(conversationId)}/threads/${encodeURIComponent(rootId)}`,
753
+ );
754
+ }
755
+
756
+ // ── Channel-attached sessions (ADR-0057 — sessions VISIT channels) ────────
757
+ // A session is brought into a channel for as long as a piece of work
758
+ // lasts: attaching shares it with the channel's members (derived access,
759
+ // revoked on detach); the session posts back attributed as itself.
760
+
761
+ /** The sessions attached to a channel, newest attach first, each with its
762
+ * durable rail status (channel read gate). 404 on non-channels. */
763
+ async listChannelSessions(channelId: string): Promise<ChannelSessionRow[]> {
764
+ const body = await this.fetch<ChannelSessionsResponse>(
765
+ `/api/v1/conversations/${encodeURIComponent(channelId)}/sessions`,
766
+ );
767
+ return body.sessions;
768
+ }
769
+
770
+ /** Attach an existing session to a channel — an explicit share act
771
+ * (ADR-0052 consent): only the session's CREATOR may attach it, with
772
+ * channel role ≥ write and a human credential. Idempotent (re-attach is
773
+ * a no-op). Failures: 403 `human_credential_required` | `role_read_only`
774
+ * | `owner_required`; 400 `not_a_session`; 409 `attach_limit_reached`. */
775
+ async attachChannelSession(channelId: string, sessionConversationId: string): Promise<void> {
776
+ await this.fetch(
777
+ `/api/v1/conversations/${encodeURIComponent(channelId)}/sessions`,
778
+ { method: "POST", body: { sessionConversationId } },
779
+ );
780
+ }
781
+
782
+ /** Detach a session from a channel — either side ends the visit (channel
783
+ * role ≥ write, OR the session's creator). Forward-only: the channel's
784
+ * members lose the derived access; relay rows already in the session
785
+ * transcript stay; explicit shares survive. 404 when not attached. */
786
+ async detachChannelSession(channelId: string, sessionConversationId: string): Promise<void> {
787
+ await this.fetch(
788
+ `/api/v1/conversations/${encodeURIComponent(channelId)}/sessions/${encodeURIComponent(sessionConversationId)}`,
789
+ { method: "DELETE" },
790
+ );
791
+ }
792
+
793
+ /** Post one message into a channel AS the calling session (ADR-0057 Seam
794
+ * 4) — progress, results, questions, attributed to the session (title +
795
+ * runtime mark). Session toolbelt credential ONLY (the calling session
796
+ * resolves from the key server-side — 403 `session_credential_required`
797
+ * otherwise); the session must be attached (409 `not_attached`). By
798
+ * default the post lands in the thread of the message that last
799
+ * addressed the session from that channel (the room when none);
800
+ * `threadRootId` overrides it — must be a root message in the channel
801
+ * (400 `invalid_thread_root`). The post never triggers any turn. */
802
+ postSessionChannelMessage(
803
+ channelId: string,
804
+ input: { text: string; threadRootId?: string },
805
+ ): Promise<SessionChannelMessagePosted> {
806
+ return this.fetch<SessionChannelMessagePosted>(
807
+ `/api/v1/conversations/${encodeURIComponent(channelId)}/session-messages`,
808
+ { method: "POST", body: { text: input.text, ...(input.threadRootId ? { threadRootId: input.threadRootId } : {}) } },
809
+ );
810
+ }
811
+
812
+ // ── Cloud-session developer surface (ADR-0052) ────────────────────────────
813
+
814
+ /** Open a dev preview on a cloud session: expose a port a dev server is
815
+ * LISTENING on inside the session sandbox at a member-gated proxy URL, and
816
+ * post an "Open preview" card to the transcript. Resumes a suspended VM
817
+ * (write-tier act — read members get 403). Returns the row + the proxy URL
818
+ * (never the raw sandbox host). */
819
+ openPreview(conversationId: string, input: OpenPreviewInput): Promise<PreviewOpened> {
820
+ return this.fetch<PreviewOpened>(
821
+ `/api/v1/conversations/${encodeURIComponent(conversationId)}/preview`,
822
+ {
823
+ method: "POST",
824
+ body: {
825
+ port: input.port,
826
+ ...(input.name ? { name: input.name } : {}),
827
+ ...(input.path ? { path: input.path } : {}),
828
+ },
829
+ },
830
+ );
831
+ }
832
+
833
+ /** The live dev previews on a cloud session (read-tier allowed). Rows carry
834
+ * `url: null` — a URL is minted on OPEN (short-lived, member-bound). */
835
+ async listPreviews(conversationId: string): Promise<SessionPreview[]> {
836
+ const body = await this.fetch<{ previews: SessionPreview[] }>(
837
+ `/api/v1/conversations/${encodeURIComponent(conversationId)}/previews`,
838
+ );
839
+ return body.previews;
840
+ }
841
+
842
+ /** Take a dev preview down (write-tier). Idempotent — `closed` is false when
843
+ * no active row matched. */
844
+ async closePreview(conversationId: string, port: number): Promise<boolean> {
845
+ const body = await this.fetch<{ closed: boolean }>(
846
+ `/api/v1/conversations/${encodeURIComponent(conversationId)}/preview/${port}`,
847
+ { method: "DELETE" },
848
+ );
849
+ return body.closed;
850
+ }
851
+
852
+ /** Fork a cloud session from HEAD: snapshot the VM + branch the drive + seed
853
+ * a new conversation from the transcript so far, booting from both. Returns
854
+ * the child conversation id to switch to. Write-tier; "Branch from here." */
855
+ forkSession(conversationId: string, input?: { title?: string }): Promise<SessionForked> {
856
+ return this.fetch<SessionForked>(
857
+ `/api/v1/conversations/${encodeURIComponent(conversationId)}/fork`,
858
+ { method: "POST", body: input?.title ? { title: input.title } : {} },
859
+ );
860
+ }
861
+
862
+ // ── Session branch proposals (ADR-0053) ───────────────────────────────────
863
+ // Every cloud session works on its own factory-drive branch; the whole
864
+ // branch is the unit of review, like a PR. Any member can VIEW the
865
+ // proposal; deciding it (merge/discard) requires role ≥ write and a human
866
+ // credential — the resident agent cannot self-approve.
867
+
868
+ /** The session's proposed change set: files changed on its drive branch
869
+ * since it forked from `main` (read-tier — any conversation member).
870
+ * `state: "unbranched"` means the session predates branching and still
871
+ * writes `main` directly. The list reflects the branch's last flush and
872
+ * is advisory; a merge re-verifies against fresh state. 404 = not found
873
+ * or not a member (uniform). */
874
+ getSessionChanges(conversationId: string): Promise<SessionChangeSet> {
875
+ return this.fetch<SessionChangeSet>(
876
+ `/api/v1/conversations/${encodeURIComponent(conversationId)}/changes`,
877
+ );
878
+ }
879
+
880
+ /** Approve the session's proposed changes: 3-way merge its branch into
881
+ * `main`, then continue the session on a fresh branch off post-merge
882
+ * `main`. Write-tier + human caller. Pass `opts.branch` (the branch you
883
+ * reviewed) to fail 409 `branch_changed` if it moved since.
884
+ *
885
+ * Failures: 403 `role_read_only` (read-only member) or a plain 403 for
886
+ * session toolbelt keys (agents cannot self-approve); 409 `turn_active`
887
+ * (a turn is running — retry when idle) | `branch_changed`; 400
888
+ * `no_branch` (session predates branching); 502 `quiesce_failed`
889
+ * (nothing changed — safe to retry) | `merge_failed` (branch retained,
890
+ * named in the body) | `rebranch_failed` (merge landed; retry safe). */
891
+ mergeSessionChanges(
892
+ conversationId: string,
893
+ opts: { branch?: string } = {},
894
+ ): Promise<SessionMergeReport> {
895
+ return this.fetch<SessionMergeReport>(
896
+ `/api/v1/conversations/${encodeURIComponent(conversationId)}/changes/merge`,
897
+ { method: "POST", body: opts.branch ? { branch: opts.branch } : {} },
898
+ );
899
+ }
900
+
901
+ /** Reject the session's proposed changes: abandon its branch (retained
902
+ * dormant, never deleted — an admin re-merge can recover a mistaken
903
+ * discard) and continue the session on a fresh branch off `main`.
904
+ * Write-tier + human caller; same 4xx/5xx contract as
905
+ * `mergeSessionChanges` minus the merge-step failures. */
906
+ discardSessionChanges(
907
+ conversationId: string,
908
+ opts: { branch?: string } = {},
909
+ ): Promise<SessionDiscardReport> {
910
+ return this.fetch<SessionDiscardReport>(
911
+ `/api/v1/conversations/${encodeURIComponent(conversationId)}/changes/discard`,
912
+ { method: "POST", body: opts.branch ? { branch: opts.branch } : {} },
913
+ );
914
+ }
915
+
916
+ // ── Conversation membership (ADR-0045) ────────────────────────────────────
917
+ // Channel rosters carry roles (`owner > write > read`). Inviting is a
918
+ // `write` action; removing and re-roling are `owner` (or team admin)
919
+ // actions. Every mutation returns the full refreshed roster.
920
+
921
+ /** The conversation's member roster with roles. Solo conversations
922
+ * return an empty roster; a dm returns the pair. */
923
+ async getConversationMembers(conversationId: string): Promise<ConversationMember[]> {
924
+ const body = await this.fetch<{ members: ConversationMember[] }>(
925
+ `/api/v1/conversations/${encodeURIComponent(conversationId)}/members`,
926
+ );
927
+ return body.members;
928
+ }
929
+
930
+ /** Invite members to a channel (requires `write` role). Per-invitee
931
+ * `role` is `'write'` (default) or `'read'` — `'owner'` is rejected
932
+ * with 400. Non-team userIds are dropped server-side. */
933
+ async addConversationMembers(
934
+ conversationId: string,
935
+ members: Array<{ userId: string; role?: "write" | "read" }>,
936
+ ): Promise<ConversationMember[]> {
937
+ const body = await this.fetch<{ members: ConversationMember[] }>(
938
+ `/api/v1/conversations/${encodeURIComponent(conversationId)}/members`,
939
+ { method: "POST", body: { members } },
940
+ );
941
+ return body.members;
942
+ }
943
+
944
+ /** Remove a member (conversation `owner` or team admin only).
945
+ * Throws 400 `last_owner` when the target is the roster's last owner. */
946
+ async removeConversationMember(conversationId: string, userId: string): Promise<ConversationMember[]> {
947
+ const body = await this.fetch<{ members: ConversationMember[] }>(
948
+ `/api/v1/conversations/${encodeURIComponent(conversationId)}/members/${encodeURIComponent(userId)}`,
949
+ { method: "DELETE" },
950
+ );
951
+ return body.members;
952
+ }
953
+
954
+ /** Change a member's role (conversation `owner` or team admin only).
955
+ * Throws 400 `last_owner` when demoting the roster's last owner. */
956
+ async setConversationMemberRole(
957
+ conversationId: string,
958
+ userId: string,
959
+ role: ConversationMemberRole,
960
+ ): Promise<ConversationMember[]> {
961
+ const body = await this.fetch<{ members: ConversationMember[] }>(
962
+ `/api/v1/conversations/${encodeURIComponent(conversationId)}/members/${encodeURIComponent(userId)}`,
963
+ { method: "PATCH", body: { role } },
964
+ );
965
+ return body.members;
966
+ }
967
+
968
+ /** Send one message into a conversation. The message persists and fans
969
+ * out before this resolves; the response carries the server's
970
+ * authoritative turn verdict (`turnState`, ADR-0037 §4) — `queued` means
971
+ * a turn is already in flight and a coalesced follow-up will answer, not
972
+ * an error. Requires the `invoke` scope. */
973
+ sendConversationMessage(
974
+ conversationId: string,
975
+ input: SendConversationMessageInput,
976
+ ): Promise<SendConversationMessageResult> {
977
+ return this.fetch<SendConversationMessageResult>(
978
+ `/api/v1/conversations/${encodeURIComponent(conversationId)}/messages`,
979
+ {
980
+ method: "POST",
981
+ body: {
982
+ text: input.text,
983
+ ...(input.threadRootId ? { threadRootId: input.threadRootId } : {}),
984
+ ...(input.pageContext ? { pageContext: input.pageContext } : {}),
985
+ },
986
+ },
987
+ );
988
+ }
989
+
990
+ /** Pre-warm a CLOUD session's sandbox (ADR-0040 §6): resumes the
991
+ * suspended VM without running a turn, so the resume latency rides the
992
+ * attach/focus gap instead of the first reply. Plain no-op
993
+ * (`warming: false`) for local/platform sessions; rate-limited
994
+ * server-side per session. Fire-and-forget by design — never block a
995
+ * surface on it. Requires the `invoke` scope. */
996
+ prewarmConversation(conversationId: string): Promise<{ warming: boolean; rateLimited?: boolean }> {
997
+ return this.fetch<{ warming: boolean; rateLimited?: boolean }>(
998
+ `/api/v1/conversations/${encodeURIComponent(conversationId)}/prewarm`,
999
+ { method: "POST", body: {} },
1000
+ );
1001
+ }
1002
+
1003
+ /** Stop the conversation's LIVE agent turn (ADR-0037 §5). Conversation-
1004
+ * scoped, not surface-scoped: any member can cancel, whichever surface
1005
+ * started the turn. The canceled turn closes with a terminal error part
1006
+ * (it is never re-run); a message sent after it stays queued and is
1007
+ * answered next. `canceled: false` = nothing was in flight. Requires
1008
+ * the `invoke` scope. */
1009
+ cancelConversationTurn(conversationId: string): Promise<{ canceled: boolean }> {
1010
+ return this.fetch<{ canceled: boolean }>(
1011
+ `/api/v1/conversations/${encodeURIComponent(conversationId)}/cancel-turn`,
1012
+ { method: "POST", body: {} },
1013
+ );
1014
+ }
1015
+
1016
+ /** Announce this client as ATTACHED to a conversation (ADR-0037 §6) —
1017
+ * beat every ~30s while a surface shows the transcript. Each beat fans
1018
+ * out one live-only `presence` event to every stream subscriber (the
1019
+ * roster assembles client-side, keyed by `clientId`) and returns a
1020
+ * fresh agent-liveness snapshot. Member-gated like the stream; no
1021
+ * scope beyond conversation access — presence is a read-side beacon. */
1022
+ heartbeatConversationPresence(
1023
+ conversationId: string,
1024
+ input: { clientId: string; surface: "dashboard" | "terminal" },
1025
+ ): Promise<ConversationPresenceSnapshot> {
1026
+ return this.fetch<ConversationPresenceSnapshot>(
1027
+ `/api/v1/conversations/${encodeURIComponent(conversationId)}/presence`,
1028
+ { method: "POST", body: input },
1029
+ );
1030
+ }
1031
+
1032
+ /** Subscribe to a conversation's SSE stream as an async iterable of
1033
+ * typed events, with two conversation-specific rules the consumer must
1034
+ * uphold:
1035
+ *
1036
+ * - advance `lastEventId` ONLY from events that carry `id` (durable
1037
+ * rows) — never from `part_partial` / `turn_state` / `presence`,
1038
+ * which are live-only and would corrupt reconnect replay;
1039
+ * - a conversation never "completes": the generator ends on the
1040
+ * server's bounded-replay batch boundary (`replay.continue` — pass
1041
+ * its `nextAfterSeq` back as `lastEventId` and reconnect at once) or
1042
+ * its 2h stream lifetime. Callers loop with their tracked id. */
1043
+ async *streamConversation(
1044
+ conversationId: string,
1045
+ opts?: StreamConversationOptions,
1046
+ ): AsyncGenerator<ConversationStreamEvent> {
1047
+ const path = `/api/v1/conversations/${encodeURIComponent(conversationId)}/stream`;
1048
+ for await (const ev of this.openSseStream(path, opts)) {
1049
+ yield normalizeConversationStreamEvent(ev.event, ev.data, ev.id > 0 ? ev.id : undefined);
1050
+ }
1051
+ }
1052
+
1053
+ /** List the team's agents (platform operators + local bridge agents).
1054
+ * Bridge rows carry live presence (`online`) and the hosting machine's
1055
+ * label — what the terminal/dashboard presence dots render from. */
1056
+ async listAgents(): Promise<AgentListRow[]> {
1057
+ const body = await this.fetch<{ agents: AgentListRow[] }>("/api/v1/agents");
1058
+ return body.agents;
1059
+ }
1060
+
1061
+ /** Search a factory drive's live files — path substring OR full-text match
1062
+ * on extracted content. Cursor-paginated by path. */
1063
+ searchFactoryFiles(query: string, opts?: SearchFactoryFilesOptions): Promise<FactoryFileSearchResult> {
1064
+ const factorySlug = opts?.factorySlug ?? DEFAULT_FACTORY;
1065
+ const q = new URLSearchParams({ q: query });
1066
+ if (opts?.limit != null) q.set("limit", String(opts.limit));
1067
+ if (opts?.cursor) q.set("cursor", opts.cursor);
1068
+ return this.fetch<FactoryFileSearchResult>(
1069
+ `/api/v1/factories/${encodeURIComponent(factorySlug)}/files/search?${q}`,
1076
1070
  );
1077
1071
  }
1078
1072
 
@@ -1152,6 +1146,226 @@ export class AgentComposeClient {
1152
1146
  return body.templates;
1153
1147
  }
1154
1148
 
1149
+ /** One template's detail (registration metadata + share scope). Falls
1150
+ * back to the published registry for platform templates. */
1151
+ getTemplate(name: string, opts?: { factorySlug?: string }): Promise<TemplateDetail> {
1152
+ return this.fetch<TemplateDetail>(templatePath(opts?.factorySlug ?? DEFAULT_FACTORY, name));
1153
+ }
1154
+
1155
+ // ── Artifact sharing (ADR-0045) ────────────────────────────────────────────
1156
+ // One scope model for templates and documents: owner + per-principal
1157
+ // capability grants. Mutations are full-replace and owner/team-admin only
1158
+ // (403 `capability_required` with capability "share" otherwise).
1159
+
1160
+ /** Full-replace a template's share grants; optionally bind/unbind its
1161
+ * owning conversation. Capabilities: `read|write|invoke|see_runs`. */
1162
+ setTemplateScope(
1163
+ name: string,
1164
+ input: SetTemplateScopeInput,
1165
+ opts?: { factorySlug?: string },
1166
+ ): Promise<{ scope: ArtifactScope }> {
1167
+ return this.fetch<{ scope: ArtifactScope }>(
1168
+ templatePath(opts?.factorySlug ?? DEFAULT_FACTORY, name, "scope"),
1169
+ {
1170
+ method: "PUT",
1171
+ body: {
1172
+ grants: input.grants,
1173
+ ...(input.conversationId !== undefined ? { conversationId: input.conversationId } : {}),
1174
+ },
1175
+ },
1176
+ );
1177
+ }
1178
+
1179
+ /** Full-replace a drive file's share grants. Capabilities: `read|write`. */
1180
+ setFileScope(
1181
+ path: string,
1182
+ input: SetScopeGrantsInput,
1183
+ opts?: { factorySlug?: string },
1184
+ ): Promise<{ scope: ArtifactScope }> {
1185
+ const factorySlug = opts?.factorySlug ?? DEFAULT_FACTORY;
1186
+ return this.fetch<{ scope: ArtifactScope }>(
1187
+ `/api/v1/factories/${encodeURIComponent(factorySlug)}/files/scope`,
1188
+ { method: "PUT", body: { path, grants: input.grants } },
1189
+ );
1190
+ }
1191
+
1192
+ /** Share a drive file WITH a cloud session — the session becomes a grantee
1193
+ * and the file appears in its fsgw mount. Fixed capabilities: the mount is
1194
+ * concealment-only, so the session can read AND edit the file. Requires the
1195
+ * `share` capability on the file (its owner or a team admin). The target
1196
+ * must be a CLOUD session (local sessions never mount fsgw → 400
1197
+ * `cloud_session_required`). No capabilities argument — semantics are fixed
1198
+ * "open and edit". */
1199
+ async shareFileWithSession(
1200
+ factorySlug: string,
1201
+ input: { path: string; conversationId: string },
1202
+ ): Promise<void> {
1203
+ await this.fetch<{ ok: boolean }>(
1204
+ `/api/v1/factories/${encodeURIComponent(factorySlug)}/files/session-grants`,
1205
+ { method: "POST", body: { path: input.path, conversationId: input.conversationId } },
1206
+ );
1207
+ }
1208
+
1209
+ /** Revoke a file's share to a session (revocation-critical — re-conceals on
1210
+ * the session's live mount within push latency). Idempotent. */
1211
+ async unshareFileWithSession(
1212
+ factorySlug: string,
1213
+ input: { path: string; conversationId: string },
1214
+ ): Promise<void> {
1215
+ await this.fetch<{ ok: boolean }>(
1216
+ `/api/v1/factories/${encodeURIComponent(factorySlug)}/files/session-grants`,
1217
+ { method: "DELETE", body: { path: input.path, conversationId: input.conversationId } },
1218
+ );
1219
+ }
1220
+
1221
+ // ── Projects (ADR-0045) ────────────────────────────────────────────────────
1222
+ // A project is a member-gated group (roles owner > write > read) that holds
1223
+ // objects (files, conversations, sessions). membership ⊆ visibility: every
1224
+ // member sees every object. Access is DERIVED (never copied into personal
1225
+ // scopes) and revokes the instant a member or object leaves. The server is
1226
+ // the sole authority — these are thin typed wrappers.
1227
+
1228
+ /** List the projects the caller is a member of, newest-activity first.
1229
+ * Cursor-paginated. A creator who has left sees nothing (no implicit
1230
+ * creator authority) — membership is the sole gate. */
1231
+ listProjects(opts?: { cursor?: string }): Promise<ProjectsPage> {
1232
+ const q = new URLSearchParams();
1233
+ if (opts?.cursor) q.set("cursor", opts.cursor);
1234
+ return this.fetch<ProjectsPage>(`/api/v1/projects${q.toString() ? `?${q}` : ""}`);
1235
+ }
1236
+
1237
+ /** Create a project. The caller is seeded as its first `owner` member. 409
1238
+ * on a duplicate name within the team. */
1239
+ async createProject(name: string): Promise<Project> {
1240
+ const body = await this.fetch<{ project: Project }>("/api/v1/projects", {
1241
+ method: "POST",
1242
+ body: { name },
1243
+ });
1244
+ return body.project;
1245
+ }
1246
+
1247
+ /** One project (with the caller's role + member/object counts). 404 when
1248
+ * the caller is not a member. */
1249
+ async getProject(id: string): Promise<Project> {
1250
+ const body = await this.fetch<{ project: Project }>(
1251
+ `/api/v1/projects/${encodeURIComponent(id)}`,
1252
+ );
1253
+ return body.project;
1254
+ }
1255
+
1256
+ /** Rename a project (requires `write` role). */
1257
+ async renameProject(id: string, name: string): Promise<Project> {
1258
+ const body = await this.fetch<{ project: Project }>(
1259
+ `/api/v1/projects/${encodeURIComponent(id)}`,
1260
+ { method: "PATCH", body: { name } },
1261
+ );
1262
+ return body.project;
1263
+ }
1264
+
1265
+ /** Delete a project (owner or team admin). Revokes every derived grant. */
1266
+ async deleteProject(id: string): Promise<void> {
1267
+ await this.fetch<{ ok: boolean }>(`/api/v1/projects/${encodeURIComponent(id)}`, {
1268
+ method: "DELETE",
1269
+ });
1270
+ }
1271
+
1272
+ /** The project's member roster with roles (member only). */
1273
+ async getProjectMembers(id: string): Promise<ProjectMember[]> {
1274
+ const body = await this.fetch<{ members: ProjectMember[] }>(
1275
+ `/api/v1/projects/${encodeURIComponent(id)}/members`,
1276
+ );
1277
+ return body.members;
1278
+ }
1279
+
1280
+ /** Invite members (requires `write` role). Per-invitee `role` is `'write'`
1281
+ * (default) or `'read'` — `'owner'` is never grantable at invite. Non-team
1282
+ * userIds are dropped server-side; the full refreshed roster is returned. */
1283
+ async addProjectMembers(
1284
+ id: string,
1285
+ members: Array<{ userId: string; role?: "write" | "read" }>,
1286
+ ): Promise<ProjectMember[]> {
1287
+ const body = await this.fetch<{ members: ProjectMember[] }>(
1288
+ `/api/v1/projects/${encodeURIComponent(id)}/members`,
1289
+ { method: "POST", body: { members } },
1290
+ );
1291
+ return body.members;
1292
+ }
1293
+
1294
+ /** Remove a member — project owner/team admin, or self-leave. Throws 400
1295
+ * `last_owner` when the target is the roster's last owner. */
1296
+ async removeProjectMember(id: string, userId: string): Promise<ProjectMember[]> {
1297
+ const body = await this.fetch<{ members: ProjectMember[] }>(
1298
+ `/api/v1/projects/${encodeURIComponent(id)}/members/${encodeURIComponent(userId)}`,
1299
+ { method: "DELETE" },
1300
+ );
1301
+ return body.members;
1302
+ }
1303
+
1304
+ /** Change a member's role (project owner or team admin). Throws 400
1305
+ * `last_owner` when demoting the roster's last owner. */
1306
+ async setProjectMemberRole(
1307
+ id: string,
1308
+ userId: string,
1309
+ role: ProjectRole,
1310
+ ): Promise<ProjectMember[]> {
1311
+ const body = await this.fetch<{ members: ProjectMember[] }>(
1312
+ `/api/v1/projects/${encodeURIComponent(id)}/members/${encodeURIComponent(userId)}`,
1313
+ { method: "PATCH", body: { role } },
1314
+ );
1315
+ return body.members;
1316
+ }
1317
+
1318
+ /** List a project's objects (member only), newest first. Cursor-paginated. */
1319
+ listProjectObjects(id: string, opts?: { cursor?: string }): Promise<ProjectObjectsPage> {
1320
+ const q = new URLSearchParams();
1321
+ if (opts?.cursor) q.set("cursor", opts.cursor);
1322
+ return this.fetch<ProjectObjectsPage>(
1323
+ `/api/v1/projects/${encodeURIComponent(id)}/objects${q.toString() ? `?${q}` : ""}`,
1324
+ );
1325
+ }
1326
+
1327
+ /** DRY-RUN preview of a session add: the files that WOULD be shared (from
1328
+ * the caller's owned scopes) + any owned-but-skipped entries (paths
1329
+ * concealed from the caller are omitted). Powers the consent dialog. Same
1330
+ * gates as the add, but mutates nothing. */
1331
+ previewProjectObject(id: string, input: { conversationId: string }): Promise<ProjectAddPreview> {
1332
+ return this.fetch<ProjectAddPreview>(
1333
+ `/api/v1/projects/${encodeURIComponent(id)}/objects/preview`,
1334
+ { method: "POST", body: { type: "session", conversationId: input.conversationId } },
1335
+ );
1336
+ }
1337
+
1338
+ /** Add an object to a project (requires `write` role AND authority on the
1339
+ * object itself). A session add also materializes the caller-owned files in
1340
+ * the session's context, returning them alongside the session object. */
1341
+ addProjectObject(id: string, input: AddProjectObjectInput): Promise<AddProjectObjectResult> {
1342
+ return this.fetch<AddProjectObjectResult>(
1343
+ `/api/v1/projects/${encodeURIComponent(id)}/objects`,
1344
+ { method: "POST", body: input },
1345
+ );
1346
+ }
1347
+
1348
+ /** Re-materialize a session object's file context (add-only — never removes;
1349
+ * picks up files scoped/created after the original add). Session objects
1350
+ * only; caller must be the session owner and a project writer. */
1351
+ refreshProjectObject(id: string, objectId: string): Promise<RefreshProjectObjectResult> {
1352
+ return this.fetch<RefreshProjectObjectResult>(
1353
+ `/api/v1/projects/${encodeURIComponent(id)}/objects/${encodeURIComponent(objectId)}/refresh`,
1354
+ { method: "POST", body: {} },
1355
+ );
1356
+ }
1357
+
1358
+ /** Remove an object from a project (revocation-critical). Authorized for a
1359
+ * project writer, the member who added it, OR — for a file object — the
1360
+ * file's owner even without project membership (share implies unshare).
1361
+ * Unauthorized → 404. */
1362
+ async removeProjectObject(id: string, objectId: string): Promise<void> {
1363
+ await this.fetch<{ ok: boolean }>(
1364
+ `/api/v1/projects/${encodeURIComponent(id)}/objects/${encodeURIComponent(objectId)}`,
1365
+ { method: "DELETE" },
1366
+ );
1367
+ }
1368
+
1155
1369
  // ── Factories ──────────────────────────────────────────────────────────────
1156
1370
  // Projects within a team. Workflows + secrets belong to exactly one factory.
1157
1371
 
@@ -1230,13 +1444,17 @@ export class AgentComposeClient {
1230
1444
  });
1231
1445
  }
1232
1446
 
1447
+ /** Both secret tiers list the same `{ secrets }` envelope — fetch + map the
1448
+ * wire's `secretKey` to `SecretListEntry.key`. */
1449
+ private async listSecretEntries(path: string): Promise<SecretListEntry[]> {
1450
+ const body = await this.fetch<{ secrets: Array<{ secretKey: string; createdAt: string; updatedAt: string }> }>(path);
1451
+ return body.secrets.map(s => ({ key: s.secretKey, createdAt: s.createdAt, updatedAt: s.updatedAt }));
1452
+ }
1453
+
1233
1454
  /** List secret keys registered for a workflow (metadata only — values are never returned). */
1234
- async listSecrets(workflowName: string, opts?: SecretOptions): Promise<SecretListEntry[]> {
1455
+ listSecrets(workflowName: string, opts?: SecretOptions): Promise<SecretListEntry[]> {
1235
1456
  const factorySlug = opts?.factorySlug ?? DEFAULT_FACTORY;
1236
- const body = await this.fetch<{ secrets: Array<{ secretKey: string; createdAt: string; updatedAt: string }> }>(
1237
- templatePath(factorySlug, workflowName, "secrets"),
1238
- );
1239
- return body.secrets.map(s => ({ key: s.secretKey, createdAt: s.createdAt, updatedAt: s.updatedAt }));
1457
+ return this.listSecretEntries(templatePath(factorySlug, workflowName, "secrets"));
1240
1458
  }
1241
1459
 
1242
1460
  /** Delete a workflow secret. */
@@ -1245,6 +1463,37 @@ export class AgentComposeClient {
1245
1463
  return this.fetch(templatePath(factorySlug, workflowName, "secrets", key), { method: "DELETE" });
1246
1464
  }
1247
1465
 
1466
+ // ── GitHub-linked drive directories (ADR-0030 P1) ───────────────────────────
1467
+
1468
+ /** List a factory's drive⇄repo links. */
1469
+ async listRepoLinks(opts?: { factorySlug?: string }): Promise<DriveRepoLink[]> {
1470
+ const slug = opts?.factorySlug ?? DEFAULT_FACTORY;
1471
+ const body = await this.fetch<{ links: DriveRepoLink[] }>(
1472
+ `/api/v1/factories/${encodeURIComponent(slug)}/repo-links`);
1473
+ return body.links;
1474
+ }
1475
+
1476
+ /** Link a drive directory to a GitHub repo + tracked branch (`manage`
1477
+ * scope). Requires the drive to be graph-authoritative — 409 names the
1478
+ * promotion prerequisite otherwise. */
1479
+ async createRepoLink(
1480
+ input: CreateDriveRepoLinkInput, opts?: { factorySlug?: string },
1481
+ ): Promise<DriveRepoLink> {
1482
+ const slug = opts?.factorySlug ?? DEFAULT_FACTORY;
1483
+ const body = await this.fetch<{ link: DriveRepoLink }>(
1484
+ `/api/v1/factories/${encodeURIComponent(slug)}/repo-links`,
1485
+ { method: "POST", body: input });
1486
+ return body.link;
1487
+ }
1488
+
1489
+ /** Unlink (§6.3: the prefix's files and history stay on the drive). */
1490
+ deleteRepoLink(linkId: string, opts?: { factorySlug?: string }): Promise<void> {
1491
+ const slug = opts?.factorySlug ?? DEFAULT_FACTORY;
1492
+ return this.fetch(
1493
+ `/api/v1/factories/${encodeURIComponent(slug)}/repo-links/${encodeURIComponent(linkId)}`,
1494
+ { method: "DELETE" });
1495
+ }
1496
+
1248
1497
  // ── Factory-level secrets (ADR-0014) ────────────────────────────────────────
1249
1498
  // The inherited tier: a factory secret is visible to EVERY workflow in the
1250
1499
  // factory; a workflow secret of the same key overrides it. Values are stored
@@ -1260,12 +1509,9 @@ export class AgentComposeClient {
1260
1509
  }
1261
1510
 
1262
1511
  /** List factory-level secret keys (metadata only — values are never returned). */
1263
- async listFactorySecrets(opts?: SecretOptions): Promise<SecretListEntry[]> {
1512
+ listFactorySecrets(opts?: SecretOptions): Promise<SecretListEntry[]> {
1264
1513
  const factorySlug = opts?.factorySlug ?? DEFAULT_FACTORY;
1265
- const body = await this.fetch<{ secrets: Array<{ secretKey: string; createdAt: string; updatedAt: string }> }>(
1266
- `/api/v1/factories/${encodeURIComponent(factorySlug)}/secrets`,
1267
- );
1268
- return body.secrets.map(s => ({ key: s.secretKey, createdAt: s.createdAt, updatedAt: s.updatedAt }));
1514
+ return this.listSecretEntries(`/api/v1/factories/${encodeURIComponent(factorySlug)}/secrets`);
1269
1515
  }
1270
1516
 
1271
1517
  /** Delete a factory-level secret. */
@@ -1313,6 +1559,79 @@ export class AgentComposeClient {
1313
1559
  );
1314
1560
  }
1315
1561
 
1562
+ // ── Break-glass compliance sessions (ADR-0051) ───────────────────────────────
1563
+ // A team admin has no default access to a scoped document. To view one they
1564
+ // don't hold a grant on, they request a READ-ONLY, owner-approved, time-boxed
1565
+ // compliance session over a scope (a factory, or the whole team). Every verb
1566
+ // here requires an `admin`-scoped key; approval additionally requires the
1567
+ // caller be a team owner (or a fallback admin ≠ requester). Every access under
1568
+ // an active session is individually audited and the doc's owner is notified.
1569
+
1570
+ /** Request a break-glass compliance session — returns it `pending` until a
1571
+ * team owner (≠ requester) approves. `scopeRef` is the factory id for
1572
+ * factory scope; omit it for team scope. `ttlSeconds` is the session's
1573
+ * lifetime once approved (15 min floor, 7 day ceiling). */
1574
+ async requestComplianceSession(input: RequestComplianceSessionInput): Promise<ComplianceSession> {
1575
+ const body = await this.fetch<{ session: ComplianceSession }>("/api/v1/compliance/sessions", {
1576
+ method: "POST",
1577
+ body: {
1578
+ scopeKind: input.scopeKind,
1579
+ reason: input.reason,
1580
+ ttlSeconds: input.ttlSeconds,
1581
+ ...(input.scopeRef != null ? { scopeRef: input.scopeRef } : {}),
1582
+ },
1583
+ });
1584
+ return body.session;
1585
+ }
1586
+
1587
+ /** Approve a pending compliance session → active with its TTL. The caller
1588
+ * must be a team owner ≠ the requester (or, when the requester is the sole
1589
+ * owner, any admin ≠ requester). Throws 403 on self-approval or wrong role,
1590
+ * 409 when the session is no longer pending. */
1591
+ async approveComplianceSession(sessionId: string): Promise<ComplianceSession> {
1592
+ const body = await this.fetch<{ session: ComplianceSession }>(
1593
+ `/api/v1/compliance/sessions/${encodeURIComponent(sessionId)}/approve`,
1594
+ { method: "POST" },
1595
+ );
1596
+ return body.session;
1597
+ }
1598
+
1599
+ /** Revoke a pending or active compliance session — revocation always
1600
+ * tightens, so any team owner/admin may do it. */
1601
+ async revokeComplianceSession(sessionId: string): Promise<ComplianceSession> {
1602
+ const body = await this.fetch<{ session: ComplianceSession }>(
1603
+ `/api/v1/compliance/sessions/${encodeURIComponent(sessionId)}/revoke`,
1604
+ { method: "POST" },
1605
+ );
1606
+ return body.session;
1607
+ }
1608
+
1609
+ /** List the team's compliance sessions, newest first. Optional `status`
1610
+ * filter; opaque `cursor` pagination. */
1611
+ listComplianceSessions(opts?: ListComplianceSessionsOptions): Promise<ComplianceSessionsPage> {
1612
+ const q = new URLSearchParams();
1613
+ if (opts?.status) q.set("status", opts.status);
1614
+ if (opts?.limit != null) q.set("limit", String(opts.limit));
1615
+ if (opts?.cursor) q.set("cursor", opts.cursor);
1616
+ return this.fetch<ComplianceSessionsPage>(
1617
+ `/api/v1/compliance/sessions${q.toString() ? `?${q}` : ""}`,
1618
+ );
1619
+ }
1620
+
1621
+ /** The documents touched under one compliance session — the individual
1622
+ * per-document audit trail its reasoned entry authorized. */
1623
+ listComplianceAccesses(
1624
+ sessionId: string,
1625
+ opts?: ListComplianceAccessesOptions,
1626
+ ): Promise<ComplianceAccessesPage> {
1627
+ const q = new URLSearchParams();
1628
+ if (opts?.limit != null) q.set("limit", String(opts.limit));
1629
+ if (opts?.cursor) q.set("cursor", opts.cursor);
1630
+ return this.fetch<ComplianceAccessesPage>(
1631
+ `/api/v1/compliance/sessions/${encodeURIComponent(sessionId)}/accesses${q.toString() ? `?${q}` : ""}`,
1632
+ );
1633
+ }
1634
+
1316
1635
  /** Stream lifecycle events for a run as an async iterable. Yields parsed
1317
1636
  * `RunEvent` payloads in order; caller breaks on terminal events
1318
1637
  * (`run_complete`, `run_failed`, `run_canceled`).
@@ -1320,33 +1639,13 @@ export class AgentComposeClient {
1320
1639
  * `lastEventId` enables resume — pass the highest `seq` you've already
1321
1640
  * processed to receive only events you missed.
1322
1641
  *
1323
- * `event` can be used to abort the stream from the caller side.
1324
- *
1325
- * Uses raw `fetch` (not ofetch) because SSE requires access to the
1326
- * response's `ReadableStream`, which ofetch consumes when parsing. Auth
1327
- * + base URL are still sourced from the same constructor inputs, and
1328
- * non-2xx responses throw the same `AgentComposeError`. */
1642
+ * `event` can be used to abort the stream from the caller side. */
1329
1643
  async *streamRunLogs(
1330
1644
  runId: string,
1331
1645
  opts?: StreamRunLogsOptions,
1332
1646
  ): AsyncGenerator<RunEvent> {
1333
- const headers: Record<string, string> = { Authorization: `Bearer ${this.apiKey}` };
1334
- if (opts?.lastEventId && opts.lastEventId > 0) {
1335
- headers["Last-Event-ID"] = String(opts.lastEventId);
1336
- }
1337
- const res = await fetch(`${this.baseUrl}/api/v1/workflows/${encodeURIComponent(runId)}/stream`, {
1338
- headers,
1339
- ...(opts?.signal ? { signal: opts.signal } : {}),
1340
- });
1341
- if (!res.ok || !res.body) {
1342
- let message = res.statusText;
1343
- try {
1344
- const body = await res.json() as { error?: string };
1345
- if (body.error) message = body.error;
1346
- } catch { /* non-JSON error body — fall back to statusText */ }
1347
- throw new AgentComposeError(res.status, message);
1348
- }
1349
- for await (const ev of parseSseStream(res.body)) {
1647
+ const path = `/api/v1/workflows/${encodeURIComponent(runId)}/stream`;
1648
+ for await (const ev of this.openSseStream(path, opts)) {
1350
1649
  // The server's `data` payload already includes `event`, `runId`, `seq`,
1351
1650
  // `at`, and the per-event payload — so `ev.data` IS the `RunEvent`.
1352
1651
  // Cast directly; unknown future event names flow through untyped, and
@@ -1355,14 +1654,3 @@ export class AgentComposeClient {
1355
1654
  }
1356
1655
  }
1357
1656
  }
1358
-
1359
- /** A factory: a project-level grouping of workflows inside a team. */
1360
- export interface FactoryRow {
1361
- id: string;
1362
- teamId: string;
1363
- slug: string;
1364
- name: string;
1365
- description: string | null;
1366
- createdAt: string;
1367
- updatedAt: string;
1368
- }