@bobannomi/client 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -87,11 +87,6 @@ function readSessionModelUsage(metadata) {
87
87
  };
88
88
  }
89
89
 
90
- // ../agent-contracts/src/conversation/reply-style.ts
91
- function isReplyStyle(value) {
92
- return value === "collaborative" || value === "direct" || value === "explanatory";
93
- }
94
-
95
90
  // ../domain-contracts/src/validation-error.ts
96
91
  var DomainValidationError = class extends Error {
97
92
  constructor(message, field, reason) {
@@ -105,6 +100,22 @@ var DomainValidationError = class extends Error {
105
100
  code = "invalid_request";
106
101
  };
107
102
 
103
+ // ../domain-contracts/src/sessions/model-connection.ts
104
+ function parseExpectedModelConnection(value) {
105
+ const proof = value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
106
+ const provider2 = proof?.provider;
107
+ const fingerprint = proof?.fingerprint;
108
+ if (!proof || Object.keys(proof).length !== 2 || !Object.hasOwn(proof, "provider") || !Object.hasOwn(proof, "fingerprint") || typeof provider2 !== "string" || !/^[a-z0-9][a-z0-9_-]{0,255}$/.test(provider2) || typeof fingerprint !== "string" || !/^[a-f0-9]{64}$/.test(fingerprint)) {
109
+ throw new DomainValidationError("invalid_expected_model_connection", "expectedModelConnection");
110
+ }
111
+ return { provider: provider2, fingerprint };
112
+ }
113
+
114
+ // ../agent-contracts/src/conversation/reply-style.ts
115
+ function isReplyStyle(value) {
116
+ return value === "collaborative" || value === "direct" || value === "explanatory";
117
+ }
118
+
108
119
  // ../domain-contracts/src/sessions/runtime-config.ts
109
120
  function isRecord(value) {
110
121
  return !!value && typeof value === "object" && !Array.isArray(value);
@@ -130,9 +141,10 @@ function booleanValue(value) {
130
141
  return typeof value === "boolean" ? value : void 0;
131
142
  }
132
143
  function readRuntimeMetadata(metadata) {
133
- const runtime = metadata?.runtime;
134
- if (runtime === void 0) return {};
135
- if (!isRecord(runtime)) throw new DomainValidationError("metadata.runtime must be an object", "metadata.runtime");
144
+ const saved = metadata?.runtime;
145
+ if (saved === void 0) return {};
146
+ if (!isRecord(saved)) throw new DomainValidationError("metadata.runtime must be an object", "metadata.runtime");
147
+ const { appServiceBindings, ...runtime } = saved;
136
148
  for (const [field, value] of Object.entries(runtime)) {
137
149
  let valid = false;
138
150
  switch (field) {
@@ -172,9 +184,6 @@ function readRuntimeMetadata(metadata) {
172
184
  case "pluginAutoSelectionEnabled":
173
185
  valid = booleanValue(value) !== void 0;
174
186
  break;
175
- case "appServiceBindings":
176
- valid = Array.isArray(value) && value.length <= 128 && value.every((item) => typeof item === "string" && /^service:[a-f0-9]{64}$/.test(item)) && new Set(value).size === value.length;
177
- break;
178
187
  case "allowedTools":
179
188
  case "disallowedTools":
180
189
  valid = Array.isArray(value) && value.every((item) => typeof item === "string" && item.trim().length > 0);
@@ -184,8 +193,23 @@ function readRuntimeMetadata(metadata) {
184
193
  throw new DomainValidationError(`Invalid runtime config field metadata.runtime.${field}`, `metadata.runtime.${field}`);
185
194
  }
186
195
  }
196
+ for (const key of ["allowedTools", "disallowedTools"]) {
197
+ const tools = runtime[key];
198
+ if (tools) runtime[key] = withoutRetiredAppMcpTools(tools, appServiceBindings);
199
+ }
187
200
  return runtime;
188
201
  }
202
+ function withoutRetiredAppMcpTools(tools, bindings) {
203
+ if (!Array.isArray(bindings)) return tools;
204
+ const prefixes = bindings.filter(
205
+ (binding) => typeof binding === "string" && /^service:[a-f0-9]{64}$/.test(binding)
206
+ ).map(
207
+ (binding) => `mcp__nomi_service_${binding.slice("service:".length)}__`
208
+ );
209
+ return prefixes.length ? tools.filter(
210
+ (tool) => !prefixes.some((prefix) => tool.startsWith(prefix))
211
+ ) : tools;
212
+ }
189
213
 
190
214
  // ../domain-contracts/src/sessions/resource-actions.ts
191
215
  var record = (v) => !!v && typeof v === "object" && !Array.isArray(v) && [Object.prototype, null].includes(Object.getPrototypeOf(v));
@@ -289,7 +313,7 @@ function fields(body, allowed) {
289
313
  // ../domain-contracts/src/sessions/configuration-validation.ts
290
314
  function parseSessionConfiguration(value) {
291
315
  const body = record2(value);
292
- fields(body, ["model", "roleId", "systemPrompt", "executionInstructions", "effort", "workMode", "maxTurns", "sessionMode", "replyStyle", "approvalMode", "tools", "pluginsEnabled", "pluginAutoSelectionEnabled", "activePluginId", "pluginIds", "serviceBindings", "memory"]);
316
+ fields(body, ["model", "roleId", "systemPrompt", "executionInstructions", "effort", "workMode", "maxTurns", "sessionMode", "replyStyle", "approvalMode", "tools", "pluginsEnabled", "pluginAutoSelectionEnabled", "activePluginId", "pluginIds", "memory"]);
293
317
  for (const key of ["roleId", "systemPrompt", "effort", "activePluginId"]) if (body[key] !== null) optionalString(body, key);
294
318
  for (const key of ["pluginsEnabled", "pluginAutoSelectionEnabled"]) optionalBoolean(body, key);
295
319
  optionalEnum(body, "workMode", ["execute", "plan"]);
@@ -297,7 +321,7 @@ function parseSessionConfiguration(value) {
297
321
  optionalEnum(body, "replyStyle", ["collaborative", "direct", "explanatory"]);
298
322
  optionalEnum(body, "approvalMode", ["ask", "auto_review", "full_access"]);
299
323
  optionalNumber(body, "maxTurns", { integer: true, minimum: 0 });
300
- for (const key of ["pluginIds", "serviceBindings"]) optionalStringArray(body, key);
324
+ optionalStringArray(body, "pluginIds");
301
325
  if (body.model !== void 0) {
302
326
  const model = record2(body.model);
303
327
  fields(model, ["provider", "model"]);
@@ -572,7 +596,7 @@ function assertPromptMetadataAllowed(input) {
572
596
  const field = `${namespace}.outputSchema`;
573
597
  throw new DomainValidationError(`${field} is a stored snapshot; use explicit outputSchema`, field);
574
598
  }
575
- for (const name of ["pluginUi", "uiAction", "pluginUiSubmission", "pluginAppAction", "pluginAppSubmission", "pluginAppSource", "consumedForkHistory", "executionBinding", "steeredRunId", "steerTargetRunId", "appliedInputState", "appliedFollowUpInputIds", "unappliedFollowUpInputIds", "unappliedPromotion", "steerDeliveryFailed", "sessionObservationGrant", "sessionObservationAccess", "promotion", "cancellation", "interruption"]) {
599
+ for (const name of ["pluginUi", "uiAction", "pluginUiSubmission", "pluginAppAction", "pluginAppSubmission", "pluginAppSource", "consumedForkHistory", "executionBinding", "steeredRunId", "steerTargetRunId", "appliedInputState", "appliedFollowUpInputIds", "unappliedFollowUpInputIds", "unappliedPromotion", "steerDeliveryFailed", "sessionObservationGrant", "sessionObservationAccess", "sessionLookupAllowed", "promotion", "cancellation", "interruption", "expectedModelConnection", "modelConnectionProofSupplied"]) {
576
600
  if (Object.hasOwn(metadata, name)) {
577
601
  const field = `${namespace}.${name}`;
578
602
  throw new DomainValidationError(
@@ -876,14 +900,24 @@ function appMetadata(value) {
876
900
  optionalRecord(metadata, "app");
877
901
  return metadata;
878
902
  }
903
+ var reservedSessionIds = /* @__PURE__ */ new Set(["directory", "activity", "search", "configuration-options", ".", ".."]);
904
+ function validateSessionId(id2) {
905
+ if (!id2.trim() || reservedSessionIds.has(id2)) {
906
+ throw new ProtocolValidationError("id must be nonempty and outside reserved session paths", "id");
907
+ }
908
+ return id2;
909
+ }
879
910
  function parseCreateSessionRequest(value) {
880
911
  const body = record3(value);
881
912
  fields2(body, ["id", "requestId", "cwd", "projectId", "title", "storage", "configuration", "optionsRevision", "metadata"]);
882
- const cwd = requiredString2(body, "cwd");
883
- const id2 = requiredString2(body, "id");
913
+ const cwd = optionalString2(body, "cwd");
914
+ const id2 = validateSessionId(requiredString2(body, "id"));
884
915
  const requestId = requiredString2(body, "requestId");
885
- if (!cwd.trim() || !id2.trim() || !requestId.trim()) throw new ProtocolValidationError("cwd, id and requestId cannot be empty");
886
- const result = { id: id2, requestId, cwd };
916
+ if (cwd !== void 0 && !cwd.trim()) throw new ProtocolValidationError("cwd cannot be empty", "cwd");
917
+ if (!requestId.trim()) throw new ProtocolValidationError("requestId cannot be empty", "requestId");
918
+ const target = cwd === void 0 ? { projectId: requiredString2(body, "projectId") } : { cwd };
919
+ if (cwd === void 0 && !target.projectId?.trim()) throw new ProtocolValidationError("projectId cannot be empty", "projectId");
920
+ const result = { id: id2, requestId, ...target };
887
921
  for (const key of ["projectId", "title", "optionsRevision"]) if (body[key] !== void 0) result[key] = optionalString2(body, key);
888
922
  if (body.storage !== void 0) result.storage = optionalEnum2(body, "storage", ["sqlite", "memory"]);
889
923
  if (body.configuration !== void 0) result.configuration = parseSessionConfiguration2(body.configuration);
@@ -892,6 +926,7 @@ function parseCreateSessionRequest(value) {
892
926
  }
893
927
  function parseForkSessionRequest(value) {
894
928
  const body = record3(value);
929
+ const id2 = optionalString2(body, "id");
895
930
  const beforeMessageId = optionalString2(body, "beforeMessageId");
896
931
  const afterMessageId = optionalString2(body, "afterMessageId");
897
932
  const storage = optionalEnum2(body, "storage", ["sqlite", "memory"]);
@@ -903,7 +938,7 @@ function parseForkSessionRequest(value) {
903
938
  );
904
939
  }
905
940
  return {
906
- ...body.id !== void 0 ? { id: optionalString2(body, "id") } : {},
941
+ ...id2 === void 0 ? {} : { id: validateSessionId(id2) },
907
942
  ...body.requestId !== void 0 ? { requestId: optionalString2(body, "requestId") } : {},
908
943
  ...copyHistory !== void 0 ? { copyHistory } : {},
909
944
  ...beforeMessageId !== void 0 ? { beforeMessageId } : {},
@@ -918,6 +953,9 @@ function parseUpdateSessionRequest(value) {
918
953
  const metadata = body.metadata === void 0 ? void 0 : appMetadata(optionalRecord(body, "metadata"));
919
954
  return { ...title === void 0 ? {} : { title }, ...metadata === void 0 ? {} : { metadata } };
920
955
  }
956
+ function parseExpectedModelConnection2(value) {
957
+ return adaptDomainInput(() => parseExpectedModelConnection(value));
958
+ }
921
959
  function adaptDomainInput(read) {
922
960
  try {
923
961
  return read();
@@ -955,7 +993,7 @@ function decodeSessionConfigurationSnapshot(value) {
955
993
  } catch {
956
994
  throw new ProtocolDataError("Invalid resolved configuration");
957
995
  }
958
- const required = ["model", "roleId", "systemPrompt", "executionInstructions", "effort", "workMode", "maxTurns", "sessionMode", "replyStyle", "approvalMode", "tools", "pluginsEnabled", "pluginAutoSelectionEnabled", "activePluginId", "pluginIds", "serviceBindings", "memory"];
996
+ const required = ["model", "roleId", "systemPrompt", "executionInstructions", "effort", "workMode", "maxTurns", "sessionMode", "replyStyle", "approvalMode", "tools", "pluginsEnabled", "pluginAutoSelectionEnabled", "activePluginId", "pluginIds", "memory"];
959
997
  if (required.some((key) => !Object.hasOwn(configuration, key)) || !configuration.tools?.allowed || !configuration.tools.denied) throw new ProtocolDataError("Resolved configuration is incomplete");
960
998
  return { revision: snapshot.revision, configuration, configurationRoot: { cwd, settingsRoot } };
961
999
  }
@@ -1691,7 +1729,7 @@ var MAX_GOAL_OBJECTIVE_CHARS = 32e3;
1691
1729
  // ../domain-contracts/src/goals/validation.ts
1692
1730
  function parseCreateSessionGoalInput(value) {
1693
1731
  const record5 = goalRecord(value);
1694
- assertGoalFields(record5, ["requestId", "objective", "maxAutoTurns", "tokenBudget", "items", "attachments"]);
1732
+ assertGoalFields(record5, ["requestId", "objective", "maxAutoTurns", "tokenBudget", "items", "attachments", "expectedModelConnection"]);
1695
1733
  return {
1696
1734
  requestId: requiredGoalString(record5.requestId, "requestId", 128),
1697
1735
  objective: requiredGoalString(record5.objective, "objective", MAX_GOAL_OBJECTIVE_CHARS),
@@ -1704,7 +1742,7 @@ function parseCreateSessionGoalInput(value) {
1704
1742
  }
1705
1743
  function parseUpdateSessionGoalInput(value) {
1706
1744
  const record5 = goalRecord(value);
1707
- assertGoalFields(record5, ["requestId", "expectedRevision", "objective", "items", "attachments"]);
1745
+ assertGoalFields(record5, ["requestId", "expectedRevision", "objective", "items", "attachments", "expectedModelConnection"]);
1708
1746
  return {
1709
1747
  requestId: requiredGoalString(record5.requestId, "requestId", 128),
1710
1748
  expectedRevision: goalNonNegativeInteger(record5.expectedRevision, "expectedRevision"),
@@ -1725,12 +1763,13 @@ function parseGoalActionInput(value) {
1725
1763
  assertGoalFields(record5, ["requestId", "expectedRevision", "action", "tokenBudget"]);
1726
1764
  return { ...common, action: "budget", tokenBudget: record5.tokenBudget === null ? null : goalPositiveTimestamp(record5.tokenBudget, "tokenBudget") };
1727
1765
  }
1728
- assertGoalFields(record5, record5.action === "resume" ? ["requestId", "expectedRevision", "action", "additionalAutoTurns", "questionId", "response", "objectiveVersion"] : ["requestId", "expectedRevision", "action"]);
1766
+ assertGoalFields(record5, record5.action === "resume" ? ["requestId", "expectedRevision", "action", "additionalAutoTurns", "questionId", "response", "objectiveVersion", "expectedModelConnection"] : ["requestId", "expectedRevision", "action"]);
1729
1767
  if (record5.questionId !== void 0) goalPositiveTimestamp(record5.objectiveVersion, "objectiveVersion");
1730
1768
  else if (record5.objectiveVersion !== void 0) throw new DomainValidationError("goal_version_requires_answer", "objectiveVersion");
1731
1769
  return {
1732
1770
  ...common,
1733
1771
  action: record5.action,
1772
+ ...record5.expectedModelConnection === void 0 ? {} : { expectedModelConnection: parseExpectedModelConnection(record5.expectedModelConnection) },
1734
1773
  ...record5.questionId === void 0 ? {} : { questionId: requiredGoalString(record5.questionId, "questionId", 256), objectiveVersion: goalPositiveTimestamp(record5.objectiveVersion, "objectiveVersion") },
1735
1774
  ...record5.response === void 0 ? {} : { response: requiredGoalString(record5.response, "response", MAX_GOAL_OBJECTIVE_CHARS) },
1736
1775
  ...record5.additionalAutoTurns === void 0 ? {} : { additionalAutoTurns: goalPositiveInteger(record5.additionalAutoTurns, "additionalAutoTurns") }
@@ -1761,7 +1800,8 @@ function goalPositiveInteger(value, field, allowUnlimited = false) {
1761
1800
  function parseGoalContent(record5) {
1762
1801
  return {
1763
1802
  ...record5.items === void 0 ? {} : { items: parseSessionInputItems(record5.items) },
1764
- ...record5.attachments === void 0 ? {} : { attachments: parsePromptAttachments(record5.attachments) }
1803
+ ...record5.attachments === void 0 ? {} : { attachments: parsePromptAttachments(record5.attachments) },
1804
+ ...record5.expectedModelConnection === void 0 ? {} : { expectedModelConnection: parseExpectedModelConnection(record5.expectedModelConnection) }
1765
1805
  };
1766
1806
  }
1767
1807
  function goalPositiveTimestamp(value, field) {
@@ -1834,6 +1874,76 @@ function decodeSessionGoalRequestReceipt(value) {
1834
1874
  return receipt2;
1835
1875
  }
1836
1876
 
1877
+ // ../protocol/src/extensions/mcp-oauth.ts
1878
+ var MCP_OAUTH_LOGIN_UPDATED_EVENT = "mcp.oauth.login.updated";
1879
+ var MCP_OAUTH_LOGIN_COMPLETED_EVENT = "mcp.oauth.login.completed";
1880
+ var MAX_OAUTH_ID_LENGTH = 200;
1881
+ function parseOAuthOperationEvent(value) {
1882
+ const record5 = requiredRecord(value, "operation event");
1883
+ if (record5.event !== MCP_OAUTH_LOGIN_UPDATED_EVENT && record5.event !== MCP_OAUTH_LOGIN_COMPLETED_EVENT) {
1884
+ throw new Error("unknown MCP OAuth event name");
1885
+ }
1886
+ const data = requiredRecord(record5.data, "operation event data");
1887
+ const event = {
1888
+ event: record5.event,
1889
+ data: {
1890
+ loginId: boundedId(data.loginId, "loginId"),
1891
+ name: boundedId(data.name, "name"),
1892
+ state: operationState(data.state),
1893
+ credentialCommitted: requiredBoolean(data.credentialCommitted, "credentialCommitted"),
1894
+ authorizationReady: requiredBoolean(data.authorizationReady, "authorizationReady"),
1895
+ ...data.errorCode !== void 0 ? { errorCode: boundedId(data.errorCode, "errorCode") } : {}
1896
+ }
1897
+ };
1898
+ if (data.runtimeSync !== void 0) {
1899
+ event.data.runtimeSync = parseRuntimeSync(data.runtimeSync);
1900
+ }
1901
+ return event;
1902
+ }
1903
+ function parseRuntimeSync(value) {
1904
+ const runtimeSync = requiredRecord(value, "runtimeSync");
1905
+ return {
1906
+ status: runtimeSyncStatus(runtimeSync.status),
1907
+ affectedRuntimes: nonNegativeInteger2(runtimeSync.affectedRuntimes, "affectedRuntimes"),
1908
+ failures: Array.isArray(runtimeSync.failures) ? runtimeSync.failures.map((failure) => {
1909
+ const item = requiredRecord(failure, "runtimeSync failure");
1910
+ return { runtimeId: boundedId(item.runtimeId, "runtimeId"), message: boundedId(item.message, "message") };
1911
+ }) : []
1912
+ };
1913
+ }
1914
+ function operationState(value) {
1915
+ if (value !== "pending" && value !== "completed" && value !== "failed" && value !== "cancelled") {
1916
+ throw new Error("invalid operation state");
1917
+ }
1918
+ return value;
1919
+ }
1920
+ function runtimeSyncStatus(value) {
1921
+ if (value !== "connected" && value !== "disconnected" && value !== "error" && value !== "unavailable") {
1922
+ throw new Error("invalid runtime status");
1923
+ }
1924
+ return value;
1925
+ }
1926
+ function boundedId(value, field) {
1927
+ if (typeof value !== "string" || value.length === 0 || value.length > MAX_OAUTH_ID_LENGTH) {
1928
+ throw new Error(`${field} must be a bounded non-empty string`);
1929
+ }
1930
+ return value;
1931
+ }
1932
+ function requiredBoolean(value, field) {
1933
+ if (typeof value !== "boolean") throw new Error(`${field} must be a boolean`);
1934
+ return value;
1935
+ }
1936
+ function nonNegativeInteger2(value, field) {
1937
+ if (!Number.isSafeInteger(value) || Number(value) < 0) throw new Error(`${field} must be a non-negative integer`);
1938
+ return Number(value);
1939
+ }
1940
+ function requiredRecord(value, field) {
1941
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
1942
+ throw new Error(`${field} must be an object`);
1943
+ }
1944
+ return value;
1945
+ }
1946
+
1837
1947
  // ../protocol/src/runtime/execution-observability.ts
1838
1948
  var EXECUTION_KINDS = [
1839
1949
  "root_agent_run",
@@ -2146,11 +2256,6 @@ var FETCH_CHUNK_BYTES = 64 * 1024;
2146
2256
  var FETCH_INLINE_BODY_BYTES = 8 * 1024;
2147
2257
  var FETCH_METADATA_BYTES = 64 * 1024;
2148
2258
 
2149
- // ../domain-contracts/src/app-host/service-host-protocol.ts
2150
- var SERVICE_HOST_MAX_FRAME_BYTES = 512 * 1024;
2151
- var worktreeBody = { workspaceId: id, expectedHead: text2(256), branch: text2(1024) };
2152
- var worktreeReceipt = object3({ requestId: id, state: enumeration("accepted", "completed", "failed", "unknown") }, { result: object3({ executionRoot: id, workspaceId: id, branch: text2(1024), sourceHead: text2(256) }) });
2153
-
2154
2259
  // ../domain-contracts/src/app-host/workspace-conversations.ts
2155
2260
  var validWorkspaceConversation = (value) => {
2156
2261
  if (!object3(
@@ -2189,7 +2294,6 @@ var workspaceConversationResult = object3({
2189
2294
  revision: count3,
2190
2295
  session: sessionRecord,
2191
2296
  operationState: enumeration("prepared", "running", "completed", "failed", "unknown"),
2192
- indexBindingPending: (v) => v === true,
2193
2297
  workspaceId: id,
2194
2298
  executionRoot: id,
2195
2299
  privateSessionId: id,
@@ -2220,7 +2324,6 @@ function validSessionControlInput(method, value) {
2220
2324
  const target = value;
2221
2325
  return target.workspaceId !== void 0 ? target.outsideProject !== true : target.outsideProject === true;
2222
2326
  }
2223
- if (method === "sessions.bindConversationIndex") return object3({ original: validWorkspaceConversation, dataScopeId: text2() })(value);
2224
2327
  if (method === "sessions.createConversation" || method === "sessions.getConversationCreationResult") return validWorkspaceConversation(value);
2225
2328
  if (method === "sessions.getControls") return object3({ connectionId: text2(), sessionId: text2() })(value);
2226
2329
  if (!object3({ requestId: id, sessionId: text2(), original: validSessionControlOriginal }, { connectionId: text2() })(value)) return false;
@@ -2230,10 +2333,9 @@ function validSessionControlInput(method, value) {
2230
2333
  function validSessionControlResult(method, value) {
2231
2334
  if (!json(value)) return false;
2232
2335
  if (method === "sessions.getDraftComposerOptions") return object3({ source: enumeration("instance"), optionsRevision: text2(), skills: array(object3({ id: text2(), name: text2(), path: text2(4096, true) }, { source: enumeration("bundled", "user", "project", "plugin") }), 128), plugins: array(object3({ id: text2(), name: text2(), agents: array(option, 128) }), 128) })(value);
2233
- if (method === "sessions.bindConversationIndex") return validWorkspaceConversationResult(value);
2234
2336
  if (method === "sessions.createConversation" || method === "sessions.getConversationCreationResult")
2235
2337
  return method === "sessions.getConversationCreationResult" && value === null || validWorkspaceConversationResult(value);
2236
- if (method === "sessions.getControls") return object3({ dataScopeId: text2(), sessionId: text2(), source: enumeration("instance", "auxiliary", "im"), revision: count3, optionsRevision: text2(), actions: object3(Object.fromEntries(["readContext", "configure", "compact", "edit", "fork", "resume", "goalRead", "goalWrite", "goalStop"].map((k) => [k, bool]))), models: choices, roles: choices, efforts: effortChoices, workModes: choices, skills: array(object3({ id: text2(), name: text2(), path: text2(4096, true) }, { source: enumeration("bundled", "user", "project", "plugin") })), commands: choices, contexts: choices }, { permissionModes: array(option, 128), appServiceBindings: array(option, 128), plugins: array(object3({ id: text2(), name: text2(), agents: choices })) })(value);
2338
+ if (method === "sessions.getControls") return object3({ dataScopeId: text2(), sessionId: text2(), source: enumeration("instance", "auxiliary", "im"), revision: count3, optionsRevision: text2(), actions: object3(Object.fromEntries(["readContext", "configure", "compact", "edit", "fork", "resume", "goalRead", "goalWrite", "goalStop"].map((k) => [k, bool]))), models: choices, roles: choices, efforts: effortChoices, workModes: choices, skills: array(object3({ id: text2(), name: text2(), path: text2(4096, true) }, { source: enumeration("bundled", "user", "project", "plugin") })), commands: choices, contexts: choices }, { permissionModes: array(option, 128), plugins: array(object3({ id: text2(), name: text2(), agents: choices })) })(value);
2237
2339
  if (method === "sessions.getControlResult") return value === null || receipt(value);
2238
2340
  if (!receipt(value)) return false;
2239
2341
  return false;
@@ -2296,7 +2398,7 @@ var validProviderDefaultsSnapshot = object3({
2296
2398
  verified,
2297
2399
  fastModeAvailable: enumeration(false),
2298
2400
  fastModeReason: text2(1024)
2299
- });
2401
+ }, { accountGatewayMatches: bool });
2300
2402
  var validProviderConnectionTestResult = object3({
2301
2403
  status: enumeration("verified", "failed"),
2302
2404
  detail: text2(8192),
@@ -2484,14 +2586,7 @@ var HttpTransport = class {
2484
2586
  this.protocolHandshake = void 0;
2485
2587
  throw error;
2486
2588
  });
2487
- if (!signal) return this.protocolHandshake;
2488
- return new Promise((resolve, reject) => {
2489
- const onAbort = () => reject(signal.reason);
2490
- signal.addEventListener("abort", onAbort, { once: true });
2491
- this.protocolHandshake.then(resolve, reject).finally(() => {
2492
- signal.removeEventListener("abort", onAbort);
2493
- });
2494
- });
2589
+ return waitForRequest(this.protocolHandshake, signal);
2495
2590
  }
2496
2591
  headers(jsonOrOptions = false, auth = true) {
2497
2592
  let json2 = false;
@@ -2558,6 +2653,21 @@ var HttpTransport = class {
2558
2653
  return throwResponseError(response);
2559
2654
  }
2560
2655
  };
2656
+ function waitForRequest(request, signal) {
2657
+ if (!signal) return request;
2658
+ return new Promise((resolve, reject) => {
2659
+ const onAbort = () => reject(signal.reason);
2660
+ if (signal.aborted) onAbort();
2661
+ else signal.addEventListener("abort", onAbort, { once: true });
2662
+ void request.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
2663
+ });
2664
+ }
2665
+ async function requireDaemonFeature(transport, feature, signal) {
2666
+ const capabilities = await transport.ensureProtocol(signal);
2667
+ if ((capabilities.features[feature] ?? 0) < 1) {
2668
+ throw new IncompatibleProtocolError(capabilities, `Daemon does not support ${feature}. Update the daemon before calling this method.`);
2669
+ }
2670
+ }
2561
2671
  function mergeHeaders(defaults, overrides) {
2562
2672
  const headers2 = new Headers(defaults);
2563
2673
  if (overrides) {
@@ -2611,8 +2721,9 @@ ${slice}` : slice;
2611
2721
  if (!data) return void 0;
2612
2722
  return JSON.parse(data);
2613
2723
  }
2614
- async function* streamServerSentEvents(open, decode = (value) => value) {
2615
- for await (const frame of readSseFrames(await open())) {
2724
+ async function* streamServerSentEvents(open, decode = (value) => value, options) {
2725
+ options?.signal?.throwIfAborted();
2726
+ for await (const frame of readSseFrames(await open(), options)) {
2616
2727
  const event = parseSseFrame(frame);
2617
2728
  if (event !== void 0) yield decode(event);
2618
2729
  }
@@ -2683,26 +2794,43 @@ var SseTransport = class {
2683
2794
  }
2684
2795
  }
2685
2796
  };
2686
- async function* readSseFrames(stream) {
2797
+ async function* readSseFrames(stream, { signal, maxFrameBytes, onChunk } = {}) {
2687
2798
  const reader = stream.getReader();
2688
2799
  const decoder = new TextDecoder();
2800
+ const encoder = new TextEncoder();
2801
+ const checkSize = (frame) => {
2802
+ if (maxFrameBytes !== void 0 && encoder.encode(frame).byteLength > maxFrameBytes) {
2803
+ throw new Error(`SSE frame exceeds ${maxFrameBytes} bytes`);
2804
+ }
2805
+ };
2806
+ const cancel = () => reader.cancel().catch(() => {
2807
+ });
2808
+ const onAbort = () => {
2809
+ void cancel();
2810
+ };
2811
+ signal?.addEventListener("abort", onAbort, { once: true });
2689
2812
  let buffer = "";
2690
2813
  try {
2691
2814
  while (true) {
2815
+ signal?.throwIfAborted();
2692
2816
  const chunk = await reader.read();
2817
+ signal?.throwIfAborted();
2693
2818
  if (chunk.done) break;
2819
+ onChunk?.();
2694
2820
  buffer += decoder.decode(chunk.value, { stream: true });
2695
2821
  const frames = buffer.split(/\r?\n\r?\n/);
2696
2822
  buffer = frames.pop() ?? "";
2697
- yield* frames;
2823
+ for (const frame of frames) {
2824
+ signal?.throwIfAborted();
2825
+ checkSize(frame);
2826
+ yield frame;
2827
+ }
2828
+ if (maxFrameBytes !== void 0) checkSize(buffer.replace(/(?:\r?\n\r?|\r)$/, ""));
2698
2829
  }
2699
2830
  } finally {
2700
- try {
2701
- await reader.cancel();
2702
- } catch {
2703
- } finally {
2704
- reader.releaseLock();
2705
- }
2831
+ signal?.removeEventListener("abort", onAbort);
2832
+ await cancel();
2833
+ reader.releaseLock();
2706
2834
  }
2707
2835
  }
2708
2836
  function waitForReconnect(ms, signal) {
@@ -2734,139 +2862,109 @@ function withoutCursor(url) {
2734
2862
 
2735
2863
  // src/resources/schedule-resource.ts
2736
2864
  var ScheduleResource = class {
2865
+ #transport;
2737
2866
  constructor(transport) {
2738
- this.transport = transport;
2739
- }
2740
- transport;
2867
+ this.#transport = transport;
2868
+ }
2869
+ tasks = {
2870
+ list: async (options = {}) => {
2871
+ const { signal, ...query } = options;
2872
+ const response = await this.#transport.request(
2873
+ this.#transport.path("/schedules/tasks", query),
2874
+ { signal }
2875
+ );
2876
+ return response.tasks;
2877
+ },
2878
+ get: async (id2, options = {}) => {
2879
+ const response = await this.#transport.request(
2880
+ `/schedules/tasks/${encodeURIComponent(id2)}`,
2881
+ { signal: options.signal }
2882
+ );
2883
+ return response.task;
2884
+ },
2885
+ create: async (input, options = {}) => {
2886
+ const response = await this.#transport.request(
2887
+ "/schedules/tasks",
2888
+ {
2889
+ method: "POST",
2890
+ body: input,
2891
+ signal: options.signal
2892
+ }
2893
+ );
2894
+ return response.task;
2895
+ },
2896
+ update: async (id2, input, options = {}) => {
2897
+ const response = await this.#transport.request(
2898
+ `/schedules/tasks/${encodeURIComponent(id2)}`,
2899
+ { method: "PATCH", body: input, signal: options.signal }
2900
+ );
2901
+ return response.task;
2902
+ },
2903
+ remove: async (id2, options = {}) => {
2904
+ await this.#transport.request(
2905
+ `/schedules/tasks/${encodeURIComponent(id2)}`,
2906
+ {
2907
+ method: "DELETE",
2908
+ signal: options.signal
2909
+ }
2910
+ );
2911
+ },
2912
+ trigger: async (id2, options = {}) => {
2913
+ const response = await this.#transport.request(
2914
+ this.#transport.path(`/schedules/tasks/${encodeURIComponent(id2)}/run`, { requestId: options.requestId }),
2915
+ { method: "POST", signal: options.signal }
2916
+ );
2917
+ return response.run;
2918
+ },
2919
+ /** Reads the exact manual request without starting work. A missing record does not authorize replay. */
2920
+ getTriggerResult: async (id2, requestId, options = {}) => {
2921
+ const response = await this.#transport.request(
2922
+ this.#transport.path(`/schedules/tasks/${encodeURIComponent(id2)}/run`, { requestId }),
2923
+ { signal: options.signal }
2924
+ );
2925
+ return response.run;
2926
+ }
2927
+ };
2928
+ runs = {
2929
+ list: async (options = {}) => {
2930
+ const { signal, unread, ...query } = options;
2931
+ const response = await this.#transport.request(
2932
+ this.#transport.path("/schedules/runs", { ...query, unread: unread === void 0 ? void 0 : String(unread) }),
2933
+ { signal }
2934
+ );
2935
+ return response.runs;
2936
+ },
2937
+ /** Reads one run belonging to this task, regardless of how it was triggered. */
2938
+ get: async (taskId, runId, options = {}) => {
2939
+ const response = await this.#transport.request(
2940
+ `/schedules/tasks/${encodeURIComponent(taskId)}/runs/${encodeURIComponent(runId)}`,
2941
+ { signal: options.signal }
2942
+ );
2943
+ return response.run;
2944
+ },
2945
+ setUnread: async (id2, unread, options = {}) => {
2946
+ const response = await this.#transport.request(
2947
+ `/schedules/runs/${encodeURIComponent(id2)}/read`,
2948
+ { method: "PATCH", body: { unread, ...options.taskId === void 0 ? {} : { taskId: options.taskId } }, signal: options.signal }
2949
+ );
2950
+ return response.run;
2951
+ }
2952
+ };
2741
2953
  async getStatus(options = {}) {
2742
- return await this.transport.request("/schedules/status", {
2954
+ return await this.#transport.request("/schedules/status", {
2743
2955
  signal: options.signal
2744
2956
  });
2745
2957
  }
2746
- async listTasks(options = {}) {
2747
- const { signal, ...query } = options;
2748
- const response = await this.transport.request(
2749
- this.transport.path("/schedules/tasks", query),
2750
- { signal }
2751
- );
2752
- return response.tasks;
2753
- }
2754
- async getTask(id2, options = {}) {
2755
- const response = await this.transport.request(
2756
- `/schedules/tasks/${encodeURIComponent(id2)}`,
2757
- { signal: options.signal }
2758
- );
2759
- return response.task;
2760
- }
2761
- async createTask(input, options = {}) {
2762
- const response = await this.transport.request(
2763
- "/schedules/tasks",
2764
- {
2765
- method: "POST",
2766
- body: input,
2767
- signal: options.signal
2768
- }
2769
- );
2770
- return response.task;
2771
- }
2772
- async updateTask(id2, input, options = {}) {
2773
- const response = await this.transport.request(
2774
- `/schedules/tasks/${encodeURIComponent(id2)}`,
2775
- { method: "PATCH", body: input, signal: options.signal }
2776
- );
2777
- return response.task;
2778
- }
2779
- async removeTask(id2, options = {}) {
2780
- await this.transport.request(
2781
- `/schedules/tasks/${encodeURIComponent(id2)}`,
2782
- {
2783
- method: "DELETE",
2784
- signal: options.signal
2785
- }
2786
- );
2787
- }
2788
- async triggerTask(id2, options = {}) {
2789
- const response = await this.transport.request(
2790
- this.transport.path(`/schedules/tasks/${encodeURIComponent(id2)}/run`, { requestId: options.requestId }),
2791
- { method: "POST", signal: options.signal }
2792
- );
2793
- return response.run;
2794
- }
2795
- /** Reads the exact manual request without starting work. A missing record does not authorize replay. */
2796
- async getTriggerTaskResult(id2, requestId, options = {}) {
2797
- const response = await this.transport.request(
2798
- this.transport.path(`/schedules/tasks/${encodeURIComponent(id2)}/run`, { requestId }),
2799
- { signal: options.signal }
2800
- );
2801
- return response.run;
2802
- }
2803
- async listRuns(options = {}) {
2804
- const { signal, ...query } = options;
2805
- const response = await this.transport.request(
2806
- this.transport.path("/schedules/runs", query),
2807
- { signal }
2808
- );
2809
- return response.runs;
2810
- }
2811
- /** Reads one run belonging to this task, regardless of how it was triggered. */
2812
- async getRun(taskId, runId, options = {}) {
2813
- const response = await this.transport.request(
2814
- `/schedules/tasks/${encodeURIComponent(taskId)}/runs/${encodeURIComponent(runId)}`,
2815
- { signal: options.signal }
2816
- );
2817
- return response.run;
2818
- }
2819
- async setRunUnread(id2, unread, options = {}) {
2820
- const response = await this.transport.request(
2821
- `/schedules/runs/${encodeURIComponent(id2)}/read`,
2822
- { method: "PATCH", body: { unread, ...options.taskId === void 0 ? {} : { taskId: options.taskId } }, signal: options.signal }
2823
- );
2824
- return response.run;
2825
- }
2826
- };
2827
-
2828
- // src/resources/runtime/runtime-resource.ts
2829
- var RuntimeResource = class {
2830
- constructor(transport) {
2831
- this.transport = transport;
2832
- }
2833
- transport;
2834
- async listModels(options = {}) {
2835
- const response = await this.transport.request("/models", options);
2836
- return response.providers;
2837
- }
2838
- async modelProviders(input = { action: "list" }, options = {}) {
2839
- const response = await this.transport.request("/providers/manage", { ...options, method: "POST", body: input });
2840
- if (!validModelProviderConnections(response?.providers)) throw new Error("Invalid model provider response");
2841
- return response.providers;
2842
- }
2843
- async providerDefaults(input = { action: "snapshot" }, options = {}) {
2844
- const result = await this.transport.request("/providers/defaults", { ...options, method: "POST", body: input });
2845
- const valid = input.action === "test" ? validProviderConnectionTestResult(result) : validProviderDefaultsSnapshot(result);
2846
- if (!valid) throw new Error("Invalid provider defaults response");
2847
- return result;
2848
- }
2849
- async listAgentPersonas(options = {}) {
2850
- const response = await this.transport.request("/agent-personas", options);
2851
- return response.agents;
2852
- }
2853
- listSkills(options = {}) {
2854
- return this.transport.request("/skills", options);
2855
- }
2856
- async getSessionMcp(sessionId, options = {}) {
2857
- const response = await this.transport.request(`/sessions/${encodeURIComponent(sessionId)}/mcp`, options);
2858
- return response.servers;
2859
- }
2860
2958
  };
2861
2959
 
2862
2960
  // src/resources/session/session-request-id.ts
2863
- var promptRequestCounter = 0;
2864
- function createPromptRequestId() {
2961
+ var sessionRequestCounter = 0;
2962
+ function createSessionRequestId() {
2865
2963
  if (typeof globalThis.crypto?.randomUUID === "function") {
2866
2964
  return globalThis.crypto.randomUUID();
2867
2965
  }
2868
- promptRequestCounter += 1;
2869
- return `prompt-${Date.now().toString(36)}-${promptRequestCounter.toString(36)}`;
2966
+ sessionRequestCounter += 1;
2967
+ return `prompt-${Date.now().toString(36)}-${sessionRequestCounter.toString(36)}`;
2870
2968
  }
2871
2969
 
2872
2970
  // src/resources/session/session-configuration-requests.ts
@@ -2889,27 +2987,31 @@ async function getDraftComposerOptions(transport, input, options = {}) {
2889
2987
  return result;
2890
2988
  }
2891
2989
  async function create(transport, input, options = {}) {
2990
+ const body = parseCreateSessionRequest({
2991
+ ...input,
2992
+ id: input.id ?? createSessionRequestId(),
2993
+ requestId: input.requestId ?? createSessionRequestId()
2994
+ });
2995
+ if (body.cwd === void 0) await requireDaemonFeature(transport, "projectSessionCreation", options.signal);
2892
2996
  const response = await transport.request(
2893
2997
  "/sessions",
2894
2998
  {
2895
2999
  method: "POST",
2896
- body: parseCreateSessionRequest({
2897
- ...input,
2898
- id: input.id ?? createPromptRequestId(),
2899
- requestId: input.requestId ?? createPromptRequestId()
2900
- }),
3000
+ body,
2901
3001
  signal: options.signal
2902
3002
  }
2903
3003
  );
2904
3004
  return response.session;
2905
3005
  }
2906
3006
  async function getConfigurationOptions(transport, input, options = {}) {
3007
+ if (input.cwd === void 0) await requireDaemonFeature(transport, "projectSessionCreation", options.signal);
2907
3008
  return transport.request(
2908
3009
  transport.path("/sessions/configuration-options", input),
2909
3010
  { signal: options.signal }
2910
3011
  );
2911
3012
  }
2912
3013
  async function getCreationResult(transport, input, options = {}) {
3014
+ if (input.original.cwd === void 0) await requireDaemonFeature(transport, "projectSessionCreation", options.signal);
2913
3015
  return transport.request("/sessions/creation-result", {
2914
3016
  method: "POST",
2915
3017
  body: input,
@@ -2946,123 +3048,39 @@ async function getConfigurationResult(transport, sessionId, input, options = {})
2946
3048
  });
2947
3049
  }
2948
3050
 
2949
- // src/resources/session/session-run-requests.ts
2950
- function checkOutputSchema(transport, input, signal) {
2951
- assertPromptMetadataAllowed2(input);
2952
- if (input.outputSchema === void 0) return;
2953
- return transport.ensureProtocol(signal).then((capabilities) => {
2954
- if ((capabilities.features.structuredDelivery ?? 0) < 1) {
2955
- throw new Error(
2956
- "Server does not support structured delivery (outputSchema)"
2957
- );
2958
- }
2959
- });
2960
- }
2961
- async function admitPrompt(transport, sessionId, input, options = {}) {
2962
- const schemaCheck = checkOutputSchema(transport, input, options.signal);
2963
- if (schemaCheck) await schemaCheck;
2964
- if (input.expectedActiveRunId !== void 0) {
2965
- const capabilities = await transport.ensureProtocol(options.signal);
2966
- if ((capabilities.features.steer ?? 0) < 2) {
2967
- throw new IncompatibleProtocolError(capabilities, "\u540E\u53F0\u7248\u672C\u4E0D\u652F\u6301\u8FD0\u884C\u4E2D\u8865\u5145\uFF0C\u8BF7\u66F4\u65B0\u540E\u91CD\u8BD5\u3002");
2968
- }
3051
+ // src/resources/session/event-resource.ts
3052
+ var EventResource = class {
3053
+ constructor(transport, sse) {
3054
+ this.transport = transport;
3055
+ this.sse = sse;
2969
3056
  }
2970
- return await transport.request(
2971
- `/sessions/${encodeURIComponent(sessionId)}/prompts`,
2972
- {
2973
- method: "POST",
2974
- body: { ...input, id: input.id ?? createPromptRequestId() },
2975
- signal: options.signal
2976
- }
2977
- );
2978
- }
2979
- async function editLatestPrompt(transport, sessionId, input, options = {}) {
2980
- await checkOutputSchema(transport, input, options.signal);
2981
- return await transport.request(
2982
- `/sessions/${encodeURIComponent(sessionId)}/prompts/latest/edit`,
2983
- {
2984
- method: "POST",
2985
- body: input,
2986
- signal: options.signal
2987
- }
2988
- );
2989
- }
2990
- async function promoteQueuedPrompt(transport, sessionId, inputId, input, options = {}) {
2991
- return await transport.request(
2992
- `/sessions/${encodeURIComponent(sessionId)}/prompts/${encodeURIComponent(inputId)}/promote`,
2993
- { method: "POST", body: input, signal: options.signal }
2994
- );
2995
- }
2996
- async function cancelQueuedPrompt(transport, sessionId, inputId, input, options = {}) {
2997
- const mode = parseCancelResponseMode(options.responseMode);
2998
- const response = await transport.request(
2999
- `/sessions/${encodeURIComponent(sessionId)}/prompts/${encodeURIComponent(inputId)}/cancel`,
3000
- {
3001
- method: "POST",
3002
- body: {
3003
- ...input,
3004
- ...options.responseMode ? { responseMode: mode } : {}
3005
- },
3006
- signal: options.signal
3007
- }
3008
- );
3009
- if (mode === "receipt") {
3010
- const receipt2 = decodeQueuedPromptCancelReceipt(response);
3011
- if (receipt2.inputId !== inputId || receipt2.queuedRunId !== input.queuedRunId)
3012
- throw new ProtocolDataError(
3013
- "Cancellation receipt does not match target"
3014
- );
3015
- return receipt2;
3057
+ transport;
3058
+ sse;
3059
+ /** `GET /events` — 用于 attach 时的历史 replay。 */
3060
+ async list(options = {}) {
3061
+ const { signal, ...query } = options;
3062
+ const response = await this.transport.request(
3063
+ this.transport.path("/events", query),
3064
+ { signal }
3065
+ );
3066
+ return responseArray2(response, "events", decodeSessionEventRecord);
3016
3067
  }
3017
- return response;
3018
- }
3019
- async function resumeInterruptedRun(transport, sessionId, runId, input = {}, options = {}) {
3020
- await checkOutputSchema(transport, input, options.signal);
3021
- return await transport.request(
3022
- `/sessions/${encodeURIComponent(sessionId)}/runs/${encodeURIComponent(runId)}/resume`,
3023
- {
3024
- method: "POST",
3025
- body: { ...input, id: input.id ?? createPromptRequestId() },
3026
- signal: options.signal
3027
- }
3028
- );
3029
- }
3030
- async function interrupt(transport, sessionId, options = {}) {
3031
- return await transport.request(
3032
- `/sessions/${encodeURIComponent(sessionId)}/interrupt`,
3033
- {
3034
- method: "POST",
3035
- body: options.expectedRunId === void 0 ? void 0 : { expectedRunId: options.expectedRunId },
3036
- signal: options.signal
3037
- }
3038
- );
3039
- }
3040
-
3041
- // src/resources/session/session-terminal-resource.ts
3042
- var SessionTerminalResource = class {
3043
- constructor(transport) {
3044
- this.transport = transport;
3045
- }
3046
- transport;
3047
- async list(sessionId, options = {}) {
3048
- const response = await this.transport.requestUnknown(path(sessionId), options);
3049
- return responseArray2(response, "terminals", decodeTerminalSessionInfo);
3050
- }
3051
- async read(sessionId, terminalId, options = {}) {
3052
- const { signal, ...query } = options;
3053
- const response = await this.transport.requestUnknown(path(sessionId, terminalId) + "/output", { signal, query });
3054
- return decodeTerminalReadResult(responseField(response, "snapshot"));
3055
- }
3056
- async stream(sessionId, terminalId, options = {}) {
3057
- const response = await this.transport.requestResponse(path(sessionId, terminalId) + "/stream", options);
3058
- const body = response.body;
3059
- if (!body) throw new Error("Terminal event stream did not return a body");
3060
- return streamServerSentEvents(async () => body, decodeTerminalEvent);
3068
+ stream(options = {}) {
3069
+ const query = {
3070
+ partView: options.partView,
3071
+ cursor: options.cursor,
3072
+ sessionId: options.sessionId
3073
+ };
3074
+ return this.sse.stream(this.transport.resolveUrl("/events/stream", query), {
3075
+ headers: this.transport.headers(),
3076
+ signal: options.signal,
3077
+ decode: decodeSessionEventRecord,
3078
+ reconnect: options.transportReconnect ?? false,
3079
+ onOpen: options.onOpen,
3080
+ idleTimeoutMs: options.idleTimeoutMs
3081
+ });
3061
3082
  }
3062
3083
  };
3063
- function path(sessionId, terminalId) {
3064
- return `/sessions/${encodeURIComponent(sessionId)}/terminals${terminalId === void 0 ? "" : `/${encodeURIComponent(terminalId)}`}`;
3065
- }
3066
3084
 
3067
3085
  // src/resources/session/session-management-resource.ts
3068
3086
  var SessionManagementResource = class {
@@ -3116,1183 +3134,2253 @@ var SessionManagementResource = class {
3116
3134
  }
3117
3135
  };
3118
3136
 
3119
- // src/resources/session/session-resource.ts
3120
- var SessionResource = class {
3121
- constructor(transport) {
3122
- this.transport = transport;
3123
- this.resources = new SessionManagementResource(transport);
3124
- this.terminals = new SessionTerminalResource(transport);
3125
- }
3126
- transport;
3127
- resources;
3128
- terminals;
3129
- /** `GET /sessions/search` - search saved conversation text without opening it. */
3130
- async search(options) {
3131
- const { signal, ...query } = options;
3132
- const response = await this.transport.request(this.transport.path("/sessions/search", query), { signal });
3133
- return response.results;
3134
- }
3135
- /** `GET /sessions` */
3136
- async list(options = {}) {
3137
- const { signal, ...query } = options;
3138
- const response = await this.transport.request(this.transport.path("/sessions", query), { signal });
3139
- return response.sessions;
3140
- }
3141
- listDirectory(options = {}) {
3142
- const { signal, ...query } = options;
3143
- return this.transport.request(
3144
- this.transport.path("/sessions/directory", query),
3145
- { signal }
3146
- );
3147
- }
3148
- getActivity(options = {}) {
3149
- return this.transport.request("/sessions/activity", {
3150
- signal: options.signal
3151
- });
3152
- }
3153
- getDraftComposerOptions(input, options = {}) {
3154
- return getDraftComposerOptions(this.transport, input, options);
3137
+ // src/state/selectors.ts
3138
+ function selectSessionMessagesWithParts(bucket) {
3139
+ if (!bucket) return [];
3140
+ return [...bucket.messages].sort((a, b) => a.seq - b.seq).map((message) => ({
3141
+ message,
3142
+ parts: [...bucket.partsByMessageId[message.id] ?? []].sort((a, b) => a.seq - b.seq)
3143
+ }));
3144
+ }
3145
+ function getVisibleSessionMessages(bucket) {
3146
+ return selectSessionMessagesWithParts(bucket).map(({ message, parts }) => ({
3147
+ message,
3148
+ parts: parts.filter((part) => !isSupersededModelPart(part))
3149
+ })).filter(
3150
+ ({ message, parts }) => parts.length > 0 || message.role !== "assistant"
3151
+ );
3152
+ }
3153
+ function selectSessionInputs(bucket) {
3154
+ if (!bucket) return [];
3155
+ return [...bucket.inputs].sort((a, b) => a.seq - b.seq);
3156
+ }
3157
+ function selectSessionOrderedMessages(bucket) {
3158
+ if (!bucket) return [];
3159
+ return [...bucket.messages].sort((a, b) => a.seq - b.seq);
3160
+ }
3161
+ function selectSessionParts(bucket) {
3162
+ if (!bucket) return [];
3163
+ return Object.values(bucket.partsByMessageId).flat().sort((a, b) => a.seq - b.seq);
3164
+ }
3165
+ function selectSessionRuns(bucket) {
3166
+ if (!bucket) return [];
3167
+ return Object.values(bucket.runs);
3168
+ }
3169
+ function selectSessionModelRetry(bucket) {
3170
+ if (!bucket) return void 0;
3171
+ const active = Object.values(bucket.runs).filter((run) => run.status === "running" || run.status === "pending").sort((a, b) => b.updatedAt - a.updatedAt);
3172
+ for (const run of active) {
3173
+ const state = readSessionModelRetryState(run.metadata);
3174
+ if (state) return state;
3155
3175
  }
3156
- async getControls(sessionId, options = {}) {
3157
- const result = await this.transport.request(
3158
- `/sessions/${encodeURIComponent(sessionId)}/controls`,
3159
- { signal: options.signal }
3160
- );
3161
- if (!validSessionControlResult("sessions.getControls", result) || result.sessionId !== sessionId) {
3162
- throw new ProtocolDataError("Session controls do not match target");
3163
- }
3164
- return result;
3176
+ return void 0;
3177
+ }
3178
+ function selectSessionModelUsage(bucket) {
3179
+ if (!bucket) return void 0;
3180
+ const runs = Object.values(bucket.runs).sort((a, b) => b.updatedAt - a.updatedAt);
3181
+ for (const run of runs) {
3182
+ const usage = readSessionModelUsage(run.metadata);
3183
+ if (usage) return usage;
3165
3184
  }
3166
- async getControlResult(sessionId, input, options = {}) {
3167
- const { requestId, original } = input;
3168
- if (!validSessionControlOriginal(original) || original.body.requestId !== requestId) throw new ProtocolDataError("Invalid original control request");
3169
- const result = await this.transport.request(
3170
- `/sessions/${encodeURIComponent(sessionId)}/control-result`,
3171
- {
3172
- method: "POST",
3173
- body: { requestId, original },
3174
- signal: options.signal
3175
- }
3185
+ return void 0;
3186
+ }
3187
+ function selectSessionTasks(bucket) {
3188
+ if (!bucket) return [];
3189
+ return Object.values(bucket.tasks);
3190
+ }
3191
+ function selectSessionPermissions(bucket) {
3192
+ if (!bucket) return [];
3193
+ return Object.values(bucket.permissions);
3194
+ }
3195
+ function selectFirstPendingPermission(state, sessionId) {
3196
+ if (!sessionId) return void 0;
3197
+ const bucket = state.buckets[sessionId];
3198
+ if (!bucket) return void 0;
3199
+ return Object.values(bucket.permissions).filter((request) => request.status === "pending").sort((a, b) => a.createdAt - b.createdAt).at(0);
3200
+ }
3201
+
3202
+ // src/state/reducer.ts
3203
+ var UnsupportedSessionEventSchemaVersionError = class extends Error {
3204
+ event;
3205
+ constructor(event) {
3206
+ const expected = sessionEventSchemaVersion(event.type);
3207
+ super(
3208
+ `Unsupported session event schema version ${event.schemaVersion} for ${event.type} at sequence ${event.seq}; expected ${expected}`
3176
3209
  );
3177
- if (!validSessionControlResult("sessions.getControlResult", result) || result && (result.sessionId !== sessionId || result.requestId !== requestId || result.action !== original.action || original.action === "fork" && result.targetSessionId !== original.body.id))
3178
- throw new ProtocolDataError(
3179
- "Control receipt does not match original request"
3180
- );
3181
- return result;
3210
+ this.name = "UnsupportedSessionEventSchemaVersionError";
3211
+ this.event = {
3212
+ seq: event.seq,
3213
+ type: event.type,
3214
+ schemaVersion: event.schemaVersion
3215
+ };
3182
3216
  }
3183
- /** Current context assembly requires execution authority; /usage is historical billing. */
3184
- async getContextUsage(sessionId, options = {}) {
3185
- return this.transport.request(
3186
- `/sessions/${encodeURIComponent(sessionId)}/context-usage`,
3187
- { signal: options.signal }
3188
- );
3217
+ };
3218
+ function createClientState() {
3219
+ return {
3220
+ sessions: {},
3221
+ sessionOrder: [],
3222
+ buckets: {},
3223
+ eventsBySeq: {},
3224
+ snapshotCursorBySession: {},
3225
+ transientCursor: 0,
3226
+ lastSeq: 0
3227
+ };
3228
+ }
3229
+ function applyEvents(state, events) {
3230
+ let next = state;
3231
+ for (const event of events) next = applyEvent(next, event);
3232
+ return next;
3233
+ }
3234
+ function replaceSessionState(state, snapshot) {
3235
+ const knownCursor = state.snapshotCursorBySession[snapshot.session.id] ?? 0;
3236
+ if (snapshot.cursor < knownCursor) return state;
3237
+ if (Object.values(state.eventsBySeq).some((event) => event.sessionId === snapshot.session.id && event.seq > snapshot.cursor)) return state;
3238
+ const partsByMessageId = {};
3239
+ for (const part of snapshot.parts) {
3240
+ const parts = partsByMessageId[part.messageId] ?? [];
3241
+ parts.push(part);
3242
+ partsByMessageId[part.messageId] = parts;
3189
3243
  }
3190
- /** `GET /sessions/:id` */
3191
- async get(sessionId, options = {}) {
3192
- const response = await this.transport.request(
3193
- `/sessions/${encodeURIComponent(sessionId)}`,
3194
- {
3195
- signal: options.signal
3244
+ for (const parts of Object.values(partsByMessageId)) parts.sort((a, b) => a.seq - b.seq);
3245
+ const sessions = { ...state.sessions, [snapshot.session.id]: snapshot.session };
3246
+ return {
3247
+ ...state,
3248
+ sessions,
3249
+ sessionOrder: sortSessionOrder(sessions),
3250
+ buckets: {
3251
+ ...state.buckets,
3252
+ [snapshot.session.id]: {
3253
+ goal: snapshot.goal,
3254
+ goalEventSeq: snapshot.cursor,
3255
+ session: snapshot.session,
3256
+ inputs: [...snapshot.inputs].sort((a, b) => a.seq - b.seq),
3257
+ messages: [...snapshot.messages].sort((a, b) => a.seq - b.seq),
3258
+ partsByMessageId,
3259
+ runs: Object.fromEntries(snapshot.runs.map((run) => [run.id, run])),
3260
+ attempts: Object.fromEntries((snapshot.attempts ?? []).map((attempt) => [attempt.id, attempt])),
3261
+ tasks: Object.fromEntries((snapshot.tasks ?? []).map((task) => [task.id, task])),
3262
+ permissions: Object.fromEntries(snapshot.permissions.map((request) => [request.id, request]))
3196
3263
  }
3197
- );
3198
- return response.session;
3199
- }
3200
- /** `POST /sessions` */
3201
- create(input, options = {}) {
3202
- return create(this.transport, input, options);
3203
- }
3204
- getConfigurationOptions(input, options = {}) {
3205
- return getConfigurationOptions(this.transport, input, options);
3206
- }
3207
- getCreationResult(input, options = {}) {
3208
- return getCreationResult(this.transport, input, options);
3209
- }
3210
- getConfiguration(sessionId, options = {}) {
3211
- return getConfiguration(this.transport, sessionId, options);
3212
- }
3213
- configure(sessionId, input, options = {}) {
3214
- return configure(this.transport, sessionId, input, options);
3215
- }
3216
- getConfigurationResult(sessionId, input, options = {}) {
3217
- return getConfigurationResult(this.transport, sessionId, input, options);
3264
+ },
3265
+ snapshotCursorBySession: {
3266
+ ...state.snapshotCursorBySession,
3267
+ [snapshot.session.id]: Math.max(
3268
+ state.snapshotCursorBySession[snapshot.session.id] ?? 0,
3269
+ snapshot.cursor
3270
+ )
3271
+ },
3272
+ transientCursor: Math.max(state.transientCursor, snapshot.cursor),
3273
+ lastSeq: Math.max(state.lastSeq, snapshot.cursor)
3274
+ };
3275
+ }
3276
+ function applyEvent(state, event) {
3277
+ if (event.schemaVersion !== sessionEventSchemaVersion(event.type)) {
3278
+ throw new UnsupportedSessionEventSchemaVersionError(event);
3218
3279
  }
3219
- /** `PATCH /sessions/:id` - update title or application metadata. */
3220
- async update(sessionId, input, options = {}) {
3221
- const response = await this.transport.request(
3222
- `/sessions/${encodeURIComponent(sessionId)}`,
3223
- {
3224
- method: "PATCH",
3225
- body: parseUpdateSessionRequest(input),
3226
- signal: options.signal
3280
+ const transient = event.type === "session.message.part.delta";
3281
+ const snapshotCursor = event.sessionId ? state.snapshotCursorBySession[event.sessionId] ?? 0 : 0;
3282
+ if (event.seq <= snapshotCursor) return state;
3283
+ if (transient && event.seq <= state.transientCursor) return state;
3284
+ if (!transient && state.eventsBySeq[event.seq]) return state;
3285
+ if (!transient) state.eventsBySeq[event.seq] = event;
3286
+ let next = {
3287
+ ...state,
3288
+ eventsBySeq: state.eventsBySeq,
3289
+ transientCursor: transient ? event.seq : state.transientCursor,
3290
+ lastSeq: Math.max(state.lastSeq, event.seq)
3291
+ };
3292
+ switch (event.type) {
3293
+ case "session.goal.created":
3294
+ case "session.goal.updated": {
3295
+ next = upsertGoal(next, event);
3296
+ break;
3297
+ }
3298
+ case "session.goal.usage.updated": {
3299
+ const bucket = event.sessionId ? next.buckets[event.sessionId] : void 0;
3300
+ const usage = readPayloadRecord(event, "usage");
3301
+ if (bucket?.goal && bucket.goal.id === event.payload.goalId && usage && usage.seq > bucket.goal.usage.seq) {
3302
+ next = { ...next, buckets: { ...next.buckets, [event.sessionId]: { ...bucket, goal: { ...bucket.goal, usage } } } };
3227
3303
  }
3228
- );
3229
- return response.session;
3230
- }
3231
- /** `POST /sessions/:id/fork` */
3232
- async fork(sessionId, input = {}, options = {}) {
3233
- const response = await this.transport.request(
3234
- `/sessions/${encodeURIComponent(sessionId)}/fork`,
3304
+ break;
3305
+ }
3306
+ case "session.created":
3307
+ case "session.updated":
3308
+ next = upsertSession(next, readPayloadRecord(event, "session"));
3309
+ break;
3310
+ case "session.archived":
3311
+ next = archiveSession(next, event);
3312
+ break;
3313
+ case "session.deleted":
3314
+ next = deleteSessions(next, event);
3315
+ break;
3316
+ case "session.input.admitted":
3317
+ next = upsertInput(next, readPayloadRecord(event, "input"));
3318
+ break;
3319
+ case "session.message.created":
3320
+ next = upsertMessage(next, readPayloadRecord(event, "message"));
3321
+ break;
3322
+ case "session.transcript.replaced":
3323
+ next = replaceTranscript(next, event);
3324
+ break;
3325
+ case "session.message.part.updated":
3326
+ next = upsertPart(next, readPayloadRecord(event, "part"));
3327
+ break;
3328
+ case "session.message.part.delta":
3329
+ next = appendPartDelta(next, event);
3330
+ break;
3331
+ case "session.run.created":
3332
+ case "session.run.updated":
3333
+ next = upsertRun(next, readPayloadRecord(event, "run"));
3334
+ break;
3335
+ case "session.run_attempt.created":
3336
+ case "session.run_attempt.updated":
3337
+ next = upsertRunAttempt(next, readPayloadRecord(event, "attempt"));
3338
+ break;
3339
+ case "session.task.created":
3340
+ case "session.task.updated":
3341
+ next = upsertTask(next, readPayloadRecord(event, "task"));
3342
+ break;
3343
+ case "permission.asked":
3344
+ case "permission.replied":
3345
+ next = upsertPermission(next, readPayloadRecord(event, "request"));
3346
+ break;
3347
+ }
3348
+ return next;
3349
+ }
3350
+ function readPayloadRecord(event, key) {
3351
+ const value = event.payload[key];
3352
+ return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
3353
+ }
3354
+ function upsertGoal(state, event) {
3355
+ const goal = readPayloadRecord(event, "goal");
3356
+ if (!goal || goal.sessionId !== event.sessionId) return state;
3357
+ const bucket = state.buckets[goal.sessionId];
3358
+ const current = bucket?.goal;
3359
+ const seq = bucket?.goalEventSeq ?? 0;
3360
+ const sameGoal = current?.id === goal.id;
3361
+ if (current && !sameGoal && (event.type !== "session.goal.created" || event.seq <= seq)) return state;
3362
+ const isNewer = !sameGoal || goal.revision > current.revision || goal.revision === current.revision && event.seq > seq;
3363
+ const record5 = isNewer ? goal : current;
3364
+ const usage = sameGoal && current.usage.seq >= goal.usage.seq ? current.usage : goal.usage;
3365
+ if (!isNewer && usage === current.usage) return state;
3366
+ return { ...state, buckets: { ...state.buckets, [goal.sessionId]: {
3367
+ ...bucket ?? cloneBucket(void 0),
3368
+ goal: usage === record5.usage ? record5 : { ...record5, usage },
3369
+ goalEventSeq: isNewer ? Math.max(seq, event.seq) : seq
3370
+ } } };
3371
+ }
3372
+ function upsertSession(state, session) {
3373
+ if (!session) return state;
3374
+ const bucket = cloneBucket(state.buckets[session.id]);
3375
+ bucket.session = session;
3376
+ const sessions = { ...state.sessions, [session.id]: session };
3377
+ return {
3378
+ ...state,
3379
+ sessions,
3380
+ sessionOrder: sortSessionOrder(sessions),
3381
+ buckets: { ...state.buckets, [session.id]: bucket }
3382
+ };
3383
+ }
3384
+ function archiveSession(state, event) {
3385
+ const sessionId = typeof event.payload.sessionId === "string" ? event.payload.sessionId : event.sessionId;
3386
+ if (!sessionId) return state;
3387
+ const current = state.sessions[sessionId];
3388
+ if (!current) return state;
3389
+ const archived = {
3390
+ ...current,
3391
+ status: "archived",
3392
+ archivedAt: current.archivedAt ?? event.createdAt,
3393
+ updatedAt: Math.max(current.updatedAt, event.createdAt)
3394
+ };
3395
+ return upsertSession(state, archived);
3396
+ }
3397
+ function deleteSessions(state, event) {
3398
+ const ids = new Set(Array.isArray(event.payload.sessionIds) ? event.payload.sessionIds.filter((id2) => typeof id2 === "string") : []);
3399
+ if (ids.size === 0) return state;
3400
+ return {
3401
+ ...state,
3402
+ sessions: Object.fromEntries(Object.entries(state.sessions).filter(([id2]) => !ids.has(id2))),
3403
+ sessionOrder: state.sessionOrder.filter((id2) => !ids.has(id2)),
3404
+ buckets: Object.fromEntries(Object.entries(state.buckets).filter(([id2]) => !ids.has(id2))),
3405
+ snapshotCursorBySession: Object.fromEntries(Object.entries(state.snapshotCursorBySession).filter(([id2]) => !ids.has(id2))),
3406
+ eventsBySeq: Object.fromEntries(Object.entries(state.eventsBySeq).filter(([, item]) => !item.sessionId || !ids.has(item.sessionId)))
3407
+ };
3408
+ }
3409
+ function upsertInput(state, input) {
3410
+ if (!input) return state;
3411
+ const bucket = cloneBucket(state.buckets[input.sessionId]);
3412
+ bucket.inputs = upsertSorted(bucket.inputs, input, (row) => row.seq);
3413
+ return { ...state, buckets: { ...state.buckets, [input.sessionId]: bucket } };
3414
+ }
3415
+ function upsertMessage(state, message) {
3416
+ if (!message) return state;
3417
+ const bucket = cloneBucket(state.buckets[message.sessionId]);
3418
+ bucket.messages = upsertSorted(bucket.messages, message, (row) => row.seq);
3419
+ return { ...state, buckets: { ...state.buckets, [message.sessionId]: bucket } };
3420
+ }
3421
+ function replaceTranscript(state, event) {
3422
+ const sessionId = event.sessionId;
3423
+ if (!sessionId) return state;
3424
+ const messages = Array.isArray(event.payload.messages) ? event.payload.messages.filter((row) => !!row && typeof row === "object" && !Array.isArray(row) && typeof row.id === "string") : [];
3425
+ const parts = Array.isArray(event.payload.parts) ? event.payload.parts.filter((row) => !!row && typeof row === "object" && !Array.isArray(row) && typeof row.id === "string") : [];
3426
+ const bucket = cloneBucket(state.buckets[sessionId]);
3427
+ const partsByMessageId = {};
3428
+ for (const part of parts) {
3429
+ const rows = partsByMessageId[part.messageId] ?? [];
3430
+ rows.push(part);
3431
+ partsByMessageId[part.messageId] = rows;
3432
+ }
3433
+ for (const rows of Object.values(partsByMessageId)) rows.sort((a, b) => a.seq - b.seq);
3434
+ bucket.messages = [...messages].sort((a, b) => a.seq - b.seq);
3435
+ bucket.partsByMessageId = partsByMessageId;
3436
+ if (bucket.session) {
3437
+ bucket.session = {
3438
+ ...bucket.session,
3439
+ updatedAt: Math.max(bucket.session.updatedAt, event.createdAt)
3440
+ };
3441
+ }
3442
+ const sessions = bucket.session ? { ...state.sessions, [sessionId]: bucket.session } : state.sessions;
3443
+ return {
3444
+ ...state,
3445
+ sessions,
3446
+ sessionOrder: sortSessionOrder(sessions),
3447
+ buckets: { ...state.buckets, [sessionId]: bucket }
3448
+ };
3449
+ }
3450
+ function upsertPart(state, part) {
3451
+ if (!part) return state;
3452
+ const bucket = cloneBucketForPartWrite(state.buckets[part.sessionId]);
3453
+ const existing = bucket.partsByMessageId[part.messageId] ?? [];
3454
+ bucket.partsByMessageId = {
3455
+ ...bucket.partsByMessageId,
3456
+ [part.messageId]: upsertSorted(existing, part, (row) => row.seq)
3457
+ };
3458
+ return { ...state, buckets: { ...state.buckets, [part.sessionId]: bucket } };
3459
+ }
3460
+ function appendPartDelta(state, event) {
3461
+ const sessionId = typeof event.payload.sessionId === "string" ? event.payload.sessionId : event.sessionId;
3462
+ const messageId = typeof event.payload.messageId === "string" ? event.payload.messageId : void 0;
3463
+ const partId = typeof event.payload.partId === "string" ? event.payload.partId : void 0;
3464
+ const field = event.payload.field;
3465
+ const delta = typeof event.payload.delta === "string" ? event.payload.delta : void 0;
3466
+ if (field !== "text" && field !== "reasoning") return state;
3467
+ if (!sessionId || !messageId || !partId || delta === void 0) return state;
3468
+ const bucket = cloneBucketForPartWrite(state.buckets[sessionId]);
3469
+ const currentParts = bucket.partsByMessageId[messageId] ?? [];
3470
+ const index = currentParts.findIndex((part) => part.id === partId);
3471
+ const nextParts = [...currentParts];
3472
+ if (index >= 0) {
3473
+ const current = nextParts[index];
3474
+ if (isSupersededModelPart(current)) return state;
3475
+ nextParts[index] = {
3476
+ ...current,
3477
+ text: `${current.text ?? ""}${delta}`,
3478
+ updatedAt: Math.max(current.updatedAt, event.createdAt)
3479
+ };
3480
+ } else {
3481
+ const seq = currentParts.reduce((max, part) => Math.max(max, part.seq), 0) + 1;
3482
+ nextParts.push({
3483
+ id: partId,
3484
+ sessionId,
3485
+ messageId,
3486
+ seq,
3487
+ type: field === "reasoning" ? "reasoning" : "text",
3488
+ status: "running",
3489
+ text: delta,
3490
+ metadata: {},
3491
+ createdAt: event.createdAt,
3492
+ updatedAt: event.createdAt
3493
+ });
3494
+ }
3495
+ const sortedParts = index >= 0 ? nextParts : nextParts.sort((a, b) => a.seq - b.seq);
3496
+ bucket.partsByMessageId = {
3497
+ ...bucket.partsByMessageId,
3498
+ [messageId]: sortedParts
3499
+ };
3500
+ return { ...state, buckets: { ...state.buckets, [sessionId]: bucket } };
3501
+ }
3502
+ function upsertRun(state, run) {
3503
+ if (!run) return state;
3504
+ const bucket = cloneBucket(state.buckets[run.sessionId]);
3505
+ bucket.runs = { ...bucket.runs, [run.id]: run };
3506
+ const session = refreshSessionStatusFromRuns(bucket.session, bucket.runs, run.updatedAt);
3507
+ bucket.session = session;
3508
+ const sessions = session ? { ...state.sessions, [run.sessionId]: session } : state.sessions;
3509
+ return {
3510
+ ...state,
3511
+ sessions,
3512
+ sessionOrder: session ? sortSessionOrder(sessions) : state.sessionOrder,
3513
+ buckets: { ...state.buckets, [run.sessionId]: bucket }
3514
+ };
3515
+ }
3516
+ function upsertRunAttempt(state, attempt) {
3517
+ if (!attempt) return state;
3518
+ const run = Object.values(state.buckets).flatMap((bucket2) => Object.values(bucket2.runs)).find((candidate) => candidate.id === attempt.runId);
3519
+ if (!run) return state;
3520
+ const bucket = cloneBucket(state.buckets[run.sessionId]);
3521
+ bucket.attempts = { ...bucket.attempts, [attempt.id]: attempt };
3522
+ return { ...state, buckets: { ...state.buckets, [run.sessionId]: bucket } };
3523
+ }
3524
+ function refreshSessionStatusFromRuns(session, runs, updatedAt) {
3525
+ if (!session || session.status === "archived" || session.status === "closing") return session;
3526
+ const running = Object.values(runs).some(
3527
+ (candidate) => candidate.status === "pending" || candidate.status === "running"
3528
+ );
3529
+ return {
3530
+ ...session,
3531
+ status: running ? "running" : "idle",
3532
+ updatedAt: Math.max(session.updatedAt, updatedAt)
3533
+ };
3534
+ }
3535
+ function upsertPermission(state, request) {
3536
+ if (!request) return state;
3537
+ const bucket = cloneBucket(state.buckets[request.sessionId]);
3538
+ bucket.permissions = { ...bucket.permissions, [request.id]: request };
3539
+ return { ...state, buckets: { ...state.buckets, [request.sessionId]: bucket } };
3540
+ }
3541
+ function upsertTask(state, task) {
3542
+ if (!task) return state;
3543
+ const bucket = cloneBucket(state.buckets[task.sessionId]);
3544
+ bucket.tasks = { ...bucket.tasks, [task.id]: task };
3545
+ return { ...state, buckets: { ...state.buckets, [task.sessionId]: bucket } };
3546
+ }
3547
+ function cloneBucket(bucket) {
3548
+ return {
3549
+ ...bucket?.goal !== void 0 ? { goal: bucket.goal } : {},
3550
+ ...bucket?.goalEventSeq !== void 0 ? { goalEventSeq: bucket.goalEventSeq } : {},
3551
+ session: bucket?.session,
3552
+ inputs: bucket?.inputs ? [...bucket.inputs] : [],
3553
+ messages: bucket?.messages ? [...bucket.messages] : [],
3554
+ partsByMessageId: bucket?.partsByMessageId ? Object.fromEntries(Object.entries(bucket.partsByMessageId).map(([id2, parts]) => [id2, [...parts]])) : {},
3555
+ runs: bucket?.runs ? { ...bucket.runs } : {},
3556
+ attempts: bucket?.attempts ? { ...bucket.attempts } : {},
3557
+ tasks: bucket?.tasks ? { ...bucket.tasks } : {},
3558
+ permissions: bucket?.permissions ? { ...bucket.permissions } : {}
3559
+ };
3560
+ }
3561
+ function cloneBucketForPartWrite(bucket) {
3562
+ return {
3563
+ ...bucket?.goal !== void 0 ? { goal: bucket.goal } : {},
3564
+ ...bucket?.goalEventSeq !== void 0 ? { goalEventSeq: bucket.goalEventSeq } : {},
3565
+ session: bucket?.session,
3566
+ inputs: bucket?.inputs ?? [],
3567
+ messages: bucket?.messages ?? [],
3568
+ partsByMessageId: bucket?.partsByMessageId ?? {},
3569
+ runs: bucket?.runs ?? {},
3570
+ attempts: bucket?.attempts ?? {},
3571
+ tasks: bucket?.tasks ?? {},
3572
+ permissions: bucket?.permissions ?? {}
3573
+ };
3574
+ }
3575
+ function upsertSorted(rows, row, sortKey) {
3576
+ const without = rows.filter((existing) => existing.id !== row.id);
3577
+ without.push(row);
3578
+ return without.sort((a, b) => sortKey(a) - sortKey(b));
3579
+ }
3580
+ function sortSessionOrder(sessions) {
3581
+ return Object.values(sessions).sort((a, b) => b.updatedAt - a.updatedAt || a.id.localeCompare(b.id)).map((session) => session.id);
3582
+ }
3583
+
3584
+ // src/state/session-stream-state.ts
3585
+ function applySessionStreamEvent(state, event) {
3586
+ if (event.seq <= state.lastSeq) return state;
3587
+ const next = applyEvent({ ...state, eventsBySeq: {} }, event);
3588
+ return { ...next, eventsBySeq: {} };
3589
+ }
3590
+ function applySessionStreamSnapshot(state, snapshot) {
3591
+ if (snapshot.cursor < state.lastSeq) return state;
3592
+ return { ...replaceSessionState(state, snapshot), eventsBySeq: {} };
3593
+ }
3594
+
3595
+ // src/state/sync.ts
3596
+ var DEFAULT_RECONNECT_DELAY_MS = (attempt) => Math.min(3e4, 250 * 2 ** Math.max(0, attempt));
3597
+ var DEFAULT_SESSION_IDLE_TIMEOUT_MS = 6e4;
3598
+ var EVENT_REPLAY_PAGE_SIZE = 128;
3599
+ function hydrateState(events) {
3600
+ return applyEvents(createClientState(), events);
3601
+ }
3602
+ async function* syncEvents(client, options = {}) {
3603
+ yield* runEventSync(client, {
3604
+ ...options,
3605
+ // 会话迭代接口从完整快照开始;只有全局 replay 使用调用方游标。
3606
+ cursor: options.sessionId ? void 0 : options.cursor,
3607
+ idleTimeoutMs: options.idleTimeoutMs ?? DEFAULT_SESSION_IDLE_TIMEOUT_MS
3608
+ });
3609
+ }
3610
+ async function* runEventSync(client, options, initialState = createClientState(), onLiveEvent) {
3611
+ let state = initialState;
3612
+ let cursor = Math.max(0, options.cursor ?? 0, state.lastSeq);
3613
+ let attempt = 0;
3614
+ const signal = options.signal;
3615
+ const delayMs = options.reconnectDelayMs ?? DEFAULT_RECONNECT_DELAY_MS;
3616
+ const reduce = options.sessionId ? applySessionStreamEvent : options.globalReducer ?? applyEvent;
3617
+ if (signal?.aborted) return;
3618
+ const session = options.sessionId ? client.sessions.byId(options.sessionId) : void 0;
3619
+ const refreshSession = async (initial) => {
3620
+ const snapshot = await session.getState({
3621
+ signal,
3622
+ partView: options.partView
3623
+ });
3624
+ if (signal?.aborted) return;
3625
+ const next = initial ? replaceSessionState(state, snapshot) : applySessionStreamSnapshot(state, snapshot);
3626
+ state = Object.keys(next.eventsBySeq).length ? { ...next, eventsBySeq: {} } : next;
3627
+ cursor = Math.max(cursor, snapshot.cursor, state.lastSeq);
3628
+ };
3629
+ const replayHistory = async function* (initial, beforeSeq) {
3630
+ let pageCursor = cursor;
3631
+ while (!signal?.aborted) {
3632
+ const page = await client.events.list({
3633
+ cursor: pageCursor,
3634
+ limit: EVENT_REPLAY_PAGE_SIZE,
3635
+ partView: options.partView,
3636
+ signal
3637
+ });
3638
+ if (signal?.aborted) return;
3639
+ for (const event of page) {
3640
+ if (signal?.aborted || beforeSeq !== void 0 && event.seq >= beforeSeq) return;
3641
+ const before = state;
3642
+ state = reduce(state, event);
3643
+ cursor = Math.max(cursor, event.seq, state.lastSeq);
3644
+ if (initial || state !== before) yield { event, state, source: "replay" };
3645
+ }
3646
+ const through = page.at(-1)?.seq ?? pageCursor;
3647
+ if (page.length < EVENT_REPLAY_PAGE_SIZE || through <= pageCursor) return;
3648
+ pageCursor = through;
3649
+ }
3650
+ };
3651
+ try {
3652
+ if (options.sessionId) {
3653
+ await refreshSession(true);
3654
+ } else {
3655
+ yield* replayHistory(true);
3656
+ }
3657
+ if (signal?.aborted) return;
3658
+ yield { state, source: "snapshot" };
3659
+ let needsSnapshot = false;
3660
+ while (!signal?.aborted) {
3661
+ try {
3662
+ if (needsSnapshot) {
3663
+ await refreshSession(false);
3664
+ if (signal?.aborted) return;
3665
+ needsSnapshot = false;
3666
+ yield { state, source: "snapshot" };
3667
+ }
3668
+ if (signal?.aborted) return;
3669
+ for await (const event of client.events.stream({
3670
+ cursor,
3671
+ sessionId: options.sessionId,
3672
+ signal,
3673
+ partView: options.partView,
3674
+ transportReconnect: false,
3675
+ idleTimeoutMs: options.idleTimeoutMs
3676
+ })) {
3677
+ if (signal?.aborted) return;
3678
+ onLiveEvent?.();
3679
+ if (signal?.aborted) return;
3680
+ attempt = 0;
3681
+ if (event.seq > cursor + 1 && !options.sessionId) {
3682
+ yield* replayHistory(false, event.seq);
3683
+ }
3684
+ if (signal?.aborted) return;
3685
+ const before = state;
3686
+ state = reduce(state, event);
3687
+ cursor = Math.max(cursor, event.seq, state.lastSeq);
3688
+ if (state !== before) yield { event, state, source: "live" };
3689
+ }
3690
+ } catch (error) {
3691
+ if (error instanceof UnsupportedSessionEventSchemaVersionError) throw error;
3692
+ if (isAbortError(error) || signal?.aborted) return;
3693
+ if (options.shouldRetry?.(error) === false) throw error;
3694
+ if (error instanceof BobanNomiApiError && error.status >= 400 && error.status < 500 && ![408, 425, 429].includes(error.status)) throw error;
3695
+ }
3696
+ if (signal?.aborted) return;
3697
+ needsSnapshot = Boolean(options.sessionId);
3698
+ yield { state, source: "reconnecting" };
3699
+ if (!await waitForReconnect2(delayMs(attempt), signal)) return;
3700
+ attempt += 1;
3701
+ }
3702
+ } catch (error) {
3703
+ if (!isAbortError(error) && !signal?.aborted) throw error;
3704
+ }
3705
+ }
3706
+ async function waitForReconnect2(ms, signal) {
3707
+ if (signal?.aborted) return false;
3708
+ if (ms <= 0) return true;
3709
+ return new Promise((resolve) => {
3710
+ const onAbort = () => {
3711
+ clearTimeout(timer);
3712
+ resolve(false);
3713
+ };
3714
+ const timer = setTimeout(() => {
3715
+ signal?.removeEventListener("abort", onAbort);
3716
+ resolve(!signal?.aborted);
3717
+ }, ms);
3718
+ signal?.addEventListener("abort", onAbort, { once: true });
3719
+ });
3720
+ }
3721
+ function isAbortError(error) {
3722
+ return Boolean(error && typeof error === "object" && "name" in error && error.name === "AbortError");
3723
+ }
3724
+
3725
+ // src/state/wait-for-run.ts
3726
+ async function waitForRun(client, options) {
3727
+ options.signal?.throwIfAborted();
3728
+ for await (const update of syncEvents(client, { sessionId: options.sessionId, signal: options.signal })) {
3729
+ options.signal?.throwIfAborted();
3730
+ const bucket = update.state.buckets[options.sessionId];
3731
+ const run = bucket?.runs[options.runId];
3732
+ if (!run || run.status === "pending" || run.status === "running") continue;
3733
+ return {
3734
+ run,
3735
+ messages: getVisibleSessionMessages(bucket).filter((item) => item.message.runId === options.runId)
3736
+ };
3737
+ }
3738
+ options.signal?.throwIfAborted();
3739
+ throw new Error(`Run ${options.runId} observation ended before a terminal state was available`);
3740
+ }
3741
+
3742
+ // src/resources/files/files-resource.ts
3743
+ var FilesResource = class {
3744
+ #transport;
3745
+ #sessionId;
3746
+ constructor(transport, sessionId) {
3747
+ this.#transport = transport;
3748
+ this.#sessionId = sessionId;
3749
+ }
3750
+ async list(options = {}) {
3751
+ const { signal, ...query } = options;
3752
+ const response = await this.#transport.request(
3753
+ this.#transport.path(`/sessions/${encodeURIComponent(this.#sessionId)}/files`, query),
3754
+ { signal }
3755
+ );
3756
+ return decodeSessionDirectoryResult(response);
3757
+ }
3758
+ async stat(path2, options = {}) {
3759
+ const response = await this.#transport.request(
3760
+ this.#transport.path(`/sessions/${encodeURIComponent(this.#sessionId)}/files/stat`, { path: path2 }),
3761
+ { signal: options.signal }
3762
+ );
3763
+ return decodeSessionFileInfo(response);
3764
+ }
3765
+ async readText(path2, options = {}) {
3766
+ const { signal, ...query } = options;
3767
+ const response = await this.#transport.request(
3768
+ this.#transport.path(`/sessions/${encodeURIComponent(this.#sessionId)}/files/text`, { path: path2, ...query }),
3769
+ { signal }
3770
+ );
3771
+ return decodeSessionTextFileResult(response);
3772
+ }
3773
+ async find(options) {
3774
+ const { signal, ...query } = options;
3775
+ const response = await this.#transport.request(
3776
+ this.#transport.path(`/sessions/${encodeURIComponent(this.#sessionId)}/files/find`, query),
3777
+ { signal }
3778
+ );
3779
+ return decodeSessionFindFilesResult(response);
3780
+ }
3781
+ async search(options) {
3782
+ const { signal, caseSensitive, ...query } = options;
3783
+ const response = await this.#transport.request(
3784
+ this.#transport.path(`/sessions/${encodeURIComponent(this.#sessionId)}/files/search`, {
3785
+ ...query,
3786
+ ...caseSensitive === void 0 ? {} : { caseSensitive: String(caseSensitive) }
3787
+ }),
3788
+ { signal }
3789
+ );
3790
+ return decodeSessionSearchFilesResult(response);
3791
+ }
3792
+ };
3793
+
3794
+ // src/resources/runtime/job-resource.ts
3795
+ var JobResource = class {
3796
+ #transport;
3797
+ #sessionId;
3798
+ constructor(transport, sessionId) {
3799
+ this.#transport = transport;
3800
+ this.#sessionId = sessionId;
3801
+ }
3802
+ async list(options = {}) {
3803
+ const { signal, kinds, statuses, includeFinished, ...query } = options;
3804
+ const response = await this.#transport.request(
3805
+ this.#transport.path("/jobs", {
3806
+ ...query,
3807
+ sessionId: this.#sessionId,
3808
+ ...kinds ? { kinds: kinds.join(",") } : {},
3809
+ ...statuses ? { statuses: statuses.join(",") } : {},
3810
+ ...includeFinished !== void 0 ? { includeFinished: String(includeFinished) } : {}
3811
+ }),
3812
+ { signal }
3813
+ );
3814
+ return decodeJobListResult(response);
3815
+ }
3816
+ async createBackgroundShell(input, options = {}) {
3817
+ return await this.#transport.request(
3818
+ "/background-shells",
3235
3819
  {
3236
3820
  method: "POST",
3237
- body: parseForkSessionRequest({
3238
- ...input,
3239
- id: input.id ?? createPromptRequestId(),
3240
- requestId: input.requestId ?? createPromptRequestId()
3241
- }),
3821
+ body: { ...input, sessionId: this.#sessionId },
3242
3822
  signal: options.signal
3243
3823
  }
3244
3824
  );
3245
- return response.session;
3246
3825
  }
3247
- /** `DELETE /sessions/:id` */
3248
- async archive(sessionId, options = {}) {
3249
- const response = await this.transport.request(
3250
- `/sessions/${encodeURIComponent(sessionId)}`,
3826
+ async read(target, options = {}) {
3827
+ const { signal, ...query } = options;
3828
+ const response = await this.#transport.request(
3829
+ this.#transport.path(`/jobs/${encodeURIComponent(target.jobId)}`, { ...query, sessionId: this.#sessionId, kind: target.kind, ...target.kind === "agent" ? { runId: target.runId } : {} }),
3830
+ { signal }
3831
+ );
3832
+ return decodeJobReadResult(response);
3833
+ }
3834
+ async wait(target, input = {}, options = {}) {
3835
+ const response = await this.#transport.request(
3836
+ `/jobs/${encodeURIComponent(target.jobId)}/wait`,
3251
3837
  {
3252
- method: "DELETE",
3838
+ method: "POST",
3839
+ body: { ...input, sessionId: this.#sessionId, target },
3253
3840
  signal: options.signal
3254
3841
  }
3255
3842
  );
3256
- return response.session;
3843
+ return decodeJobWaitResult(response);
3844
+ }
3845
+ async send(target, input, options = {}) {
3846
+ const response = await this.#transport.request(`/jobs/${encodeURIComponent(target.jobId)}/input`, {
3847
+ method: "POST",
3848
+ body: { ...input, sessionId: this.#sessionId, target },
3849
+ signal: options.signal
3850
+ });
3851
+ if (responseField(response, "sent") !== true) throw new ProtocolDataError("Job input was not accepted", "sent");
3852
+ const receipt2 = response.receipt;
3853
+ return receipt2 === void 0 ? void 0 : decodeJobInputReceipt(receipt2);
3854
+ }
3855
+ async cancel(target, input = {}, options = {}) {
3856
+ const mode = parseCancelResponseMode(options.responseMode);
3857
+ const response = await this.#transport.request(
3858
+ `/jobs/${encodeURIComponent(target.jobId)}/cancel`,
3859
+ { method: "POST", body: { ...input, sessionId: this.#sessionId, target, ...options.responseMode ? { responseMode: mode } : {} }, signal: options.signal }
3860
+ );
3861
+ if (mode === "receipt") {
3862
+ const receipt2 = decodeJobCancelReceipt(response);
3863
+ if (receipt2.id !== target.jobId) throw new ProtocolDataError("Cancellation receipt does not match target");
3864
+ return receipt2;
3865
+ }
3866
+ return decodeJobSnapshot(responseField(response, "snapshot"));
3867
+ }
3868
+ };
3869
+
3870
+ // src/resources/session/session-terminal-resource.ts
3871
+ var SessionTerminalResource = class {
3872
+ #transport;
3873
+ #sessionId;
3874
+ constructor(transport, sessionId) {
3875
+ this.#transport = transport;
3876
+ this.#sessionId = sessionId;
3877
+ }
3878
+ async list(options = {}) {
3879
+ const response = await this.#transport.requestUnknown(path(this.#sessionId), options);
3880
+ return responseArray2(response, "terminals", decodeTerminalSessionInfo);
3881
+ }
3882
+ async read(terminalId, options = {}) {
3883
+ const { signal, ...query } = options;
3884
+ const response = await this.#transport.requestUnknown(path(this.#sessionId, terminalId) + "/output", { signal, query });
3885
+ return decodeTerminalReadResult(responseField(response, "snapshot"));
3886
+ }
3887
+ async stream(terminalId, options = {}) {
3888
+ const response = await this.#transport.requestResponse(path(this.#sessionId, terminalId) + "/stream", options);
3889
+ const body = response.body;
3890
+ if (!body) throw new Error("Terminal event stream did not return a body");
3891
+ return streamServerSentEvents(async () => body, decodeTerminalEvent);
3892
+ }
3893
+ };
3894
+ function path(sessionId, terminalId) {
3895
+ return `/sessions/${encodeURIComponent(sessionId)}/terminals${terminalId === void 0 ? "" : `/${encodeURIComponent(terminalId)}`}`;
3896
+ }
3897
+
3898
+ // src/resources/session/session-run-requests.ts
3899
+ async function checkModelConnectionBinding(transport, input, signal) {
3900
+ const binding = parseExpectedModelConnection2(input);
3901
+ await requireDaemonFeature(transport, "runModelConnectionBinding", signal);
3902
+ return binding;
3903
+ }
3904
+ function checkOutputSchema(transport, input, signal) {
3905
+ assertPromptMetadataAllowed2(input);
3906
+ if (input.outputSchema === void 0) return;
3907
+ return transport.ensureProtocol(signal).then((capabilities) => {
3908
+ if ((capabilities.features.structuredDelivery ?? 0) < 1) {
3909
+ throw new Error(
3910
+ "Server does not support structured delivery (outputSchema)"
3911
+ );
3912
+ }
3913
+ });
3914
+ }
3915
+ async function admitPrompt(transport, sessionId, input, options = {}) {
3916
+ const expectedModelConnection = input.expectedModelConnection === void 0 ? void 0 : await checkModelConnectionBinding(transport, input.expectedModelConnection, options.signal);
3917
+ const schemaCheck = checkOutputSchema(transport, input, options.signal);
3918
+ if (schemaCheck) await schemaCheck;
3919
+ if (input.expectedActiveRunId !== void 0) {
3920
+ const capabilities = await transport.ensureProtocol(options.signal);
3921
+ if ((capabilities.features.steer ?? 0) < 2) {
3922
+ throw new IncompatibleProtocolError(capabilities, "\u540E\u53F0\u7248\u672C\u4E0D\u652F\u6301\u8FD0\u884C\u4E2D\u8865\u5145\uFF0C\u8BF7\u66F4\u65B0\u540E\u91CD\u8BD5\u3002");
3923
+ }
3924
+ }
3925
+ return await transport.request(
3926
+ `/sessions/${encodeURIComponent(sessionId)}/prompts`,
3927
+ {
3928
+ method: "POST",
3929
+ body: { ...input, expectedModelConnection, id: input.id ?? createSessionRequestId() },
3930
+ signal: options.signal
3931
+ }
3932
+ );
3933
+ }
3934
+ async function editLatestPrompt(transport, sessionId, input, options = {}) {
3935
+ const expectedModelConnection = input.expectedModelConnection === void 0 ? void 0 : await checkModelConnectionBinding(transport, input.expectedModelConnection, options.signal);
3936
+ await checkOutputSchema(transport, input, options.signal);
3937
+ return await transport.request(
3938
+ `/sessions/${encodeURIComponent(sessionId)}/prompts/latest/edit`,
3939
+ {
3940
+ method: "POST",
3941
+ body: { ...input, expectedModelConnection },
3942
+ signal: options.signal
3943
+ }
3944
+ );
3945
+ }
3946
+ async function promoteQueuedPrompt(transport, sessionId, inputId, input, options = {}) {
3947
+ return await transport.request(
3948
+ `/sessions/${encodeURIComponent(sessionId)}/prompts/${encodeURIComponent(inputId)}/promote`,
3949
+ { method: "POST", body: input, signal: options.signal }
3950
+ );
3951
+ }
3952
+ async function cancelQueuedPrompt(transport, sessionId, inputId, input, options = {}) {
3953
+ const mode = parseCancelResponseMode(options.responseMode);
3954
+ const response = await transport.request(
3955
+ `/sessions/${encodeURIComponent(sessionId)}/prompts/${encodeURIComponent(inputId)}/cancel`,
3956
+ {
3957
+ method: "POST",
3958
+ body: {
3959
+ ...input,
3960
+ ...options.responseMode ? { responseMode: mode } : {}
3961
+ },
3962
+ signal: options.signal
3963
+ }
3964
+ );
3965
+ if (mode === "receipt") {
3966
+ const receipt2 = decodeQueuedPromptCancelReceipt(response);
3967
+ if (receipt2.inputId !== inputId || receipt2.queuedRunId !== input.queuedRunId)
3968
+ throw new ProtocolDataError(
3969
+ "Cancellation receipt does not match target"
3970
+ );
3971
+ return receipt2;
3257
3972
  }
3258
- /** `DELETE /sessions/:id/hard` */
3259
- async delete(sessionId, options = {}) {
3260
- const response = await this.transport.request(`/sessions/${encodeURIComponent(sessionId)}/hard`, {
3261
- method: "DELETE",
3973
+ return response;
3974
+ }
3975
+ async function resumeInterruptedRun(transport, sessionId, runId, input = {}, options = {}) {
3976
+ await checkOutputSchema(transport, input, options.signal);
3977
+ return await transport.request(
3978
+ `/sessions/${encodeURIComponent(sessionId)}/runs/${encodeURIComponent(runId)}/resume`,
3979
+ {
3980
+ method: "POST",
3981
+ body: { ...input, id: input.id ?? createSessionRequestId() },
3262
3982
  signal: options.signal
3263
- });
3264
- return response.deletedSessionIds;
3983
+ }
3984
+ );
3985
+ }
3986
+ async function interrupt(transport, sessionId, options = {}) {
3987
+ return await transport.request(
3988
+ `/sessions/${encodeURIComponent(sessionId)}/interrupt`,
3989
+ {
3990
+ method: "POST",
3991
+ body: options.expectedRunId === void 0 ? void 0 : { expectedRunId: options.expectedRunId },
3992
+ signal: options.signal
3993
+ }
3994
+ );
3995
+ }
3996
+
3997
+ // src/resources/session/session-handle.ts
3998
+ function createSessionHandle(transport, syncClient, management, sessionId) {
3999
+ function cancelQueuedPrompt2(inputId, input, options) {
4000
+ return cancelQueuedPrompt(transport, sessionId, inputId, input, options);
4001
+ }
4002
+ const path2 = `/sessions/${encodeURIComponent(sessionId)}`;
4003
+ async function saveGoal(target, method, input) {
4004
+ const expectedModelConnection = input.expectedModelConnection === void 0 ? void 0 : await checkModelConnectionBinding(transport, input.expectedModelConnection);
4005
+ const response = await transport.request(target, { method, body: { ...input, expectedModelConnection } });
4006
+ return response.goal;
3265
4007
  }
3266
- /** `GET /sessions/:id/state` - atomic attach snapshot plus SSE cursor. */
3267
- async getState(sessionId, options = {}) {
3268
- const response = await this.transport.request(
3269
- this.transport.path(`/sessions/${encodeURIComponent(sessionId)}/state`, {
3270
- partView: options.partView
3271
- }),
3272
- {
3273
- signal: options.signal
4008
+ return {
4009
+ id: sessionId,
4010
+ waitForRun: (runId, options) => waitForRun(syncClient, { sessionId, runId, signal: options?.signal }),
4011
+ async updateAppMetadata(metadata, options) {
4012
+ const body = parseUpdateSessionRequest({ metadata: { app: metadata } });
4013
+ const response = await transport.request(path2, {
4014
+ method: "PATCH",
4015
+ body,
4016
+ signal: options?.signal
4017
+ });
4018
+ return response.session;
4019
+ },
4020
+ /** `GET /sessions/:id` */
4021
+ async get(options = {}) {
4022
+ const response = await transport.request(
4023
+ path2,
4024
+ {
4025
+ signal: options.signal
4026
+ }
4027
+ );
4028
+ if (response?.session?.id !== sessionId) {
4029
+ throw new ProtocolDataError("Response does not contain the bound session", "session");
3274
4030
  }
3275
- );
3276
- return decodeAgentSessionStateSnapshot(response);
4031
+ return response.session;
4032
+ },
4033
+ /** `GET /sessions/:id/state` - atomic attach snapshot plus SSE cursor. */
4034
+ async getState(options = {}) {
4035
+ const response = await transport.request(
4036
+ transport.path(`${path2}/state`, {
4037
+ partView: options.partView
4038
+ }),
4039
+ {
4040
+ signal: options.signal
4041
+ }
4042
+ );
4043
+ return decodeAgentSessionStateSnapshot(response);
4044
+ },
4045
+ /** `POST /sessions/:id/prompts` — 提交用户输入并触发/排队一次 run。 */
4046
+ prompt(input, options = {}) {
4047
+ return admitPrompt(transport, sessionId, input, options);
4048
+ },
4049
+ /** `POST /sessions/:id/interrupt` — 中断当前/排队中的 run。 */
4050
+ interrupt(options = {}) {
4051
+ return interrupt(transport, sessionId, options);
4052
+ },
4053
+ async getControls(options = {}) {
4054
+ const result = await transport.request(
4055
+ `${path2}/controls`,
4056
+ { signal: options.signal }
4057
+ );
4058
+ if (!validSessionControlResult("sessions.getControls", result) || result.sessionId !== sessionId) {
4059
+ throw new ProtocolDataError("Session controls do not match target");
4060
+ }
4061
+ return result;
4062
+ },
4063
+ async getControlResult(input, options = {}) {
4064
+ const { requestId, original } = input;
4065
+ if (!validSessionControlOriginal(original) || original.body.requestId !== requestId) throw new ProtocolDataError("Invalid original control request");
4066
+ const result = await transport.request(
4067
+ `${path2}/control-result`,
4068
+ {
4069
+ method: "POST",
4070
+ body: { requestId, original },
4071
+ signal: options.signal
4072
+ }
4073
+ );
4074
+ if (!validSessionControlResult("sessions.getControlResult", result) || result && (result.sessionId !== sessionId || result.requestId !== requestId || result.action !== original.action || original.action === "fork" && result.targetSessionId !== original.body.id))
4075
+ throw new ProtocolDataError(
4076
+ "Control receipt does not match original request"
4077
+ );
4078
+ return result;
4079
+ },
4080
+ /** Current context assembly requires execution authority; /usage is historical billing. */
4081
+ async getContextUsage(options = {}) {
4082
+ return transport.request(
4083
+ `${path2}/context-usage`,
4084
+ { signal: options.signal }
4085
+ );
4086
+ },
4087
+ /** `GET /sessions/:id/usage` */
4088
+ async getUsage(options = {}) {
4089
+ return transport.request(
4090
+ `${path2}/usage`,
4091
+ { signal: options.signal }
4092
+ );
4093
+ },
4094
+ /** `POST /sessions/:id/prompts/latest/edit` */
4095
+ editLatestPrompt(input, options = {}) {
4096
+ return editLatestPrompt(transport, sessionId, input, options);
4097
+ },
4098
+ /**
4099
+ * `POST /sessions/:id/runs/:runId/resume` — 显式重放一次中断 run 的原始 prompt。
4100
+ * 服务端复用原 Input,创建一个带恢复来源的新 Run。旧模型连接已经结束。
4101
+ */
4102
+ resumeInterruptedRun(runId, input = {}, options = {}) {
4103
+ return resumeInterruptedRun(transport, sessionId, runId, input, options);
4104
+ },
4105
+ /** `POST /sessions/:id/fork` */
4106
+ async fork(input = {}, options = {}) {
4107
+ const response = await transport.request(
4108
+ `${path2}/fork`,
4109
+ {
4110
+ method: "POST",
4111
+ body: parseForkSessionRequest({
4112
+ ...input,
4113
+ id: input.id ?? createSessionRequestId(),
4114
+ requestId: input.requestId ?? createSessionRequestId()
4115
+ }),
4116
+ signal: options.signal
4117
+ }
4118
+ );
4119
+ return response.session;
4120
+ },
4121
+ /** `POST /sessions/:id/compact` */
4122
+ async compact(input, options) {
4123
+ const body = { ...input };
4124
+ if (!validSessionControlOriginal({ action: "compact", body }))
4125
+ throw new ProtocolDataError("Invalid original compact request");
4126
+ const result = await transport.request(
4127
+ `${path2}/compact`,
4128
+ { method: "POST", body, signal: options?.signal }
4129
+ );
4130
+ if (!validSessionControlResult("sessions.getControlResult", result) || !result || result.action !== "compact" || result.sessionId !== sessionId || result.requestId !== body.requestId || result.revision !== body.expectedRevision) throw new ProtocolDataError("Compact receipt does not match original request");
4131
+ return result;
4132
+ },
4133
+ /** `POST /sessions/:id/rewind` */
4134
+ async rewind(input = {}, options = {}) {
4135
+ return transport.request(
4136
+ `${path2}/rewind`,
4137
+ { method: "POST", body: input, signal: options.signal }
4138
+ );
4139
+ },
4140
+ /** `POST /sessions/:id/remember` */
4141
+ async remember(options = {}) {
4142
+ return transport.request(
4143
+ `${path2}/remember`,
4144
+ { method: "POST", signal: options.signal }
4145
+ );
4146
+ },
4147
+ /** `POST /sessions/:id/export` */
4148
+ async export(input = {}, options = {}) {
4149
+ return transport.request(
4150
+ `${path2}/export`,
4151
+ { method: "POST", body: input, signal: options.signal }
4152
+ );
4153
+ },
4154
+ configuration: {
4155
+ get(options = {}) {
4156
+ return getConfiguration(transport, sessionId, options);
4157
+ },
4158
+ update(input, options = {}) {
4159
+ return configure(transport, sessionId, input, options);
4160
+ },
4161
+ getResult(input, options = {}) {
4162
+ return getConfigurationResult(transport, sessionId, input, options);
4163
+ }
4164
+ },
4165
+ queue: {
4166
+ /** Promote one durable queued prompt into the exact active run. */
4167
+ promote(inputId, input, options = {}) {
4168
+ return promoteQueuedPrompt(transport, sessionId, inputId, input, options);
4169
+ },
4170
+ cancel: cancelQueuedPrompt2
4171
+ },
4172
+ goal: {
4173
+ /** `GET /sessions/:id/goal` */
4174
+ async get() {
4175
+ const response = await transport.request(
4176
+ `${path2}/goal`
4177
+ );
4178
+ return response.goal;
4179
+ },
4180
+ /** `POST /sessions/:id/goals` */
4181
+ async create(input) {
4182
+ return saveGoal(`${path2}/goals`, "POST", input);
4183
+ },
4184
+ /** `PATCH /sessions/:id/goals/:goalId` */
4185
+ async update(goalId, input) {
4186
+ return saveGoal(`${path2}/goals/${encodeURIComponent(goalId)}`, "PATCH", input);
4187
+ },
4188
+ /** `POST /sessions/:id/goals/:goalId/actions` */
4189
+ async applyAction(goalId, input) {
4190
+ return saveGoal(`${path2}/goals/${encodeURIComponent(goalId)}/actions`, "POST", input);
4191
+ },
4192
+ /** Reads the original durable action receipt after a response was lost. */
4193
+ async getRequest(requestId) {
4194
+ const receipt2 = decodeSessionGoalRequestReceipt(
4195
+ await transport.request(
4196
+ `${path2}/goal/requests/${encodeURIComponent(requestId)}`
4197
+ )
4198
+ );
4199
+ if (receipt2.sessionId !== sessionId || receipt2.requestId !== requestId)
4200
+ throw new ProtocolDataError(
4201
+ "Goal request receipt does not match request"
4202
+ );
4203
+ return receipt2;
4204
+ }
4205
+ },
4206
+ messages: {
4207
+ /** `GET /sessions/:id/messages` */
4208
+ async list(options = {}) {
4209
+ const { signal, ...query } = options;
4210
+ const response = await transport.request(
4211
+ transport.path(
4212
+ `${path2}/messages`,
4213
+ query
4214
+ ),
4215
+ { signal }
4216
+ );
4217
+ return response.messages;
4218
+ },
4219
+ /** `GET /sessions/:id/parts` */
4220
+ async listParts(options = {}) {
4221
+ const { signal, ...query } = options;
4222
+ const response = await transport.request(
4223
+ transport.path(
4224
+ `${path2}/parts`,
4225
+ query
4226
+ ),
4227
+ { signal }
4228
+ );
4229
+ return response.parts;
4230
+ },
4231
+ /** Read full canonical content for one part in its session/message scope. */
4232
+ async getPart(messageId, partId, options = {}) {
4233
+ const response = await transport.request(
4234
+ `${path2}/messages/${encodeURIComponent(messageId)}/parts/${encodeURIComponent(partId)}`,
4235
+ options
4236
+ );
4237
+ return response.part;
4238
+ }
4239
+ },
4240
+ management: {
4241
+ async archiveAndInterrupt(options) {
4242
+ const response = await transport.request(path2, { ...options, method: "DELETE" });
4243
+ return response.session;
4244
+ },
4245
+ getRevision: management.getRevision.bind(management, sessionId),
4246
+ rename: management.rename.bind(management, sessionId),
4247
+ setPinned: management.setPinned.bind(management, sessionId),
4248
+ archive: management.archive.bind(management, sessionId),
4249
+ delete: management.delete.bind(management, sessionId),
4250
+ getMutation: management.getMutation.bind(management, sessionId)
4251
+ },
4252
+ files: new FilesResource(transport, sessionId),
4253
+ terminals: new SessionTerminalResource(transport, sessionId),
4254
+ jobs: new JobResource(transport, sessionId),
4255
+ mcp: {
4256
+ async list(options) {
4257
+ const response = await transport.request(`${path2}/mcp`, options);
4258
+ return response.servers;
4259
+ }
4260
+ }
4261
+ };
4262
+ }
4263
+
4264
+ // src/resources/session/session-resource.ts
4265
+ var SessionResource = class {
4266
+ #management;
4267
+ #events;
4268
+ #transport;
4269
+ constructor(transport, events) {
4270
+ this.#transport = transport;
4271
+ this.#management = new SessionManagementResource(transport);
4272
+ this.#events = events ?? new EventResource(transport, new SseTransport(transport));
4273
+ }
4274
+ /** Bind a session ID locally. Operations use this resource's daemon connection when called. */
4275
+ byId(sessionId) {
4276
+ return createSessionHandle(this.#transport, { sessions: this, events: this.#events }, this.#management, sessionId);
3277
4277
  }
3278
- /** `GET /sessions/:id/messages` */
3279
- async listMessages(sessionId, options = {}) {
4278
+ /** `GET /sessions/search` - search saved conversation text without opening it. */
4279
+ async search(options) {
3280
4280
  const { signal, ...query } = options;
3281
- const response = await this.transport.request(
3282
- this.transport.path(
3283
- `/sessions/${encodeURIComponent(sessionId)}/messages`,
3284
- query
3285
- ),
3286
- { signal }
3287
- );
3288
- return response.messages;
4281
+ const response = await this.#transport.request(this.#transport.path("/sessions/search", query), { signal });
4282
+ return response.results;
3289
4283
  }
3290
- /** `GET /sessions/:id/parts` */
3291
- async listMessageParts(sessionId, options = {}) {
4284
+ /** `GET /sessions` */
4285
+ async list(options = {}) {
3292
4286
  const { signal, ...query } = options;
3293
- const response = await this.transport.request(
3294
- this.transport.path(
3295
- `/sessions/${encodeURIComponent(sessionId)}/parts`,
3296
- query
3297
- ),
4287
+ const response = await this.#transport.request(this.#transport.path("/sessions", query), { signal });
4288
+ return response.sessions;
4289
+ }
4290
+ listDirectory(options = {}) {
4291
+ const { signal, ...query } = options;
4292
+ return this.#transport.request(
4293
+ this.#transport.path("/sessions/directory", query),
3298
4294
  { signal }
3299
4295
  );
3300
- return response.parts;
3301
4296
  }
3302
- /** Read full canonical content for one part in its session/message scope. */
3303
- async getMessagePart(sessionId, messageId, partId, options = {}) {
3304
- const response = await this.transport.request(
3305
- `/sessions/${encodeURIComponent(sessionId)}/messages/${encodeURIComponent(messageId)}/parts/${encodeURIComponent(partId)}`,
3306
- options
3307
- );
3308
- return response.part;
4297
+ getActivity(options = {}) {
4298
+ return this.#transport.request("/sessions/activity", {
4299
+ signal: options.signal
4300
+ });
3309
4301
  }
3310
- /** `POST /sessions/:id/prompts` — 提交用户输入并触发/排队一次 run。 */
3311
- admitPrompt(sessionId, input, options = {}) {
3312
- return admitPrompt(this.transport, sessionId, input, options);
4302
+ getDraftComposerOptions(input, options = {}) {
4303
+ return getDraftComposerOptions(this.#transport, input, options);
3313
4304
  }
3314
- /** `POST /sessions/:id/prompts/latest/edit` */
3315
- editLatestPrompt(sessionId, input, options = {}) {
3316
- return editLatestPrompt(this.transport, sessionId, input, options);
4305
+ /** `POST /sessions` */
4306
+ create(input, options = {}) {
4307
+ return create(this.#transport, input, options);
3317
4308
  }
3318
- /** Promote one durable queued prompt into the exact active run. */
3319
- promoteQueuedPrompt(sessionId, inputId, input, options = {}) {
3320
- return promoteQueuedPrompt(this.transport, sessionId, inputId, input, options);
4309
+ getConfigurationOptions(input, options = {}) {
4310
+ return getConfigurationOptions(this.#transport, input, options);
3321
4311
  }
3322
- cancelQueuedPrompt(sessionId, inputId, input, options = {}) {
3323
- return cancelQueuedPrompt(this.transport, sessionId, inputId, input, options);
4312
+ getCreationResult(input, options = {}) {
4313
+ return getCreationResult(this.#transport, input, options);
3324
4314
  }
3325
- /**
3326
- * `POST /sessions/:id/runs/:runId/resume` — 显式重放一次中断 run 的原始 prompt。
3327
- * 服务端复用原 Input,创建一个带恢复来源的新 Run。旧模型连接已经结束。
3328
- */
3329
- resumeInterruptedRun(sessionId, runId, input = {}, options = {}) {
3330
- return resumeInterruptedRun(this.transport, sessionId, runId, input, options);
4315
+ };
4316
+
4317
+ // src/resources/session/attachment-resource.ts
4318
+ var AttachmentResource = class {
4319
+ constructor(transport) {
4320
+ this.transport = transport;
3331
4321
  }
3332
- /** `POST /sessions/:id/interrupt` — 中断当前/排队中的 run。 */
3333
- interrupt(sessionId, options = {}) {
3334
- return interrupt(this.transport, sessionId, options);
4322
+ transport;
4323
+ /** Manage daemon attachment storage. Ordinary session connections cannot use these methods. */
4324
+ storage = {
4325
+ scan: (options) => this.transport.request("/attachments/storage", options),
4326
+ repair: (options) => this.transport.request("/attachments/storage/actions", { ...options, method: "POST", body: { action: "repair-safe" } }),
4327
+ gc: (options) => this.transport.request("/attachments/storage/actions", { ...options, method: "POST", body: { action: "gc" } })
4328
+ };
4329
+ /** `POST /attachments` — upload bytes without JSON or multipart buffering. */
4330
+ async upload(input) {
4331
+ const headers2 = uploadIdentityHeaders(input);
4332
+ headers2["x-bobannomi-filename"] = encodeURIComponent(input.displayName);
4333
+ if (input.mediaType) headers2["content-type"] = input.mediaType;
4334
+ const response = await this.transport.requestResponse("/attachments", {
4335
+ method: "POST",
4336
+ headers: headers2,
4337
+ body: input.body,
4338
+ signal: input.signal
4339
+ });
4340
+ return parseAttachmentAssetRecord(await response.json());
3335
4341
  }
3336
- /** `POST /sessions/:id/compact` */
3337
- async compact(sessionId, options = {}) {
3338
- return await this.transport.request(
3339
- `/sessions/${encodeURIComponent(sessionId)}/compact`,
3340
- {
3341
- method: "POST",
3342
- signal: options.signal,
3343
- ...options.requestId ? {
3344
- body: {
3345
- requestId: options.requestId,
3346
- expectedRevision: options.expectedRevision
3347
- }
3348
- } : {}
3349
- }
3350
- );
4342
+ async getUpload(input) {
4343
+ const response = await this.transport.requestResponse("/attachments/uploads", { headers: uploadIdentityHeaders(input), signal: input.signal });
4344
+ const value = await response.json();
4345
+ return value === null ? null : parseAttachmentAssetRecord(value);
3351
4346
  }
3352
- /** `POST /sessions/:id/rewind` */
3353
- async rewind(sessionId, input = {}, options = {}) {
3354
- return await this.transport.request(
3355
- `/sessions/${encodeURIComponent(sessionId)}/rewind`,
3356
- { method: "POST", body: input, signal: options.signal }
4347
+ async get(id2, options = {}) {
4348
+ const value = await this.transport.request(
4349
+ `/attachments/${encodeURIComponent(id2)}`,
4350
+ { signal: options.signal }
3357
4351
  );
4352
+ return parseAttachmentAssetRecord(value);
3358
4353
  }
3359
- /** `POST /sessions/:id/remember` */
3360
- async remember(sessionId, options = {}) {
3361
- return await this.transport.request(
3362
- `/sessions/${encodeURIComponent(sessionId)}/remember`,
3363
- { method: "POST", signal: options.signal }
4354
+ /** Returns the raw response so callers can consume the body as a stream. */
4355
+ async download(id2, options = {}) {
4356
+ const range = attachmentRangeHeader(options.range);
4357
+ const headers2 = {};
4358
+ if (range) headers2.range = range;
4359
+ return await this.transport.requestResponse(
4360
+ `/attachments/${encodeURIComponent(id2)}/content`,
4361
+ { method: "GET", headers: headers2, signal: options.signal }
3364
4362
  );
3365
4363
  }
3366
- /** `POST /sessions/:id/export` */
3367
- async export(sessionId, input = {}, options = {}) {
3368
- return await this.transport.request(
3369
- `/sessions/${encodeURIComponent(sessionId)}/export`,
3370
- { method: "POST", body: input, signal: options.signal }
4364
+ async delete(id2, options = {}) {
4365
+ const value = await this.transport.request(
4366
+ `/attachments/${encodeURIComponent(id2)}`,
4367
+ { method: "DELETE", signal: options.signal }
3371
4368
  );
4369
+ return parseAttachmentAssetRecord(value);
3372
4370
  }
3373
- /** `GET /sessions/:id/usage` */
3374
- async getUsage(sessionId, options = {}) {
3375
- return await this.transport.request(
3376
- `/sessions/${encodeURIComponent(sessionId)}/usage`,
3377
- { signal: options.signal }
3378
- );
4371
+ };
4372
+ function uploadIdentityHeaders(input) {
4373
+ parseAttachmentUploadRequest({ ...input, declaredMediaType: input.mediaType });
4374
+ return { "x-bobannomi-request-id": input.requestId, "x-bobannomi-draft-id": input.draftId, "x-bobannomi-sha256": input.expectedSha256, "x-bobannomi-byte-length": String(input.byteLength), "x-bobannomi-filename": encodeURIComponent(input.displayName), ...input.mediaType ? { "content-type": input.mediaType } : {} };
4375
+ }
4376
+
4377
+ // src/resources/configuration/permission-resource.ts
4378
+ var PermissionResource = class {
4379
+ #transport;
4380
+ constructor(transport) {
4381
+ this.#transport = transport;
4382
+ }
4383
+ requests = {
4384
+ /** `GET /permissions` */
4385
+ list: async (options = {}) => {
4386
+ const { signal, ...query } = options;
4387
+ const response = await this.#transport.request(this.#transport.path("/permissions", query), { signal });
4388
+ return response.requests;
4389
+ },
4390
+ /** `POST /permissions/:id/reply` — 批准/拒绝工具权限请求。 */
4391
+ reply: async (requestId, input, options = {}) => {
4392
+ const response = await this.#transport.request(
4393
+ `/permissions/${encodeURIComponent(requestId)}/reply`,
4394
+ {
4395
+ method: "POST",
4396
+ body: input,
4397
+ signal: options.signal
4398
+ }
4399
+ );
4400
+ return response.request;
4401
+ },
4402
+ /** Answer an actual AskUser question; this cannot approve tools. */
4403
+ answerQuestion: async (requestId, input, options = {}) => {
4404
+ const capabilities = await this.#transport.ensureProtocol(options.signal);
4405
+ if ((capabilities.features.questions ?? 0) < 1) throw new Error("Server does not support questions");
4406
+ const response = await this.#transport.request(
4407
+ `/permissions/${encodeURIComponent(requestId)}/answer`,
4408
+ { method: "POST", body: input, signal: options.signal }
4409
+ );
4410
+ return response.request;
4411
+ }
4412
+ };
4413
+ approvals = {
4414
+ list: async () => {
4415
+ const response = await this.#transport.request("/permissions/approvals");
4416
+ return response.requests;
4417
+ },
4418
+ revoke: async (requestId) => {
4419
+ const response = await this.#transport.request(
4420
+ `/permissions/${encodeURIComponent(requestId)}/revoke`,
4421
+ { method: "POST" }
4422
+ );
4423
+ return response.request;
4424
+ }
4425
+ };
4426
+ };
4427
+
4428
+ // src/resources/runtime/runtime-resource.ts
4429
+ function createRuntimeResources(transport, providers) {
4430
+ const catalog = typeof providers === "function" || providers === void 0 ? providers : structuredClone([...providers]);
4431
+ async function modelProviders(input, options = {}) {
4432
+ const response = await transport.request("/providers/manage", { ...options, method: "POST", body: input });
4433
+ if (!validModelProviderConnections(response?.providers)) throw new Error("Invalid model provider response");
4434
+ return response.providers;
3379
4435
  }
3380
- /** `GET /sessions/:id/goal` */
3381
- async getGoal(sessionId) {
3382
- const response = await this.transport.request(
3383
- `/sessions/${encodeURIComponent(sessionId)}/goal`
3384
- );
3385
- return response.goal;
4436
+ async function providerDefaults(input, options = {}) {
4437
+ const result = await transport.request("/providers/defaults", { ...options, method: "POST", body: input });
4438
+ const valid = input.action === "test" ? validProviderConnectionTestResult(result) : validProviderDefaultsSnapshot(result);
4439
+ if (!valid) throw new Error("Invalid provider defaults response");
4440
+ return result;
3386
4441
  }
3387
- /** Reads the original durable action receipt after a response was lost. */
3388
- async getGoalRequest(sessionId, requestId) {
3389
- const receipt2 = decodeSessionGoalRequestReceipt(
3390
- await this.transport.request(
3391
- `/sessions/${encodeURIComponent(sessionId)}/goal/requests/${encodeURIComponent(requestId)}`
3392
- )
3393
- );
3394
- if (receipt2.sessionId !== sessionId || receipt2.requestId !== requestId)
3395
- throw new ProtocolDataError(
3396
- "Goal request receipt does not match request"
3397
- );
3398
- return receipt2;
4442
+ return {
4443
+ models: {
4444
+ async list({ signal } = {}) {
4445
+ if (catalog === void 0) {
4446
+ const response = await transport.request("/models", { signal });
4447
+ return response.providers;
4448
+ }
4449
+ signal?.throwIfAborted();
4450
+ const providers2 = typeof catalog === "function" ? await waitForRequest(Promise.resolve().then(() => {
4451
+ signal?.throwIfAborted();
4452
+ return catalog({ signal });
4453
+ }), signal) : catalog;
4454
+ signal?.throwIfAborted();
4455
+ return structuredClone([...providers2]);
4456
+ }
4457
+ },
4458
+ agents: {
4459
+ async list(options) {
4460
+ const response = await transport.request("/agent-personas", options);
4461
+ return response.agents;
4462
+ }
4463
+ },
4464
+ skills: {
4465
+ list: (options) => transport.request("/skills", options),
4466
+ marketplace: {
4467
+ list: (options) => transport.request("/skills/marketplace", options),
4468
+ install: (body, options) => transport.request("/skills/marketplace/install", { ...options, method: "POST", body })
4469
+ },
4470
+ remove: (id2, body, options) => transport.request(`/skills/${encodeURIComponent(id2)}`, { ...options, method: "DELETE", body })
4471
+ },
4472
+ modelProviders: {
4473
+ /** Provider catalog including non-connected providers. See list() for management status. */
4474
+ async catalog(options) {
4475
+ const response = await transport.request("/providers", options);
4476
+ return response.providers;
4477
+ },
4478
+ auth: {
4479
+ async status(options) {
4480
+ const response = await transport.request("/auth", options);
4481
+ return response.auth;
4482
+ },
4483
+ login: (body, options) => transport.request("/auth/login", { ...options, method: "POST", body }),
4484
+ logout: (body, options) => transport.request("/auth/logout", { ...options, method: "POST", body })
4485
+ },
4486
+ list: (options) => modelProviders({ action: "list" }, options),
4487
+ refresh: (options) => modelProviders({ action: "refresh" }, options),
4488
+ connect: (input, options) => modelProviders({ ...input, action: "connect" }, options),
4489
+ updateHeaders: (input, options) => modelProviders({ ...input, action: "updateHeaders" }, options),
4490
+ createCustom: (input, options) => modelProviders({ ...input, action: "createCustom" }, options),
4491
+ syncAccount: (input, options) => modelProviders({ ...input, action: "syncAccount" }, options),
4492
+ updateCustom: (input, options) => modelProviders({ ...input, action: "updateCustom" }, options),
4493
+ disconnect: (input, options) => modelProviders({ ...input, action: "disconnect" }, options),
4494
+ removeCustom: (input, options) => modelProviders({ ...input, action: "removeCustom" }, options),
4495
+ defaults: {
4496
+ get: ({ accountGatewayProof, signal } = {}) => providerDefaults({ action: "snapshot", accountGatewayProof }, { signal }),
4497
+ updateModel: (input, options) => providerDefaults({ ...input, action: "updateModel" }, options),
4498
+ updateEffort: (input, options) => providerDefaults({ ...input, action: "updateEffort" }, options),
4499
+ test: (input, options) => providerDefaults({ ...input, action: "test" }, options)
4500
+ }
4501
+ }
4502
+ };
4503
+ }
4504
+
4505
+ // src/resources/plugins/plugin-marketplace-resource.ts
4506
+ var market = "/plugins/marketplace";
4507
+ var PluginMarketplaceResource = class {
4508
+ constructor(transport) {
4509
+ this.transport = transport;
4510
+ }
4511
+ transport;
4512
+ catalog({ signal, ...query }) {
4513
+ return this.transport.request(`${market}/catalog`, { query, signal });
4514
+ }
4515
+ listSources(options) {
4516
+ return this.transport.request(`${market}/sources`, options);
4517
+ }
4518
+ addSource(input, options) {
4519
+ return this.transport.request(`${market}/sources`, { ...options, method: "POST", body: input });
4520
+ }
4521
+ setSourceEnabled(sourceId, input, options) {
4522
+ return this.transport.request(`${market}/sources/${encodeURIComponent(sourceId)}`, { ...options, method: "PATCH", body: input });
4523
+ }
4524
+ removeSource(sourceId, options) {
4525
+ return this.transport.request(`${market}/sources/${encodeURIComponent(sourceId)}`, { ...options, method: "DELETE" });
4526
+ }
4527
+ preview(input, options) {
4528
+ return this.transport.request(`${market}/preview`, { ...options, method: "POST", body: input });
3399
4529
  }
3400
- /** `POST /sessions/:id/goals` */
3401
- async createGoal(sessionId, input) {
3402
- const response = await this.transport.request(
3403
- `/sessions/${encodeURIComponent(sessionId)}/goals`,
3404
- { method: "POST", body: input }
3405
- );
3406
- return response.goal;
4530
+ cancel(input, options) {
4531
+ return this.transport.request(`${market}/cancel`, { ...options, method: "POST", body: input });
3407
4532
  }
3408
- /** `PATCH /sessions/:id/goals/:goalId` */
3409
- async updateGoal(sessionId, goalId, input) {
3410
- const response = await this.transport.request(
3411
- `/sessions/${encodeURIComponent(sessionId)}/goals/${encodeURIComponent(goalId)}`,
3412
- { method: "PATCH", body: input }
3413
- );
3414
- return response.goal;
4533
+ /** Save the operation ID before submitting. Recover an uncertain result with getOperation. */
4534
+ async install(input, options) {
4535
+ const { operationId } = input;
4536
+ const receipt2 = await this.transport.request(`${market}/install`, { ...options, method: "POST", body: input });
4537
+ return matchingOperation(receipt2, operationId);
3415
4538
  }
3416
- /** `POST /sessions/:id/goals/:goalId/actions` */
3417
- async applyGoalAction(sessionId, goalId, input) {
3418
- const response = await this.transport.request(
3419
- `/sessions/${encodeURIComponent(sessionId)}/goals/${encodeURIComponent(goalId)}/actions`,
3420
- { method: "POST", body: input }
3421
- );
3422
- return response.goal;
4539
+ /** Look up the original operation without repeating its install. */
4540
+ async getOperation(operationId, options) {
4541
+ const receipt2 = await this.transport.request(`${market}/operations/${encodeURIComponent(operationId)}`, options);
4542
+ return matchingOperation(receipt2, operationId);
3423
4543
  }
3424
4544
  };
4545
+ function matchingOperation(receipt2, operationId) {
4546
+ if (receipt2?.operationId !== operationId) {
4547
+ throw new ProtocolDataError("Marketplace receipt does not match original operation", "operationId");
4548
+ }
4549
+ return receipt2;
4550
+ }
3425
4551
 
3426
- // src/resources/session/attachment-resource.ts
3427
- var AttachmentResource = class {
4552
+ // src/resources/plugins/plugin-resource.ts
4553
+ var PluginResource = class {
3428
4554
  constructor(transport) {
3429
4555
  this.transport = transport;
4556
+ this.marketplace = new PluginMarketplaceResource(transport);
3430
4557
  }
3431
4558
  transport;
3432
- /** `POST /attachments` — upload bytes without JSON or multipart buffering. */
3433
- async upload(input) {
3434
- const headers2 = uploadIdentityHeaders(input);
3435
- headers2["x-bobannomi-filename"] = encodeURIComponent(input.displayName);
3436
- if (input.mediaType) headers2["content-type"] = input.mediaType;
3437
- const response = await this.transport.requestResponse("/attachments", {
3438
- method: "POST",
3439
- headers: headers2,
3440
- body: input.body,
3441
- signal: input.signal
3442
- });
3443
- return parseAttachmentAssetRecord(await response.json());
4559
+ marketplace;
4560
+ /** List native plugins for a directory in the daemon environment. */
4561
+ list({ signal, cwd }) {
4562
+ return this.transport.request("/plugins", { query: { cwd }, signal });
4563
+ }
4564
+ enable(id2, input, options) {
4565
+ return this.transport.request(`/plugins/${encodeURIComponent(id2)}/enable`, { ...options, method: "POST", body: input });
4566
+ }
4567
+ disable(id2, input, options) {
4568
+ return this.transport.request(`/plugins/${encodeURIComponent(id2)}/disable`, { ...options, method: "POST", body: input });
4569
+ }
4570
+ /** Read the identity, digest and requested permissions for a directory on the daemon machine. */
4571
+ async previewLocal(input, options) {
4572
+ await requireDaemonFeature(this.transport, "pluginLocalPreview", options?.signal);
4573
+ const preview = await this.transport.request("/plugins/local/preview", { ...options, method: "POST", body: input });
4574
+ if (typeof preview?.sourceDigest !== "string" || !/^[a-f0-9]{64}$/.test(preview.sourceDigest)) {
4575
+ throw new ProtocolDataError("Plugin directory preview must include a SHA-256 digest", "sourceDigest");
4576
+ }
4577
+ return preview;
3444
4578
  }
3445
- async getUpload(input) {
3446
- const response = await this.transport.requestResponse("/attachments/uploads", { headers: uploadIdentityHeaders(input), signal: input.signal });
3447
- const value = await response.json();
3448
- return value === null ? null : parseAttachmentAssetRecord(value);
4579
+ /** Install or link a plugin directory the daemon can read after approval. */
4580
+ async installLocal(input, options) {
4581
+ if (input.expectedSourceDigest !== void 0 || input.allowSourceChange === true) {
4582
+ await requireDaemonFeature(this.transport, "pluginLocalPreview", options?.signal);
4583
+ }
4584
+ return this.transport.request(input.link ? "/plugins/link-local" : "/plugins/install-local", { ...options, method: "POST", body: input });
3449
4585
  }
3450
- async get(id2, options = {}) {
3451
- const value = await this.transport.request(
3452
- `/attachments/${encodeURIComponent(id2)}`,
3453
- { signal: options.signal }
3454
- );
3455
- return parseAttachmentAssetRecord(value);
4586
+ /** Read the digest and required permissions for an archive on the daemon machine. */
4587
+ previewArchive(input, options) {
4588
+ return this.transport.request("/plugins/archive/preview", { ...options, method: "POST", body: input });
3456
4589
  }
3457
- /** Returns the raw response so callers can consume the body as a stream. */
3458
- async download(id2, options = {}) {
3459
- const range = attachmentRangeHeader(options.range);
3460
- const headers2 = {};
3461
- if (range) headers2.range = range;
3462
- return await this.transport.requestResponse(
3463
- `/attachments/${encodeURIComponent(id2)}/content`,
3464
- { method: "GET", headers: headers2, signal: options.signal }
3465
- );
4590
+ /** Install the previewed archive with its original digest and approved permissions. */
4591
+ installArchive(input, options) {
4592
+ return this.transport.request("/plugins/archive/install", { ...options, method: "POST", body: input });
3466
4593
  }
3467
- async delete(id2, options = {}) {
3468
- const value = await this.transport.request(
3469
- `/attachments/${encodeURIComponent(id2)}`,
3470
- { method: "DELETE", signal: options.signal }
3471
- );
3472
- return parseAttachmentAssetRecord(value);
4594
+ /** Read the digest and required permissions for a Git source. */
4595
+ previewGit(input, options) {
4596
+ return this.transport.request("/plugins/git/preview", { ...options, method: "POST", body: input });
4597
+ }
4598
+ /** Install the previewed Git source with its original digest and approved permissions. */
4599
+ installGit(input, options) {
4600
+ return this.transport.request("/plugins/git/install", { ...options, method: "POST", body: input });
4601
+ }
4602
+ uninstall(id2, input, options) {
4603
+ return this.transport.request(`/plugins/${encodeURIComponent(id2)}`, { ...options, method: "DELETE", body: input });
4604
+ }
4605
+ reload(input, options) {
4606
+ return this.transport.request("/plugins/reload", { ...options, method: "POST", body: input });
3473
4607
  }
3474
4608
  };
3475
- function uploadIdentityHeaders(input) {
3476
- parseAttachmentUploadRequest({ ...input, declaredMediaType: input.mediaType });
3477
- return { "x-bobannomi-request-id": input.requestId, "x-bobannomi-draft-id": input.draftId, "x-bobannomi-sha256": input.expectedSha256, "x-bobannomi-byte-length": String(input.byteLength), "x-bobannomi-filename": encodeURIComponent(input.displayName), ...input.mediaType ? { "content-type": input.mediaType } : {} };
3478
- }
3479
4609
 
3480
- // src/resources/configuration/permission-resource.ts
3481
- var PermissionResource = class {
4610
+ // src/resources/channels/channel-resource.ts
4611
+ var ChannelResource = class {
3482
4612
  constructor(transport) {
3483
4613
  this.transport = transport;
3484
4614
  }
3485
4615
  transport;
3486
- /** Answer an actual AskUser question; this cannot approve tools. */
3487
- async answerQuestion(requestId, input, options = {}) {
3488
- const capabilities = await this.transport.ensureProtocol(options.signal);
3489
- if ((capabilities.features.questions ?? 0) < 1) throw new Error("Server does not support questions");
3490
- const response = await this.transport.request(
3491
- `/permissions/${encodeURIComponent(requestId)}/answer`,
3492
- { method: "POST", body: input, signal: options.signal }
3493
- );
3494
- return response.request;
3495
- }
3496
- async listApprovals() {
3497
- const response = await this.transport.request("/permissions/approvals");
3498
- return response.requests;
3499
- }
3500
- async revokeApproval(requestId) {
3501
- const response = await this.transport.request(
3502
- `/permissions/${encodeURIComponent(requestId)}/revoke`,
3503
- { method: "POST" }
3504
- );
3505
- return response.request;
4616
+ /** Read the running connectors or temporarily start and stop them. */
4617
+ runtime = {
4618
+ status: (options) => this.transport.request("/channels/runtime/status", options),
4619
+ start: (input = {}, options) => this.transport.request("/channels/runtime/start", { ...options, method: "POST", body: input }),
4620
+ stop: (input = {}, options) => this.transport.request("/channels/runtime/stop", { ...options, method: "POST", body: input })
4621
+ };
4622
+ /** Configure Feishu or Lark. Status snapshots omit credentials. */
4623
+ feishu = {
4624
+ status: (options) => this.transport.request("/channels/feishu", options),
4625
+ connect: (input, options) => this.transport.request("/channels/feishu/connect", { ...options, method: "POST", body: input }),
4626
+ update: (input, options) => this.transport.request("/channels/feishu", { ...options, method: "PATCH", body: input }),
4627
+ disconnect: (options) => this.transport.request("/channels/feishu", { ...options, method: "DELETE" }),
4628
+ allowlist: {
4629
+ add: (input, options) => this.transport.request("/channels/feishu/allow", { ...options, method: "POST", body: input }),
4630
+ remove: (key, options) => this.transport.request(`/channels/feishu/allow/${encodeURIComponent(key)}`, { ...options, method: "DELETE" })
4631
+ },
4632
+ registration: {
4633
+ start: (input = {}, options) => this.transport.request("/channels/feishu/registration", { ...options, method: "POST", body: input }),
4634
+ status: (options) => this.transport.request("/channels/feishu/registration", options),
4635
+ cancel: (options) => this.transport.request("/channels/feishu/registration", { ...options, method: "DELETE" })
4636
+ }
4637
+ };
4638
+ /** Submit external messages and work with durable delivery records. */
4639
+ connector = {
4640
+ /** Retain the external message ID when retrying the same input. */
4641
+ submitMessage: (input, options) => this.transport.request("/channels/messages", { ...options, method: "POST", body: input }),
4642
+ status: (query, options) => this.transport.request("/channels/status", { ...options, query: { ...query } }),
4643
+ listPendingDeliveries: async (query, options) => {
4644
+ const response = await this.transport.request(
4645
+ "/channels/deliveries/pending",
4646
+ { ...options, query: { ...query } }
4647
+ );
4648
+ return response.deliveries;
4649
+ },
4650
+ /** Look up the stored result after an interrupted request. Returns null for an unknown ID. */
4651
+ getDelivery: async (deliveryId, options) => {
4652
+ await requireDaemonFeature(this.transport, "channelDeliveryLookup", options?.signal);
4653
+ const response = await this.transport.request(
4654
+ `/channels/deliveries/${encodeURIComponent(deliveryId)}/result`,
4655
+ options
4656
+ );
4657
+ return response.delivery;
4658
+ },
4659
+ recordDelivery: async (deliveryId, input, options) => {
4660
+ const response = await this.transport.request(
4661
+ `/channels/deliveries/${encodeURIComponent(deliveryId)}/result`,
4662
+ { ...options, method: "POST", body: input }
4663
+ );
4664
+ return response.delivery;
4665
+ }
4666
+ };
4667
+ };
4668
+
4669
+ // src/resources/workspace/project-resource.ts
4670
+ var ProjectResource = class {
4671
+ constructor(transport) {
4672
+ this.transport = transport;
3506
4673
  }
3507
- /** `GET /permissions` */
4674
+ transport;
4675
+ /** `GET /projects` */
3508
4676
  async list(options = {}) {
3509
4677
  const { signal, ...query } = options;
3510
- const response = await this.transport.request(this.transport.path("/permissions", query), { signal });
3511
- return response.requests;
3512
- }
3513
- /** `POST /permissions/:id/reply` — 批准/拒绝工具权限请求。 */
3514
- async reply(requestId, input, options = {}) {
3515
4678
  const response = await this.transport.request(
3516
- `/permissions/${encodeURIComponent(requestId)}/reply`,
3517
- {
3518
- method: "POST",
3519
- body: input,
3520
- signal: options.signal
3521
- }
4679
+ this.transport.path("/projects", query),
4680
+ { signal }
3522
4681
  );
3523
- return response.request;
4682
+ return response.projects;
4683
+ }
4684
+ /** Register or reopen a directory on the daemon host and update its last-opened time. */
4685
+ async register(path2, options) {
4686
+ return (await this.transport.request("/projects/inspect", {
4687
+ ...options,
4688
+ method: "POST",
4689
+ body: { path: path2 }
4690
+ })).project;
4691
+ }
4692
+ /** Alias for register. This can create or restore a project record. */
4693
+ inspect(path2, options) {
4694
+ return this.register(path2, options);
4695
+ }
4696
+ /** `PATCH /projects/:id` (name) */
4697
+ async rename(projectId, name, options) {
4698
+ return (await this.transport.request(
4699
+ `/projects/${encodeURIComponent(projectId)}`,
4700
+ { ...options, method: "PATCH", body: { name } }
4701
+ )).project;
4702
+ }
4703
+ /** `PATCH /projects/:id` (pinned) */
4704
+ async setPinned(projectId, pinned, options) {
4705
+ return (await this.transport.request(
4706
+ `/projects/${encodeURIComponent(projectId)}`,
4707
+ { ...options, method: "PATCH", body: { pinned } }
4708
+ )).project;
4709
+ }
4710
+ /** `PATCH /projects/:id` (defaultShell) */
4711
+ async setDefaultShell(projectId, defaultShell, options) {
4712
+ return (await this.transport.request(
4713
+ `/projects/${encodeURIComponent(projectId)}`,
4714
+ { ...options, method: "PATCH", body: { defaultShell } }
4715
+ )).project;
4716
+ }
4717
+ /** `POST /projects/:id/rebind` */
4718
+ async rebind(projectId, path2, options) {
4719
+ const { expectedPath, signal } = typeof options === "string" ? { expectedPath: options } : options ?? {};
4720
+ return (await this.transport.request(
4721
+ `/projects/${encodeURIComponent(projectId)}/rebind`,
4722
+ { signal, method: "POST", body: { path: path2, expectedPath } }
4723
+ )).project;
4724
+ }
4725
+ /** `DELETE /projects/:id` */
4726
+ async archive(projectId, options) {
4727
+ return (await this.transport.request(
4728
+ `/projects/${encodeURIComponent(projectId)}`,
4729
+ { ...options, method: "DELETE" }
4730
+ )).project;
4731
+ }
4732
+ /** `POST /project/init` */
4733
+ async init(input, options = {}) {
4734
+ const response = await this.transport.request("/project/init", {
4735
+ method: "POST",
4736
+ body: input,
4737
+ signal: options.signal
4738
+ });
4739
+ return response.report;
3524
4740
  }
3525
4741
  };
3526
4742
 
3527
- // src/resources/runtime/job-resource.ts
3528
- var JobResource = class {
4743
+ // src/resources/workspace/worktree-resource.ts
4744
+ var WorktreeResource = class {
3529
4745
  constructor(transport) {
3530
4746
  this.transport = transport;
3531
4747
  }
3532
4748
  transport;
3533
4749
  async list(options) {
3534
- const { signal, kinds, statuses, includeFinished, ...query } = options;
4750
+ await requireDaemonFeature(this.transport, "taskWorktrees", options?.signal);
4751
+ const result = await this.transport.request("/worktrees", options);
4752
+ if (!Array.isArray(result)) throw new ProtocolDataError("Task worktrees must be an array");
4753
+ return result;
4754
+ }
4755
+ async cleanup(id2, options) {
4756
+ await requireDaemonFeature(this.transport, "taskWorktrees", options?.signal);
4757
+ await this.transport.request(`/worktrees/${encodeURIComponent(id2)}/cleanup`, { ...options, method: "POST", body: {} });
4758
+ }
4759
+ async setDisposable(id2, disposable, options) {
4760
+ await requireDaemonFeature(this.transport, "taskWorktrees", options?.signal);
4761
+ await this.transport.request(`/worktrees/${encodeURIComponent(id2)}/disposable`, { ...options, method: "POST", body: { disposable } });
4762
+ }
4763
+ };
4764
+
4765
+ // src/resources/workspace/git-resource.ts
4766
+ var GitResource = class {
4767
+ constructor(transport) {
4768
+ this.transport = transport;
4769
+ }
4770
+ transport;
4771
+ /** `GET /git/diff?cwd=&full=` */
4772
+ async getDiff(options) {
4773
+ const { signal, cwd, full } = options;
3535
4774
  const response = await this.transport.request(
3536
- this.transport.path("/jobs", {
3537
- ...query,
3538
- ...kinds ? { kinds: kinds.join(",") } : {},
3539
- ...statuses ? { statuses: statuses.join(",") } : {},
3540
- ...includeFinished !== void 0 ? { includeFinished: String(includeFinished) } : {}
3541
- }),
4775
+ this.transport.path("/git/diff", { cwd, ...full ? { full: "true" } : {} }),
3542
4776
  { signal }
3543
4777
  );
3544
- return decodeJobListResult(response);
3545
- }
3546
- async createBackgroundShell(input, options = {}) {
3547
- return await this.transport.request(
3548
- "/background-shells",
3549
- {
3550
- method: "POST",
3551
- body: input,
3552
- signal: options.signal
3553
- }
3554
- );
4778
+ return response.output;
3555
4779
  }
3556
- async read(target, options) {
3557
- const { signal, ...query } = options;
4780
+ /** `GET /git/branch?cwd=&list=` */
4781
+ async getBranch(options) {
4782
+ const { signal, cwd, list } = options;
3558
4783
  const response = await this.transport.request(
3559
- this.transport.path(`/jobs/${encodeURIComponent(target.jobId)}`, { ...query, kind: target.kind, ...target.kind === "agent" ? { runId: target.runId } : {} }),
4784
+ this.transport.path("/git/branch", { cwd, ...list ? { list: "true" } : {} }),
3560
4785
  { signal }
3561
4786
  );
3562
- return decodeJobReadResult(response);
4787
+ return response.output;
3563
4788
  }
3564
- async wait(target, input, options = {}) {
4789
+ /** `GET /git/status?cwd=` */
4790
+ async getStatus(options) {
4791
+ const { signal, cwd } = options;
3565
4792
  const response = await this.transport.request(
3566
- `/jobs/${encodeURIComponent(target.jobId)}/wait`,
3567
- {
3568
- method: "POST",
3569
- body: { ...input, target },
3570
- signal: options.signal
3571
- }
4793
+ this.transport.path("/git/status", { cwd }),
4794
+ { signal }
3572
4795
  );
3573
- return decodeJobWaitResult(response);
4796
+ return response.output;
3574
4797
  }
3575
- async send(target, input, options = {}) {
3576
- const response = await this.transport.request(`/jobs/${encodeURIComponent(target.jobId)}/input`, {
4798
+ /** `POST /git/commit` */
4799
+ async commit(input, options = {}) {
4800
+ const response = await this.transport.request("/git/commit", {
3577
4801
  method: "POST",
3578
- body: { ...input, target },
4802
+ body: input,
3579
4803
  signal: options.signal
3580
4804
  });
3581
- if (responseField(response, "sent") !== true) throw new ProtocolDataError("Job input was not accepted", "sent");
3582
- const receipt2 = response.receipt;
3583
- return receipt2 === void 0 ? void 0 : decodeJobInputReceipt(receipt2);
3584
- }
3585
- async cancel(target, input, options = {}) {
3586
- const mode = parseCancelResponseMode(options.responseMode);
3587
- const response = await this.transport.request(
3588
- `/jobs/${encodeURIComponent(target.jobId)}/cancel`,
3589
- { method: "POST", body: { ...input, target, ...options.responseMode ? { responseMode: mode } : {} }, signal: options.signal }
3590
- );
3591
- if (mode === "receipt") {
3592
- const receipt2 = decodeJobCancelReceipt(response);
3593
- if (receipt2.id !== target.jobId) throw new ProtocolDataError("Cancellation receipt does not match target");
3594
- return receipt2;
3595
- }
3596
- return decodeJobSnapshot(responseField(response, "snapshot"));
4805
+ return response.output;
3597
4806
  }
3598
4807
  };
3599
4808
 
3600
- // src/resources/session/event-resource.ts
3601
- var EventResource = class {
3602
- constructor(transport, sse) {
4809
+ // src/resources/workspace/hook-resource.ts
4810
+ var HookResource = class {
4811
+ constructor(transport) {
3603
4812
  this.transport = transport;
3604
- this.sse = sse;
3605
4813
  }
3606
4814
  transport;
3607
- sse;
3608
- /** `GET /events` — 用于 attach 时的历史 replay。 */
3609
- async list(options = {}) {
4815
+ /** `GET /hooks?cwd=&sessionId=` */
4816
+ async list(options) {
3610
4817
  const { signal, ...query } = options;
3611
4818
  const response = await this.transport.request(
3612
- this.transport.path("/events", query),
4819
+ this.transport.path("/hooks", query),
3613
4820
  { signal }
3614
4821
  );
3615
- return responseArray2(response, "events", decodeSessionEventRecord);
3616
- }
3617
- stream(options = {}) {
3618
- const query = {
3619
- partView: options.partView,
3620
- cursor: options.cursor,
3621
- sessionId: options.sessionId
3622
- };
3623
- return this.sse.stream(this.transport.resolveUrl("/events/stream", query), {
3624
- headers: this.transport.headers(),
3625
- signal: options.signal,
3626
- decode: decodeSessionEventRecord,
3627
- reconnect: options.transportReconnect ?? false,
3628
- onOpen: options.onOpen,
3629
- idleTimeoutMs: options.idleTimeoutMs
3630
- });
4822
+ return response.hooks;
3631
4823
  }
3632
4824
  };
3633
4825
 
3634
- // src/resources/files/files-resource.ts
3635
- var FilesResource = class {
4826
+ // src/resources/configuration/mcp-resource.ts
4827
+ var McpServersResource = class {
3636
4828
  constructor(transport) {
3637
4829
  this.transport = transport;
3638
4830
  }
3639
4831
  transport;
3640
- async list(sessionId, options = {}) {
3641
- const { signal, ...query } = options;
3642
- const response = await this.transport.request(
3643
- this.transport.path(`/sessions/${encodeURIComponent(sessionId)}/files`, query),
3644
- { signal }
4832
+ basePath = "/mcp/config/servers";
4833
+ list(options) {
4834
+ return this.request(this.basePath, options);
4835
+ }
4836
+ getConfig(name, options) {
4837
+ return this.request(this.serverPath(name), options);
4838
+ }
4839
+ exportConfig(options) {
4840
+ return this.request(`${this.basePath}/config/export`, options);
4841
+ }
4842
+ add(input, options) {
4843
+ return this.request(this.basePath, { ...options, method: "POST", body: input });
4844
+ }
4845
+ update({ name, ...body }, options) {
4846
+ return this.request(this.serverPath(name), { ...options, method: "PUT", body });
4847
+ }
4848
+ setEnabled({ name, enabled }, options) {
4849
+ return this.request(`${this.serverPath(name)}/enabled`, { ...options, method: "PUT", body: { enabled } });
4850
+ }
4851
+ remove(name, options) {
4852
+ return this.request(this.serverPath(name), { ...options, method: "DELETE" });
4853
+ }
4854
+ serverPath(name) {
4855
+ return `${this.basePath}/${encodeURIComponent(name)}`;
4856
+ }
4857
+ async request(path2, options) {
4858
+ await requireDaemonFeature(this.transport, "mcpServerManagement", options?.signal);
4859
+ return this.transport.request(path2, options);
4860
+ }
4861
+ };
4862
+ var McpResource = class {
4863
+ constructor(transport) {
4864
+ this.transport = transport;
4865
+ this.servers = new McpServersResource(transport);
4866
+ }
4867
+ transport;
4868
+ servers;
4869
+ listAppServers(options = {}) {
4870
+ return this.transport.request("/mcp/app-servers", {
4871
+ signal: options.signal
4872
+ });
4873
+ }
4874
+ runtimeStatus(ref, fingerprintOrOptions, legacyOptions) {
4875
+ const { name, fingerprint, options } = runtimeRequest(ref, fingerprintOrOptions, legacyOptions);
4876
+ return this.transport.request(
4877
+ this.transport.path(
4878
+ `/mcp/${encodeURIComponent(name)}/runtime-status`,
4879
+ { fingerprint }
4880
+ ),
4881
+ options
3645
4882
  );
3646
- return decodeSessionDirectoryResult(response);
3647
4883
  }
3648
- async stat(sessionId, path2, options = {}) {
3649
- const response = await this.transport.request(
3650
- this.transport.path(`/sessions/${encodeURIComponent(sessionId)}/files/stat`, { path: path2 }),
3651
- { signal: options.signal }
4884
+ synchronize(ref, fingerprintOrOptions, legacyOptions) {
4885
+ const { name, fingerprint, options } = runtimeRequest(ref, fingerprintOrOptions, legacyOptions);
4886
+ return this.transport.request(
4887
+ `/mcp/${encodeURIComponent(name)}/synchronize`,
4888
+ { ...options, method: "POST", body: { fingerprint } }
3652
4889
  );
3653
- return decodeSessionFileInfo(response);
3654
4890
  }
3655
- async readText(sessionId, path2, options = {}) {
3656
- const { signal, ...query } = options;
3657
- const response = await this.transport.request(
3658
- this.transport.path(`/sessions/${encodeURIComponent(sessionId)}/files/text`, { path: path2, ...query }),
3659
- { signal }
4891
+ /**
4892
+ * Ask every active Runtime to re-check the latest global config for `name`.
4893
+ * Only the server name crosses the wire.
4894
+ */
4895
+ async reconcileGlobal(name, options = {}) {
4896
+ return await this.transport.request(
4897
+ `/mcp/${encodeURIComponent(name)}/reconcile-global`,
4898
+ { method: "POST", body: {}, signal: options.signal }
3660
4899
  );
3661
- return decodeSessionTextFileResult(response);
3662
4900
  }
3663
- async find(sessionId, options) {
3664
- const { signal, ...query } = options;
3665
- const response = await this.transport.request(
3666
- this.transport.path(`/sessions/${encodeURIComponent(sessionId)}/files/find`, query),
3667
- { signal }
4901
+ // --- MCP OAuth login operations -----------------------------------------
4902
+ async authStatus(options = {}) {
4903
+ return await this.transport.request("/mcp/oauth/status", { signal: options.signal });
4904
+ }
4905
+ async startLogin(name, input, options = {}) {
4906
+ return await this.transport.request(
4907
+ `/mcp/${encodeURIComponent(name)}/oauth/login`,
4908
+ { method: "POST", body: input, signal: options.signal }
3668
4909
  );
3669
- return decodeSessionFindFilesResult(response);
3670
4910
  }
3671
- async search(sessionId, options) {
3672
- const { signal, caseSensitive, ...query } = options;
3673
- const response = await this.transport.request(
3674
- this.transport.path(`/sessions/${encodeURIComponent(sessionId)}/files/search`, {
3675
- ...query,
3676
- ...caseSensitive === void 0 ? {} : { caseSensitive: String(caseSensitive) }
3677
- }),
3678
- { signal }
4911
+ async getLogin(loginId, options = {}) {
4912
+ return await this.transport.request(
4913
+ `/mcp/oauth/operations/${encodeURIComponent(loginId)}`,
4914
+ { signal: options.signal }
3679
4915
  );
3680
- return decodeSessionSearchFilesResult(response);
3681
4916
  }
3682
- };
3683
-
3684
- // src/transport/http-client.ts
3685
- var BobanNomiClient = class {
3686
- protocol;
3687
- runtime;
3688
- schedules;
3689
- sessions;
3690
- attachments;
3691
- permissions;
3692
- jobs;
3693
- events;
3694
- files;
3695
- constructor(options) {
3696
- const transport = new HttpTransport(options);
3697
- const sse = new SseTransport(transport);
3698
- this.protocol = new ProtocolClient(transport);
3699
- this.runtime = new RuntimeResource(transport);
3700
- this.schedules = new ScheduleResource(transport);
3701
- this.sessions = new SessionResource(transport);
3702
- this.attachments = new AttachmentResource(transport);
3703
- this.permissions = new PermissionResource(transport);
3704
- this.jobs = new JobResource(transport);
3705
- this.events = new EventResource(transport, sse);
3706
- this.files = new FilesResource(transport);
4917
+ async submitCallback(loginId, callbackUrl, options = {}) {
4918
+ return await this.transport.request(
4919
+ `/mcp/oauth/operations/${encodeURIComponent(loginId)}/callback`,
4920
+ { method: "POST", body: { callbackUrl }, signal: options.signal }
4921
+ );
4922
+ }
4923
+ async cancelLogin(loginId, options = {}) {
4924
+ return await this.transport.request(
4925
+ `/mcp/oauth/operations/${encodeURIComponent(loginId)}`,
4926
+ { method: "DELETE", signal: options.signal }
4927
+ );
4928
+ }
4929
+ async logout(name, options = {}) {
4930
+ return await this.transport.request(
4931
+ `/mcp/${encodeURIComponent(name)}/oauth/logout`,
4932
+ { method: "POST", body: {}, signal: options.signal }
4933
+ );
3707
4934
  }
3708
- };
3709
-
3710
- // src/state/reducer.ts
3711
- var UnsupportedSessionEventSchemaVersionError = class extends Error {
3712
- event;
3713
- constructor(event) {
3714
- const expected = sessionEventSchemaVersion(event.type);
3715
- super(
3716
- `Unsupported session event schema version ${event.schemaVersion} for ${event.type} at sequence ${event.seq}; expected ${expected}`
4935
+ async *watchLogin(loginId, options = {}) {
4936
+ const response = await this.transport.requestResponse(
4937
+ `/mcp/oauth/operations/${encodeURIComponent(loginId)}/events`,
4938
+ { signal: options.signal }
3717
4939
  );
3718
- this.name = "UnsupportedSessionEventSchemaVersionError";
3719
- this.event = {
3720
- seq: event.seq,
3721
- type: event.type,
3722
- schemaVersion: event.schemaVersion
3723
- };
4940
+ if (!response.body) return;
4941
+ try {
4942
+ yield* streamServerSentEvents(async () => response.body, parseOAuthOperationEvent);
4943
+ } finally {
4944
+ await response.body.cancel().catch(() => void 0);
4945
+ }
3724
4946
  }
3725
4947
  };
3726
- function createInitialClientState() {
3727
- return {
3728
- sessions: {},
3729
- sessionOrder: [],
3730
- buckets: {},
3731
- eventsBySeq: {},
3732
- snapshotCursorBySession: {},
3733
- transientCursor: 0,
3734
- lastSeq: 0
3735
- };
3736
- }
3737
- function applyEvents(state, events) {
3738
- let next = state;
3739
- for (const event of events) next = applyEvent(next, event);
3740
- return next;
4948
+ function runtimeRequest(ref, fingerprintOrOptions, legacyOptions) {
4949
+ return typeof ref === "string" ? { name: ref, fingerprint: fingerprintOrOptions, options: legacyOptions } : { name: ref.name, fingerprint: ref.endpointFingerprint, options: fingerprintOrOptions };
3741
4950
  }
3742
- function applySessionSnapshot(state, snapshot) {
3743
- const knownCursor = state.snapshotCursorBySession[snapshot.session.id] ?? 0;
3744
- if (snapshot.cursor < knownCursor) return state;
3745
- if (Object.values(state.eventsBySeq).some((event) => event.sessionId === snapshot.session.id && event.seq > snapshot.cursor)) return state;
3746
- const partsByMessageId = {};
3747
- for (const part of snapshot.parts) {
3748
- const parts = partsByMessageId[part.messageId] ?? [];
3749
- parts.push(part);
3750
- partsByMessageId[part.messageId] = parts;
4951
+
4952
+ // src/resources/configuration/command-resource.ts
4953
+ var CommandResource = class {
4954
+ constructor(transport) {
4955
+ this.transport = transport;
3751
4956
  }
3752
- for (const parts of Object.values(partsByMessageId)) parts.sort((a, b) => a.seq - b.seq);
3753
- const sessions = { ...state.sessions, [snapshot.session.id]: snapshot.session };
3754
- return {
3755
- ...state,
3756
- sessions,
3757
- sessionOrder: sortSessionOrder(sessions),
3758
- buckets: {
3759
- ...state.buckets,
3760
- [snapshot.session.id]: {
3761
- goal: snapshot.goal,
3762
- goalEventSeq: snapshot.cursor,
3763
- session: snapshot.session,
3764
- inputs: [...snapshot.inputs].sort((a, b) => a.seq - b.seq),
3765
- messages: [...snapshot.messages].sort((a, b) => a.seq - b.seq),
3766
- partsByMessageId,
3767
- runs: Object.fromEntries(snapshot.runs.map((run) => [run.id, run])),
3768
- attempts: Object.fromEntries((snapshot.attempts ?? []).map((attempt) => [attempt.id, attempt])),
3769
- tasks: Object.fromEntries((snapshot.tasks ?? []).map((task) => [task.id, task])),
3770
- permissions: Object.fromEntries(snapshot.permissions.map((request) => [request.id, request]))
3771
- }
3772
- },
3773
- snapshotCursorBySession: {
3774
- ...state.snapshotCursorBySession,
3775
- [snapshot.session.id]: Math.max(
3776
- state.snapshotCursorBySession[snapshot.session.id] ?? 0,
3777
- snapshot.cursor
3778
- )
3779
- },
3780
- transientCursor: Math.max(state.transientCursor, snapshot.cursor),
3781
- lastSeq: Math.max(state.lastSeq, snapshot.cursor)
3782
- };
3783
- }
3784
- function applyEvent(state, event) {
3785
- if (event.schemaVersion !== sessionEventSchemaVersion(event.type)) {
3786
- throw new UnsupportedSessionEventSchemaVersionError(event);
4957
+ transport;
4958
+ /** `GET /commands` */
4959
+ async list(options) {
4960
+ const { signal, ...query } = options;
4961
+ const response = await this.transport.request(
4962
+ this.transport.path("/commands", query),
4963
+ { signal }
4964
+ );
4965
+ return response.commands;
3787
4966
  }
3788
- const transient = event.type === "session.message.part.delta";
3789
- const snapshotCursor = event.sessionId ? state.snapshotCursorBySession[event.sessionId] ?? 0 : 0;
3790
- if (event.seq <= snapshotCursor) return state;
3791
- if (transient && event.seq <= state.transientCursor) return state;
3792
- if (!transient && state.eventsBySeq[event.seq]) return state;
3793
- if (!transient) state.eventsBySeq[event.seq] = event;
3794
- let next = {
3795
- ...state,
3796
- eventsBySeq: state.eventsBySeq,
3797
- transientCursor: transient ? event.seq : state.transientCursor,
3798
- lastSeq: Math.max(state.lastSeq, event.seq)
3799
- };
3800
- switch (event.type) {
3801
- case "session.goal.created":
3802
- case "session.goal.updated": {
3803
- next = upsertGoal(next, event);
3804
- break;
3805
- }
3806
- case "session.goal.usage.updated": {
3807
- const bucket = event.sessionId ? next.buckets[event.sessionId] : void 0;
3808
- const usage = readPayloadRecord(event, "usage");
3809
- if (bucket?.goal && bucket.goal.id === event.payload.goalId && usage && usage.seq > bucket.goal.usage.seq) {
3810
- next = { ...next, buckets: { ...next.buckets, [event.sessionId]: { ...bucket, goal: { ...bucket.goal, usage } } } };
3811
- }
3812
- break;
3813
- }
3814
- case "session.created":
3815
- case "session.updated":
3816
- next = upsertSession(next, readPayloadRecord(event, "session"));
3817
- break;
3818
- case "session.archived":
3819
- next = archiveSession(next, event);
3820
- break;
3821
- case "session.deleted":
3822
- next = deleteSessions(next, event);
3823
- break;
3824
- case "session.input.admitted":
3825
- next = upsertInput(next, readPayloadRecord(event, "input"));
3826
- break;
3827
- case "session.message.created":
3828
- next = upsertMessage(next, readPayloadRecord(event, "message"));
3829
- break;
3830
- case "session.transcript.replaced":
3831
- next = replaceTranscript(next, event);
3832
- break;
3833
- case "session.message.part.updated":
3834
- next = upsertPart(next, readPayloadRecord(event, "part"));
3835
- break;
3836
- case "session.message.part.delta":
3837
- next = appendPartDelta(next, event);
3838
- break;
3839
- case "session.run.created":
3840
- case "session.run.updated":
3841
- next = upsertRun(next, readPayloadRecord(event, "run"));
3842
- break;
3843
- case "session.run_attempt.created":
3844
- case "session.run_attempt.updated":
3845
- next = upsertRunAttempt(next, readPayloadRecord(event, "attempt"));
3846
- break;
3847
- case "session.task.created":
3848
- case "session.task.updated":
3849
- next = upsertTask(next, readPayloadRecord(event, "task"));
3850
- break;
3851
- case "permission.asked":
3852
- case "permission.replied":
3853
- next = upsertPermission(next, readPayloadRecord(event, "request"));
3854
- break;
4967
+ };
4968
+
4969
+ // src/resources/configuration/context-resource.ts
4970
+ var ContextResource = class {
4971
+ constructor(transport) {
4972
+ this.transport = transport;
3855
4973
  }
3856
- return next;
3857
- }
3858
- function readPayloadRecord(event, key) {
3859
- const value = event.payload[key];
3860
- return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
3861
- }
3862
- function upsertGoal(state, event) {
3863
- const goal = readPayloadRecord(event, "goal");
3864
- if (!goal || goal.sessionId !== event.sessionId) return state;
3865
- const bucket = state.buckets[goal.sessionId];
3866
- const current = bucket?.goal;
3867
- const seq = bucket?.goalEventSeq ?? 0;
3868
- const sameGoal = current?.id === goal.id;
3869
- if (current && !sameGoal && (event.type !== "session.goal.created" || event.seq <= seq)) return state;
3870
- const isNewer = !sameGoal || goal.revision > current.revision || goal.revision === current.revision && event.seq > seq;
3871
- const record5 = isNewer ? goal : current;
3872
- const usage = sameGoal && current.usage.seq >= goal.usage.seq ? current.usage : goal.usage;
3873
- if (!isNewer && usage === current.usage) return state;
3874
- return { ...state, buckets: { ...state.buckets, [goal.sessionId]: {
3875
- ...bucket ?? cloneBucket(void 0),
3876
- goal: usage === record5.usage ? record5 : { ...record5, usage },
3877
- goalEventSeq: isNewer ? Math.max(seq, event.seq) : seq
3878
- } } };
3879
- }
3880
- function upsertSession(state, session) {
3881
- if (!session) return state;
3882
- const bucket = cloneBucket(state.buckets[session.id]);
3883
- bucket.session = session;
3884
- const sessions = { ...state.sessions, [session.id]: session };
3885
- return {
3886
- ...state,
3887
- sessions,
3888
- sessionOrder: sortSessionOrder(sessions),
3889
- buckets: { ...state.buckets, [session.id]: bucket }
3890
- };
3891
- }
3892
- function archiveSession(state, event) {
3893
- const sessionId = typeof event.payload.sessionId === "string" ? event.payload.sessionId : event.sessionId;
3894
- if (!sessionId) return state;
3895
- const current = state.sessions[sessionId];
3896
- if (!current) return state;
3897
- const archived = {
3898
- ...current,
3899
- status: "archived",
3900
- archivedAt: current.archivedAt ?? event.createdAt,
3901
- updatedAt: Math.max(current.updatedAt, event.createdAt)
3902
- };
3903
- return upsertSession(state, archived);
3904
- }
3905
- function deleteSessions(state, event) {
3906
- const ids = new Set(Array.isArray(event.payload.sessionIds) ? event.payload.sessionIds.filter((id2) => typeof id2 === "string") : []);
3907
- if (ids.size === 0) return state;
3908
- return {
3909
- ...state,
3910
- sessions: Object.fromEntries(Object.entries(state.sessions).filter(([id2]) => !ids.has(id2))),
3911
- sessionOrder: state.sessionOrder.filter((id2) => !ids.has(id2)),
3912
- buckets: Object.fromEntries(Object.entries(state.buckets).filter(([id2]) => !ids.has(id2))),
3913
- snapshotCursorBySession: Object.fromEntries(Object.entries(state.snapshotCursorBySession).filter(([id2]) => !ids.has(id2))),
3914
- eventsBySeq: Object.fromEntries(Object.entries(state.eventsBySeq).filter(([, item]) => !item.sessionId || !ids.has(item.sessionId)))
3915
- };
3916
- }
3917
- function upsertInput(state, input) {
3918
- if (!input) return state;
3919
- const bucket = cloneBucket(state.buckets[input.sessionId]);
3920
- bucket.inputs = upsertSorted(bucket.inputs, input, (row) => row.seq);
3921
- return { ...state, buckets: { ...state.buckets, [input.sessionId]: bucket } };
3922
- }
3923
- function upsertMessage(state, message) {
3924
- if (!message) return state;
3925
- const bucket = cloneBucket(state.buckets[message.sessionId]);
3926
- bucket.messages = upsertSorted(bucket.messages, message, (row) => row.seq);
3927
- return { ...state, buckets: { ...state.buckets, [message.sessionId]: bucket } };
3928
- }
3929
- function replaceTranscript(state, event) {
3930
- const sessionId = event.sessionId;
3931
- if (!sessionId) return state;
3932
- const messages = Array.isArray(event.payload.messages) ? event.payload.messages.filter((row) => !!row && typeof row === "object" && !Array.isArray(row) && typeof row.id === "string") : [];
3933
- const parts = Array.isArray(event.payload.parts) ? event.payload.parts.filter((row) => !!row && typeof row === "object" && !Array.isArray(row) && typeof row.id === "string") : [];
3934
- const bucket = cloneBucket(state.buckets[sessionId]);
3935
- const partsByMessageId = {};
3936
- for (const part of parts) {
3937
- const rows = partsByMessageId[part.messageId] ?? [];
3938
- rows.push(part);
3939
- partsByMessageId[part.messageId] = rows;
4974
+ transport;
4975
+ /** `GET /context?cwd=` */
4976
+ async getPreview(options) {
4977
+ const { signal, ...query } = options;
4978
+ const response = await this.transport.request(
4979
+ this.transport.path("/context", query),
4980
+ { signal }
4981
+ );
4982
+ return response.report;
3940
4983
  }
3941
- for (const rows of Object.values(partsByMessageId)) rows.sort((a, b) => a.seq - b.seq);
3942
- bucket.messages = [...messages].sort((a, b) => a.seq - b.seq);
3943
- bucket.partsByMessageId = partsByMessageId;
3944
- if (bucket.session) {
3945
- bucket.session = {
3946
- ...bucket.session,
3947
- updatedAt: Math.max(bucket.session.updatedAt, event.createdAt)
3948
- };
4984
+ /** `GET /context/status?cwd=` */
4985
+ async getStatus(options) {
4986
+ const { signal, ...query } = options;
4987
+ const response = await this.transport.request(
4988
+ this.transport.path("/context/status", query),
4989
+ { signal }
4990
+ );
4991
+ return response.report;
3949
4992
  }
3950
- const sessions = bucket.session ? { ...state.sessions, [sessionId]: bucket.session } : state.sessions;
3951
- return {
3952
- ...state,
3953
- sessions,
3954
- sessionOrder: sortSessionOrder(sessions),
3955
- buckets: { ...state.buckets, [sessionId]: bucket }
3956
- };
3957
- }
3958
- function upsertPart(state, part) {
3959
- if (!part) return state;
3960
- const bucket = cloneBucketForPartWrite(state.buckets[part.sessionId]);
3961
- const existing = bucket.partsByMessageId[part.messageId] ?? [];
3962
- bucket.partsByMessageId = {
3963
- ...bucket.partsByMessageId,
3964
- [part.messageId]: upsertSorted(existing, part, (row) => row.seq)
3965
- };
3966
- return { ...state, buckets: { ...state.buckets, [part.sessionId]: bucket } };
3967
- }
3968
- function appendPartDelta(state, event) {
3969
- const sessionId = typeof event.payload.sessionId === "string" ? event.payload.sessionId : event.sessionId;
3970
- const messageId = typeof event.payload.messageId === "string" ? event.payload.messageId : void 0;
3971
- const partId = typeof event.payload.partId === "string" ? event.payload.partId : void 0;
3972
- const field = event.payload.field;
3973
- const delta = typeof event.payload.delta === "string" ? event.payload.delta : void 0;
3974
- if (field !== "text" && field !== "reasoning") return state;
3975
- if (!sessionId || !messageId || !partId || delta === void 0) return state;
3976
- const bucket = cloneBucketForPartWrite(state.buckets[sessionId]);
3977
- const currentParts = bucket.partsByMessageId[messageId] ?? [];
3978
- const index = currentParts.findIndex((part) => part.id === partId);
3979
- const nextParts = [...currentParts];
3980
- if (index >= 0) {
3981
- const current = nextParts[index];
3982
- if (isSupersededModelPart(current)) return state;
3983
- nextParts[index] = {
3984
- ...current,
3985
- text: `${current.text ?? ""}${delta}`,
3986
- updatedAt: Math.max(current.updatedAt, event.createdAt)
4993
+ /** `GET /context/usage?cwd=&sessionId=&refresh=` */
4994
+ async getUsage(options) {
4995
+ const { signal, refresh, previousContextWindow, ...rest } = options;
4996
+ const query = {
4997
+ ...rest,
4998
+ ...refresh !== void 0 ? { refresh: refresh ? "true" : "false" } : {},
4999
+ ...previousContextWindow !== void 0 ? { previousContextWindow: String(previousContextWindow) } : {}
3987
5000
  };
3988
- } else {
3989
- const seq = currentParts.reduce((max, part) => Math.max(max, part.seq), 0) + 1;
3990
- nextParts.push({
3991
- id: partId,
3992
- sessionId,
3993
- messageId,
3994
- seq,
3995
- type: field === "reasoning" ? "reasoning" : "text",
3996
- status: "running",
3997
- text: delta,
3998
- metadata: {},
3999
- createdAt: event.createdAt,
4000
- updatedAt: event.createdAt
5001
+ return await this.transport.request(
5002
+ this.transport.path("/context/usage", query),
5003
+ { signal }
5004
+ );
5005
+ }
5006
+ };
5007
+
5008
+ // src/resources/configuration/diagnostic-resource.ts
5009
+ var diagnosticPaths = {
5010
+ readiness: "/maintenance/readiness",
5011
+ runtime: "/debug/runtime",
5012
+ storageHealth: "/maintenance/storage/health",
5013
+ environment: "/maintenance/environment",
5014
+ logs: "/maintenance/logs",
5015
+ errors: "/maintenance/errors",
5016
+ details: "/maintenance/diagnostics/details"
5017
+ };
5018
+ var DiagnosticResource = class {
5019
+ constructor(transport) {
5020
+ this.transport = transport;
5021
+ }
5022
+ transport;
5023
+ /** The original normalized endpoint, without this connection's bearer token. */
5024
+ target() {
5025
+ return this.transport.baseUrl;
5026
+ }
5027
+ /** Finite native-host diagnostics; this never accepts an arbitrary route or mutation. */
5028
+ async get(kind, options = {}) {
5029
+ if (!Object.hasOwn(diagnosticPaths, kind)) throw new Error("Unknown diagnostic kind");
5030
+ return this.transport.request(diagnosticPaths[kind], { signal: options.signal });
5031
+ }
5032
+ getRun(runId, { signal, ...query } = {}) {
5033
+ return this.transport.request(`/debug/runs/${encodeURIComponent(runId)}`, { query, signal });
5034
+ }
5035
+ listSettlements({ signal, ...query } = {}) {
5036
+ return this.transport.request("/debug/projection-settlements", { query, signal });
5037
+ }
5038
+ listExecutions({ signal, ...query } = {}) {
5039
+ return this.transport.request("/debug/executions", { query, signal });
5040
+ }
5041
+ setDetails(minutes, options) {
5042
+ return this.transport.request("/maintenance/diagnostics/details", {
5043
+ ...options,
5044
+ method: "POST",
5045
+ body: { minutes }
4001
5046
  });
4002
5047
  }
4003
- const sortedParts = index >= 0 ? nextParts : nextParts.sort((a, b) => a.seq - b.seq);
4004
- bucket.partsByMessageId = {
4005
- ...bucket.partsByMessageId,
4006
- [messageId]: sortedParts
4007
- };
4008
- return { ...state, buckets: { ...state.buckets, [sessionId]: bucket } };
4009
- }
4010
- function upsertRun(state, run) {
4011
- if (!run) return state;
4012
- const bucket = cloneBucket(state.buckets[run.sessionId]);
4013
- bucket.runs = { ...bucket.runs, [run.id]: run };
4014
- const session = refreshSessionStatusFromRuns(bucket.session, bucket.runs, run.updatedAt);
4015
- bucket.session = session;
4016
- const sessions = session ? { ...state.sessions, [run.sessionId]: session } : state.sessions;
4017
- return {
4018
- ...state,
4019
- sessions,
4020
- sessionOrder: session ? sortSessionOrder(sessions) : state.sessionOrder,
4021
- buckets: { ...state.buckets, [run.sessionId]: bucket }
5048
+ };
5049
+
5050
+ // src/resources/configuration/maintenance-resource.ts
5051
+ var MaintenanceResource = class {
5052
+ constructor(transport) {
5053
+ this.transport = transport;
5054
+ }
5055
+ transport;
5056
+ getRestartPreview(options) {
5057
+ return this.transport.request("/maintenance/restart-preview", options);
5058
+ }
5059
+ prepareRestart({ stopActive = false, signal } = {}) {
5060
+ return this.post("/prepare-restart", { stopActive }, { signal });
5061
+ }
5062
+ cleanup = {
5063
+ preview: (input, options) => this.post("/cleanup/preview", input, options),
5064
+ execute: (input, options) => this.post("/cleanup/execute", input, options),
5065
+ audits: (options) => this.transport.request("/maintenance/cleanup/audits", options),
5066
+ getPolicy: (options) => this.transport.request("/maintenance/cleanup/policy", options),
5067
+ updatePolicy: (input, options) => this.post("/cleanup/policy", input, options),
5068
+ runPolicy: (options) => this.post("/cleanup/policy/run", {}, options)
4022
5069
  };
4023
- }
4024
- function upsertRunAttempt(state, attempt) {
4025
- if (!attempt) return state;
4026
- const run = Object.values(state.buckets).flatMap((bucket2) => Object.values(bucket2.runs)).find((candidate) => candidate.id === attempt.runId);
4027
- if (!run) return state;
4028
- const bucket = cloneBucket(state.buckets[run.sessionId]);
4029
- bucket.attempts = { ...bucket.attempts, [attempt.id]: attempt };
4030
- return { ...state, buckets: { ...state.buckets, [run.sessionId]: bucket } };
4031
- }
4032
- function refreshSessionStatusFromRuns(session, runs, updatedAt) {
4033
- if (!session || session.status === "archived" || session.status === "closing") return session;
4034
- const running = Object.values(runs).some(
4035
- (candidate) => candidate.status === "pending" || candidate.status === "running"
4036
- );
4037
- return {
4038
- ...session,
4039
- status: running ? "running" : "idle",
4040
- updatedAt: Math.max(session.updatedAt, updatedAt)
5070
+ usage = {
5071
+ get: (input = {}, options) => this.post("/usage", input, options),
5072
+ getSettings: (options) => this.transport.request("/maintenance/usage/settings", options),
5073
+ updateBudget: (input, options) => this.post("/usage/budget", input, options),
5074
+ addPrice: (input, options) => this.post("/usage/price", input, options)
4041
5075
  };
4042
- }
4043
- function upsertPermission(state, request) {
4044
- if (!request) return state;
4045
- const bucket = cloneBucket(state.buckets[request.sessionId]);
4046
- bucket.permissions = { ...bucket.permissions, [request.id]: request };
4047
- return { ...state, buckets: { ...state.buckets, [request.sessionId]: bucket } };
4048
- }
4049
- function upsertTask(state, task) {
4050
- if (!task) return state;
4051
- const bucket = cloneBucket(state.buckets[task.sessionId]);
4052
- bucket.tasks = { ...bucket.tasks, [task.id]: task };
4053
- return { ...state, buckets: { ...state.buckets, [task.sessionId]: bucket } };
4054
- }
4055
- function cloneBucket(bucket) {
4056
- return {
4057
- ...bucket?.goal !== void 0 ? { goal: bucket.goal } : {},
4058
- ...bucket?.goalEventSeq !== void 0 ? { goalEventSeq: bucket.goalEventSeq } : {},
4059
- session: bucket?.session,
4060
- inputs: bucket?.inputs ? [...bucket.inputs] : [],
4061
- messages: bucket?.messages ? [...bucket.messages] : [],
4062
- partsByMessageId: bucket?.partsByMessageId ? Object.fromEntries(Object.entries(bucket.partsByMessageId).map(([id2, parts]) => [id2, [...parts]])) : {},
4063
- runs: bucket?.runs ? { ...bucket.runs } : {},
4064
- attempts: bucket?.attempts ? { ...bucket.attempts } : {},
4065
- tasks: bucket?.tasks ? { ...bucket.tasks } : {},
4066
- permissions: bucket?.permissions ? { ...bucket.permissions } : {}
5076
+ storage = {
5077
+ get: (options) => this.transport.request("/maintenance/storage", options)
4067
5078
  };
4068
- }
4069
- function cloneBucketForPartWrite(bucket) {
4070
- return {
4071
- ...bucket?.goal !== void 0 ? { goal: bucket.goal } : {},
4072
- ...bucket?.goalEventSeq !== void 0 ? { goalEventSeq: bucket.goalEventSeq } : {},
4073
- session: bucket?.session,
4074
- inputs: bucket?.inputs ?? [],
4075
- messages: bucket?.messages ?? [],
4076
- partsByMessageId: bucket?.partsByMessageId ?? {},
4077
- runs: bucket?.runs ?? {},
4078
- attempts: bucket?.attempts ?? {},
4079
- tasks: bucket?.tasks ?? {},
4080
- permissions: bucket?.permissions ?? {}
5079
+ backups = {
5080
+ create: (input, options) => this.post("/backup", input, options),
5081
+ verify: (source, options) => this.post("/backup/verify", { source }, options),
5082
+ restore: (input, options) => this.post("/backup/restore", input, options)
4081
5083
  };
4082
- }
4083
- function upsertSorted(rows, row, sortKey) {
4084
- const without = rows.filter((existing) => existing.id !== row.id);
4085
- without.push(row);
4086
- return without.sort((a, b) => sortKey(a) - sortKey(b));
4087
- }
4088
- function sortSessionOrder(sessions) {
4089
- return Object.values(sessions).sort((a, b) => b.updatedAt - a.updatedAt || a.id.localeCompare(b.id)).map((session) => session.id);
4090
- }
5084
+ post(path2, body, options) {
5085
+ return this.transport.request(`/maintenance${path2}`, { ...options, method: "POST", body });
5086
+ }
5087
+ };
4091
5088
 
4092
- // src/state/selectors.ts
4093
- function selectSessionMessagesWithParts(bucket) {
4094
- if (!bucket) return [];
4095
- return [...bucket.messages].sort((a, b) => a.seq - b.seq).map((message) => ({
4096
- message,
4097
- parts: [...bucket.partsByMessageId[message.id] ?? []].sort((a, b) => a.seq - b.seq)
4098
- }));
4099
- }
4100
- function selectVisibleSessionMessagesWithParts(bucket) {
4101
- return selectSessionMessagesWithParts(bucket).map(({ message, parts }) => ({
4102
- message,
4103
- parts: parts.filter((part) => !isSupersededModelPart(part))
4104
- })).filter(
4105
- ({ message, parts }) => parts.length > 0 || message.role !== "assistant"
4106
- );
4107
- }
4108
- function selectSessionInputs(bucket) {
4109
- if (!bucket) return [];
4110
- return [...bucket.inputs].sort((a, b) => a.seq - b.seq);
4111
- }
4112
- function selectSessionOrderedMessages(bucket) {
4113
- if (!bucket) return [];
4114
- return [...bucket.messages].sort((a, b) => a.seq - b.seq);
4115
- }
4116
- function selectSessionParts(bucket) {
4117
- if (!bucket) return [];
4118
- return Object.values(bucket.partsByMessageId).flat().sort((a, b) => a.seq - b.seq);
4119
- }
4120
- function selectSessionRuns(bucket) {
4121
- if (!bucket) return [];
4122
- return Object.values(bucket.runs);
4123
- }
4124
- function selectSessionModelRetry(bucket) {
4125
- if (!bucket) return void 0;
4126
- const active = Object.values(bucket.runs).filter((run) => run.status === "running" || run.status === "pending").sort((a, b) => b.updatedAt - a.updatedAt);
4127
- for (const run of active) {
4128
- const state = readSessionModelRetryState(run.metadata);
4129
- if (state) return state;
5089
+ // src/resources/configuration/memory-resource.ts
5090
+ var MemoryResource = class {
5091
+ constructor(transport) {
5092
+ this.transport = transport;
5093
+ }
5094
+ transport;
5095
+ /** `GET /memory?cwd=` */
5096
+ async listMemory(options) {
5097
+ const { signal, ...query } = options;
5098
+ return await this.transport.request(
5099
+ this.transport.path("/memory", query),
5100
+ { signal }
5101
+ );
5102
+ }
5103
+ /** `GET /facts?cwd=` — current project environment facts. */
5104
+ async listFacts(options) {
5105
+ const { signal, ...query } = options;
5106
+ return await this.transport.request(
5107
+ this.transport.path("/facts", query),
5108
+ { signal }
5109
+ );
5110
+ }
5111
+ /** `POST /facts/replace` — replace exactly one selected environment fact. */
5112
+ async replaceFact(input, options = {}) {
5113
+ const response = await this.transport.request(
5114
+ "/facts/replace",
5115
+ { method: "POST", body: input, signal: options.signal }
5116
+ );
5117
+ return response.result;
5118
+ }
5119
+ /** `GET /memory/:id?cwd=` */
5120
+ async getMemory(entryId, options) {
5121
+ const { signal, cwd } = options;
5122
+ const response = await this.transport.request(
5123
+ this.transport.path(`/memory/${encodeURIComponent(entryId)}`, { cwd }),
5124
+ { signal }
5125
+ );
5126
+ return response.entry;
5127
+ }
5128
+ /** `POST /memory` */
5129
+ async addMemory(input, options = {}) {
5130
+ const response = await this.transport.request(
5131
+ "/memory",
5132
+ {
5133
+ method: "POST",
5134
+ body: input,
5135
+ signal: options.signal
5136
+ }
5137
+ );
5138
+ return response.entry;
5139
+ }
5140
+ /** `DELETE /memory/:id?cwd=` */
5141
+ async removeMemory(entryId, options) {
5142
+ const { signal, cwd, expectedRevision } = options;
5143
+ await this.transport.request(
5144
+ this.transport.path(`/memory/${encodeURIComponent(entryId)}`, { cwd, expectedRevision }),
5145
+ { method: "DELETE", signal }
5146
+ );
5147
+ }
5148
+ async updateMemory(input, options = {}) {
5149
+ const { id: id2, ...body } = input;
5150
+ const result = await this.transport.request(`/memory/${encodeURIComponent(id2)}`, { method: "PATCH", body, signal: options.signal });
5151
+ return result.entry;
5152
+ }
5153
+ async clearMemory(input, options = {}) {
5154
+ return this.transport.request("/memory/clear", { method: "POST", body: input, signal: options.signal });
5155
+ }
5156
+ async getDreamStatus(input) {
5157
+ return this.transport.request(this.transport.path("/dream", input));
5158
+ }
5159
+ /** `POST /dream` */
5160
+ async startDream(input, options = {}) {
5161
+ return await this.transport.request("/dream", {
5162
+ method: "POST",
5163
+ body: input,
5164
+ signal: options.signal
5165
+ });
5166
+ }
5167
+ };
5168
+
5169
+ // src/resources/configuration/settings-resource.ts
5170
+ var SettingsResource = class {
5171
+ constructor(transport) {
5172
+ this.transport = transport;
5173
+ }
5174
+ transport;
5175
+ /** Read the daemon's current global settings. */
5176
+ getGlobal({ signal } = {}) {
5177
+ return this.get({ signal });
5178
+ }
5179
+ /** Read effective settings including overrides for a daemon-side project directory. */
5180
+ getEffective(options) {
5181
+ if (typeof options.cwd !== "string" || !options.cwd.trim())
5182
+ return Promise.reject(new TypeError("cwd must be a nonempty daemon directory"));
5183
+ return this.get(options);
5184
+ }
5185
+ /** Read global settings without cwd, or the merged project settings with cwd. */
5186
+ async get(options = {}) {
5187
+ const response = await this.transport.request(
5188
+ options.cwd ? `/settings?cwd=${encodeURIComponent(options.cwd)}` : "/settings",
5189
+ { signal: options.signal }
5190
+ );
5191
+ return response.settings;
5192
+ }
5193
+ /** Apply a targeted change to global settings. Pass only the fields the caller changes. */
5194
+ updateGlobal(patch, options) {
5195
+ return this.update(patch, options);
5196
+ }
5197
+ /** Apply a global patch. Existing callers may use this alias. */
5198
+ async update(patch, options = {}) {
5199
+ const response = await this.transport.request(
5200
+ "/settings",
5201
+ {
5202
+ method: "PATCH",
5203
+ body: patch,
5204
+ signal: options.signal
5205
+ }
5206
+ );
5207
+ return response.settings;
4130
5208
  }
4131
- return void 0;
4132
- }
4133
- function selectSessionModelUsage(bucket) {
4134
- if (!bucket) return void 0;
4135
- const runs = Object.values(bucket.runs).sort((a, b) => b.updatedAt - a.updatedAt);
4136
- for (const run of runs) {
4137
- const usage = readSessionModelUsage(run.metadata);
4138
- if (usage) return usage;
5209
+ /** `GET /profile` */
5210
+ async getProfileStatus(options = {}) {
5211
+ const response = await this.transport.request("/profile", {
5212
+ signal: options.signal
5213
+ });
5214
+ return response.report;
4139
5215
  }
4140
- return void 0;
4141
- }
4142
- function selectSessionTasks(bucket) {
4143
- if (!bucket) return [];
4144
- return Object.values(bucket.tasks);
4145
- }
4146
- function selectSessionPermissions(bucket) {
4147
- if (!bucket) return [];
4148
- return Object.values(bucket.permissions);
4149
- }
4150
- function selectFirstPendingPermission(state, sessionId) {
4151
- if (!sessionId) return void 0;
4152
- const bucket = state.buckets[sessionId];
4153
- if (!bucket) return void 0;
4154
- return Object.values(bucket.permissions).filter((request) => request.status === "pending").sort((a, b) => a.createdAt - b.createdAt).at(0);
4155
- }
4156
-
4157
- // src/state/session-stream-state.ts
4158
- function applySessionStreamEvent(state, event) {
4159
- if (event.seq <= state.lastSeq) return state;
4160
- const next = applyEvent({ ...state, eventsBySeq: {} }, event);
4161
- return { ...next, eventsBySeq: {} };
4162
- }
4163
- function applySessionStreamSnapshot(state, snapshot) {
4164
- if (snapshot.cursor < state.lastSeq) return state;
4165
- return { ...applySessionSnapshot(state, snapshot), eventsBySeq: {} };
4166
- }
5216
+ /** `POST /profile/init` */
5217
+ async initProfile(options = {}) {
5218
+ const response = await this.transport.request(
5219
+ "/profile/init",
5220
+ {
5221
+ method: "POST",
5222
+ signal: options.signal
5223
+ }
5224
+ );
5225
+ return response.report;
5226
+ }
5227
+ /** `GET /output-styles` */
5228
+ async listOutputStyles(options = {}) {
5229
+ const response = await this.transport.request(
5230
+ "/output-styles",
5231
+ {
5232
+ signal: options.signal
5233
+ }
5234
+ );
5235
+ return response.styles;
5236
+ }
5237
+ };
4167
5238
 
4168
- // src/state/sync.ts
4169
- var DEFAULT_RECONNECT_DELAY_MS = (attempt) => Math.min(3e4, 250 * 2 ** Math.max(0, attempt));
4170
- var DEFAULT_SESSION_IDLE_TIMEOUT_MS = 6e4;
4171
- var EVENT_REPLAY_PAGE_SIZE = 128;
4172
- function hydrateState(events) {
4173
- return applyEvents(createInitialClientState(), events);
4174
- }
4175
- async function* syncEvents(client, options = {}) {
4176
- yield* runEventSync(client, {
4177
- ...options,
4178
- // 会话迭代接口从完整快照开始;只有全局 replay 使用调用方游标。
4179
- cursor: options.sessionId ? void 0 : options.cursor,
4180
- idleTimeoutMs: options.idleTimeoutMs ?? DEFAULT_SESSION_IDLE_TIMEOUT_MS
4181
- });
4182
- }
4183
- async function* runEventSync(client, options, initialState = createInitialClientState(), onLiveEvent) {
4184
- let state = initialState;
4185
- let cursor = Math.max(0, options.cursor ?? 0, state.lastSeq);
4186
- let attempt = 0;
4187
- const signal = options.signal;
4188
- const delayMs = options.reconnectDelayMs ?? DEFAULT_RECONNECT_DELAY_MS;
4189
- const reduce = options.sessionId ? applySessionStreamEvent : options.globalReducer ?? applyEvent;
4190
- if (signal?.aborted) return;
4191
- const refreshSession = async (initial) => {
4192
- const snapshot = await client.sessions.getState(options.sessionId, {
4193
- signal,
4194
- partView: options.partView
5239
+ // src/resources/runtime/terminal-resource.ts
5240
+ var TerminalResource = class {
5241
+ constructor(transport, sse) {
5242
+ this.transport = transport;
5243
+ this.sse = sse;
5244
+ }
5245
+ transport;
5246
+ sse;
5247
+ async create(input, options = {}) {
5248
+ const response = await this.transport.request("/terminals", {
5249
+ method: "POST",
5250
+ body: input,
5251
+ signal: options.signal
4195
5252
  });
4196
- if (signal?.aborted) return;
4197
- const next = initial ? applySessionSnapshot(state, snapshot) : applySessionStreamSnapshot(state, snapshot);
4198
- state = Object.keys(next.eventsBySeq).length ? { ...next, eventsBySeq: {} } : next;
4199
- cursor = Math.max(cursor, snapshot.cursor, state.lastSeq);
4200
- };
4201
- const replayHistory = async function* (initial, beforeSeq) {
4202
- let pageCursor = cursor;
4203
- while (!signal?.aborted) {
4204
- const page = await client.events.list({
4205
- cursor: pageCursor,
4206
- limit: EVENT_REPLAY_PAGE_SIZE,
4207
- partView: options.partView,
4208
- signal
4209
- });
4210
- if (signal?.aborted) return;
4211
- for (const event of page) {
4212
- if (signal?.aborted || beforeSeq !== void 0 && event.seq >= beforeSeq) return;
4213
- const before = state;
4214
- state = reduce(state, event);
4215
- cursor = Math.max(cursor, event.seq, state.lastSeq);
4216
- if (initial || state !== before) yield { event, state, source: "replay" };
5253
+ return decodeTerminalSessionInfo(responseField(response, "terminal"));
5254
+ }
5255
+ async list(options = {}) {
5256
+ const { signal, ...query } = options;
5257
+ const response = await this.transport.request(
5258
+ this.transport.path("/terminals", query),
5259
+ { signal }
5260
+ );
5261
+ return responseArray2(response, "terminals", decodeTerminalSessionInfo);
5262
+ }
5263
+ async get(terminalId, options = {}) {
5264
+ const response = await this.transport.request(
5265
+ `/terminals/${encodeURIComponent(terminalId)}`,
5266
+ { signal: options.signal }
5267
+ );
5268
+ return decodeTerminalSessionInfo(responseField(response, "terminal"));
5269
+ }
5270
+ async read(terminalId, options = {}) {
5271
+ const response = await this.transport.request(
5272
+ `/terminals/${encodeURIComponent(terminalId)}/output`,
5273
+ { signal: options.signal }
5274
+ );
5275
+ return decodeTerminalReadResult(responseField(response, "snapshot"));
5276
+ }
5277
+ async write(input, options = {}) {
5278
+ await this.transport.request(
5279
+ `/terminals/${encodeURIComponent(input.terminalId)}/input`,
5280
+ { method: "POST", body: { data: input.data }, signal: options.signal }
5281
+ );
5282
+ }
5283
+ async resize(input, options = {}) {
5284
+ await this.transport.request(
5285
+ `/terminals/${encodeURIComponent(input.terminalId)}/resize`,
5286
+ {
5287
+ method: "POST",
5288
+ body: { cols: input.cols, rows: input.rows },
5289
+ signal: options.signal
4217
5290
  }
4218
- const through = page.at(-1)?.seq ?? pageCursor;
4219
- if (page.length < EVENT_REPLAY_PAGE_SIZE || through <= pageCursor) return;
4220
- pageCursor = through;
4221
- }
4222
- };
4223
- try {
4224
- if (options.sessionId) {
4225
- await refreshSession(true);
4226
- } else {
4227
- yield* replayHistory(true);
4228
- }
4229
- if (signal?.aborted) return;
4230
- yield { state, source: "snapshot" };
4231
- let needsSnapshot = false;
4232
- while (!signal?.aborted) {
4233
- try {
4234
- if (needsSnapshot) {
4235
- await refreshSession(false);
4236
- if (signal?.aborted) return;
4237
- needsSnapshot = false;
4238
- yield { state, source: "snapshot" };
4239
- }
4240
- if (signal?.aborted) return;
4241
- for await (const event of client.events.stream({
4242
- cursor,
4243
- sessionId: options.sessionId,
4244
- signal,
4245
- partView: options.partView,
4246
- transportReconnect: false,
4247
- idleTimeoutMs: options.idleTimeoutMs
4248
- })) {
4249
- if (signal?.aborted) return;
4250
- onLiveEvent?.();
4251
- if (signal?.aborted) return;
4252
- attempt = 0;
4253
- if (event.seq > cursor + 1 && !options.sessionId) {
4254
- yield* replayHistory(false, event.seq);
4255
- }
4256
- if (signal?.aborted) return;
4257
- const before = state;
4258
- state = reduce(state, event);
4259
- cursor = Math.max(cursor, event.seq, state.lastSeq);
4260
- if (state !== before) yield { event, state, source: "live" };
4261
- }
4262
- } catch (error) {
4263
- if (error instanceof UnsupportedSessionEventSchemaVersionError) throw error;
4264
- if (isAbortError(error) || signal?.aborted) return;
4265
- if (options.shouldRetry?.(error) === false) throw error;
4266
- if (error instanceof BobanNomiApiError && error.status >= 400 && error.status < 500 && ![408, 425, 429].includes(error.status)) throw error;
5291
+ );
5292
+ }
5293
+ async signal(terminalId, signal, options = {}) {
5294
+ await this.transport.request(
5295
+ `/terminals/${encodeURIComponent(terminalId)}/signal`,
5296
+ { method: "POST", body: { signal }, signal: options.signal }
5297
+ );
5298
+ }
5299
+ async close(terminalId, options = {}) {
5300
+ await this.transport.request(
5301
+ `/terminals/${encodeURIComponent(terminalId)}`,
5302
+ {
5303
+ method: "DELETE",
5304
+ signal: options.signal
4267
5305
  }
4268
- if (signal?.aborted) return;
4269
- needsSnapshot = Boolean(options.sessionId);
4270
- yield { state, source: "reconnecting" };
4271
- if (!await waitForReconnect2(delayMs(attempt), signal)) return;
4272
- attempt += 1;
4273
- }
4274
- } catch (error) {
4275
- if (!isAbortError(error) && !signal?.aborted) throw error;
5306
+ );
4276
5307
  }
4277
- }
4278
- async function waitForReconnect2(ms, signal) {
4279
- if (signal?.aborted) return false;
4280
- if (ms <= 0) return true;
4281
- return new Promise((resolve) => {
4282
- const onAbort = () => {
4283
- clearTimeout(timer);
4284
- resolve(false);
4285
- };
4286
- const timer = setTimeout(() => {
4287
- signal?.removeEventListener("abort", onAbort);
4288
- resolve(!signal?.aborted);
4289
- }, ms);
4290
- signal?.addEventListener("abort", onAbort, { once: true });
4291
- });
4292
- }
4293
- function isAbortError(error) {
4294
- return Boolean(error && typeof error === "object" && "name" in error && error.name === "AbortError");
4295
- }
5308
+ streamEvents(options = {}) {
5309
+ return this.sse.stream(
5310
+ this.transport.resolveUrl("/terminals/stream"),
5311
+ {
5312
+ headers: this.transport.headers(),
5313
+ signal: options.signal,
5314
+ decode: decodeTerminalEvent,
5315
+ noBodyMessage: "Terminal event stream response has no body"
5316
+ }
5317
+ );
5318
+ }
5319
+ };
5320
+
5321
+ // src/transport/http-client.ts
5322
+ var BobanNomiClient = class {
5323
+ protocol;
5324
+ /** Models grouped by provider, from the caller's catalog or the daemon. */
5325
+ models;
5326
+ /** Model-provider connections and defaults. Requires daemon management access. */
5327
+ modelProviders;
5328
+ /** Agent roles available to this connection. */
5329
+ agents;
5330
+ /** Available skills and their sources. */
5331
+ skills;
5332
+ schedules;
5333
+ sessions;
5334
+ attachments;
5335
+ permissions;
5336
+ events;
5337
+ /** Daemon plugin installation and lifecycle. Requires management access. */
5338
+ plugins;
5339
+ channels;
5340
+ projects;
5341
+ worktrees;
5342
+ git;
5343
+ hooks;
5344
+ mcp;
5345
+ commands;
5346
+ context;
5347
+ diagnostics;
5348
+ maintenance;
5349
+ memory;
5350
+ settings;
5351
+ /** Global daemon execution terminal access. Session-scoped output is under sessions.byId(). */
5352
+ terminals;
5353
+ constructor(options) {
5354
+ const transport = options instanceof HttpTransport ? options : new HttpTransport(options);
5355
+ const sse = new SseTransport(transport);
5356
+ this.protocol = new ProtocolClient(transport);
5357
+ const providers = options instanceof HttpTransport ? void 0 : options.providers;
5358
+ const { models, modelProviders, agents, skills } = createRuntimeResources(transport, providers);
5359
+ this.models = models;
5360
+ this.modelProviders = modelProviders;
5361
+ this.agents = agents;
5362
+ this.skills = skills;
5363
+ this.schedules = new ScheduleResource(transport);
5364
+ this.attachments = new AttachmentResource(transport);
5365
+ this.permissions = new PermissionResource(transport);
5366
+ this.events = new EventResource(transport, sse);
5367
+ this.sessions = new SessionResource(transport, this.events);
5368
+ this.plugins = new PluginResource(transport);
5369
+ this.channels = new ChannelResource(transport);
5370
+ this.projects = new ProjectResource(transport);
5371
+ this.worktrees = new WorktreeResource(transport);
5372
+ this.git = new GitResource(transport);
5373
+ this.hooks = new HookResource(transport);
5374
+ this.mcp = new McpResource(transport);
5375
+ this.commands = new CommandResource(transport);
5376
+ this.context = new ContextResource(transport);
5377
+ this.diagnostics = new DiagnosticResource(transport);
5378
+ this.maintenance = new MaintenanceResource(transport);
5379
+ this.memory = new MemoryResource(transport);
5380
+ this.settings = new SettingsResource(transport);
5381
+ this.terminals = new TerminalResource(transport, sse);
5382
+ }
5383
+ };
4296
5384
 
4297
5385
  // src/state/session-sync-controller.ts
4298
5386
  var SessionSyncController = class {
@@ -4305,7 +5393,7 @@ var SessionSyncController = class {
4305
5393
  running = false;
4306
5394
  constructor(options) {
4307
5395
  this.options = { ...options };
4308
- this.state = options.initialState ?? createInitialClientState();
5396
+ this.state = options.initialState ?? createClientState();
4309
5397
  if ((options.cursor ?? 0) > 0 && !options.initialState) {
4310
5398
  throw new Error("A non-zero cursor requires initialState so durable state is not skipped");
4311
5399
  }
@@ -4375,23 +5463,6 @@ var SessionSyncController = class {
4375
5463
  }
4376
5464
  };
4377
5465
 
4378
- // src/state/wait-for-run.ts
4379
- async function waitForRun(client, options) {
4380
- options.signal?.throwIfAborted();
4381
- for await (const update of syncEvents(client, { sessionId: options.sessionId, signal: options.signal })) {
4382
- options.signal?.throwIfAborted();
4383
- const bucket = update.state.buckets[options.sessionId];
4384
- const run = bucket?.runs[options.runId];
4385
- if (!run || run.status === "pending" || run.status === "running") continue;
4386
- return {
4387
- run,
4388
- messages: selectVisibleSessionMessagesWithParts(bucket).filter((item) => item.message.runId === options.runId)
4389
- };
4390
- }
4391
- options.signal?.throwIfAborted();
4392
- throw new Error(`Run ${options.runId} observation ended before a terminal state was available`);
4393
- }
4394
-
4395
5466
  // src/configuration/runtime-configuration.ts
4396
5467
  function normalizeApprovalMode(value) {
4397
5468
  if (value === "ask" || value === "auto_review" || value === "full_access") return value;
@@ -4480,28 +5551,26 @@ export {
4480
5551
  BobanNomiApiError,
4481
5552
  BobanNomiClient,
4482
5553
  CURRENT_PROTOCOL_VERSION,
5554
+ ChannelResource,
4483
5555
  EventResource,
4484
- FilesResource,
4485
5556
  HttpTransport,
4486
5557
  IncompatibleProtocolError,
4487
- JobResource,
4488
5558
  PermissionResource,
5559
+ PluginResource,
4489
5560
  ProtocolClient,
4490
5561
  ProtocolValidationError,
4491
- RuntimeResource,
4492
5562
  ScheduleResource,
4493
- SessionManagementResource,
4494
5563
  SessionResource,
4495
5564
  SessionSyncController,
4496
5565
  SseTransport,
4497
5566
  UnsupportedSessionEventSchemaVersionError,
4498
5567
  applyEvent,
4499
5568
  applyEvents,
4500
- applySessionSnapshot,
4501
5569
  attachmentRangeHeader,
4502
5570
  checkProtocolCompatibility,
4503
- createInitialClientState,
4504
- createPromptRequestId,
5571
+ createClientState,
5572
+ createSessionRequestId,
5573
+ getVisibleSessionMessages,
4505
5574
  hydrateState,
4506
5575
  isSupersededModelPart,
4507
5576
  isWorkMode,
@@ -4518,6 +5587,7 @@ export {
4518
5587
  readSessionModelUsage,
4519
5588
  readSessionRuntimeConfig,
4520
5589
  readWorkspaceChangesMetadata,
5590
+ replaceSessionState,
4521
5591
  responseArray2 as responseArray,
4522
5592
  responseField,
4523
5593
  selectFirstPendingPermission,
@@ -4530,10 +5600,8 @@ export {
4530
5600
  selectSessionPermissions,
4531
5601
  selectSessionRuns,
4532
5602
  selectSessionTasks,
4533
- selectVisibleSessionMessagesWithParts,
4534
5603
  streamServerSentEvents,
4535
5604
  supportsFeature,
4536
- syncEvents,
4537
- waitForRun
5605
+ syncEvents
4538
5606
  };
4539
5607
  //# sourceMappingURL=index.js.map