Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(agent-sessions): serve the folded session log and add AgentSession.foldedLog() (#8383)

Wolf Mermelsteinb857ccb4cbc1
diff --git a/apps/web/justfile b/apps/web/justfile
index 3ef53542a2..14e7750128 100644
--- a/apps/web/justfile
+++ b/apps/web/justfile
@@ -438,7 +438,8 @@ ensure-ai-engine-wasm:
just --justfile "{{justfile()}}" build-ai-engine-wasm
fi
-# Regenerate src/lib/service-clients/service-agent-fold/generated/types.ts
+# Regenerate src/lib/service-clients/service-agent-fold/generated/types.ts (and
+# the SDK's packages/sdk/generated/agent-fold/index.ts)
# from agent_fold's Rust wire types with specta. Run after changing anything
# under crates/folds/agent_fold/src/inbound/wire.rs. Specta's own output is tabs and
# commas, not this project's style, so biome reformats it in place - without
diff --git a/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts b/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts
index 654e270556..5866bfd53b 100644
--- a/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts
+++ b/apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts
@@ -496,7 +496,7 @@ export type FileDiff = {
newText: string;
};
-/** One renderable message, scoped to its agent session for the browser. */
+/** One renderable message, scoped to its agent session for its reader. */
export type FoldedMessage = {
/** Session that scopes this message id. */
agentSessionId: string;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
index 9fb18b5c60..e71e70967f 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts
@@ -10,6 +10,7 @@ import type {
AgentRepositoryBranchesResponse,
AgentSessionChangesPatchResponse,
AgentSessionChangesResponse,
+ AgentSessionFoldedLogResponse,
AgentSessionLogResponse,
AgentSessionQueueResponse,
AgentSessionResponse,
@@ -1832,6 +1833,73 @@ export const getAgentSessionLog = async (
} as getAgentSessionLogResponse;
};
+/**
+ * For readers that do not run the fold themselves, such as SDK programs and
+agents reading another session's history.
+ * @summary One agent session's history folded into renderable messages: the same
+fold the web client runs over [`get_agent_session_log_handler`]'s frames.
+ */
+export type getAgentSessionFoldedLogResponse200 = {
+ data: AgentSessionFoldedLogResponse;
+ status: 200;
+};
+
+export type getAgentSessionFoldedLogResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type getAgentSessionFoldedLogResponse403 = {
+ data: string;
+ status: 403;
+};
+
+export type getAgentSessionFoldedLogResponse500 = {
+ data: string;
+ status: 500;
+};
+
+export type getAgentSessionFoldedLogResponseSuccess =
+ getAgentSessionFoldedLogResponse200 & {
+ headers: Headers;
+ };
+export type getAgentSessionFoldedLogResponseError = (
+ | getAgentSessionFoldedLogResponse401
+ | getAgentSessionFoldedLogResponse403
+ | getAgentSessionFoldedLogResponse500
+) & {
+ headers: Headers;
+};
+
+export type getAgentSessionFoldedLogResponse =
+ | getAgentSessionFoldedLogResponseSuccess
+ | getAgentSessionFoldedLogResponseError;
+
+export const getGetAgentSessionFoldedLogUrl = (sessionId: string) => {
+ return `/agent-sessions/${sessionId}/log/folded`;
+};
+
+export const getAgentSessionFoldedLog = async (
+ sessionId: string,
+ options?: RequestInit
+): Promise<getAgentSessionFoldedLogResponse> => {
+ const res = await fetch(getGetAgentSessionFoldedLogUrl(sessionId), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: getAgentSessionFoldedLogResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as getAgentSessionFoldedLogResponse;
+};
+
/**
* @summary Rename an agent session.
*/
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionFoldedLogResponse.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionFoldedLogResponse.ts
new file mode 100644
index 0000000000..da168b77bd
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionFoldedLogResponse.ts
@@ -0,0 +1,23 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+import type { AgentSessionFoldedLogResponseMessagesItem } from './agentSessionFoldedLogResponseMessagesItem';
+import type { SessionBot } from './sessionBot';
+
+/**
+ * Response body for one session's folded log.
+ */
+export interface AgentSessionFoldedLogResponse {
+ /** The agent whose messages these are; it sent every agent message. */
+ bot: SessionBot;
+ /** The conversation, oldest first: prompts, replies, tool calls and their
+results, plans, permission requests and how each turn ended. Each
+element is a `FoldedMessage` from the fold's TypeScript contract,
+which the SDK exports; the schema is opaque here because those types
+are described with specta rather than utoipa. */
+ messages: AgentSessionFoldedLogResponseMessagesItem[];
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionFoldedLogResponseMessagesItem.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionFoldedLogResponseMessagesItem.ts
new file mode 100644
index 0000000000..b6a942dc26
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/agentSessionFoldedLogResponseMessagesItem.ts
@@ -0,0 +1,10 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+export type AgentSessionFoldedLogResponseMessagesItem = {
+ [key: string]: unknown;
+};
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
index 9eb82af32f..e49dbe3ba9 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
@@ -62,6 +62,8 @@ export * from './agentSessionChangesPatchResponse';
export * from './agentSessionChangesResponse';
export * from './agentSessionChangesResponseAttempt';
export * from './agentSessionChangesResponseChangeset';
+export * from './agentSessionFoldedLogResponse';
+export * from './agentSessionFoldedLogResponseMessagesItem';
export * from './agentSessionLogEntryDto';
export * from './agentSessionLogEntryDtoAllOf';
export * from './agentSessionLogEntryDtoAllOfUserId';
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
index 6fa8876338..acf218e6cd 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
+++ b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json
@@ -1490,6 +1490,68 @@
}
}
},
+ "/agent-sessions/{session_id}/log/folded": {
+ "get": {
+ "tags": ["agent-sessions"],
+ "summary": "One agent session's history folded into renderable messages: the same\nfold the web client runs over [`get_agent_session_log_handler`]'s frames.",
+ "description": "For readers that do not run the fold themselves, such as SDK programs and\nagents reading another session's history.",
+ "operationId": "get_agent_session_folded_log",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AgentSessionFoldedLogResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/agent-sessions/{session_id}/name": {
"put": {
"tags": ["agent-sessions"],
@@ -3204,6 +3266,24 @@
}
}
},
+ "AgentSessionFoldedLogResponse": {
+ "type": "object",
+ "description": "Response body for one session's folded log.",
+ "required": ["bot", "messages"],
+ "properties": {
+ "bot": {
+ "$ref": "#/components/schemas/SessionBot",
+ "description": "The agent whose messages these are; it sent every agent message."
+ },
+ "messages": {
+ "type": "array",
+ "items": {
+ "type": "object"
+ },
+ "description": "The conversation, oldest first: prompts, replies, tool calls and their\nresults, plans, permission requests and how each turn ended. Each\nelement is a `FoldedMessage` from the fold's TypeScript contract,\nwhich the SDK exports; the schema is opaque here because those types\nare described with specta rather than utoipa."
+ }
+ }
+ },
"AgentSessionLogEntryDto": {
"allOf": [
{
diff --git a/crates/agent_code_mode/src/domain/documentation.json b/crates/agent_code_mode/src/domain/documentation.json
index 88d733e0f7..472ac11b64 100644
--- a/crates/agent_code_mode/src/domain/documentation.json
+++ b/crates/agent_code_mode/src/domain/documentation.json
@@ -1,9 +1,9 @@
[
{
"name": "agentSessions",
- "description": "Create and inspect agent sessions, saved code executions, and editable email or calendar review stacks.",
+ "description": "Create and inspect agent sessions, read any viewable session's history as folded messages (`session.foldedLog()`), saved code executions, and editable email or calendar review stacks.",
"overview": "<!-- src/entities/agent-sessions/agent-session/type-aliases/CreateManagedSessionOptions.md -->\n# Type Alias: CreateManagedSessionOptions\n\n> **CreateManagedSessionOptions** = \\{ `instructions?`: `string`; `model?`: `string`; `prompt?`: `string`; `repoBranch?`: `string`; `repoUrl?`: `string`; \\}\n\nWhat a managed session is created with.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-instructions\"></a> `instructions?` | `string` | Instructions the session's runtime works under, fixed for its life. |\n| <a id=\"property-model\"></a> `model?` | `string` | The model the session runs on, instead of its persona's. The session's model from creation, read back as [AgentSession.model](../classes/AgentSession.md#property-model). |\n| <a id=\"property-prompt\"></a> `prompt?` | `string` | First prompt to deliver once the session is running. |\n| <a id=\"property-repobranch\"></a> `repoBranch?` | `string` | The branch the session starts on; needs `repoUrl`. Omitted, the repository's default branch. |\n| <a id=\"property-repourl\"></a> `repoUrl?` | `string` | The repository the session works on, as one of the URLs [AgentSession.repositories](../classes/AgentSession.md#repositories) lists for the caller. Omitted, the runtime chooses from the prompt. Honored for Cursor sessions. |\n\n\n<!-- src/entities/agent-sessions/agent-session/type-aliases/SelectableRepository.md -->\n# Type Alias: SelectableRepository\n\n> **SelectableRepository** = \\{ `defaultBranch?`: `string`; `url`: `string`; \\}\n\nA GitHub repository the caller can point a managed session at.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-defaultbranch\"></a> `defaultBranch?` | `string` | The branch its clones check out, and where a session starts unless `createManaged` names another. Absent for a repository with no commits. |\n| <a id=\"property-url\"></a> `url` | `string` | The canonical `https://github.com/owner/name` URL, as `createManaged` takes it. |\n\n\n<!-- src/entities/agent-sessions/namespace/classes/AgentSessionNamespace.md -->\n# Class: AgentSessionNamespace\n\nEntry point for coding-agent sessions.\n\n## Constructors\n\n### Constructor\n\n> **new AgentSessionNamespace**(`client`): `AgentSessionNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`AgentSessionNamespace`\n\n## Methods\n\n### byId()\n\n> **byId**(`id`): [`AgentSession`](../../agent-session/classes/AgentSession.md)\n\nA handle to an agent session by id. Details load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`AgentSession`](../../agent-session/classes/AgentSession.md)\n\n***\n\n### codingPreferences()\n\n> **codingPreferences**(): `Promise`\\<[`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md)\\>\n\nWhat the caller's new coding sessions are told to do beyond their assignment.\n\n#### Returns\n\n`Promise`\\<[`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md)\\>\n\n***\n\n### createManaged()\n\n> **createManaged**(`opts?`): `Promise`\\<[`AgentSession`](../../agent-session/classes/AgentSession.md)\\>\n\nCreate a managed agent session.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | [`CreateManagedSessionOptions`](../../agent-session/type-aliases/CreateManagedSessionOptions.md) |\n\n#### Returns\n\n`Promise`\\<[`AgentSession`](../../agent-session/classes/AgentSession.md)\\>\n\n***\n\n### defaultSandboxSize()\n\n> **defaultSandboxSize**(): `Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\>\n\nThe caller's default sandbox size for new `@coder` sessions.\n\n#### Returns\n\n`Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\>\n\n***\n\n### forPullRequest()\n\n> **forPullRequest**(`url`): `Promise`\\<[`AgentSession`](../../agent-session/classes/AgentSession.md)[]\\>\n\nThe sessions linked to the GitHub pull request at `url` that the caller\ncan view.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `url` | `string` |\n\n#### Returns\n\n`Promise`\\<[`AgentSession`](../../agent-session/classes/AgentSession.md)[]\\>\n\n***\n\n### repositories()\n\n> **repositories**(): `Promise`\\<[`SelectableRepository`](../../agent-session/type-aliases/SelectableRepository.md)[]\\>\n\nThe GitHub repositories the caller can hand a managed session, with the\nbranch each one's sessions start on by default.\n\n#### Returns\n\n`Promise`\\<[`SelectableRepository`](../../agent-session/type-aliases/SelectableRepository.md)[]\\>\n\n***\n\n### repositoryBranches()\n\n> **repositoryBranches**(`repoUrl`): `Promise`\\<`string`[]\\>\n\nBranch names on one repository the caller can start a managed session\nfrom. `repoUrl` is one of the URLs [AgentSessionNamespace.repositories](#repositories)\nlists.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `repoUrl` | `string` |\n\n#### Returns\n\n`Promise`\\<`string`[]\\>\n\n***\n\n### setCodingPreferences()\n\n> **setCodingPreferences**(`preferences`): `Promise`\\<[`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md)\\>\n\nReplace the caller's coding preferences.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `preferences` | [`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md) |\n\n#### Returns\n\n`Promise`\\<[`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md)\\>\n\n***\n\n### setDefaultSandboxSize()\n\n> **setDefaultSandboxSize**(`size`): `Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\>\n\nSet the caller's default sandbox size for the next `@coder` mention.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `size` | [`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md) |\n\n#### Returns\n\n`Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\>\n",
- "documentation": "# Macro SDK: agentSessions\n\nGenerated by TypeDoc. Paths below refer to the canonical Markdown hierarchy. Other entity handles are documented in their named section; request core for shared SDK helpers.\n\n<!-- generated/agent-harness/types.gen/type-aliases/AccessLevel.md -->\n# Type Alias: AccessLevel\n\n> **AccessLevel** = `\"view\"` \\| `\"comment\"` \\| `\"edit\"` \\| `\"owner\"`\n\nOrdered from least to most access top -> bottom\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentAction.md -->\n# Type Alias: AgentAction\n\n> **AgentAction** = [`AgentPromptAction`](AgentPromptAction.md) & \\{ `type`: `\"prompt\"`; \\} \\| [`AgentSetModelAction`](AgentSetModelAction.md) & \\{ `type`: `\"setModel\"`; \\} \\| [`AgentSetConfigOptionAction`](AgentSetConfigOptionAction.md) & \\{ `type`: `\"setConfigOption\"`; \\} \\| \\{ `type`: `\"compact\"`; \\} \\| \\{ `type`: `\"stop\"`; \\} \\| [`AgentRespondElicitationAction`](AgentRespondElicitationAction.md) & \\{ `type`: `\"respondElicitation\"`; \\} \\| [`AgentPermissionAction`](AgentPermissionAction.md) & \\{ `type`: `\"respondToPermission\"`; \\}\n\nOne thing a caller wants an agent to do.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentActionId.md -->\n# Type Alias: AgentActionId\n\n> **AgentActionId** = `string`\n\nIdentifies one accepted [`AgentAction`] end to end: returned by the\ncontrol endpoint, written as the JSON-RPC request id on the action's wire\nframe, and read back off that frame as `request_id` on the folded message\nit derives.\n\nA v7 uuid, so ids sort by mint time. Minted by the server at accept time,\nor by a client that speculated the action and named it in the control\nrequest - either way the server is the only writer of runtime-bound\nframes, so a uuid-shaped request id remains the whole ownership test. The\nmachine's own handshake request ids (`agent_session:{session}:{n}`) are\nnot uuids and stay `None`.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentConversationDto.md -->\n# Type Alias: AgentConversationDto\n\n> **AgentConversationDto** = \\{ `available`: `boolean`; `avatarUrl?`: `string` \\| `null`; `botId`: `string`; `channelId`: `string`; `name`: `string`; `sessions`: [`AgentConversationSessionDto`](AgentConversationSessionDto.md)[]; `settingsChanged`: `boolean`; `turns`: [`AgentConversationTurnDto`](AgentConversationTurnDto.md)[]; \\}\n\nAn agent's conversation in a channel, as the person it is with sees it.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-available\"></a> `available` | `boolean` | Whether the caller may currently send a new prompt. |\n| <a id=\"property-avatarurl\"></a> `avatarUrl?` | `string` \\| `null` | Optional persona avatar. |\n| <a id=\"property-botid\"></a> `botId` | `string` | Persona id (without the bot principal prefix). |\n| <a id=\"property-channelid\"></a> `channelId` | `string` | The channel containing the visible transcript. |\n| <a id=\"property-name\"></a> `name` | `string` | Persona's historical display name. |\n| <a id=\"property-sessions\"></a> `sessions` | [`AgentConversationSessionDto`](AgentConversationSessionDto.md)[] | The sessions the conversation has run on, oldest first. |\n| <a id=\"property-settingschanged\"></a> `settingsChanged` | `boolean` | Whether new persona settings are available to adopt explicitly. |\n| <a id=\"property-turns\"></a> `turns` | [`AgentConversationTurnDto`](AgentConversationTurnDto.md)[] | Persistent state of each accepted message and its current attempt. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentConversationSessionDto.md -->\n# Type Alias: AgentConversationSessionDto\n\n> **AgentConversationSessionDto** = \\{ `createdAt`: `string`; `isCurrent`: `boolean`; `sessionId`: `string`; \\}\n\nOne session a conversation has run on; every channel message stays visible.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | When the session began. |\n| <a id=\"property-iscurrent\"></a> `isCurrent` | `boolean` | Whether this is the current agent context. |\n| <a id=\"property-sessionid\"></a> `sessionId` | `string` | Session whose controls and live events belong to this context. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentConversationTurnDto.md -->\n# Type Alias: AgentConversationTurnDto\n\n> **AgentConversationTurnDto** = \\{ `actionId`: `string`; `createdAt`: `string`; `replyMessageId?`: `string` \\| `null`; `retryable`: `boolean`; `sessionId`: `string`; `sourceMessageId`: `string`; `state`: [`ConversationTurnState`](ConversationTurnState.md); \\}\n\nExecution status without exposing the persona prompt or stored credentials.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-actionid\"></a> `actionId` | `string` | Current runtime attempt identity. |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | When the source message was first accepted. |\n| <a id=\"property-replymessageid\"></a> `replyMessageId?` | `string` \\| `null` | The associated agent reply, if it has been posted. |\n| <a id=\"property-retryable\"></a> `retryable` | `boolean` | Whether Retry would be accepted now. A failed attempt is not retryable until its reply says how it ended. |\n| <a id=\"property-sessionid\"></a> `sessionId` | `string` | Session carrying this turn. |\n| <a id=\"property-sourcemessageid\"></a> `sourceMessageId` | `string` | The user's message in the channel timeline. |\n| <a id=\"property-state\"></a> `state` | [`ConversationTurnState`](ConversationTurnState.md) | Durable execution state. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentPermissionAction.md -->\n# Type Alias: AgentPermissionAction\n\n> **AgentPermissionAction** = \\{ `answer`: [`PermissionAnswer`](PermissionAnswer.md); `requestId`: `unknown`; \\}\n\nA user's answer to the agent's `session/request_permission`.\n\nUnlike every other action this is not a new request but the reply to one\nthe agent made, so it carries the agent's own request id rather than\nreceiving a server-minted one.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-answer\"></a> `answer` | [`PermissionAnswer`](PermissionAnswer.md) | What the user decided. |\n| <a id=\"property-requestid\"></a> `requestId` | `unknown` | The agent's JSON-RPC request id, echoed verbatim from the folded permission part. A string or a number on the wire; agents mint both, and `7` does not answer `\"7\"`. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentPromptAction.md -->\n# Type Alias: AgentPromptAction\n\n> **AgentPromptAction** = \\{ `attachments?`: [`PromptAttachment`](PromptAttachment.md)[]; `prompt`: `string`; \\}\n\nAsk the agent to work on something.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attachments\"></a> `attachments?` | [`PromptAttachment`](PromptAttachment.md)[] | Files the prompt refers to, in the order the user attached them. Delivered after the text as one `resource_link` block each. |\n| <a id=\"property-prompt\"></a> `prompt` | `string` | What to tell the agent. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentRespondElicitationAction.md -->\n# Type Alias: AgentRespondElicitationAction\n\n> **AgentRespondElicitationAction** = [`ElicitationAnswer`](ElicitationAnswer.md) & \\{ `requestId`: [`ElicitationRequestId`](ElicitationRequestId.md); \\}\n\nAnswer an elicitation the agent is waiting on.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `requestId` | [`ElicitationRequestId`](ElicitationRequestId.md) | The agent's `elicitation/create` request id - not an [`AgentActionId`], because the agent minted it. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentSessionChangesResponse.md -->\n# Type Alias: AgentSessionChangesResponse\n\n> **AgentSessionChangesResponse** = \\{ `attempt?`: `null` \\| [`CaptureAttemptDto`](CaptureAttemptDto.md); `capturing`: `boolean`; `changeset?`: `null` \\| [`ChangesetDto`](ChangesetDto.md); \\}\n\nResponse body for `GET /agent-sessions/{session_id}/changes`.\n\nClients deserialize this, so both derives are used.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attempt\"></a> `attempt?` | `null` \\| [`CaptureAttemptDto`](CaptureAttemptDto.md) | - |\n| <a id=\"property-capturing\"></a> `capturing` | `boolean` | A capture is running right now. |\n| <a id=\"property-changeset\"></a> `changeset?` | `null` \\| [`ChangesetDto`](ChangesetDto.md) | - |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentSessionLogEntryDto.md -->\n# Type Alias: AgentSessionLogEntryDto\n\n> **AgentSessionLogEntryDto** = [`LogFrameDto`](LogFrameDto.md) & \\{ `createdAt`: `string`; `id`: `string`; `userId?`: `string` \\| `null`; \\}\n\nOne entry of a session's protocol log.\n\nSerializes as `{\"userId\": ..., \"direction\": ..., \"content\": ...}` - the\nframe's own two fields, flattened in beside the attribution, which is the\nsame shape a recorded session's JSONL carries. A reader can deserialize the\n`direction`/`content` pair straight back into the fold's own log type\nrather than through a transport vocabulary of its own.\n\n`agentSessionId` is not repeated per entry: every entry in a response\nbelongs to the session named once at the top.\n\n`Deserialize` is for the wire-contract tests only - nothing server-side\ndecodes its own response type.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `createdAt` | `string` | When the log recorded the frame. The frame itself carries no time, so this comes from the log row. It is what a reader has to order these against anything else it is showing beside them - the fold derives an order among the messages of one session and nothing more. |\n| `id` | `string` | Durable transport row identity; together with `createdAt`, its order cursor. |\n| `userId?` | `string` \\| `null` | The user whose action produced the frame, absent when no user did. Only prompts carry one, and only when the frame was attributed at the time - a replayed or recorded session's are anonymous. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentSessionLogResponse.md -->\n# Type Alias: AgentSessionLogResponse\n\n> **AgentSessionLogResponse** = \\{ `bot`: [`SessionBot`](SessionBot.md); `entries`: [`AgentSessionLogEntryDto`](AgentSessionLogEntryDto.md)[]; \\}\n\nResponse body for one session's raw protocol log.\n\nA wrapper rather than a bare array so that anything which is about the\nresponse rather than about a frame has somewhere to go later without\nbreaking every client.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-bot\"></a> `bot` | [`SessionBot`](SessionBot.md) | The agent whose messages the log derives. Here because a client renders those messages and cannot otherwise work out who sent them: the sender of an agent message is this session's bot, and nothing else names it. |\n| <a id=\"property-entries\"></a> `entries` | [`AgentSessionLogEntryDto`](AgentSessionLogEntryDto.md)[] | Effective history in ascending `(createdAt, id)` order. The first row is the inclusive history boundary cursor: buffered rows before it are obsolete. Reconcile snapshot overlap by row ID, never content. An empty history has no boundary or overlapping rows. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentSessionResponse.md -->\n# Type Alias: AgentSessionResponse\n\n> **AgentSessionResponse** = \\{ `acpSessionId?`: `string` \\| `null`; `botId`: `string`; `canEdit`: `boolean`; `createdAt`: `string`; `external?`: `null` \\| [`ExternalSessionResponse`](ExternalSessionResponse.md); `harness`: `string`; `id`: `string`; `instructions?`: `string` \\| `null`; `isArchived`: `boolean`; `model`: `string`; `modifiedAt`: `string`; `name`: `string`; `originatingMessageId?`: `string` \\| `null`; `ownerId`: `string`; `pullRequestUrl?`: `string` \\| `null`; `repoUrl?`: `string` \\| `null`; `sandboxSize`: [`SandboxSize`](SandboxSize.md); `status`: [`SessionStatusDto`](SessionStatusDto.md); `taskId?`: `string` \\| `null`; `threadChannelId?`: `string` \\| `null`; `threadId?`: `string` \\| `null`; `threadParent?`: `null` \\| [`MessageParent`](MessageParent.md); `workspace`: `string`; \\}\n\nResponse body describing an agent session.\n\nClients deserialize this, so both derives are used.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-acpsessionid\"></a> `acpSessionId?` | `string` \\| `null` | The ACP session id, if one exists. |\n| <a id=\"property-botid\"></a> `botId` | `string` | The bot running the agent. |\n| <a id=\"property-canedit\"></a> `canEdit` | `boolean` | Whether the caller may drive the session - prompt it, answer its questions, stop it - rather than only watch. Edit access; the creator owns the session, so a create response always says so. |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | When the session was created. |\n| <a id=\"property-external\"></a> `external?` | `null` \\| [`ExternalSessionResponse`](ExternalSessionResponse.md) | - |\n| <a id=\"property-harness\"></a> `harness` | `string` | Harness slug. |\n| <a id=\"property-id\"></a> `id` | `string` | The session id. |\n| <a id=\"property-instructions\"></a> `instructions?` | `string` \\| `null` | Instructions the session's runtime works under, when any were stated at creation. Absent otherwise, so existing payloads are unchanged. |\n| <a id=\"property-isarchived\"></a> `isArchived` | `boolean` | Whether the session is archived and read-only. |\n| <a id=\"property-model\"></a> `model` | `string` | Model slug. |\n| <a id=\"property-modifiedat\"></a> `modifiedAt` | `string` | When the session was last modified. |\n| <a id=\"property-name\"></a> `name` | `string` | User-facing session name. |\n| <a id=\"property-originatingmessageid\"></a> `originatingMessageId?` | `string` \\| `null` | The exact message that invoked the bot, if any. |\n| <a id=\"property-ownerid\"></a> `ownerId` | `string` | The user who created and owns the session. |\n| <a id=\"property-pullrequesturl\"></a> `pullRequestUrl?` | `string` \\| `null` | The session's linked pull request. |\n| <a id=\"property-repourl\"></a> `repoUrl?` | `string` \\| `null` | The repository the session works with, when one was stated. |\n| <a id=\"property-sandboxsize\"></a> `sandboxSize` | [`SandboxSize`](SandboxSize.md) | Compute tier of the managed sandbox. |\n| <a id=\"property-status\"></a> `status` | [`SessionStatusDto`](SessionStatusDto.md) | The session's status. |\n| <a id=\"property-taskid\"></a> `taskId?` | `string` \\| `null` | The Macro task the session was linked to. |\n| <a id=\"property-threadchannelid\"></a> `threadChannelId?` | `string` \\| `null` | The channel `thread_id` lives in, when the session was spawned from a channel thread. Derived from `thread_parent`. |\n| <a id=\"property-threadid\"></a> `threadId?` | `string` \\| `null` | The root message of the thread the session was created from, if any. |\n| <a id=\"property-threadparent\"></a> `threadParent?` | `null` \\| [`MessageParent`](MessageParent.md) | - |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentSetConfigOptionAction.md -->\n# Type Alias: AgentSetConfigOptionAction\n\n> **AgentSetConfigOptionAction** = \\{ `configId`: `string`; `value`: `string`; \\}\n\nAsk the agent to change one advertised select-style session setting.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-configid\"></a> `configId` | `string` | Opaque ACP config id advertised by the agent. |\n| <a id=\"property-value\"></a> `value` | `string` | Opaque select value advertised for that config option. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentSetModelAction.md -->\n# Type Alias: AgentSetModelAction\n\n> **AgentSetModelAction** = \\{ `model`: `string`; \\}\n\nAsk the agent to run on a different model from here on.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-model\"></a> `model` | `string` | The model slug the agent should switch to. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AnswerToolApprovalResponse.md -->\n# Type Alias: AnswerToolApprovalResponse\n\n> **AnswerToolApprovalResponse** = \\{ `status`: [`ToolApprovalStatusDto`](ToolApprovalStatusDto.md); \\}\n\nResponse body for answering a held tool call.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-status\"></a> `status` | [`ToolApprovalStatusDto`](ToolApprovalStatusDto.md) | Where the call stands now. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/BotId.md -->\n# Type Alias: BotId\n\n> **BotId** = `string`\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/CaptureAttemptDto.md -->\n# Type Alias: CaptureAttemptDto\n\n> **CaptureAttemptDto** = \\{ `error?`: `string` \\| `null`; `finishedAt?`: `string` \\| `null`; `outcome?`: `null` \\| [`CaptureOutcomeDto`](CaptureOutcomeDto.md); `startedAt`: `string`; \\}\n\nThe latest capture attempt.\n\nClients deserialize this, so both derives are used.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-error\"></a> `error?` | `string` \\| `null` | Why it did not capture, in a sentence the user can read. |\n| <a id=\"property-finishedat\"></a> `finishedAt?` | `string` \\| `null` | When it ended; absent while it runs. |\n| <a id=\"property-outcome\"></a> `outcome?` | `null` \\| [`CaptureOutcomeDto`](CaptureOutcomeDto.md) | - |\n| <a id=\"property-startedat\"></a> `startedAt` | `string` | When it started. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/CaptureOutcomeDto.md -->\n# Type Alias: CaptureOutcomeDto\n\n> **CaptureOutcomeDto** = `\"captured\"` \\| `\"not_ready\"` \\| `\"failed\"`\n\nHow the latest capture attempt ended, on the wire.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ChangedFileDto.md -->\n# Type Alias: ChangedFileDto\n\n> **ChangedFileDto** = \\{ `additions`: `number`; `binary`: `boolean`; `deletions`: `number`; `kind`: [`FileChangeKindDto`](FileChangeKindDto.md); `patchOmitted`: `boolean`; `path`: `string`; `previousPath?`: `string` \\| `null`; \\}\n\nOne changed file.\n\nClients deserialize this, so both derives are used.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-additions\"></a> `additions` | `number` | Lines added. |\n| <a id=\"property-binary\"></a> `binary` | `boolean` | The diff carries no text for this file. |\n| <a id=\"property-deletions\"></a> `deletions` | `number` | Lines removed. |\n| <a id=\"property-kind\"></a> `kind` | [`FileChangeKindDto`](FileChangeKindDto.md) | What happened to the file. |\n| <a id=\"property-patchomitted\"></a> `patchOmitted` | `boolean` | The file's hunks were left out of the patch to fit the size budget. |\n| <a id=\"property-path\"></a> `path` | `string` | The file's path after the change, or before it for a deletion. |\n| <a id=\"property-previouspath\"></a> `previousPath?` | `string` \\| `null` | Where a renamed file came from. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ChangesetDto.md -->\n# Type Alias: ChangesetDto\n\n> **ChangesetDto** = \\{ `additions`: `number`; `base`: [`GitRefDto`](GitRefDto.md); `capturedAt`: `string`; `deletions`: `number`; `files`: [`ChangedFileDto`](ChangedFileDto.md)[]; `head`: [`GitRefDto`](GitRefDto.md); `id`: `string`; `patchBytes`: `number`; `repository?`: `string` \\| `null`; `source`: [`ChangesetSourceDto`](ChangesetSourceDto.md); `truncated`: `boolean`; \\}\n\nOne changeset: the files a patch touches and what happened to each.\n\nClients deserialize this, so both derives are used.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-additions\"></a> `additions` | `number` | Lines added across all files. |\n| <a id=\"property-base\"></a> `base` | [`GitRefDto`](GitRefDto.md) | The side the work started from. |\n| <a id=\"property-capturedat\"></a> `capturedAt` | `string` | When the diff was taken. |\n| <a id=\"property-deletions\"></a> `deletions` | `number` | Lines removed across all files. |\n| <a id=\"property-files\"></a> `files` | [`ChangedFileDto`](ChangedFileDto.md)[] | Every changed file, in patch order. |\n| <a id=\"property-head\"></a> `head` | [`GitRefDto`](GitRefDto.md) | The side carrying the work. |\n| <a id=\"property-id\"></a> `id` | `string` | The changeset's id; a different id means different changes. |\n| <a id=\"property-patchbytes\"></a> `patchBytes` | `number` | Size of the patch the matching patch route serves; zero when nothing changed. |\n| <a id=\"property-repository\"></a> `repository?` | `string` \\| `null` | `https://github.com/owner/name`, when known. |\n| <a id=\"property-source\"></a> `source` | [`ChangesetSourceDto`](ChangesetSourceDto.md) | Where the diff was read from. |\n| <a id=\"property-truncated\"></a> `truncated` | `boolean` | Some files' hunks were left out of the patch. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ChangesetSourceDto.md -->\n# Type Alias: ChangesetSourceDto\n\n> **ChangesetSourceDto** = `\"github_pull_request\"`\n\nThe source of a changeset's diff, on the wire.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ChannelSharePermission.md -->\n# Type Alias: ChannelSharePermission\n\n> **ChannelSharePermission** = \\{ `access_level`: [`AccessLevel`](AccessLevel.md); `channel_id`: `string`; \\}\n\nThe channel share permission\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-access_level\"></a> `access_level` | [`AccessLevel`](AccessLevel.md) | The access level for the channel |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | The channel id |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md -->\n# Type Alias: CodingPreferencesBody\n\n> **CodingPreferencesBody** = \\{ `createTasks`: `boolean`; `openPullRequests`: `boolean`; \\}\n\nRequest or response body for the caller's coding preferences.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-createtasks\"></a> `createTasks` | `boolean` | Whether new coding sessions research prior work and link a Macro task. |\n| <a id=\"property-openpullrequests\"></a> `openPullRequests` | `boolean` | Whether new coding sessions deliver their work as a pull request. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ControlResponse.md -->\n# Type Alias: ControlResponse\n\n> **ControlResponse** = \\{ `actionId`: [`AgentActionId`](AgentActionId.md); `status`: [`ControlStatusDto`](ControlStatusDto.md); \\}\n\nResponse body for a control operation.\n\nClients deserialize this, so both derives are used.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-actionid\"></a> `actionId` | [`AgentActionId`](AgentActionId.md) | Matches `requestId` on the folded message this action derives once it dispatches, and names the queue entry until then. The caller's own `actionId` when it supplied one; a freshly minted id otherwise. |\n| <a id=\"property-status\"></a> `status` | [`ControlStatusDto`](ControlStatusDto.md) | Whether the action went out or waits in the queue. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ControlStatusDto.md -->\n# Type Alias: ControlStatusDto\n\n> **ControlStatusDto** = `\"sent\"` \\| `\"queued\"`\n\nWhat accepting a control operation did with it, on the wire.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ConversationTurnState.md -->\n# Type Alias: ConversationTurnState\n\n> **ConversationTurnState** = `\"queued\"` \\| `\"running\"` \\| `\"succeeded\"` \\| `\"failed\"` \\| `\"stopped\"` \\| `\"interrupted\"`\n\nThe state of one source message, retained after completion for deduplication.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/DocumentId.md -->\n# Type Alias: DocumentId\n\n> **DocumentId** = `string`\n\nA validated document identifier. Historical document ids need not be UUIDs.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ElicitationAnswer.md -->\n# Type Alias: ElicitationAnswer\n\n> **ElicitationAnswer** = \\{ `action`: `\"accept\"`; `content?`: \\{\\[`key`: `string`\\]: [`ElicitationContentValue`](ElicitationContentValue.md); \\} \\| `null`; \\} \\| \\{ `action`: `\"decline\"`; \\} \\| \\{ `action`: `\"cancel\"`; \\}\n\nWhat the user decided about an elicitation. Mirrors ACP's three actions;\nthere is no `Other` because we never originate an action we do not know.\n\n## Union Members\n\n### Type Literal\n\n\\{ `action`: `\"accept\"`; `content?`: \\{\\[`key`: `string`\\]: [`ElicitationContentValue`](ElicitationContentValue.md); \\} \\| `null`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `action` | `\"accept\"` | - |\n| `content?` | \\{\\[`key`: `string`\\]: [`ElicitationContentValue`](ElicitationContentValue.md); \\} \\| `null` | Form: the submitted values keyed by property. URL: omitted. |\n\n***\n\n### Type Literal\n\n\\{ `action`: `\"decline\"`; \\}\n\n***\n\n### Type Literal\n\n\\{ `action`: `\"cancel\"`; \\}\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ElicitationContentValue.md -->\n# Type Alias: ElicitationContentValue\n\n> **ElicitationContentValue** = `string` \\| `boolean` \\| `number` \\| `number` \\| `string`[]\n\nA value ACP accepts in an elicitation answer.\n\nMirrors ACP's `ElicitationContentValue` so that the contract a caller\nanswers against is the closed union ACP will accept, rather than arbitrary\nJSON narrowed on the way out. An object, a null, or a mixed array is\nrefused when the request is deserialized - where the caller learns of it -\ninstead of at send time, when the elicitation slot has already been\nreleased.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ElicitationRequestId.md -->\n# Type Alias: ElicitationRequestId\n\n> **ElicitationRequestId** = `number` \\| `string`\n\nThe JSON-RPC id of an agent's `elicitation/create` request, carried whole\nso the answer echoes exactly what the agent sent.\n\nAgents pick these, not us: Claude Code counts from `0`, others use\nstrings. `null` is not a legal id for a request that expects a response,\nso it is not representable here.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ExecutionActivity.md -->\n# Type Alias: ExecutionActivity\n\n> **ExecutionActivity** = \\{ `id`: `number`; `label`: `string`; `status`: [`RecordedCallStatus`](RecordedCallStatus.md); \\}\n\nA bounded SDK operation observed during execution; not an authorization or write receipt.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `number` | Request identity within the execution. |\n| <a id=\"property-label\"></a> `label` | `string` | Server-selected label from the generated operation catalog. |\n| <a id=\"property-status\"></a> `status` | [`RecordedCallStatus`](RecordedCallStatus.md) | Observed request state; unfinished operations have unknown outcomes. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ExecutionId.md -->\n# Type Alias: ExecutionId\n\n> **ExecutionId** = `string`\n\nCaller-selected UUID persisted in tool input before execution begins.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ExecutionRecord.md -->\n# Type Alias: ExecutionRecord\n\n> **ExecutionRecord** = \\{ `activity?`: [`ExecutionActivity`](ExecutionActivity.md)[]; `activityTruncated?`: `boolean`; `calls`: [`RecordedToolCall`](RecordedToolCall.md)[]; `error?`: `string` \\| `null`; `executionId`: [`ExecutionId`](ExecutionId.md); `result?`: `unknown`; `source`: `string`; `status`: [`ExecutionStatus`](ExecutionStatus.md); \\}\n\nDurable source and final outcome, with historical bridge calls when present.\nThe full journal is not included in the model's tool result.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-activity\"></a> `activity?` | [`ExecutionActivity`](ExecutionActivity.md)[] | Advisory SDK operation activity, without arguments or response contents. |\n| <a id=\"property-activitytruncated\"></a> `activityTruncated?` | `boolean` | Additional request activity was omitted at the bounded observation limit. |\n| <a id=\"property-calls\"></a> `calls` | [`RecordedToolCall`](RecordedToolCall.md)[] | Historical bridge calls. Direct HTTP executions leave this empty. |\n| <a id=\"property-error\"></a> `error?` | `string` \\| `null` | Safe execution failure text. |\n| <a id=\"property-executionid\"></a> `executionId` | [`ExecutionId`](ExecutionId.md) | Execution identity. |\n| <a id=\"property-result\"></a> `result?` | `unknown` | JSON returned by the program, if successful. |\n| <a id=\"property-source\"></a> `source` | `string` | The submitted JavaScript module. |\n| <a id=\"property-status\"></a> `status` | [`ExecutionStatus`](ExecutionStatus.md) | Overall execution state. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ExecutionStatus.md -->\n# Type Alias: ExecutionStatus\n\n> **ExecutionStatus** = `\"running\"` \\| `\"succeeded\"` \\| `\"failed\"` \\| `\"cancelled\"` \\| `\"timed_out\"`\n\nThe recorded outcome of a program.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ExternalSessionResponse.md -->\n# Type Alias: ExternalSessionResponse\n\n> **ExternalSessionResponse** = \\{ `name?`: `string` \\| `null`; `provider`: `string`; `url?`: `string` \\| `null`; \\}\n\nThe provider-side identity of an externally-served session.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name?` | `string` \\| `null` | The provider's display name for the agent, when it reported one. |\n| <a id=\"property-provider\"></a> `provider` | `string` | Which provider serves the session, e.g. `cursor`. |\n| <a id=\"property-url\"></a> `url?` | `string` \\| `null` | The agent's page on the provider's site, for a client to link out to. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/FileChangeKindDto.md -->\n# Type Alias: FileChangeKindDto\n\n> **FileChangeKindDto** = `\"added\"` \\| `\"modified\"` \\| `\"deleted\"` \\| `\"renamed\"`\n\nWhat happened to a file, on the wire.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/GitRefDto.md -->\n# Type Alias: GitRefDto\n\n> **GitRefDto** = \\{ `name?`: `string` \\| `null`; `sha?`: `string` \\| `null`; \\}\n\nOne end of the compared range.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name?` | `string` \\| `null` | The branch name, when known. |\n| <a id=\"property-sha\"></a> `sha?` | `string` \\| `null` | The commit, when known. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/LinkShare.md -->\n# Type Alias: LinkShare\n\n> **LinkShare** = `\"PUBLIC\"` \\| `\"TEAM\"`\n\nDefines who can access an item through its share link.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/LogDirectionDto.md -->\n# Type Alias: LogDirectionDto\n\n> **LogDirectionDto** = `\"to_server\"` \\| `\"to_runtime\"`\n\nWhich way a logged frame travelled, mirroring [`Message`]'s discriminant.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/LogFrameDto.md -->\n# Type Alias: LogFrameDto\n\n> **LogFrameDto** = \\{ `content`: \\{\\[`key`: `string`\\]: `unknown`; \\}; `direction`: [`LogDirectionDto`](LogDirectionDto.md); \\}\n\nThe two fields [`AgentSessionLogEntryDto`] flattens in.\n\nSchema only. Nothing constructs one: the entry serializes through\n[`Message`], and this exists so the generated clients see `direction` and\n`content` as named fields instead of an open map. A hand-built copy could\ndrift from the fold's wire format, and the point of the endpoint is that it\ncannot - so this describes that format without being able to produce it.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-content\"></a> `content` | \\{\\[`key`: `string`\\]: `unknown`; \\} | The protocol envelope, verbatim. Opaque here: it is Agent Runtime Protocol, whose shape belongs to the fold rather than this endpoint. |\n| <a id=\"property-direction\"></a> `direction` | [`LogDirectionDto`](LogDirectionDto.md) | Which way the frame travelled. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/MessageParent.md -->\n# Type Alias: MessageParent\n\n> **MessageParent** = \\{ `id`: `string`; `type`: `\"channel\"`; \\} \\| \\{ `id`: [`DocumentId`](DocumentId.md); `type`: `\"document\"`; \\} \\| \\{ `id`: `string`; `type`: `\"initiative\"`; \\} \\| \\{ `id`: `string`; `type`: `\"crm_company\"`; \\} \\| \\{ `id`: `string`; `type`: `\"crm_contact\"`; \\} \\| \\{ `id`: `string`; `type`: `\"call\"`; \\}\n\nThe entity whose permissions and lifecycle govern a message.\n\n## Union Members\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"channel\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A channel, including direct messages. |\n| `type` | `\"channel\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: [`DocumentId`](DocumentId.md); `type`: `\"document\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | [`DocumentId`](DocumentId.md) | A document, including tasks and PDFs. |\n| `type` | `\"document\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"initiative\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | An initiative, presented as a project in the application. |\n| `type` | `\"initiative\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"crm_company\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A CRM company. |\n| `type` | `\"crm_company\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"crm_contact\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A CRM contact. |\n| `type` | `\"crm_contact\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"call\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A video call and its persistent chat thread. |\n| `type` | `\"call\"` | - |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/PermissionAnswer.md -->\n# Type Alias: PermissionAnswer\n\n> **PermissionAnswer** = \\{ `kind`: `\"selected\"`; `optionId`: `string`; \\} \\| \\{ `kind`: `\"cancelled\"`; \\}\n\nThe decision carried by an [`AgentPermissionAction`].\n\n## Union Members\n\n### Type Literal\n\n\\{ `kind`: `\"selected\"`; `optionId`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `kind` | `\"selected\"` | - |\n| `optionId` | `string` | The chosen option's id, as the agent listed it. |\n\n***\n\n### Type Literal\n\n\\{ `kind`: `\"cancelled\"`; \\}\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/PromptAttachment.md -->\n# Type Alias: PromptAttachment\n\n> **PromptAttachment** = \\{ `mimeType?`: `string` \\| `null`; `name`: `string`; `size?`: `number` \\| `null`; `uri`: `string`; \\}\n\nA file the prompt refers to, by where the agent can fetch it.\n\nMirrors ACP's `resource_link` content block, which every agent must\naccept: bytes never ride the prompt, only a URI (a static file service URL\nin practice) with enough metadata for a client to render a chip and for\nthe agent to decide whether to fetch it. Keeping the wire shape ACP-native\nmeans the harness translates without resolving anything, and the fold\nreads the same fields back off the logged frame.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-mimetype\"></a> `mimeType?` | `string` \\| `null` | The file's media type, when known. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name, typically the original file name. |\n| <a id=\"property-size\"></a> `size?` | `number` \\| `null` | Size in bytes, when known. |\n| <a id=\"property-uri\"></a> `uri` | `string` | Where the agent can fetch the file. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/PullRequestLinkSource.md -->\n# Type Alias: PullRequestLinkSource\n\n> **PullRequestLinkSource** = `\"agent\"` \\| `\"user\"`\n\nWho associated a pull request with a session.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/QueuedActionDto.md -->\n# Type Alias: QueuedActionDto\n\n> **QueuedActionDto** = \\{ `actionId`: [`AgentActionId`](AgentActionId.md); `actorUserId?`: `string` \\| `null`; `attachments?`: [`PromptAttachment`](PromptAttachment.md)[]; `createdAt`: `string`; `kind`: `string`; `prompt?`: `string` \\| `null`; \\}\n\nOne action waiting in a session's queue.\n\nClients deserialize this, so both derives are used.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-actionid\"></a> `actionId` | [`AgentActionId`](AgentActionId.md) | The id the action was accepted under. |\n| <a id=\"property-actoruserid\"></a> `actorUserId?` | `string` \\| `null` | The user who queued it, absent when a bot acted on nobody's behalf. |\n| <a id=\"property-attachments\"></a> `attachments?` | [`PromptAttachment`](PromptAttachment.md)[] | Files the prompt refers to, for prompts only. Kept through an edit, which replaces the text alone. |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | When it was accepted. |\n| <a id=\"property-kind\"></a> `kind` | `string` | What kind of action waits - `prompt` or `compact`; only turn-occupying actions are ever queued. |\n| <a id=\"property-prompt\"></a> `prompt?` | `string` \\| `null` | The prompt's raw text, present for prompts only. What an edit replaces. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/RecordedCallStatus.md -->\n# Type Alias: RecordedCallStatus\n\n> **RecordedCallStatus** = `\"running\"` \\| `\"completed\"` \\| `\"failed\"` \\| `\"unknown\"`\n\nA dispatch result; unfinished work is never reported as success.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/RecordedToolCall.md -->\n# Type Alias: RecordedToolCall\n\n> **RecordedToolCall** = \\{ `error?`: `string` \\| `null`; `id`: `string`; `input`: `unknown`; `name`: `string`; `output?`: `unknown`; `outputOmitted`: `boolean`; `status`: [`RecordedCallStatus`](RecordedCallStatus.md); \\}\n\nA real inner call, recorded by trusted dispatch for the existing renderers.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-error\"></a> `error?` | `string` \\| `null` | Safe tool failure, if one was returned. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable, execution-scoped component identity. |\n| <a id=\"property-input\"></a> `input` | `unknown` | Arguments passed to the actual tool. |\n| <a id=\"property-name\"></a> `name` | `string` | Canonical Macro tool name from the allowlisted registry. |\n| <a id=\"property-output\"></a> `output?` | `unknown` | Original tool output, retained independently of the program's return value. |\n| <a id=\"property-outputomitted\"></a> `outputOmitted` | `boolean` | Whether the response was omitted to keep the durable journal bounded. |\n| <a id=\"property-status\"></a> `status` | [`RecordedCallStatus`](RecordedCallStatus.md) | A started call that never replied has an unknown side-effect outcome. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ReviewId.md -->\n# Type Alias: ReviewId\n\n> **ReviewId** = `string`\n\nPersisted review identity.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ReviewItem.md -->\n# Type Alias: ReviewItem\n\n> **ReviewItem** = \\{ `draft`: `unknown`; `error?`: `string` \\| `null`; `id`: `string`; `result?`: `unknown`; `status`: [`ReviewItemStatus`](ReviewItemStatus.md); \\}\n\nOne editable item and its durable outcome.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-draft\"></a> `draft` | `unknown` | Validated arguments for the existing composer/action. |\n| <a id=\"property-error\"></a> `error?` | `string` \\| `null` | Failure or uncertainty description. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable item identity across stack navigation and edits. |\n| <a id=\"property-result\"></a> `result?` | `unknown` | Actual backend response, never a model assertion. |\n| <a id=\"property-status\"></a> `status` | [`ReviewItemStatus`](ReviewItemStatus.md) | Current outcome. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ReviewItemStatus.md -->\n# Type Alias: ReviewItemStatus\n\n> **ReviewItemStatus** = `\"pending\"` \\| `\"submitting\"` \\| `\"completed\"` \\| `\"dismissed\"` \\| `\"unknown\"`\n\nA review item never retries an ambiguous external result automatically.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ReviewKind.md -->\n# Type Alias: ReviewKind\n\n> **ReviewKind** = `\"email\"` \\| `\"calendar\"`\n\nThe component and action used to finish a review.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ReviewRecord.md -->\n# Type Alias: ReviewRecord\n\n> **ReviewRecord** = \\{ `executionId?`: `null` \\| [`ExecutionId`](ExecutionId.md); `id`: [`ReviewId`](ReviewId.md); `items`: [`ReviewItem`](ReviewItem.md)[]; `kind`: [`ReviewKind`](ReviewKind.md); `notificationAttemptAt?`: `number` \\| `null`; `notificationId?`: `string` \\| `null`; `presentedAt?`: `number` \\| `null`; `revision`: `number`; `sessionId`: `string`; `title`: `string`; `updatedAt`: `number`; \\}\n\nFull UI record, fetched outside the model context.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-executionid\"></a> `executionId?` | `null` \\| [`ExecutionId`](ExecutionId.md) | - |\n| <a id=\"property-id\"></a> `id` | [`ReviewId`](ReviewId.md) | Review identity. |\n| <a id=\"property-items\"></a> `items` | [`ReviewItem`](ReviewItem.md)[] | Drafts and per-item outcomes. |\n| <a id=\"property-kind\"></a> `kind` | [`ReviewKind`](ReviewKind.md) | Component kind. |\n| <a id=\"property-notificationattemptat\"></a> `notificationAttemptAt?` | `number` \\| `null` | Most recent delivery claim, allowing retry after a replica stops. |\n| <a id=\"property-notificationid\"></a> `notificationId?` | `string` \\| `null` | Stable queued-action identity until the outcome has reached the session. A failed notification may be retried without repeating external actions. |\n| <a id=\"property-presentedat\"></a> `presentedAt?` | `number` \\| `null` | Durable presentation acknowledgment, separate from user decisions. |\n| <a id=\"property-revision\"></a> `revision` | `number` | Compare-and-swap revision for edits and submissions. |\n| <a id=\"property-sessionid\"></a> `sessionId` | `string` | Owning session. |\n| <a id=\"property-title\"></a> `title` | `string` | Stack label. |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `number` | Milliseconds since epoch of the last state change. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/SandboxSize.md -->\n# Type Alias: SandboxSize\n\n> **SandboxSize** = `\"small\"` \\| `\"default\"` \\| `\"large\"`\n\nNamed compute tier for a managed sandbox.\n\nThe API and database store the name. CPU, RAM, and disk live in\n`crates/agent_harness/sandbox_sizes.json`.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/SessionBot.md -->\n# Type Alias: SessionBot\n\n> **SessionBot** = \\{ `avatarUrl?`: `string` \\| `null`; `handle`: `string`; `id`: [`BotId`](BotId.md); `name`: `string`; \\}\n\nThe agent behind a session, as much of it as rendering a message needs.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-avatarurl\"></a> `avatarUrl?` | `string` \\| `null` | Avatar, when it has one. |\n| <a id=\"property-handle\"></a> `handle` | `string` | Stable `@` handle, without a leading `@`. |\n| <a id=\"property-id\"></a> `id` | [`BotId`](BotId.md) | The bot's id. A message it sent has `\"bot\\|{id}\"` as its sender. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/SessionStatusDto.md -->\n# Type Alias: SessionStatusDto\n\n> **SessionStatusDto** = \\{ `kind`: `\"no_messages\"`; \\} \\| \\{ `event`: `string`; `kind`: `\"event\"`; \\} \\| \\{ `kind`: `\"disconnected\"`; \\}\n\nTransport representation of a session's status, mirroring\n[`SessionStatus`].\n\n## Union Members\n\n### Type Literal\n\n\\{ `kind`: `\"no_messages\"`; \\}\n\n***\n\n### Type Literal\n\n\\{ `event`: `string`; `kind`: `\"event\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `event` | `string` | The wire name of the system event, e.g. `acp_ready`. |\n| `kind` | `\"event\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `kind`: `\"disconnected\"`; \\}\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/SharePermissionV2.md -->\n# Type Alias: SharePermissionV2\n\n> **SharePermissionV2** = \\{ `channelSharePermissions?`: [`ChannelSharePermission`](ChannelSharePermission.md)[] \\| `null`; `id`: `string`; `linkShare?`: `null` \\| [`LinkShare`](LinkShare.md); `linkShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `owner`: `string`; `teamShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channelsharepermissions\"></a> `channelSharePermissions?` | [`ChannelSharePermission`](ChannelSharePermission.md)[] \\| `null` | The channel share permissions for the item |\n| <a id=\"property-id\"></a> `id` | `string` | The share permission id |\n| <a id=\"property-linkshare\"></a> `linkShare?` | `null` \\| [`LinkShare`](LinkShare.md) | - |\n| <a id=\"property-linkshareaccesslevel\"></a> `linkShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-owner\"></a> `owner` | `string` | The owner of the item |\n| <a id=\"property-teamshareaccesslevel\"></a> `teamShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ToolApprovalAnswerDto.md -->\n# Type Alias: ToolApprovalAnswerDto\n\n> **ToolApprovalAnswerDto** = `\"approve\"` \\| `\"approve_and_remember\"` \\| `\"deny\"` \\| `\"cancel\"`\n\nHow a person answers a held tool call.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ToolApprovalStatusDto.md -->\n# Type Alias: ToolApprovalStatusDto\n\n> **ToolApprovalStatusDto** = `\"pending\"` \\| `\"approved\"` \\| `\"denied\"` \\| `\"cancelled\"` \\| `\"expired\"`\n\nWhere a held tool call stands once answered.\n\n\n<!-- generated/calendar/types.gen/type-aliases/EventTime.md -->\n# Type Alias: EventTime\n\n> **EventTime** = \\{ `endsAt`: `string`; `kind`: `\"timed\"`; `startsAt`: `string`; `timeZone?`: `string` \\| `null`; \\} \\| \\{ `endDate`: `string`; `kind`: `\"allDay\"`; `startDate`: `string`; \\}\n\nThe mutually exclusive time shape of a calendar event.\n\nFields are renamed per variant rather than with `rename_all_fields`\nbecause utoipa only honors variant-level serde renames when it\nderives the OpenAPI schema.\n\n## Union Members\n\n### Type Literal\n\n\\{ `endsAt`: `string`; `kind`: `\"timed\"`; `startsAt`: `string`; `timeZone?`: `string` \\| `null`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `endsAt` | `string` | Exclusive end instant; equal to the start for an imported point event. |\n| `kind` | `\"timed\"` | - |\n| `startsAt` | `string` | Inclusive start instant. |\n| `timeZone?` | `string` \\| `null` | Original IANA time-zone identifier, when supplied. |\n\n***\n\n### Type Literal\n\n\\{ `endDate`: `string`; `kind`: `\"allDay\"`; `startDate`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `endDate` | `string` | Exclusive local end date. |\n| `kind` | `\"allDay\"` | - |\n| `startDate` | `string` | Inclusive local start date. |\n\n\n<!-- src/entities/agent-sessions/agent-session/classes/AgentSession.md -->\n# Class: AgentSession\n\nA managed or externally hosted coding-agent session.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`AgentSessionResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionResponse.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-access\"></a> `access` | `readonly` | [`EntityAccess`](../../../sharing/access/classes/EntityAccess.md) | Access requests and direct user grants. | - |\n| <a id=\"property-codeexecutions\"></a> `codeExecutions` | `readonly` | \\{ `byId`: (`id`) => [`CodeExecution`](../../code-execution/classes/CodeExecution.md); \\} | Saved code executions scoped to this session. Handle construction makes no request. | - |\n| `codeExecutions.byId` | `public` | (`id`) => [`CodeExecution`](../../code-execution/classes/CodeExecution.md) | - | - |\n| <a id=\"property-createdat\"></a> `createdAt` | `readonly` | () => `Promise`\\<`string`\\> | When the session was created. | - |\n| <a id=\"property-harness\"></a> `harness` | `readonly` | () => `Promise`\\<`string`\\> | The agent harness implementation serving the session. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-instructions\"></a> `instructions` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Instructions the session's runtime works under, when any were stated at creation. Fixed for the session's life. | - |\n| <a id=\"property-isarchived\"></a> `isArchived` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether the session is archived and read-only. | - |\n| <a id=\"property-model\"></a> `model` | `readonly` | () => `Promise`\\<`string`\\> | The model currently configured for the session. | - |\n| <a id=\"property-modifiedat\"></a> `modifiedAt` | `readonly` | () => `Promise`\\<`string`\\> | When the session was last modified. | - |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | The session's user-facing display name. | - |\n| <a id=\"property-repourl\"></a> `repoUrl` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | The repository the agent works with, when one was supplied. | - |\n| <a id=\"property-reviews\"></a> `reviews` | `readonly` | \\{ `byId`: (`id`) => [`SessionReview`](../../review/classes/SessionReview.md); `create`: (`input`) => `Promise`\\<[`SessionReview`](../../review/classes/SessionReview.md)\\>; \\} | Persisted reviews scoped to this session, with or without a code execution. | - |\n| `reviews.byId` | `public` | (`id`) => [`SessionReview`](../../review/classes/SessionReview.md) | - | - |\n| `reviews.create` | `public` | (`input`) => `Promise`\\<[`SessionReview`](../../review/classes/SessionReview.md)\\> | - | - |\n| <a id=\"property-sandboxsize\"></a> `sandboxSize` | `readonly` | () => `Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\> | Compute tier of the managed sandbox. | - |\n| <a id=\"property-status\"></a> `status` | `readonly` | () => `Promise`\\<[`SessionStatusDto`](../../../../../generated/agent-harness/types.gen/type-aliases/SessionStatusDto.md)\\> | The session's latest runtime status. | - |\n\n## Methods\n\n### archive()\n\n> **archive**(): `Promise`\\<`void`\\>\n\nArchive this session, making it read-only until unarchived.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### changes()\n\n> **changes**(): `Promise`\\<[`AgentSessionChangesResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionChangesResponse.md)\\>\n\nRead the latest captured GitHub pull request changes and capture status.\n\n#### Returns\n\n`Promise`\\<[`AgentSessionChangesResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionChangesResponse.md)\\>\n\n***\n\n### changesPatch()\n\n> **changesPatch**(): `Promise`\\<`string`\\>\n\nRead the unified diff of the latest captured changeset.\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n***\n\n### control()\n\n> **control**(`action`): `Promise`\\<[`ControlResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/ControlResponse.md)\\>\n\nSend a prompt or lifecycle operation to the live agent session.\n\nThe returned `actionId` matches `requestId` on the folded message the\naction derives once it dispatches. A `queued` status means a turn was\nrunning: the action waits in the session's queue ([queue](#queue)) and\ndispatches when that turn ends.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `action` | [`AgentAction`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentAction.md) |\n\n#### Returns\n\n`Promise`\\<[`ControlResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/ControlResponse.md)\\>\n\n***\n\n### delete()\n\n> **delete**(): `Promise`\\<`void`\\>\n\nDelete this session and any live resources it owns.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### linkPullRequest()\n\n> **linkPullRequest**(`url`): `Promise`\\<`void`\\>\n\nLink the GitHub pull request at `url` to this session. Linking one that\nis already linked changes nothing.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `url` | `string` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### log()\n\n> **log**(): `Promise`\\<[`AgentSessionLogResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionLogResponse.md)\\>\n\nRead the complete raw protocol log for this session.\n\n#### Returns\n\n`Promise`\\<[`AgentSessionLogResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionLogResponse.md)\\>\n\n***\n\n### prompt()\n\n> **prompt**(`text`, `attachments?`): `Promise`\\<[`ControlResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/ControlResponse.md)\\>\n\nSend a prompt to the session — sugar over [control](#control).\n\n`attachments` are files the prompt refers to, each by a URL the agent\ncan fetch (a static file service URL in practice); they reach the agent\nas ACP `resource_link` blocks after the text.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `text` | `string` |\n| `attachments?` | [`PromptAttachment`](../../../../../generated/agent-harness/types.gen/type-aliases/PromptAttachment.md)[] |\n\n#### Returns\n\n`Promise`\\<[`ControlResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/ControlResponse.md)\\>\n\n***\n\n### pullRequests()\n\n> **pullRequests**(): `Promise`\\<[`SessionPullRequest`](../type-aliases/SessionPullRequest.md)[]\\>\n\nThe GitHub pull requests linked to this session: the one its agent\nopened and any a person linked, oldest first.\n\n#### Returns\n\n`Promise`\\<[`SessionPullRequest`](../type-aliases/SessionPullRequest.md)[]\\>\n\n***\n\n### queue()\n\n> **queue**(): `Promise`\\<[`QueuedAction`](../../queued-action/classes/QueuedAction.md)[]\\>\n\nThe actions waiting to dispatch in this session, oldest first. Each can\nbe edited or removed until it dispatches.\n\n#### Returns\n\n`Promise`\\<[`QueuedAction`](../../queued-action/classes/QueuedAction.md)[]\\>\n\n***\n\n### refreshChanges()\n\n> **refreshChanges**(): `Promise`\\<[`AgentSessionChangesResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionChangesResponse.md)\\>\n\nRequest a fresh capture and return the current state while it runs.\n\n#### Returns\n\n`Promise`\\<[`AgentSessionChangesResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionChangesResponse.md)\\>\n\n***\n\n### rename()\n\n> **rename**(`name`): `Promise`\\<`void`\\>\n\nRename this session.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `name` | `string` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### setSandboxSize()\n\n> **setSandboxSize**(`size`): `Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\>\n\nResize this session's sandbox and remember the size as the owner's default.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `size` | [`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md) |\n\n#### Returns\n\n`Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\>\n\n***\n\n### sharePermissions()\n\n> **sharePermissions**(): `Promise`\\<[`SharePermissionV2`](../../../../../generated/agent-harness/types.gen/type-aliases/SharePermissionV2.md)\\>\n\nSharing configuration.\n\n#### Returns\n\n`Promise`\\<[`SharePermissionV2`](../../../../../generated/agent-harness/types.gen/type-aliases/SharePermissionV2.md)\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`AgentSessionResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionResponse.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`AgentSessionResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionResponse.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`AgentSessionResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionResponse.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### toolApprovalById()\n\n> **toolApprovalById**(`id`): [`ToolApproval`](../../tool-approval/classes/ToolApproval.md)\n\nConstruct an approval handle scoped to this session.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`ToolApproval`](../../tool-approval/classes/ToolApproval.md)\n\n***\n\n### unarchive()\n\n> **unarchive**(): `Promise`\\<`void`\\>\n\nRestore an archived session so it can be edited and prompted again.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### unlinkPullRequest()\n\n> **unlinkPullRequest**(`url`): `Promise`\\<`void`\\>\n\nUnlink a GitHub pull request a person linked to this session. The pull\nrequest the session's agent opened stays linked.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `url` | `string` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### updateSharePermissions()\n\n> **updateSharePermissions**(`options`): `Promise`\\<[`SharePermissionV2`](../../../../../generated/agent-harness/types.gen/type-aliases/SharePermissionV2.md)\\>\n\nReplace sharing grants.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`SharePermissionOptions`](../../../sharing/permissions/type-aliases/SharePermissionOptions.md) |\n\n#### Returns\n\n`Promise`\\<[`SharePermissionV2`](../../../../../generated/agent-harness/types.gen/type-aliases/SharePermissionV2.md)\\>\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `AgentSession`\n\nA handle to an agent session by id. Details load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`AgentSession`\n\n***\n\n### codingPreferences()\n\n> `static` **codingPreferences**(`client`): `Promise`\\<[`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md)\\>\n\nWhat the caller's new coding sessions are told to do beyond their assignment.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`Promise`\\<[`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md)\\>\n\n***\n\n### createManaged()\n\n> `static` **createManaged**(`client`, `opts?`): `Promise`\\<`AgentSession`\\>\n\nCreate a managed session, optionally delivering its first prompt.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `opts?` | [`CreateManagedSessionOptions`](../type-aliases/CreateManagedSessionOptions.md) |\n\n#### Returns\n\n`Promise`\\<`AgentSession`\\>\n\n***\n\n### defaultSandboxSize()\n\n> `static` **defaultSandboxSize**(`client`): `Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\>\n\nThe caller's default sandbox size for new `@coder` sessions.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\>\n\n***\n\n### forPullRequest()\n\n> `static` **forPullRequest**(`client`, `url`): `Promise`\\<`AgentSession`[]\\>\n\nThe sessions linked to the GitHub pull request at `url` that the caller\ncan view, oldest link first.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `url` | `string` |\n\n#### Returns\n\n`Promise`\\<`AgentSession`[]\\>\n\n***\n\n### repositories()\n\n> `static` **repositories**(`client`): `Promise`\\<[`SelectableRepository`](../type-aliases/SelectableRepository.md)[]\\>\n\nThe GitHub repositories the caller can hand a managed session: every\nrepository under an installation of Macro's GitHub App they or their\nteams made, sorted by `owner/name`. Empty when the App is installed\nnowhere they reach.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`Promise`\\<[`SelectableRepository`](../type-aliases/SelectableRepository.md)[]\\>\n\n***\n\n### repositoryBranches()\n\n> `static` **repositoryBranches**(`client`, `repoUrl`): `Promise`\\<`string`[]\\>\n\nBranch names on one repository the caller can start a managed session\nfrom, in the order GitHub listed them. Empty when the repository has\nno commits yet. `repoUrl` is one of the URLs [AgentSession.repositories](#repositories)\nlists.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `repoUrl` | `string` |\n\n#### Returns\n\n`Promise`\\<`string`[]\\>\n\n***\n\n### setCodingPreferences()\n\n> `static` **setCodingPreferences**(`client`, `preferences`): `Promise`\\<[`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md)\\>\n\nReplace the caller's coding preferences.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `preferences` | [`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md) |\n\n#### Returns\n\n`Promise`\\<[`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md)\\>\n\n***\n\n### setDefaultSandboxSize()\n\n> `static` **setDefaultSandboxSize**(`client`, `size`): `Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\>\n\nSet the caller's default sandbox size for the next `@coder` mention.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `size` | [`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md) |\n\n#### Returns\n\n`Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\>\n\n\n<!-- src/entities/agent-sessions/agent-session/type-aliases/CreateManagedSessionOptions.md -->\n# Type Alias: CreateManagedSessionOptions\n\n> **CreateManagedSessionOptions** = \\{ `instructions?`: `string`; `model?`: `string`; `prompt?`: `string`; `repoBranch?`: `string`; `repoUrl?`: `string`; \\}\n\nWhat a managed session is created with.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-instructions\"></a> `instructions?` | `string` | Instructions the session's runtime works under, fixed for its life. |\n| <a id=\"property-model\"></a> `model?` | `string` | The model the session runs on, instead of its persona's. The session's model from creation, read back as [AgentSession.model](../classes/AgentSession.md#property-model). |\n| <a id=\"property-prompt\"></a> `prompt?` | `string` | First prompt to deliver once the session is running. |\n| <a id=\"property-repobranch\"></a> `repoBranch?` | `string` | The branch the session starts on; needs `repoUrl`. Omitted, the repository's default branch. |\n| <a id=\"property-repourl\"></a> `repoUrl?` | `string` | The repository the session works on, as one of the URLs [AgentSession.repositories](../classes/AgentSession.md#repositories) lists for the caller. Omitted, the runtime chooses from the prompt. Honored for Cursor sessions. |\n\n\n<!-- src/entities/agent-sessions/agent-session/type-aliases/SelectableRepository.md -->\n# Type Alias: SelectableRepository\n\n> **SelectableRepository** = \\{ `defaultBranch?`: `string`; `url`: `string`; \\}\n\nA GitHub repository the caller can point a managed session at.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-defaultbranch\"></a> `defaultBranch?` | `string` | The branch its clones check out, and where a session starts unless `createManaged` names another. Absent for a repository with no commits. |\n| <a id=\"property-url\"></a> `url` | `string` | The canonical `https://github.com/owner/name` URL, as `createManaged` takes it. |\n\n\n<!-- src/entities/agent-sessions/agent-session/type-aliases/SessionPullRequest.md -->\n# Type Alias: SessionPullRequest\n\n> **SessionPullRequest** = \\{ `createdAt`: `string`; `githubKey`: `string`; `linkedBy?`: [`User`](../../../users/user/classes/User.md); `source`: [`PullRequestLinkSource`](../../../../../generated/agent-harness/types.gen/type-aliases/PullRequestLinkSource.md); `url`: `string`; \\}\n\nA GitHub pull request linked to a session.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | When it was linked. |\n| <a id=\"property-githubkey\"></a> `githubKey` | `string` | The pull request's `owner/repo/pull/number` key. |\n| <a id=\"property-linkedby\"></a> `linkedBy?` | [`User`](../../../users/user/classes/User.md) | Who linked it, for pull requests a person linked. |\n| <a id=\"property-source\"></a> `source` | [`PullRequestLinkSource`](../../../../../generated/agent-harness/types.gen/type-aliases/PullRequestLinkSource.md) | Whether the session's agent opened it or a person linked it. |\n| <a id=\"property-url\"></a> `url` | `string` | The pull request's GitHub URL. |\n\n\n<!-- src/entities/agent-sessions/code-execution/classes/CodeExecution.md -->\n# Class: CodeExecution\n\nA saved code execution belonging to one agent session.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`ExecutionRecord`](../../../../../generated/agent-harness/types.gen/type-aliases/ExecutionRecord.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-calls\"></a> `calls` | `readonly` | () => `Promise`\\<[`RecordedToolCall`](../../../../../generated/agent-harness/types.gen/type-aliases/RecordedToolCall.md)[]\\> | Legacy bridge calls; direct HTTP executions leave this empty. | - |\n| <a id=\"property-error\"></a> `error` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Execution failure text, when present. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-reviews\"></a> `reviews` | `readonly` | \\{ `create`: (`input`) => `Promise`\\<[`SessionReview`](../../review/classes/SessionReview.md)\\>; `list`: () => `Promise`\\<[`SessionReview`](../../review/classes/SessionReview.md)[]\\>; \\} | Persistent UI blocks, independent of the execution lifetime. | - |\n| `reviews.create` | `public` | (`input`) => `Promise`\\<[`SessionReview`](../../review/classes/SessionReview.md)\\> | - | - |\n| `reviews.list` | `public` | () => `Promise`\\<[`SessionReview`](../../review/classes/SessionReview.md)[]\\> | - | - |\n| <a id=\"property-source\"></a> `source` | `readonly` | () => `Promise`\\<`string`\\> | The submitted JavaScript module source. | - |\n| <a id=\"property-status\"></a> `status` | `readonly` | () => `Promise`\\<[`ExecutionStatus`](../../../../../generated/agent-harness/types.gen/type-aliases/ExecutionStatus.md)\\> | Saved execution state. Call refresh to observe subsequent changes. | - |\n\n## Methods\n\n### refresh()\n\n> **refresh**(): `Promise`\\<`CodeExecution`\\>\n\nReload the saved state, for example after a running execution completes.\n\n#### Returns\n\n`Promise`\\<`CodeExecution`\\>\n\n***\n\n### result()\n\n> **result**(): `Promise`\\<`unknown`\\>\n\nThe program's returned JSON; preserves an explicit null result.\n\n#### Returns\n\n`Promise`\\<`unknown`\\>\n\n***\n\n### session()\n\n> **session**(): [`AgentSession`](../../agent-session/classes/AgentSession.md)\n\nThe session this execution belongs to.\n\n#### Returns\n\n[`AgentSession`](../../agent-session/classes/AgentSession.md)\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`ExecutionRecord`](../../../../../generated/agent-harness/types.gen/type-aliases/ExecutionRecord.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`ExecutionRecord`](../../../../../generated/agent-harness/types.gen/type-aliases/ExecutionRecord.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`ExecutionRecord`](../../../../../generated/agent-harness/types.gen/type-aliases/ExecutionRecord.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `session`, `id`): `CodeExecution`\n\nConstruct a lazy execution handle within its owning session.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `session` | [`AgentSession`](../../agent-session/classes/AgentSession.md) |\n| `id` | `string` |\n\n#### Returns\n\n`CodeExecution`\n\n\n<!-- src/entities/agent-sessions/code-execution/type-aliases/CodeResult.md -->\n# Type Alias: CodeResult\n\n> **CodeResult** = \\{ `data`: [`JsonValue`](JsonValue.md); `reviews`: \\{ `id`: `string`; `kind`: `\"email\"` \\| `\"calendar\"`; \\}[]; \\}\n\nJSON data returned to the model, plus references to independently saved UI.\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-data\"></a> `data` | [`JsonValue`](JsonValue.md) |\n| <a id=\"property-reviews\"></a> `reviews` | \\{ `id`: `string`; `kind`: `\"email\"` \\| `\"calendar\"`; \\}[] |\n\n\n<!-- src/entities/agent-sessions/code-execution/type-aliases/JsonValue.md -->\n# Type Alias: JsonValue\n\n> **JsonValue** = `null` \\| `boolean` \\| `number` \\| `string` \\| `JsonValue`[] \\| \\{\\[`key`: `string`\\]: `JsonValue`; \\}\n\n\n<!-- src/entities/agent-sessions/conversation/classes/AgentConversation.md -->\n# Class: AgentConversation\n\nAn agent's conversation in one channel.\n\n## Constructors\n\n### Constructor\n\n> **new AgentConversation**(`client`, `channel`, `record`): `AgentConversation`\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `client` | `MacroClient` | - |\n| `channel` | [`Channel`](../../../channels/channel/classes/Channel.md) | Parent channel. |\n| `record` | [`AgentConversationDto`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentConversationDto.md) | - |\n\n#### Returns\n\n`AgentConversation`\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-channel\"></a> `channel` | `readonly` | [`Channel`](../../../channels/channel/classes/Channel.md) | Parent channel. |\n\n## Methods\n\n### agent()\n\n> **agent**(): [`Agent`](../../../agents/agent/classes/Agent.md)\n\nThe agent taking part.\n\n#### Returns\n\n[`Agent`](../../../agents/agent/classes/Agent.md)\n\n***\n\n### sessions()\n\n> **sessions**(): \\{ `createdAt`: `string`; `isCurrent`: `boolean`; `session`: [`AgentSession`](../../agent-session/classes/AgentSession.md); \\}[]\n\nConversation sessions with their current flag.\n\n#### Returns\n\n\\{ `createdAt`: `string`; `isCurrent`: `boolean`; `session`: [`AgentSession`](../../agent-session/classes/AgentSession.md); \\}[]\n\n***\n\n### startFresh()\n\n> **startFresh**(`session`): `Promise`\\<`void`\\>\n\nStart a fresh conversation from one of its sessions.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `session` | [`AgentSession`](../../agent-session/classes/AgentSession.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `agentId`: `string`; `channelId`: `string`; \\}\n\nSerialize scoped identity.\n\n#### Returns\n\n\\{ `agentId`: `string`; `channelId`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `agentId` | `string` |\n| `channelId` | `string` |\n\n***\n\n### turns()\n\n> **turns**(): [`ConversationTurn`](ConversationTurn.md)[]\n\nRecorded conversation turns.\n\n#### Returns\n\n[`ConversationTurn`](ConversationTurn.md)[]\n\n\n<!-- src/entities/agent-sessions/conversation/classes/ConversationTurn.md -->\n# Class: ConversationTurn\n\nOne agent conversation turn, identified by its source message.\n\n## Constructors\n\n### Constructor\n\n> **new ConversationTurn**(`client`, `conversation`, `record`): `ConversationTurn`\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `client` | `MacroClient` | - |\n| `conversation` | [`AgentConversation`](AgentConversation.md) | Parent conversation. |\n| `record` | [`AgentConversationTurnDto`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentConversationTurnDto.md) | - |\n\n#### Returns\n\n`ConversationTurn`\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-conversation\"></a> `conversation` | `readonly` | [`AgentConversation`](AgentConversation.md) | Parent conversation. |\n\n## Methods\n\n### retry()\n\n> **retry**(`actionId`): `Promise`\\<`void`\\>\n\nRetry with a caller persisted action nonce. Never retries automatically.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `actionId` | `string` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### session()\n\n> **session**(): [`AgentSession`](../../agent-session/classes/AgentSession.md)\n\nSession that handled this turn.\n\n#### Returns\n\n[`AgentSession`](../../agent-session/classes/AgentSession.md)\n\n***\n\n### source()\n\n> **source**(): [`Message`](../../../channels/message/classes/Message.md)\n\nOriginating message.\n\n#### Returns\n\n[`Message`](../../../channels/message/classes/Message.md)\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `channelId`: `string`; `sourceMessageId`: `string`; \\}\n\nSerialize scoped identity.\n\n#### Returns\n\n\\{ `channelId`: `string`; `sourceMessageId`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `channelId` | `string` |\n| `sourceMessageId` | `string` |\n\n\n<!-- src/entities/agent-sessions/namespace/classes/AgentSessionNamespace.md -->\n# Class: AgentSessionNamespace\n\nEntry point for coding-agent sessions.\n\n## Constructors\n\n### Constructor\n\n> **new AgentSessionNamespace**(`client`): `AgentSessionNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`AgentSessionNamespace`\n\n## Methods\n\n### byId()\n\n> **byId**(`id`): [`AgentSession`](../../agent-session/classes/AgentSession.md)\n\nA handle to an agent session by id. Details load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`AgentSession`](../../agent-session/classes/AgentSession.md)\n\n***\n\n### codingPreferences()\n\n> **codingPreferences**(): `Promise`\\<[`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md)\\>\n\nWhat the caller's new coding sessions are told to do beyond their assignment.\n\n#### Returns\n\n`Promise`\\<[`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md)\\>\n\n***\n\n### createManaged()\n\n> **createManaged**(`opts?`): `Promise`\\<[`AgentSession`](../../agent-session/classes/AgentSession.md)\\>\n\nCreate a managed agent session.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | [`CreateManagedSessionOptions`](../../agent-session/type-aliases/CreateManagedSessionOptions.md) |\n\n#### Returns\n\n`Promise`\\<[`AgentSession`](../../agent-session/classes/AgentSession.md)\\>\n\n***\n\n### defaultSandboxSize()\n\n> **defaultSandboxSize**(): `Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\>\n\nThe caller's default sandbox size for new `@coder` sessions.\n\n#### Returns\n\n`Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\>\n\n***\n\n### forPullRequest()\n\n> **forPullRequest**(`url`): `Promise`\\<[`AgentSession`](../../agent-session/classes/AgentSession.md)[]\\>\n\nThe sessions linked to the GitHub pull request at `url` that the caller\ncan view.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `url` | `string` |\n\n#### Returns\n\n`Promise`\\<[`AgentSession`](../../agent-session/classes/AgentSession.md)[]\\>\n\n***\n\n### repositories()\n\n> **repositories**(): `Promise`\\<[`SelectableRepository`](../../agent-session/type-aliases/SelectableRepository.md)[]\\>\n\nThe GitHub repositories the caller can hand a managed session, with the\nbranch each one's sessions start on by default.\n\n#### Returns\n\n`Promise`\\<[`SelectableRepository`](../../agent-session/type-aliases/SelectableRepository.md)[]\\>\n\n***\n\n### repositoryBranches()\n\n> **repositoryBranches**(`repoUrl`): `Promise`\\<`string`[]\\>\n\nBranch names on one repository the caller can start a managed session\nfrom. `repoUrl` is one of the URLs [AgentSessionNamespace.repositories](#repositories)\nlists.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `repoUrl` | `string` |\n\n#### Returns\n\n`Promise`\\<`string`[]\\>\n\n***\n\n### setCodingPreferences()\n\n> **setCodingPreferences**(`preferences`): `Promise`\\<[`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md)\\>\n\nReplace the caller's coding preferences.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `preferences` | [`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md) |\n\n#### Returns\n\n`Promise`\\<[`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md)\\>\n\n***\n\n### setDefaultSandboxSize()\n\n> **setDefaultSandboxSize**(`size`): `Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\>\n\nSet the caller's default sandbox size for the next `@coder` mention.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `size` | [`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md) |\n\n#### Returns\n\n`Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\>\n\n\n<!-- src/entities/agent-sessions/queued-action/classes/QueuedAction.md -->\n# Class: QueuedAction\n\nOne action waiting in an agent session's server-side queue: a prompt or a\ncompact accepted while a turn was running, dispatching when that turn\nends. Until then it can be edited (prompts only), steered, or removed; once\nit has dispatched, these actions answer 404 — there is no un-sending.\n\nList-sourced only - there is no per-action GET, only the queue snapshot -\nso this wraps whatever DTO the caller already has, the same shape\n`CrmComment` wraps a list-sourced record, rather than `MacroEntity`'s\nlazy-fetch-by-id.\n\n## Accessors\n\n### actionId\n\n#### Get Signature\n\n> **get** **actionId**(): `string`\n\nThe id the action was accepted under. Once it dispatches, this equals\n`requestId` on the folded message the action derives.\n\n##### Returns\n\n`string`\n\n***\n\n### actorUserId\n\n#### Get Signature\n\n> **get** **actorUserId**(): `string` \\| `undefined`\n\nThe user who queued it, absent when a bot acted on nobody's behalf.\n\n##### Returns\n\n`string` \\| `undefined`\n\n***\n\n### attachments\n\n#### Get Signature\n\n> **get** **attachments**(): [`PromptAttachment`](../../../../../generated/agent-harness/types.gen/type-aliases/PromptAttachment.md)[]\n\nFiles the prompt refers to; empty for a compact. Kept through an edit.\n\n##### Returns\n\n[`PromptAttachment`](../../../../../generated/agent-harness/types.gen/type-aliases/PromptAttachment.md)[]\n\n***\n\n### createdAt\n\n#### Get Signature\n\n> **get** **createdAt**(): `string`\n\nWhen the action was accepted, as an RFC 3339 timestamp.\n\n##### Returns\n\n`string`\n\n***\n\n### kind\n\n#### Get Signature\n\n> **get** **kind**(): `string`\n\n`prompt` or `compact`; only turn-occupying actions are ever queued.\n\n##### Returns\n\n`string`\n\n***\n\n### prompt\n\n#### Get Signature\n\n> **get** **prompt**(): `string` \\| `undefined`\n\nThe prompt's raw text, present for prompts only. What an edit replaces.\n\n##### Returns\n\n`string` \\| `undefined`\n\n## Methods\n\n### edit()\n\n> **edit**(`prompt`): `Promise`\\<`QueuedAction`\\>\n\nReplace this queued prompt's text before it dispatches. Returns this\nhandle for chaining; the edit endpoint answers 204, so `prompt` is\napplied locally rather than reread from a response body.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `prompt` | `string` |\n\n#### Returns\n\n`Promise`\\<`QueuedAction`\\>\n\n***\n\n### remove()\n\n> **remove**(): `Promise`\\<`void`\\>\n\nRemove this action from the queue before it dispatches.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### steer()\n\n> **steer**(): `Promise`\\<`void`\\>\n\nMove this action to the front and interrupt the current turn to run it next.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### from()\n\n> `static` **from**(`client`, `sessionId`, `dto`): `QueuedAction`\n\nWrap a queue entry already in hand (e.g. from `AgentSession.queue()`).\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `sessionId` | `string` |\n| `dto` | [`QueuedActionDto`](../../../../../generated/agent-harness/types.gen/type-aliases/QueuedActionDto.md) |\n\n#### Returns\n\n`QueuedAction`\n\n\n<!-- src/entities/agent-sessions/review/classes/ReviewItem.md -->\n# Class: ReviewItem\n\nAn item handle scopes edits and decisions to its persisted review.\n\n## Constructors\n\n### Constructor\n\n> **new ReviewItem**(`snapshot`, `actions`): `ReviewItem`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `snapshot` | [`ReviewItem`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewItem.md) |\n| `actions` | \\{ `dismiss`: () => `Promise`\\<`void`\\>; `edit`: (`draft`) => `Promise`\\<`void`\\>; `submit`: () => `Promise`\\<`void`\\>; \\} |\n| `actions.dismiss` | () => `Promise`\\<`void`\\> |\n| `actions.edit` | (`draft`) => `Promise`\\<`void`\\> |\n| `actions.submit` | () => `Promise`\\<`void`\\> |\n\n#### Returns\n\n`ReviewItem`\n\n## Accessors\n\n### draft\n\n#### Get Signature\n\n> **get** **draft**(): `unknown`\n\n##### Returns\n\n`unknown`\n\n***\n\n### id\n\n#### Get Signature\n\n> **get** **id**(): `string`\n\n##### Returns\n\n`string`\n\n***\n\n### result\n\n#### Get Signature\n\n> **get** **result**(): `unknown`\n\n##### Returns\n\n`unknown`\n\n***\n\n### status\n\n#### Get Signature\n\n> **get** **status**(): [`ReviewItemStatus`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewItemStatus.md)\n\n##### Returns\n\n[`ReviewItemStatus`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewItemStatus.md)\n\n## Methods\n\n### dismiss()\n\n> **dismiss**(): `Promise`\\<`void`\\>\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### edit()\n\n> **edit**(`draft`): `Promise`\\<`void`\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `draft` | `unknown` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### submit()\n\n> **submit**(): `Promise`\\<`void`\\>\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n\n<!-- src/entities/agent-sessions/review/classes/SessionReview.md -->\n# Class: SessionReview\n\nA persistent review remains actionable after the code execution ends.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`ReviewRecord`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewRecord.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Inherited from |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-kind\"></a> `kind` | `readonly` | () => `Promise`\\<[`ReviewKind`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewKind.md)\\> | - |\n| <a id=\"property-title\"></a> `title` | `readonly` | () => `Promise`\\<`string`\\> | - |\n\n## Methods\n\n### dismissAll()\n\n> **dismissAll**(): `Promise`\\<`void`\\>\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### items()\n\n> **items**(): `Promise`\\<[`ReviewItem`](ReviewItem.md)[]\\>\n\n#### Returns\n\n`Promise`\\<[`ReviewItem`](ReviewItem.md)[]\\>\n\n***\n\n### reference()\n\n> **reference**(): `Promise`\\<\\{ `id`: `string`; `kind`: [`ReviewKind`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewKind.md); \\}\\>\n\nCompact reference for main()'s returned reviews array.\n\n#### Returns\n\n`Promise`\\<\\{ `id`: `string`; `kind`: [`ReviewKind`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewKind.md); \\}\\>\n\n***\n\n### refresh()\n\n> **refresh**(): `Promise`\\<`SessionReview`\\>\n\n#### Returns\n\n`Promise`\\<`SessionReview`\\>\n\n***\n\n### session()\n\n> **session**(): [`AgentSession`](../../agent-session/classes/AgentSession.md)\n\n#### Returns\n\n[`AgentSession`](../../agent-session/classes/AgentSession.md)\n\n***\n\n### submitAll()\n\n> **submitAll**(): `Promise`\\<`void`\\>\n\nSubmit the saved pending drafts. Never retries a conflict or ambiguous send.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`ReviewRecord`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewRecord.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`ReviewRecord`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewRecord.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`ReviewRecord`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewRecord.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `session`, `id`): `SessionReview`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `session` | [`AgentSession`](../../agent-session/classes/AgentSession.md) |\n| `id` | `string` |\n\n#### Returns\n\n`SessionReview`\n\n***\n\n### create()\n\n> `static` **create**(`client`, `execution`, `input`): `Promise`\\<`SessionReview`\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `execution` | [`CodeExecution`](../../code-execution/classes/CodeExecution.md) |\n| `input` | [`CreateReviewOptions`](../type-aliases/CreateReviewOptions.md) |\n\n#### Returns\n\n`Promise`\\<`SessionReview`\\>\n\n***\n\n### createForSession()\n\n> `static` **createForSession**(`client`, `session`, `input`, `execution?`): `Promise`\\<`SessionReview`\\>\n\nPresent a review in a session without requiring a code execution.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `session` | [`AgentSession`](../../agent-session/classes/AgentSession.md) |\n| `input` | [`CreateReviewOptions`](../type-aliases/CreateReviewOptions.md) |\n| `execution?` | [`CodeExecution`](../../code-execution/classes/CodeExecution.md) |\n\n#### Returns\n\n`Promise`\\<`SessionReview`\\>\n\n***\n\n### fromRecord()\n\n> `static` **fromRecord**(`client`, `session`, `record`): `SessionReview`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `session` | [`AgentSession`](../../agent-session/classes/AgentSession.md) |\n| `record` | [`ReviewRecord`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewRecord.md) |\n\n#### Returns\n\n`SessionReview`\n\n***\n\n### list()\n\n> `static` **list**(`client`, `execution`): `Promise`\\<`SessionReview`[]\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `execution` | [`CodeExecution`](../../code-execution/classes/CodeExecution.md) |\n\n#### Returns\n\n`Promise`\\<`SessionReview`[]\\>\n\n\n<!-- src/entities/agent-sessions/review/type-aliases/CreateReviewOptions.md -->\n# Type Alias: CreateReviewOptions\n\n> **CreateReviewOptions** = \\{ `drafts`: [`ReviewEmailDraft`](ReviewEmailDraft.md)[]; `kind`: `\"email\"`; `title`: `string`; \\} \\| \\{ `drafts`: [`ReviewCalendarDraft`](ReviewCalendarDraft.md)[]; `kind`: `\"calendar\"`; `title`: `string`; \\}\n\n\n<!-- src/entities/agent-sessions/review/type-aliases/ReviewCalendarDraft.md -->\n# Type Alias: ReviewCalendarDraft\n\n> **ReviewCalendarDraft** = \\{ `addGoogleMeet?`: `boolean`; `addMacroCall?`: `boolean`; `attendees?`: \\{ `email`: `string`; `isOptional?`: `boolean`; \\}[]; `calendarId?`: `string` \\| `null`; `description?`: `string` \\| `null`; `eventType?`: `\"default\"` \\| `\"out_of_office\"`; `location?`: `string` \\| `null`; `outOfOffice?`: \\{ `autoDeclineMode?`: `\"decline_none\"` \\| `\"decline_all\"` \\| `\"decline_new_only\"`; `declineMessage?`: `string` \\| `null`; \\} \\| `null`; `recurrenceLines?`: `string`[]; `reminders?`: \\{ `overrides?`: \\{ `method`: `string`; `minutes`: `number`; \\}[]; `useDefault`: `boolean`; \\} \\| `null`; `time`: [`EventTime`](../../../../../generated/calendar/types.gen/type-aliases/EventTime.md); `title`: `string`; \\}\n\nCalendar drafts use the existing calendar composer and creation action.\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-addgooglemeet\"></a> `addGoogleMeet?` | `boolean` |\n| <a id=\"property-addmacrocall\"></a> `addMacroCall?` | `boolean` |\n| <a id=\"property-attendees\"></a> `attendees?` | \\{ `email`: `string`; `isOptional?`: `boolean`; \\}[] |\n| <a id=\"property-calendarid\"></a> `calendarId?` | `string` \\| `null` |\n| <a id=\"property-description\"></a> `description?` | `string` \\| `null` |\n| <a id=\"property-eventtype\"></a> `eventType?` | `\"default\"` \\| `\"out_of_office\"` |\n| <a id=\"property-location\"></a> `location?` | `string` \\| `null` |\n| <a id=\"property-outofoffice\"></a> `outOfOffice?` | \\{ `autoDeclineMode?`: `\"decline_none\"` \\| `\"decline_all\"` \\| `\"decline_new_only\"`; `declineMessage?`: `string` \\| `null`; \\} \\| `null` |\n| <a id=\"property-recurrencelines\"></a> `recurrenceLines?` | `string`[] |\n| <a id=\"property-reminders\"></a> `reminders?` | \\{ `overrides?`: \\{ `method`: `string`; `minutes`: `number`; \\}[]; `useDefault`: `boolean`; \\} \\| `null` |\n| <a id=\"property-time\"></a> `time` | [`EventTime`](../../../../../generated/calendar/types.gen/type-aliases/EventTime.md) |\n| <a id=\"property-title\"></a> `title` | `string` |\n\n\n<!-- src/entities/agent-sessions/review/type-aliases/ReviewEmailDraft.md -->\n# Type Alias: ReviewEmailDraft\n\n> **ReviewEmailDraft** = \\{ `attachments?`: \\{ `documentId`: `string`; \\}[]; `bcc?`: \\{ `email`: `string`; `name?`: `string` \\| `null`; \\}[]; `body`: `string`; `cc?`: \\{ `email`: `string`; `name?`: `string` \\| `null`; \\}[]; `includeSignature?`: `boolean` \\| `null`; `replyingToId?`: `string` \\| `null`; `subject`: `string`; `to`: \\{ `email`: `string`; `name?`: `string` \\| `null`; \\}[]; \\}\n\nMarkdown is rendered by the ordinary email action; the UI can edit each draft.\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-attachments\"></a> `attachments?` | \\{ `documentId`: `string`; \\}[] |\n| <a id=\"property-bcc\"></a> `bcc?` | \\{ `email`: `string`; `name?`: `string` \\| `null`; \\}[] |\n| <a id=\"property-body\"></a> `body` | `string` |\n| <a id=\"property-cc\"></a> `cc?` | \\{ `email`: `string`; `name?`: `string` \\| `null`; \\}[] |\n| <a id=\"property-includesignature\"></a> `includeSignature?` | `boolean` \\| `null` |\n| <a id=\"property-replyingtoid\"></a> `replyingToId?` | `string` \\| `null` |\n| <a id=\"property-subject\"></a> `subject` | `string` |\n| <a id=\"property-to\"></a> `to` | \\{ `email`: `string`; `name?`: `string` \\| `null`; \\}[] |\n\n\n<!-- src/entities/agent-sessions/tool-approval/classes/ToolApproval.md -->\n# Class: ToolApproval\n\nA permission request scoped to its originating agent session.\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `readonly` | `string` | Approval identity. |\n| <a id=\"property-session\"></a> `session` | `readonly` | [`AgentSession`](../../agent-session/classes/AgentSession.md) | Owning session. |\n\n## Methods\n\n### answer()\n\n> **answer**(`answer`): `Promise`\\<[`AnswerToolApprovalResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AnswerToolApprovalResponse.md)\\>\n\nAnswer the approval using the generated discriminated answer contract.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `answer` | [`ToolApprovalAnswerDto`](../../../../../generated/agent-harness/types.gen/type-aliases/ToolApprovalAnswerDto.md) |\n\n#### Returns\n\n`Promise`\\<[`AnswerToolApprovalResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AnswerToolApprovalResponse.md)\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `id`: `string`; `sessionId`: `string`; \\}\n\nSerialize scoped identity only.\n\n#### Returns\n\n\\{ `id`: `string`; `sessionId`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `id` | `string` |\n| `sessionId` | `string` |\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `session`, `id`): `ToolApproval`\n\nConstruct a scoped approval handle.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `session` | [`AgentSession`](../../agent-session/classes/AgentSession.md) |\n| `id` | `string` |\n\n#### Returns\n\n`ToolApproval`\n"
+ "documentation": "# Macro SDK: agentSessions\n\nGenerated by TypeDoc. Paths below refer to the canonical Markdown hierarchy. Other entity handles are documented in their named section; request core for shared SDK helpers.\n\n<!-- generated/agent-harness/types.gen/type-aliases/AccessLevel.md -->\n# Type Alias: AccessLevel\n\n> **AccessLevel** = `\"view\"` \\| `\"comment\"` \\| `\"edit\"` \\| `\"owner\"`\n\nOrdered from least to most access top -> bottom\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentAction.md -->\n# Type Alias: AgentAction\n\n> **AgentAction** = [`AgentPromptAction`](AgentPromptAction.md) & \\{ `type`: `\"prompt\"`; \\} \\| [`AgentSetModelAction`](AgentSetModelAction.md) & \\{ `type`: `\"setModel\"`; \\} \\| [`AgentSetConfigOptionAction`](AgentSetConfigOptionAction.md) & \\{ `type`: `\"setConfigOption\"`; \\} \\| \\{ `type`: `\"compact\"`; \\} \\| \\{ `type`: `\"stop\"`; \\} \\| [`AgentRespondElicitationAction`](AgentRespondElicitationAction.md) & \\{ `type`: `\"respondElicitation\"`; \\} \\| [`AgentPermissionAction`](AgentPermissionAction.md) & \\{ `type`: `\"respondToPermission\"`; \\}\n\nOne thing a caller wants an agent to do.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentActionId.md -->\n# Type Alias: AgentActionId\n\n> **AgentActionId** = `string`\n\nIdentifies one accepted [`AgentAction`] end to end: returned by the\ncontrol endpoint, written as the JSON-RPC request id on the action's wire\nframe, and read back off that frame as `request_id` on the folded message\nit derives.\n\nA v7 uuid, so ids sort by mint time. Minted by the server at accept time,\nor by a client that speculated the action and named it in the control\nrequest - either way the server is the only writer of runtime-bound\nframes, so a uuid-shaped request id remains the whole ownership test. The\nmachine's own handshake request ids (`agent_session:{session}:{n}`) are\nnot uuids and stay `None`.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentConversationDto.md -->\n# Type Alias: AgentConversationDto\n\n> **AgentConversationDto** = \\{ `available`: `boolean`; `avatarUrl?`: `string` \\| `null`; `botId`: `string`; `channelId`: `string`; `name`: `string`; `sessions`: [`AgentConversationSessionDto`](AgentConversationSessionDto.md)[]; `settingsChanged`: `boolean`; `turns`: [`AgentConversationTurnDto`](AgentConversationTurnDto.md)[]; \\}\n\nAn agent's conversation in a channel, as the person it is with sees it.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-available\"></a> `available` | `boolean` | Whether the caller may currently send a new prompt. |\n| <a id=\"property-avatarurl\"></a> `avatarUrl?` | `string` \\| `null` | Optional persona avatar. |\n| <a id=\"property-botid\"></a> `botId` | `string` | Persona id (without the bot principal prefix). |\n| <a id=\"property-channelid\"></a> `channelId` | `string` | The channel containing the visible transcript. |\n| <a id=\"property-name\"></a> `name` | `string` | Persona's historical display name. |\n| <a id=\"property-sessions\"></a> `sessions` | [`AgentConversationSessionDto`](AgentConversationSessionDto.md)[] | The sessions the conversation has run on, oldest first. |\n| <a id=\"property-settingschanged\"></a> `settingsChanged` | `boolean` | Whether new persona settings are available to adopt explicitly. |\n| <a id=\"property-turns\"></a> `turns` | [`AgentConversationTurnDto`](AgentConversationTurnDto.md)[] | Persistent state of each accepted message and its current attempt. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentConversationSessionDto.md -->\n# Type Alias: AgentConversationSessionDto\n\n> **AgentConversationSessionDto** = \\{ `createdAt`: `string`; `isCurrent`: `boolean`; `sessionId`: `string`; \\}\n\nOne session a conversation has run on; every channel message stays visible.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | When the session began. |\n| <a id=\"property-iscurrent\"></a> `isCurrent` | `boolean` | Whether this is the current agent context. |\n| <a id=\"property-sessionid\"></a> `sessionId` | `string` | Session whose controls and live events belong to this context. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentConversationTurnDto.md -->\n# Type Alias: AgentConversationTurnDto\n\n> **AgentConversationTurnDto** = \\{ `actionId`: `string`; `createdAt`: `string`; `replyMessageId?`: `string` \\| `null`; `retryable`: `boolean`; `sessionId`: `string`; `sourceMessageId`: `string`; `state`: [`ConversationTurnState`](ConversationTurnState.md); \\}\n\nExecution status without exposing the persona prompt or stored credentials.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-actionid\"></a> `actionId` | `string` | Current runtime attempt identity. |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | When the source message was first accepted. |\n| <a id=\"property-replymessageid\"></a> `replyMessageId?` | `string` \\| `null` | The associated agent reply, if it has been posted. |\n| <a id=\"property-retryable\"></a> `retryable` | `boolean` | Whether Retry would be accepted now. A failed attempt is not retryable until its reply says how it ended. |\n| <a id=\"property-sessionid\"></a> `sessionId` | `string` | Session carrying this turn. |\n| <a id=\"property-sourcemessageid\"></a> `sourceMessageId` | `string` | The user's message in the channel timeline. |\n| <a id=\"property-state\"></a> `state` | [`ConversationTurnState`](ConversationTurnState.md) | Durable execution state. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentPermissionAction.md -->\n# Type Alias: AgentPermissionAction\n\n> **AgentPermissionAction** = \\{ `answer`: [`PermissionAnswer`](PermissionAnswer.md); `requestId`: `unknown`; \\}\n\nA user's answer to the agent's `session/request_permission`.\n\nUnlike every other action this is not a new request but the reply to one\nthe agent made, so it carries the agent's own request id rather than\nreceiving a server-minted one.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-answer\"></a> `answer` | [`PermissionAnswer`](PermissionAnswer.md) | What the user decided. |\n| <a id=\"property-requestid\"></a> `requestId` | `unknown` | The agent's JSON-RPC request id, echoed verbatim from the folded permission part. A string or a number on the wire; agents mint both, and `7` does not answer `\"7\"`. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentPromptAction.md -->\n# Type Alias: AgentPromptAction\n\n> **AgentPromptAction** = \\{ `attachments?`: [`PromptAttachment`](PromptAttachment.md)[]; `prompt`: `string`; \\}\n\nAsk the agent to work on something.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attachments\"></a> `attachments?` | [`PromptAttachment`](PromptAttachment.md)[] | Files the prompt refers to, in the order the user attached them. Delivered after the text as one `resource_link` block each. |\n| <a id=\"property-prompt\"></a> `prompt` | `string` | What to tell the agent. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentRespondElicitationAction.md -->\n# Type Alias: AgentRespondElicitationAction\n\n> **AgentRespondElicitationAction** = [`ElicitationAnswer`](ElicitationAnswer.md) & \\{ `requestId`: [`ElicitationRequestId`](ElicitationRequestId.md); \\}\n\nAnswer an elicitation the agent is waiting on.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `requestId` | [`ElicitationRequestId`](ElicitationRequestId.md) | The agent's `elicitation/create` request id - not an [`AgentActionId`], because the agent minted it. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentSessionChangesResponse.md -->\n# Type Alias: AgentSessionChangesResponse\n\n> **AgentSessionChangesResponse** = \\{ `attempt?`: `null` \\| [`CaptureAttemptDto`](CaptureAttemptDto.md); `capturing`: `boolean`; `changeset?`: `null` \\| [`ChangesetDto`](ChangesetDto.md); \\}\n\nResponse body for `GET /agent-sessions/{session_id}/changes`.\n\nClients deserialize this, so both derives are used.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-attempt\"></a> `attempt?` | `null` \\| [`CaptureAttemptDto`](CaptureAttemptDto.md) | - |\n| <a id=\"property-capturing\"></a> `capturing` | `boolean` | A capture is running right now. |\n| <a id=\"property-changeset\"></a> `changeset?` | `null` \\| [`ChangesetDto`](ChangesetDto.md) | - |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentSessionLogEntryDto.md -->\n# Type Alias: AgentSessionLogEntryDto\n\n> **AgentSessionLogEntryDto** = [`LogFrameDto`](LogFrameDto.md) & \\{ `createdAt`: `string`; `id`: `string`; `userId?`: `string` \\| `null`; \\}\n\nOne entry of a session's protocol log.\n\nSerializes as `{\"userId\": ..., \"direction\": ..., \"content\": ...}` - the\nframe's own two fields, flattened in beside the attribution, which is the\nsame shape a recorded session's JSONL carries. A reader can deserialize the\n`direction`/`content` pair straight back into the fold's own log type\nrather than through a transport vocabulary of its own.\n\n`agentSessionId` is not repeated per entry: every entry in a response\nbelongs to the session named once at the top.\n\n`Deserialize` is for the wire-contract tests only - nothing server-side\ndecodes its own response type.\n\n## Type Declaration\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `createdAt` | `string` | When the log recorded the frame. The frame itself carries no time, so this comes from the log row. It is what a reader has to order these against anything else it is showing beside them - the fold derives an order among the messages of one session and nothing more. |\n| `id` | `string` | Durable transport row identity; together with `createdAt`, its order cursor. |\n| `userId?` | `string` \\| `null` | The user whose action produced the frame, absent when no user did. Only prompts carry one, and only when the frame was attributed at the time - a replayed or recorded session's are anonymous. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentSessionLogResponse.md -->\n# Type Alias: AgentSessionLogResponse\n\n> **AgentSessionLogResponse** = \\{ `bot`: [`SessionBot`](SessionBot.md); `entries`: [`AgentSessionLogEntryDto`](AgentSessionLogEntryDto.md)[]; \\}\n\nResponse body for one session's raw protocol log.\n\nA wrapper rather than a bare array so that anything which is about the\nresponse rather than about a frame has somewhere to go later without\nbreaking every client.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-bot\"></a> `bot` | [`SessionBot`](SessionBot.md) | The agent whose messages the log derives. Here because a client renders those messages and cannot otherwise work out who sent them: the sender of an agent message is this session's bot, and nothing else names it. |\n| <a id=\"property-entries\"></a> `entries` | [`AgentSessionLogEntryDto`](AgentSessionLogEntryDto.md)[] | Effective history in ascending `(createdAt, id)` order. The first row is the inclusive history boundary cursor: buffered rows before it are obsolete. Reconcile snapshot overlap by row ID, never content. An empty history has no boundary or overlapping rows. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentSessionResponse.md -->\n# Type Alias: AgentSessionResponse\n\n> **AgentSessionResponse** = \\{ `acpSessionId?`: `string` \\| `null`; `botId`: `string`; `canEdit`: `boolean`; `createdAt`: `string`; `external?`: `null` \\| [`ExternalSessionResponse`](ExternalSessionResponse.md); `harness`: `string`; `id`: `string`; `instructions?`: `string` \\| `null`; `isArchived`: `boolean`; `model`: `string`; `modifiedAt`: `string`; `name`: `string`; `originatingMessageId?`: `string` \\| `null`; `ownerId`: `string`; `pullRequestUrl?`: `string` \\| `null`; `repoUrl?`: `string` \\| `null`; `sandboxSize`: [`SandboxSize`](SandboxSize.md); `status`: [`SessionStatusDto`](SessionStatusDto.md); `taskId?`: `string` \\| `null`; `threadChannelId?`: `string` \\| `null`; `threadId?`: `string` \\| `null`; `threadParent?`: `null` \\| [`MessageParent`](MessageParent.md); `workspace`: `string`; \\}\n\nResponse body describing an agent session.\n\nClients deserialize this, so both derives are used.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-acpsessionid\"></a> `acpSessionId?` | `string` \\| `null` | The ACP session id, if one exists. |\n| <a id=\"property-botid\"></a> `botId` | `string` | The bot running the agent. |\n| <a id=\"property-canedit\"></a> `canEdit` | `boolean` | Whether the caller may drive the session - prompt it, answer its questions, stop it - rather than only watch. Edit access; the creator owns the session, so a create response always says so. |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | When the session was created. |\n| <a id=\"property-external\"></a> `external?` | `null` \\| [`ExternalSessionResponse`](ExternalSessionResponse.md) | - |\n| <a id=\"property-harness\"></a> `harness` | `string` | Harness slug. |\n| <a id=\"property-id\"></a> `id` | `string` | The session id. |\n| <a id=\"property-instructions\"></a> `instructions?` | `string` \\| `null` | Instructions the session's runtime works under, when any were stated at creation. Absent otherwise, so existing payloads are unchanged. |\n| <a id=\"property-isarchived\"></a> `isArchived` | `boolean` | Whether the session is archived and read-only. |\n| <a id=\"property-model\"></a> `model` | `string` | Model slug. |\n| <a id=\"property-modifiedat\"></a> `modifiedAt` | `string` | When the session was last modified. |\n| <a id=\"property-name\"></a> `name` | `string` | User-facing session name. |\n| <a id=\"property-originatingmessageid\"></a> `originatingMessageId?` | `string` \\| `null` | The exact message that invoked the bot, if any. |\n| <a id=\"property-ownerid\"></a> `ownerId` | `string` | The user who created and owns the session. |\n| <a id=\"property-pullrequesturl\"></a> `pullRequestUrl?` | `string` \\| `null` | The session's linked pull request. |\n| <a id=\"property-repourl\"></a> `repoUrl?` | `string` \\| `null` | The repository the session works with, when one was stated. |\n| <a id=\"property-sandboxsize\"></a> `sandboxSize` | [`SandboxSize`](SandboxSize.md) | Compute tier of the managed sandbox. |\n| <a id=\"property-status\"></a> `status` | [`SessionStatusDto`](SessionStatusDto.md) | The session's status. |\n| <a id=\"property-taskid\"></a> `taskId?` | `string` \\| `null` | The Macro task the session was linked to. |\n| <a id=\"property-threadchannelid\"></a> `threadChannelId?` | `string` \\| `null` | The channel `thread_id` lives in, when the session was spawned from a channel thread. Derived from `thread_parent`. |\n| <a id=\"property-threadid\"></a> `threadId?` | `string` \\| `null` | The root message of the thread the session was created from, if any. |\n| <a id=\"property-threadparent\"></a> `threadParent?` | `null` \\| [`MessageParent`](MessageParent.md) | - |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentSetConfigOptionAction.md -->\n# Type Alias: AgentSetConfigOptionAction\n\n> **AgentSetConfigOptionAction** = \\{ `configId`: `string`; `value`: `string`; \\}\n\nAsk the agent to change one advertised select-style session setting.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-configid\"></a> `configId` | `string` | Opaque ACP config id advertised by the agent. |\n| <a id=\"property-value\"></a> `value` | `string` | Opaque select value advertised for that config option. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AgentSetModelAction.md -->\n# Type Alias: AgentSetModelAction\n\n> **AgentSetModelAction** = \\{ `model`: `string`; \\}\n\nAsk the agent to run on a different model from here on.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-model\"></a> `model` | `string` | The model slug the agent should switch to. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/AnswerToolApprovalResponse.md -->\n# Type Alias: AnswerToolApprovalResponse\n\n> **AnswerToolApprovalResponse** = \\{ `status`: [`ToolApprovalStatusDto`](ToolApprovalStatusDto.md); \\}\n\nResponse body for answering a held tool call.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-status\"></a> `status` | [`ToolApprovalStatusDto`](ToolApprovalStatusDto.md) | Where the call stands now. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/BotId.md -->\n# Type Alias: BotId\n\n> **BotId** = `string`\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/CaptureAttemptDto.md -->\n# Type Alias: CaptureAttemptDto\n\n> **CaptureAttemptDto** = \\{ `error?`: `string` \\| `null`; `finishedAt?`: `string` \\| `null`; `outcome?`: `null` \\| [`CaptureOutcomeDto`](CaptureOutcomeDto.md); `startedAt`: `string`; \\}\n\nThe latest capture attempt.\n\nClients deserialize this, so both derives are used.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-error\"></a> `error?` | `string` \\| `null` | Why it did not capture, in a sentence the user can read. |\n| <a id=\"property-finishedat\"></a> `finishedAt?` | `string` \\| `null` | When it ended; absent while it runs. |\n| <a id=\"property-outcome\"></a> `outcome?` | `null` \\| [`CaptureOutcomeDto`](CaptureOutcomeDto.md) | - |\n| <a id=\"property-startedat\"></a> `startedAt` | `string` | When it started. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/CaptureOutcomeDto.md -->\n# Type Alias: CaptureOutcomeDto\n\n> **CaptureOutcomeDto** = `\"captured\"` \\| `\"not_ready\"` \\| `\"failed\"`\n\nHow the latest capture attempt ended, on the wire.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ChangedFileDto.md -->\n# Type Alias: ChangedFileDto\n\n> **ChangedFileDto** = \\{ `additions`: `number`; `binary`: `boolean`; `deletions`: `number`; `kind`: [`FileChangeKindDto`](FileChangeKindDto.md); `patchOmitted`: `boolean`; `path`: `string`; `previousPath?`: `string` \\| `null`; \\}\n\nOne changed file.\n\nClients deserialize this, so both derives are used.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-additions\"></a> `additions` | `number` | Lines added. |\n| <a id=\"property-binary\"></a> `binary` | `boolean` | The diff carries no text for this file. |\n| <a id=\"property-deletions\"></a> `deletions` | `number` | Lines removed. |\n| <a id=\"property-kind\"></a> `kind` | [`FileChangeKindDto`](FileChangeKindDto.md) | What happened to the file. |\n| <a id=\"property-patchomitted\"></a> `patchOmitted` | `boolean` | The file's hunks were left out of the patch to fit the size budget. |\n| <a id=\"property-path\"></a> `path` | `string` | The file's path after the change, or before it for a deletion. |\n| <a id=\"property-previouspath\"></a> `previousPath?` | `string` \\| `null` | Where a renamed file came from. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ChangesetDto.md -->\n# Type Alias: ChangesetDto\n\n> **ChangesetDto** = \\{ `additions`: `number`; `base`: [`GitRefDto`](GitRefDto.md); `capturedAt`: `string`; `deletions`: `number`; `files`: [`ChangedFileDto`](ChangedFileDto.md)[]; `head`: [`GitRefDto`](GitRefDto.md); `id`: `string`; `patchBytes`: `number`; `repository?`: `string` \\| `null`; `source`: [`ChangesetSourceDto`](ChangesetSourceDto.md); `truncated`: `boolean`; \\}\n\nOne changeset: the files a patch touches and what happened to each.\n\nClients deserialize this, so both derives are used.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-additions\"></a> `additions` | `number` | Lines added across all files. |\n| <a id=\"property-base\"></a> `base` | [`GitRefDto`](GitRefDto.md) | The side the work started from. |\n| <a id=\"property-capturedat\"></a> `capturedAt` | `string` | When the diff was taken. |\n| <a id=\"property-deletions\"></a> `deletions` | `number` | Lines removed across all files. |\n| <a id=\"property-files\"></a> `files` | [`ChangedFileDto`](ChangedFileDto.md)[] | Every changed file, in patch order. |\n| <a id=\"property-head\"></a> `head` | [`GitRefDto`](GitRefDto.md) | The side carrying the work. |\n| <a id=\"property-id\"></a> `id` | `string` | The changeset's id; a different id means different changes. |\n| <a id=\"property-patchbytes\"></a> `patchBytes` | `number` | Size of the patch the matching patch route serves; zero when nothing changed. |\n| <a id=\"property-repository\"></a> `repository?` | `string` \\| `null` | `https://github.com/owner/name`, when known. |\n| <a id=\"property-source\"></a> `source` | [`ChangesetSourceDto`](ChangesetSourceDto.md) | Where the diff was read from. |\n| <a id=\"property-truncated\"></a> `truncated` | `boolean` | Some files' hunks were left out of the patch. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ChangesetSourceDto.md -->\n# Type Alias: ChangesetSourceDto\n\n> **ChangesetSourceDto** = `\"github_pull_request\"`\n\nThe source of a changeset's diff, on the wire.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ChannelSharePermission.md -->\n# Type Alias: ChannelSharePermission\n\n> **ChannelSharePermission** = \\{ `access_level`: [`AccessLevel`](AccessLevel.md); `channel_id`: `string`; \\}\n\nThe channel share permission\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-access_level\"></a> `access_level` | [`AccessLevel`](AccessLevel.md) | The access level for the channel |\n| <a id=\"property-channel_id\"></a> `channel_id` | `string` | The channel id |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md -->\n# Type Alias: CodingPreferencesBody\n\n> **CodingPreferencesBody** = \\{ `createTasks`: `boolean`; `openPullRequests`: `boolean`; \\}\n\nRequest or response body for the caller's coding preferences.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-createtasks\"></a> `createTasks` | `boolean` | Whether new coding sessions research prior work and link a Macro task. |\n| <a id=\"property-openpullrequests\"></a> `openPullRequests` | `boolean` | Whether new coding sessions deliver their work as a pull request. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ControlResponse.md -->\n# Type Alias: ControlResponse\n\n> **ControlResponse** = \\{ `actionId`: [`AgentActionId`](AgentActionId.md); `status`: [`ControlStatusDto`](ControlStatusDto.md); \\}\n\nResponse body for a control operation.\n\nClients deserialize this, so both derives are used.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-actionid\"></a> `actionId` | [`AgentActionId`](AgentActionId.md) | Matches `requestId` on the folded message this action derives once it dispatches, and names the queue entry until then. The caller's own `actionId` when it supplied one; a freshly minted id otherwise. |\n| <a id=\"property-status\"></a> `status` | [`ControlStatusDto`](ControlStatusDto.md) | Whether the action went out or waits in the queue. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ControlStatusDto.md -->\n# Type Alias: ControlStatusDto\n\n> **ControlStatusDto** = `\"sent\"` \\| `\"queued\"`\n\nWhat accepting a control operation did with it, on the wire.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ConversationTurnState.md -->\n# Type Alias: ConversationTurnState\n\n> **ConversationTurnState** = `\"queued\"` \\| `\"running\"` \\| `\"succeeded\"` \\| `\"failed\"` \\| `\"stopped\"` \\| `\"interrupted\"`\n\nThe state of one source message, retained after completion for deduplication.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/DocumentId.md -->\n# Type Alias: DocumentId\n\n> **DocumentId** = `string`\n\nA validated document identifier. Historical document ids need not be UUIDs.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ElicitationAnswer.md -->\n# Type Alias: ElicitationAnswer\n\n> **ElicitationAnswer** = \\{ `action`: `\"accept\"`; `content?`: \\{\\[`key`: `string`\\]: [`ElicitationContentValue`](ElicitationContentValue.md); \\} \\| `null`; \\} \\| \\{ `action`: `\"decline\"`; \\} \\| \\{ `action`: `\"cancel\"`; \\}\n\nWhat the user decided about an elicitation. Mirrors ACP's three actions;\nthere is no `Other` because we never originate an action we do not know.\n\n## Union Members\n\n### Type Literal\n\n\\{ `action`: `\"accept\"`; `content?`: \\{\\[`key`: `string`\\]: [`ElicitationContentValue`](ElicitationContentValue.md); \\} \\| `null`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `action` | `\"accept\"` | - |\n| `content?` | \\{\\[`key`: `string`\\]: [`ElicitationContentValue`](ElicitationContentValue.md); \\} \\| `null` | Form: the submitted values keyed by property. URL: omitted. |\n\n***\n\n### Type Literal\n\n\\{ `action`: `\"decline\"`; \\}\n\n***\n\n### Type Literal\n\n\\{ `action`: `\"cancel\"`; \\}\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ElicitationContentValue.md -->\n# Type Alias: ElicitationContentValue\n\n> **ElicitationContentValue** = `string` \\| `boolean` \\| `number` \\| `number` \\| `string`[]\n\nA value ACP accepts in an elicitation answer.\n\nMirrors ACP's `ElicitationContentValue` so that the contract a caller\nanswers against is the closed union ACP will accept, rather than arbitrary\nJSON narrowed on the way out. An object, a null, or a mixed array is\nrefused when the request is deserialized - where the caller learns of it -\ninstead of at send time, when the elicitation slot has already been\nreleased.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ElicitationRequestId.md -->\n# Type Alias: ElicitationRequestId\n\n> **ElicitationRequestId** = `number` \\| `string`\n\nThe JSON-RPC id of an agent's `elicitation/create` request, carried whole\nso the answer echoes exactly what the agent sent.\n\nAgents pick these, not us: Claude Code counts from `0`, others use\nstrings. `null` is not a legal id for a request that expects a response,\nso it is not representable here.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ExecutionActivity.md -->\n# Type Alias: ExecutionActivity\n\n> **ExecutionActivity** = \\{ `id`: `number`; `label`: `string`; `status`: [`RecordedCallStatus`](RecordedCallStatus.md); \\}\n\nA bounded SDK operation observed during execution; not an authorization or write receipt.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `number` | Request identity within the execution. |\n| <a id=\"property-label\"></a> `label` | `string` | Server-selected label from the generated operation catalog. |\n| <a id=\"property-status\"></a> `status` | [`RecordedCallStatus`](RecordedCallStatus.md) | Observed request state; unfinished operations have unknown outcomes. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ExecutionId.md -->\n# Type Alias: ExecutionId\n\n> **ExecutionId** = `string`\n\nCaller-selected UUID persisted in tool input before execution begins.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ExecutionRecord.md -->\n# Type Alias: ExecutionRecord\n\n> **ExecutionRecord** = \\{ `activity?`: [`ExecutionActivity`](ExecutionActivity.md)[]; `activityTruncated?`: `boolean`; `calls`: [`RecordedToolCall`](RecordedToolCall.md)[]; `error?`: `string` \\| `null`; `executionId`: [`ExecutionId`](ExecutionId.md); `result?`: `unknown`; `source`: `string`; `status`: [`ExecutionStatus`](ExecutionStatus.md); \\}\n\nDurable source and final outcome, with historical bridge calls when present.\nThe full journal is not included in the model's tool result.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-activity\"></a> `activity?` | [`ExecutionActivity`](ExecutionActivity.md)[] | Advisory SDK operation activity, without arguments or response contents. |\n| <a id=\"property-activitytruncated\"></a> `activityTruncated?` | `boolean` | Additional request activity was omitted at the bounded observation limit. |\n| <a id=\"property-calls\"></a> `calls` | [`RecordedToolCall`](RecordedToolCall.md)[] | Historical bridge calls. Direct HTTP executions leave this empty. |\n| <a id=\"property-error\"></a> `error?` | `string` \\| `null` | Safe execution failure text. |\n| <a id=\"property-executionid\"></a> `executionId` | [`ExecutionId`](ExecutionId.md) | Execution identity. |\n| <a id=\"property-result\"></a> `result?` | `unknown` | JSON returned by the program, if successful. |\n| <a id=\"property-source\"></a> `source` | `string` | The submitted JavaScript module. |\n| <a id=\"property-status\"></a> `status` | [`ExecutionStatus`](ExecutionStatus.md) | Overall execution state. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ExecutionStatus.md -->\n# Type Alias: ExecutionStatus\n\n> **ExecutionStatus** = `\"running\"` \\| `\"succeeded\"` \\| `\"failed\"` \\| `\"cancelled\"` \\| `\"timed_out\"`\n\nThe recorded outcome of a program.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ExternalSessionResponse.md -->\n# Type Alias: ExternalSessionResponse\n\n> **ExternalSessionResponse** = \\{ `name?`: `string` \\| `null`; `provider`: `string`; `url?`: `string` \\| `null`; \\}\n\nThe provider-side identity of an externally-served session.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name?` | `string` \\| `null` | The provider's display name for the agent, when it reported one. |\n| <a id=\"property-provider\"></a> `provider` | `string` | Which provider serves the session, e.g. `cursor`. |\n| <a id=\"property-url\"></a> `url?` | `string` \\| `null` | The agent's page on the provider's site, for a client to link out to. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/FileChangeKindDto.md -->\n# Type Alias: FileChangeKindDto\n\n> **FileChangeKindDto** = `\"added\"` \\| `\"modified\"` \\| `\"deleted\"` \\| `\"renamed\"`\n\nWhat happened to a file, on the wire.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/GitRefDto.md -->\n# Type Alias: GitRefDto\n\n> **GitRefDto** = \\{ `name?`: `string` \\| `null`; `sha?`: `string` \\| `null`; \\}\n\nOne end of the compared range.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-name\"></a> `name?` | `string` \\| `null` | The branch name, when known. |\n| <a id=\"property-sha\"></a> `sha?` | `string` \\| `null` | The commit, when known. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/LinkShare.md -->\n# Type Alias: LinkShare\n\n> **LinkShare** = `\"PUBLIC\"` \\| `\"TEAM\"`\n\nDefines who can access an item through its share link.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/LogDirectionDto.md -->\n# Type Alias: LogDirectionDto\n\n> **LogDirectionDto** = `\"to_server\"` \\| `\"to_runtime\"`\n\nWhich way a logged frame travelled, mirroring [`Message`]'s discriminant.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/LogFrameDto.md -->\n# Type Alias: LogFrameDto\n\n> **LogFrameDto** = \\{ `content`: \\{\\[`key`: `string`\\]: `unknown`; \\}; `direction`: [`LogDirectionDto`](LogDirectionDto.md); \\}\n\nThe two fields [`AgentSessionLogEntryDto`] flattens in.\n\nSchema only. Nothing constructs one: the entry serializes through\n[`Message`], and this exists so the generated clients see `direction` and\n`content` as named fields instead of an open map. A hand-built copy could\ndrift from the fold's wire format, and the point of the endpoint is that it\ncannot - so this describes that format without being able to produce it.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-content\"></a> `content` | \\{\\[`key`: `string`\\]: `unknown`; \\} | The protocol envelope, verbatim. Opaque here: it is Agent Runtime Protocol, whose shape belongs to the fold rather than this endpoint. |\n| <a id=\"property-direction\"></a> `direction` | [`LogDirectionDto`](LogDirectionDto.md) | Which way the frame travelled. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/MessageParent.md -->\n# Type Alias: MessageParent\n\n> **MessageParent** = \\{ `id`: `string`; `type`: `\"channel\"`; \\} \\| \\{ `id`: [`DocumentId`](DocumentId.md); `type`: `\"document\"`; \\} \\| \\{ `id`: `string`; `type`: `\"initiative\"`; \\} \\| \\{ `id`: `string`; `type`: `\"crm_company\"`; \\} \\| \\{ `id`: `string`; `type`: `\"crm_contact\"`; \\} \\| \\{ `id`: `string`; `type`: `\"call\"`; \\}\n\nThe entity whose permissions and lifecycle govern a message.\n\n## Union Members\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"channel\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A channel, including direct messages. |\n| `type` | `\"channel\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: [`DocumentId`](DocumentId.md); `type`: `\"document\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | [`DocumentId`](DocumentId.md) | A document, including tasks and PDFs. |\n| `type` | `\"document\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"initiative\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | An initiative, presented as a project in the application. |\n| `type` | `\"initiative\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"crm_company\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A CRM company. |\n| `type` | `\"crm_company\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"crm_contact\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A CRM contact. |\n| `type` | `\"crm_contact\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `id`: `string`; `type`: `\"call\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `id` | `string` | A video call and its persistent chat thread. |\n| `type` | `\"call\"` | - |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/PermissionAnswer.md -->\n# Type Alias: PermissionAnswer\n\n> **PermissionAnswer** = \\{ `kind`: `\"selected\"`; `optionId`: `string`; \\} \\| \\{ `kind`: `\"cancelled\"`; \\}\n\nThe decision carried by an [`AgentPermissionAction`].\n\n## Union Members\n\n### Type Literal\n\n\\{ `kind`: `\"selected\"`; `optionId`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `kind` | `\"selected\"` | - |\n| `optionId` | `string` | The chosen option's id, as the agent listed it. |\n\n***\n\n### Type Literal\n\n\\{ `kind`: `\"cancelled\"`; \\}\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/PromptAttachment.md -->\n# Type Alias: PromptAttachment\n\n> **PromptAttachment** = \\{ `mimeType?`: `string` \\| `null`; `name`: `string`; `size?`: `number` \\| `null`; `uri`: `string`; \\}\n\nA file the prompt refers to, by where the agent can fetch it.\n\nMirrors ACP's `resource_link` content block, which every agent must\naccept: bytes never ride the prompt, only a URI (a static file service URL\nin practice) with enough metadata for a client to render a chip and for\nthe agent to decide whether to fetch it. Keeping the wire shape ACP-native\nmeans the harness translates without resolving anything, and the fold\nreads the same fields back off the logged frame.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-mimetype\"></a> `mimeType?` | `string` \\| `null` | The file's media type, when known. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name, typically the original file name. |\n| <a id=\"property-size\"></a> `size?` | `number` \\| `null` | Size in bytes, when known. |\n| <a id=\"property-uri\"></a> `uri` | `string` | Where the agent can fetch the file. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/PullRequestLinkSource.md -->\n# Type Alias: PullRequestLinkSource\n\n> **PullRequestLinkSource** = `\"agent\"` \\| `\"user\"`\n\nWho associated a pull request with a session.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/QueuedActionDto.md -->\n# Type Alias: QueuedActionDto\n\n> **QueuedActionDto** = \\{ `actionId`: [`AgentActionId`](AgentActionId.md); `actorUserId?`: `string` \\| `null`; `attachments?`: [`PromptAttachment`](PromptAttachment.md)[]; `createdAt`: `string`; `kind`: `string`; `prompt?`: `string` \\| `null`; \\}\n\nOne action waiting in a session's queue.\n\nClients deserialize this, so both derives are used.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-actionid\"></a> `actionId` | [`AgentActionId`](AgentActionId.md) | The id the action was accepted under. |\n| <a id=\"property-actoruserid\"></a> `actorUserId?` | `string` \\| `null` | The user who queued it, absent when a bot acted on nobody's behalf. |\n| <a id=\"property-attachments\"></a> `attachments?` | [`PromptAttachment`](PromptAttachment.md)[] | Files the prompt refers to, for prompts only. Kept through an edit, which replaces the text alone. |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | When it was accepted. |\n| <a id=\"property-kind\"></a> `kind` | `string` | What kind of action waits - `prompt` or `compact`; only turn-occupying actions are ever queued. |\n| <a id=\"property-prompt\"></a> `prompt?` | `string` \\| `null` | The prompt's raw text, present for prompts only. What an edit replaces. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/RecordedCallStatus.md -->\n# Type Alias: RecordedCallStatus\n\n> **RecordedCallStatus** = `\"running\"` \\| `\"completed\"` \\| `\"failed\"` \\| `\"unknown\"`\n\nA dispatch result; unfinished work is never reported as success.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/RecordedToolCall.md -->\n# Type Alias: RecordedToolCall\n\n> **RecordedToolCall** = \\{ `error?`: `string` \\| `null`; `id`: `string`; `input`: `unknown`; `name`: `string`; `output?`: `unknown`; `outputOmitted`: `boolean`; `status`: [`RecordedCallStatus`](RecordedCallStatus.md); \\}\n\nA real inner call, recorded by trusted dispatch for the existing renderers.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-error\"></a> `error?` | `string` \\| `null` | Safe tool failure, if one was returned. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable, execution-scoped component identity. |\n| <a id=\"property-input\"></a> `input` | `unknown` | Arguments passed to the actual tool. |\n| <a id=\"property-name\"></a> `name` | `string` | Canonical Macro tool name from the allowlisted registry. |\n| <a id=\"property-output\"></a> `output?` | `unknown` | Original tool output, retained independently of the program's return value. |\n| <a id=\"property-outputomitted\"></a> `outputOmitted` | `boolean` | Whether the response was omitted to keep the durable journal bounded. |\n| <a id=\"property-status\"></a> `status` | [`RecordedCallStatus`](RecordedCallStatus.md) | A started call that never replied has an unknown side-effect outcome. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ReviewId.md -->\n# Type Alias: ReviewId\n\n> **ReviewId** = `string`\n\nPersisted review identity.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ReviewItem.md -->\n# Type Alias: ReviewItem\n\n> **ReviewItem** = \\{ `draft`: `unknown`; `error?`: `string` \\| `null`; `id`: `string`; `result?`: `unknown`; `status`: [`ReviewItemStatus`](ReviewItemStatus.md); \\}\n\nOne editable item and its durable outcome.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-draft\"></a> `draft` | `unknown` | Validated arguments for the existing composer/action. |\n| <a id=\"property-error\"></a> `error?` | `string` \\| `null` | Failure or uncertainty description. |\n| <a id=\"property-id\"></a> `id` | `string` | Stable item identity across stack navigation and edits. |\n| <a id=\"property-result\"></a> `result?` | `unknown` | Actual backend response, never a model assertion. |\n| <a id=\"property-status\"></a> `status` | [`ReviewItemStatus`](ReviewItemStatus.md) | Current outcome. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ReviewItemStatus.md -->\n# Type Alias: ReviewItemStatus\n\n> **ReviewItemStatus** = `\"pending\"` \\| `\"submitting\"` \\| `\"completed\"` \\| `\"dismissed\"` \\| `\"unknown\"`\n\nA review item never retries an ambiguous external result automatically.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ReviewKind.md -->\n# Type Alias: ReviewKind\n\n> **ReviewKind** = `\"email\"` \\| `\"calendar\"`\n\nThe component and action used to finish a review.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ReviewRecord.md -->\n# Type Alias: ReviewRecord\n\n> **ReviewRecord** = \\{ `executionId?`: `null` \\| [`ExecutionId`](ExecutionId.md); `id`: [`ReviewId`](ReviewId.md); `items`: [`ReviewItem`](ReviewItem.md)[]; `kind`: [`ReviewKind`](ReviewKind.md); `notificationAttemptAt?`: `number` \\| `null`; `notificationId?`: `string` \\| `null`; `presentedAt?`: `number` \\| `null`; `revision`: `number`; `sessionId`: `string`; `title`: `string`; `updatedAt`: `number`; \\}\n\nFull UI record, fetched outside the model context.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-executionid\"></a> `executionId?` | `null` \\| [`ExecutionId`](ExecutionId.md) | - |\n| <a id=\"property-id\"></a> `id` | [`ReviewId`](ReviewId.md) | Review identity. |\n| <a id=\"property-items\"></a> `items` | [`ReviewItem`](ReviewItem.md)[] | Drafts and per-item outcomes. |\n| <a id=\"property-kind\"></a> `kind` | [`ReviewKind`](ReviewKind.md) | Component kind. |\n| <a id=\"property-notificationattemptat\"></a> `notificationAttemptAt?` | `number` \\| `null` | Most recent delivery claim, allowing retry after a replica stops. |\n| <a id=\"property-notificationid\"></a> `notificationId?` | `string` \\| `null` | Stable queued-action identity until the outcome has reached the session. A failed notification may be retried without repeating external actions. |\n| <a id=\"property-presentedat\"></a> `presentedAt?` | `number` \\| `null` | Durable presentation acknowledgment, separate from user decisions. |\n| <a id=\"property-revision\"></a> `revision` | `number` | Compare-and-swap revision for edits and submissions. |\n| <a id=\"property-sessionid\"></a> `sessionId` | `string` | Owning session. |\n| <a id=\"property-title\"></a> `title` | `string` | Stack label. |\n| <a id=\"property-updatedat\"></a> `updatedAt` | `number` | Milliseconds since epoch of the last state change. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/SandboxSize.md -->\n# Type Alias: SandboxSize\n\n> **SandboxSize** = `\"small\"` \\| `\"default\"` \\| `\"large\"`\n\nNamed compute tier for a managed sandbox.\n\nThe API and database store the name. CPU, RAM, and disk live in\n`crates/agent_harness/sandbox_sizes.json`.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/SessionBot.md -->\n# Type Alias: SessionBot\n\n> **SessionBot** = \\{ `avatarUrl?`: `string` \\| `null`; `handle`: `string`; `id`: [`BotId`](BotId.md); `name`: `string`; \\}\n\nThe agent behind a session, as much of it as rendering a message needs.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-avatarurl\"></a> `avatarUrl?` | `string` \\| `null` | Avatar, when it has one. |\n| <a id=\"property-handle\"></a> `handle` | `string` | Stable `@` handle, without a leading `@`. |\n| <a id=\"property-id\"></a> `id` | [`BotId`](BotId.md) | The bot's id. A message it sent has `\"bot\\|{id}\"` as its sender. |\n| <a id=\"property-name\"></a> `name` | `string` | Display name. |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/SessionStatusDto.md -->\n# Type Alias: SessionStatusDto\n\n> **SessionStatusDto** = \\{ `kind`: `\"no_messages\"`; \\} \\| \\{ `event`: `string`; `kind`: `\"event\"`; \\} \\| \\{ `kind`: `\"disconnected\"`; \\}\n\nTransport representation of a session's status, mirroring\n[`SessionStatus`].\n\n## Union Members\n\n### Type Literal\n\n\\{ `kind`: `\"no_messages\"`; \\}\n\n***\n\n### Type Literal\n\n\\{ `event`: `string`; `kind`: `\"event\"`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `event` | `string` | The wire name of the system event, e.g. `acp_ready`. |\n| `kind` | `\"event\"` | - |\n\n***\n\n### Type Literal\n\n\\{ `kind`: `\"disconnected\"`; \\}\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/SharePermissionV2.md -->\n# Type Alias: SharePermissionV2\n\n> **SharePermissionV2** = \\{ `channelSharePermissions?`: [`ChannelSharePermission`](ChannelSharePermission.md)[] \\| `null`; `id`: `string`; `linkShare?`: `null` \\| [`LinkShare`](LinkShare.md); `linkShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); `owner`: `string`; `teamShareAccessLevel?`: `null` \\| [`AccessLevel`](AccessLevel.md); \\}\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-channelsharepermissions\"></a> `channelSharePermissions?` | [`ChannelSharePermission`](ChannelSharePermission.md)[] \\| `null` | The channel share permissions for the item |\n| <a id=\"property-id\"></a> `id` | `string` | The share permission id |\n| <a id=\"property-linkshare\"></a> `linkShare?` | `null` \\| [`LinkShare`](LinkShare.md) | - |\n| <a id=\"property-linkshareaccesslevel\"></a> `linkShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n| <a id=\"property-owner\"></a> `owner` | `string` | The owner of the item |\n| <a id=\"property-teamshareaccesslevel\"></a> `teamShareAccessLevel?` | `null` \\| [`AccessLevel`](AccessLevel.md) | - |\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ToolApprovalAnswerDto.md -->\n# Type Alias: ToolApprovalAnswerDto\n\n> **ToolApprovalAnswerDto** = `\"approve\"` \\| `\"approve_and_remember\"` \\| `\"deny\"` \\| `\"cancel\"`\n\nHow a person answers a held tool call.\n\n\n<!-- generated/agent-harness/types.gen/type-aliases/ToolApprovalStatusDto.md -->\n# Type Alias: ToolApprovalStatusDto\n\n> **ToolApprovalStatusDto** = `\"pending\"` \\| `\"approved\"` \\| `\"denied\"` \\| `\"cancelled\"` \\| `\"expired\"`\n\nWhere a held tool call stands once answered.\n\n\n<!-- generated/calendar/types.gen/type-aliases/EventTime.md -->\n# Type Alias: EventTime\n\n> **EventTime** = \\{ `endsAt`: `string`; `kind`: `\"timed\"`; `startsAt`: `string`; `timeZone?`: `string` \\| `null`; \\} \\| \\{ `endDate`: `string`; `kind`: `\"allDay\"`; `startDate`: `string`; \\}\n\nThe mutually exclusive time shape of a calendar event.\n\nFields are renamed per variant rather than with `rename_all_fields`\nbecause utoipa only honors variant-level serde renames when it\nderives the OpenAPI schema.\n\n## Union Members\n\n### Type Literal\n\n\\{ `endsAt`: `string`; `kind`: `\"timed\"`; `startsAt`: `string`; `timeZone?`: `string` \\| `null`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `endsAt` | `string` | Exclusive end instant; equal to the start for an imported point event. |\n| `kind` | `\"timed\"` | - |\n| `startsAt` | `string` | Inclusive start instant. |\n| `timeZone?` | `string` \\| `null` | Original IANA time-zone identifier, when supplied. |\n\n***\n\n### Type Literal\n\n\\{ `endDate`: `string`; `kind`: `\"allDay\"`; `startDate`: `string`; \\}\n\n| Name | Type | Description |\n| ------ | ------ | ------ |\n| `endDate` | `string` | Exclusive local end date. |\n| `kind` | `\"allDay\"` | - |\n| `startDate` | `string` | Inclusive local start date. |\n\n\n<!-- src/entities/agent-sessions/agent-session/classes/AgentSession.md -->\n# Class: AgentSession\n\nA managed or externally hosted coding-agent session.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`AgentSessionResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionResponse.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-access\"></a> `access` | `readonly` | [`EntityAccess`](../../../sharing/access/classes/EntityAccess.md) | Access requests and direct user grants. | - |\n| <a id=\"property-codeexecutions\"></a> `codeExecutions` | `readonly` | \\{ `byId`: (`id`) => [`CodeExecution`](../../code-execution/classes/CodeExecution.md); \\} | Saved code executions scoped to this session. Handle construction makes no request. | - |\n| `codeExecutions.byId` | `public` | (`id`) => [`CodeExecution`](../../code-execution/classes/CodeExecution.md) | - | - |\n| <a id=\"property-createdat\"></a> `createdAt` | `readonly` | () => `Promise`\\<`string`\\> | When the session was created. | - |\n| <a id=\"property-harness\"></a> `harness` | `readonly` | () => `Promise`\\<`string`\\> | The agent harness implementation serving the session. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-instructions\"></a> `instructions` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Instructions the session's runtime works under, when any were stated at creation. Fixed for the session's life. | - |\n| <a id=\"property-isarchived\"></a> `isArchived` | `readonly` | () => `Promise`\\<`boolean`\\> | Whether the session is archived and read-only. | - |\n| <a id=\"property-model\"></a> `model` | `readonly` | () => `Promise`\\<`string`\\> | The model currently configured for the session. | - |\n| <a id=\"property-modifiedat\"></a> `modifiedAt` | `readonly` | () => `Promise`\\<`string`\\> | When the session was last modified. | - |\n| <a id=\"property-name\"></a> `name` | `readonly` | () => `Promise`\\<`string`\\> | The session's user-facing display name. | - |\n| <a id=\"property-repourl\"></a> `repoUrl` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | The repository the agent works with, when one was supplied. | - |\n| <a id=\"property-reviews\"></a> `reviews` | `readonly` | \\{ `byId`: (`id`) => [`SessionReview`](../../review/classes/SessionReview.md); `create`: (`input`) => `Promise`\\<[`SessionReview`](../../review/classes/SessionReview.md)\\>; \\} | Persisted reviews scoped to this session, with or without a code execution. | - |\n| `reviews.byId` | `public` | (`id`) => [`SessionReview`](../../review/classes/SessionReview.md) | - | - |\n| `reviews.create` | `public` | (`input`) => `Promise`\\<[`SessionReview`](../../review/classes/SessionReview.md)\\> | - | - |\n| <a id=\"property-sandboxsize\"></a> `sandboxSize` | `readonly` | () => `Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\> | Compute tier of the managed sandbox. | - |\n| <a id=\"property-status\"></a> `status` | `readonly` | () => `Promise`\\<[`SessionStatusDto`](../../../../../generated/agent-harness/types.gen/type-aliases/SessionStatusDto.md)\\> | The session's latest runtime status. | - |\n\n## Methods\n\n### archive()\n\n> **archive**(): `Promise`\\<`void`\\>\n\nArchive this session, making it read-only until unarchived.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### changes()\n\n> **changes**(): `Promise`\\<[`AgentSessionChangesResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionChangesResponse.md)\\>\n\nRead the latest captured GitHub pull request changes and capture status.\n\n#### Returns\n\n`Promise`\\<[`AgentSessionChangesResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionChangesResponse.md)\\>\n\n***\n\n### changesPatch()\n\n> **changesPatch**(): `Promise`\\<`string`\\>\n\nRead the unified diff of the latest captured changeset.\n\n#### Returns\n\n`Promise`\\<`string`\\>\n\n***\n\n### control()\n\n> **control**(`action`): `Promise`\\<[`ControlResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/ControlResponse.md)\\>\n\nSend a prompt or lifecycle operation to the live agent session.\n\nThe returned `actionId` matches `requestId` on the folded message the\naction derives once it dispatches. A `queued` status means a turn was\nrunning: the action waits in the session's queue ([queue](#queue)) and\ndispatches when that turn ends.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `action` | [`AgentAction`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentAction.md) |\n\n#### Returns\n\n`Promise`\\<[`ControlResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/ControlResponse.md)\\>\n\n***\n\n### delete()\n\n> **delete**(): `Promise`\\<`void`\\>\n\nDelete this session and any live resources it owns.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### foldedLog()\n\n> **foldedLog**(): `Promise`\\<[`FoldedAgentSessionLog`](../type-aliases/FoldedAgentSessionLog.md)\\>\n\nRead this session's whole history as the conversation the app renders:\neach user prompt and agent reply, oldest first, with tool calls and their\nresults, plans, permission requests and how each turn ended. Works on any\nsession the caller can view, live or finished, so it is the way to read\nwhat another agent session did. Prefer it to [log](#log), which returns\nraw protocol frames.\n\n#### Returns\n\n`Promise`\\<[`FoldedAgentSessionLog`](../type-aliases/FoldedAgentSessionLog.md)\\>\n\n***\n\n### linkPullRequest()\n\n> **linkPullRequest**(`url`): `Promise`\\<`void`\\>\n\nLink the GitHub pull request at `url` to this session. Linking one that\nis already linked changes nothing.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `url` | `string` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### log()\n\n> **log**(): `Promise`\\<[`AgentSessionLogResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionLogResponse.md)\\>\n\nRead the complete raw protocol log for this session.\n\n#### Returns\n\n`Promise`\\<[`AgentSessionLogResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionLogResponse.md)\\>\n\n***\n\n### prompt()\n\n> **prompt**(`text`, `attachments?`): `Promise`\\<[`ControlResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/ControlResponse.md)\\>\n\nSend a prompt to the session — sugar over [control](#control).\n\n`attachments` are files the prompt refers to, each by a URL the agent\ncan fetch (a static file service URL in practice); they reach the agent\nas ACP `resource_link` blocks after the text.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `text` | `string` |\n| `attachments?` | [`PromptAttachment`](../../../../../generated/agent-harness/types.gen/type-aliases/PromptAttachment.md)[] |\n\n#### Returns\n\n`Promise`\\<[`ControlResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/ControlResponse.md)\\>\n\n***\n\n### pullRequests()\n\n> **pullRequests**(): `Promise`\\<[`SessionPullRequest`](../type-aliases/SessionPullRequest.md)[]\\>\n\nThe GitHub pull requests linked to this session: the one its agent\nopened and any a person linked, oldest first.\n\n#### Returns\n\n`Promise`\\<[`SessionPullRequest`](../type-aliases/SessionPullRequest.md)[]\\>\n\n***\n\n### queue()\n\n> **queue**(): `Promise`\\<[`QueuedAction`](../../queued-action/classes/QueuedAction.md)[]\\>\n\nThe actions waiting to dispatch in this session, oldest first. Each can\nbe edited or removed until it dispatches.\n\n#### Returns\n\n`Promise`\\<[`QueuedAction`](../../queued-action/classes/QueuedAction.md)[]\\>\n\n***\n\n### refreshChanges()\n\n> **refreshChanges**(): `Promise`\\<[`AgentSessionChangesResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionChangesResponse.md)\\>\n\nRequest a fresh capture and return the current state while it runs.\n\n#### Returns\n\n`Promise`\\<[`AgentSessionChangesResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionChangesResponse.md)\\>\n\n***\n\n### rename()\n\n> **rename**(`name`): `Promise`\\<`void`\\>\n\nRename this session.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `name` | `string` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### setSandboxSize()\n\n> **setSandboxSize**(`size`): `Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\>\n\nResize this session's sandbox and remember the size as the owner's default.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `size` | [`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md) |\n\n#### Returns\n\n`Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\>\n\n***\n\n### sharePermissions()\n\n> **sharePermissions**(): `Promise`\\<[`SharePermissionV2`](../../../../../generated/agent-harness/types.gen/type-aliases/SharePermissionV2.md)\\>\n\nSharing configuration.\n\n#### Returns\n\n`Promise`\\<[`SharePermissionV2`](../../../../../generated/agent-harness/types.gen/type-aliases/SharePermissionV2.md)\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`AgentSessionResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionResponse.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`AgentSessionResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionResponse.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`AgentSessionResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentSessionResponse.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### toolApprovalById()\n\n> **toolApprovalById**(`id`): [`ToolApproval`](../../tool-approval/classes/ToolApproval.md)\n\nConstruct an approval handle scoped to this session.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`ToolApproval`](../../tool-approval/classes/ToolApproval.md)\n\n***\n\n### unarchive()\n\n> **unarchive**(): `Promise`\\<`void`\\>\n\nRestore an archived session so it can be edited and prompted again.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### unlinkPullRequest()\n\n> **unlinkPullRequest**(`url`): `Promise`\\<`void`\\>\n\nUnlink a GitHub pull request a person linked to this session. The pull\nrequest the session's agent opened stays linked.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `url` | `string` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### updateSharePermissions()\n\n> **updateSharePermissions**(`options`): `Promise`\\<[`SharePermissionV2`](../../../../../generated/agent-harness/types.gen/type-aliases/SharePermissionV2.md)\\>\n\nReplace sharing grants.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `options` | [`SharePermissionOptions`](../../../sharing/permissions/type-aliases/SharePermissionOptions.md) |\n\n#### Returns\n\n`Promise`\\<[`SharePermissionV2`](../../../../../generated/agent-harness/types.gen/type-aliases/SharePermissionV2.md)\\>\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `id`): `AgentSession`\n\nA handle to an agent session by id. Details load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `id` | `string` |\n\n#### Returns\n\n`AgentSession`\n\n***\n\n### codingPreferences()\n\n> `static` **codingPreferences**(`client`): `Promise`\\<[`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md)\\>\n\nWhat the caller's new coding sessions are told to do beyond their assignment.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`Promise`\\<[`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md)\\>\n\n***\n\n### createManaged()\n\n> `static` **createManaged**(`client`, `opts?`): `Promise`\\<`AgentSession`\\>\n\nCreate a managed session, optionally delivering its first prompt.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `opts?` | [`CreateManagedSessionOptions`](../type-aliases/CreateManagedSessionOptions.md) |\n\n#### Returns\n\n`Promise`\\<`AgentSession`\\>\n\n***\n\n### defaultSandboxSize()\n\n> `static` **defaultSandboxSize**(`client`): `Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\>\n\nThe caller's default sandbox size for new `@coder` sessions.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\>\n\n***\n\n### forPullRequest()\n\n> `static` **forPullRequest**(`client`, `url`): `Promise`\\<`AgentSession`[]\\>\n\nThe sessions linked to the GitHub pull request at `url` that the caller\ncan view, oldest link first.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `url` | `string` |\n\n#### Returns\n\n`Promise`\\<`AgentSession`[]\\>\n\n***\n\n### repositories()\n\n> `static` **repositories**(`client`): `Promise`\\<[`SelectableRepository`](../type-aliases/SelectableRepository.md)[]\\>\n\nThe GitHub repositories the caller can hand a managed session: every\nrepository under an installation of Macro's GitHub App they or their\nteams made, sorted by `owner/name`. Empty when the App is installed\nnowhere they reach.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`Promise`\\<[`SelectableRepository`](../type-aliases/SelectableRepository.md)[]\\>\n\n***\n\n### repositoryBranches()\n\n> `static` **repositoryBranches**(`client`, `repoUrl`): `Promise`\\<`string`[]\\>\n\nBranch names on one repository the caller can start a managed session\nfrom, in the order GitHub listed them. Empty when the repository has\nno commits yet. `repoUrl` is one of the URLs [AgentSession.repositories](#repositories)\nlists.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `repoUrl` | `string` |\n\n#### Returns\n\n`Promise`\\<`string`[]\\>\n\n***\n\n### setCodingPreferences()\n\n> `static` **setCodingPreferences**(`client`, `preferences`): `Promise`\\<[`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md)\\>\n\nReplace the caller's coding preferences.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `preferences` | [`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md) |\n\n#### Returns\n\n`Promise`\\<[`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md)\\>\n\n***\n\n### setDefaultSandboxSize()\n\n> `static` **setDefaultSandboxSize**(`client`, `size`): `Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\>\n\nSet the caller's default sandbox size for the next `@coder` mention.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `size` | [`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md) |\n\n#### Returns\n\n`Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\>\n\n\n<!-- src/entities/agent-sessions/agent-session/type-aliases/CreateManagedSessionOptions.md -->\n# Type Alias: CreateManagedSessionOptions\n\n> **CreateManagedSessionOptions** = \\{ `instructions?`: `string`; `model?`: `string`; `prompt?`: `string`; `repoBranch?`: `string`; `repoUrl?`: `string`; \\}\n\nWhat a managed session is created with.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-instructions\"></a> `instructions?` | `string` | Instructions the session's runtime works under, fixed for its life. |\n| <a id=\"property-model\"></a> `model?` | `string` | The model the session runs on, instead of its persona's. The session's model from creation, read back as [AgentSession.model](../classes/AgentSession.md#property-model). |\n| <a id=\"property-prompt\"></a> `prompt?` | `string` | First prompt to deliver once the session is running. |\n| <a id=\"property-repobranch\"></a> `repoBranch?` | `string` | The branch the session starts on; needs `repoUrl`. Omitted, the repository's default branch. |\n| <a id=\"property-repourl\"></a> `repoUrl?` | `string` | The repository the session works on, as one of the URLs [AgentSession.repositories](../classes/AgentSession.md#repositories) lists for the caller. Omitted, the runtime chooses from the prompt. Honored for Cursor sessions. |\n\n\n<!-- src/entities/agent-sessions/agent-session/type-aliases/FoldedAgentSessionLog.md -->\n# Type Alias: FoldedAgentSessionLog\n\n> **FoldedAgentSessionLog** = \\{ `bot`: [`SessionBot`](../../../../../generated/agent-harness/types.gen/type-aliases/SessionBot.md); `messages`: `FoldedMessage`[]; \\}\n\nA session's history folded into readable messages, oldest first.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-bot\"></a> `bot` | [`SessionBot`](../../../../../generated/agent-harness/types.gen/type-aliases/SessionBot.md) | The agent that sent every agent message. |\n| <a id=\"property-messages\"></a> `messages` | `FoldedMessage`[] | Prompts and replies with their tool calls, results, plans, permission requests and how each turn ended. |\n\n\n<!-- src/entities/agent-sessions/agent-session/type-aliases/SelectableRepository.md -->\n# Type Alias: SelectableRepository\n\n> **SelectableRepository** = \\{ `defaultBranch?`: `string`; `url`: `string`; \\}\n\nA GitHub repository the caller can point a managed session at.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-defaultbranch\"></a> `defaultBranch?` | `string` | The branch its clones check out, and where a session starts unless `createManaged` names another. Absent for a repository with no commits. |\n| <a id=\"property-url\"></a> `url` | `string` | The canonical `https://github.com/owner/name` URL, as `createManaged` takes it. |\n\n\n<!-- src/entities/agent-sessions/agent-session/type-aliases/SessionPullRequest.md -->\n# Type Alias: SessionPullRequest\n\n> **SessionPullRequest** = \\{ `createdAt`: `string`; `githubKey`: `string`; `linkedBy?`: [`User`](../../../users/user/classes/User.md); `source`: [`PullRequestLinkSource`](../../../../../generated/agent-harness/types.gen/type-aliases/PullRequestLinkSource.md); `url`: `string`; \\}\n\nA GitHub pull request linked to a session.\n\n## Properties\n\n| Property | Type | Description |\n| ------ | ------ | ------ |\n| <a id=\"property-createdat\"></a> `createdAt` | `string` | When it was linked. |\n| <a id=\"property-githubkey\"></a> `githubKey` | `string` | The pull request's `owner/repo/pull/number` key. |\n| <a id=\"property-linkedby\"></a> `linkedBy?` | [`User`](../../../users/user/classes/User.md) | Who linked it, for pull requests a person linked. |\n| <a id=\"property-source\"></a> `source` | [`PullRequestLinkSource`](../../../../../generated/agent-harness/types.gen/type-aliases/PullRequestLinkSource.md) | Whether the session's agent opened it or a person linked it. |\n| <a id=\"property-url\"></a> `url` | `string` | The pull request's GitHub URL. |\n\n\n<!-- src/entities/agent-sessions/code-execution/classes/CodeExecution.md -->\n# Class: CodeExecution\n\nA saved code execution belonging to one agent session.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`ExecutionRecord`](../../../../../generated/agent-harness/types.gen/type-aliases/ExecutionRecord.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Description | Inherited from |\n| ------ | ------ | ------ | ------ | ------ |\n| <a id=\"property-calls\"></a> `calls` | `readonly` | () => `Promise`\\<[`RecordedToolCall`](../../../../../generated/agent-harness/types.gen/type-aliases/RecordedToolCall.md)[]\\> | Legacy bridge calls; direct HTTP executions leave this empty. | - |\n| <a id=\"property-error\"></a> `error` | `readonly` | () => `Promise`\\<`string` \\| `undefined`\\> | Execution failure text, when present. | - |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | - | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-reviews\"></a> `reviews` | `readonly` | \\{ `create`: (`input`) => `Promise`\\<[`SessionReview`](../../review/classes/SessionReview.md)\\>; `list`: () => `Promise`\\<[`SessionReview`](../../review/classes/SessionReview.md)[]\\>; \\} | Persistent UI blocks, independent of the execution lifetime. | - |\n| `reviews.create` | `public` | (`input`) => `Promise`\\<[`SessionReview`](../../review/classes/SessionReview.md)\\> | - | - |\n| `reviews.list` | `public` | () => `Promise`\\<[`SessionReview`](../../review/classes/SessionReview.md)[]\\> | - | - |\n| <a id=\"property-source\"></a> `source` | `readonly` | () => `Promise`\\<`string`\\> | The submitted JavaScript module source. | - |\n| <a id=\"property-status\"></a> `status` | `readonly` | () => `Promise`\\<[`ExecutionStatus`](../../../../../generated/agent-harness/types.gen/type-aliases/ExecutionStatus.md)\\> | Saved execution state. Call refresh to observe subsequent changes. | - |\n\n## Methods\n\n### refresh()\n\n> **refresh**(): `Promise`\\<`CodeExecution`\\>\n\nReload the saved state, for example after a running execution completes.\n\n#### Returns\n\n`Promise`\\<`CodeExecution`\\>\n\n***\n\n### result()\n\n> **result**(): `Promise`\\<`unknown`\\>\n\nThe program's returned JSON; preserves an explicit null result.\n\n#### Returns\n\n`Promise`\\<`unknown`\\>\n\n***\n\n### session()\n\n> **session**(): [`AgentSession`](../../agent-session/classes/AgentSession.md)\n\nThe session this execution belongs to.\n\n#### Returns\n\n[`AgentSession`](../../agent-session/classes/AgentSession.md)\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`ExecutionRecord`](../../../../../generated/agent-harness/types.gen/type-aliases/ExecutionRecord.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`ExecutionRecord`](../../../../../generated/agent-harness/types.gen/type-aliases/ExecutionRecord.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`ExecutionRecord`](../../../../../generated/agent-harness/types.gen/type-aliases/ExecutionRecord.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `session`, `id`): `CodeExecution`\n\nConstruct a lazy execution handle within its owning session.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `session` | [`AgentSession`](../../agent-session/classes/AgentSession.md) |\n| `id` | `string` |\n\n#### Returns\n\n`CodeExecution`\n\n\n<!-- src/entities/agent-sessions/code-execution/type-aliases/CodeResult.md -->\n# Type Alias: CodeResult\n\n> **CodeResult** = \\{ `data`: [`JsonValue`](JsonValue.md); `reviews`: \\{ `id`: `string`; `kind`: `\"email\"` \\| `\"calendar\"`; \\}[]; \\}\n\nJSON data returned to the model, plus references to independently saved UI.\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-data\"></a> `data` | [`JsonValue`](JsonValue.md) |\n| <a id=\"property-reviews\"></a> `reviews` | \\{ `id`: `string`; `kind`: `\"email\"` \\| `\"calendar\"`; \\}[] |\n\n\n<!-- src/entities/agent-sessions/code-execution/type-aliases/JsonValue.md -->\n# Type Alias: JsonValue\n\n> **JsonValue** = `null` \\| `boolean` \\| `number` \\| `string` \\| `JsonValue`[] \\| \\{\\[`key`: `string`\\]: `JsonValue`; \\}\n\n\n<!-- src/entities/agent-sessions/conversation/classes/AgentConversation.md -->\n# Class: AgentConversation\n\nAn agent's conversation in one channel.\n\n## Constructors\n\n### Constructor\n\n> **new AgentConversation**(`client`, `channel`, `record`): `AgentConversation`\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `client` | `MacroClient` | - |\n| `channel` | [`Channel`](../../../channels/channel/classes/Channel.md) | Parent channel. |\n| `record` | [`AgentConversationDto`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentConversationDto.md) | - |\n\n#### Returns\n\n`AgentConversation`\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-channel\"></a> `channel` | `readonly` | [`Channel`](../../../channels/channel/classes/Channel.md) | Parent channel. |\n\n## Methods\n\n### agent()\n\n> **agent**(): [`Agent`](../../../agents/agent/classes/Agent.md)\n\nThe agent taking part.\n\n#### Returns\n\n[`Agent`](../../../agents/agent/classes/Agent.md)\n\n***\n\n### sessions()\n\n> **sessions**(): \\{ `createdAt`: `string`; `isCurrent`: `boolean`; `session`: [`AgentSession`](../../agent-session/classes/AgentSession.md); \\}[]\n\nConversation sessions with their current flag.\n\n#### Returns\n\n\\{ `createdAt`: `string`; `isCurrent`: `boolean`; `session`: [`AgentSession`](../../agent-session/classes/AgentSession.md); \\}[]\n\n***\n\n### startFresh()\n\n> **startFresh**(`session`): `Promise`\\<`void`\\>\n\nStart a fresh conversation from one of its sessions.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `session` | [`AgentSession`](../../agent-session/classes/AgentSession.md) |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `agentId`: `string`; `channelId`: `string`; \\}\n\nSerialize scoped identity.\n\n#### Returns\n\n\\{ `agentId`: `string`; `channelId`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `agentId` | `string` |\n| `channelId` | `string` |\n\n***\n\n### turns()\n\n> **turns**(): [`ConversationTurn`](ConversationTurn.md)[]\n\nRecorded conversation turns.\n\n#### Returns\n\n[`ConversationTurn`](ConversationTurn.md)[]\n\n\n<!-- src/entities/agent-sessions/conversation/classes/ConversationTurn.md -->\n# Class: ConversationTurn\n\nOne agent conversation turn, identified by its source message.\n\n## Constructors\n\n### Constructor\n\n> **new ConversationTurn**(`client`, `conversation`, `record`): `ConversationTurn`\n\n#### Parameters\n\n| Parameter | Type | Description |\n| ------ | ------ | ------ |\n| `client` | `MacroClient` | - |\n| `conversation` | [`AgentConversation`](AgentConversation.md) | Parent conversation. |\n| `record` | [`AgentConversationTurnDto`](../../../../../generated/agent-harness/types.gen/type-aliases/AgentConversationTurnDto.md) | - |\n\n#### Returns\n\n`ConversationTurn`\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-conversation\"></a> `conversation` | `readonly` | [`AgentConversation`](AgentConversation.md) | Parent conversation. |\n\n## Methods\n\n### retry()\n\n> **retry**(`actionId`): `Promise`\\<`void`\\>\n\nRetry with a caller persisted action nonce. Never retries automatically.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `actionId` | `string` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### session()\n\n> **session**(): [`AgentSession`](../../agent-session/classes/AgentSession.md)\n\nSession that handled this turn.\n\n#### Returns\n\n[`AgentSession`](../../agent-session/classes/AgentSession.md)\n\n***\n\n### source()\n\n> **source**(): [`Message`](../../../channels/message/classes/Message.md)\n\nOriginating message.\n\n#### Returns\n\n[`Message`](../../../channels/message/classes/Message.md)\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `channelId`: `string`; `sourceMessageId`: `string`; \\}\n\nSerialize scoped identity.\n\n#### Returns\n\n\\{ `channelId`: `string`; `sourceMessageId`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `channelId` | `string` |\n| `sourceMessageId` | `string` |\n\n\n<!-- src/entities/agent-sessions/namespace/classes/AgentSessionNamespace.md -->\n# Class: AgentSessionNamespace\n\nEntry point for coding-agent sessions.\n\n## Constructors\n\n### Constructor\n\n> **new AgentSessionNamespace**(`client`): `AgentSessionNamespace`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n\n#### Returns\n\n`AgentSessionNamespace`\n\n## Methods\n\n### byId()\n\n> **byId**(`id`): [`AgentSession`](../../agent-session/classes/AgentSession.md)\n\nA handle to an agent session by id. Details load on first access.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `id` | `string` |\n\n#### Returns\n\n[`AgentSession`](../../agent-session/classes/AgentSession.md)\n\n***\n\n### codingPreferences()\n\n> **codingPreferences**(): `Promise`\\<[`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md)\\>\n\nWhat the caller's new coding sessions are told to do beyond their assignment.\n\n#### Returns\n\n`Promise`\\<[`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md)\\>\n\n***\n\n### createManaged()\n\n> **createManaged**(`opts?`): `Promise`\\<[`AgentSession`](../../agent-session/classes/AgentSession.md)\\>\n\nCreate a managed agent session.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `opts?` | [`CreateManagedSessionOptions`](../../agent-session/type-aliases/CreateManagedSessionOptions.md) |\n\n#### Returns\n\n`Promise`\\<[`AgentSession`](../../agent-session/classes/AgentSession.md)\\>\n\n***\n\n### defaultSandboxSize()\n\n> **defaultSandboxSize**(): `Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\>\n\nThe caller's default sandbox size for new `@coder` sessions.\n\n#### Returns\n\n`Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\>\n\n***\n\n### forPullRequest()\n\n> **forPullRequest**(`url`): `Promise`\\<[`AgentSession`](../../agent-session/classes/AgentSession.md)[]\\>\n\nThe sessions linked to the GitHub pull request at `url` that the caller\ncan view.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `url` | `string` |\n\n#### Returns\n\n`Promise`\\<[`AgentSession`](../../agent-session/classes/AgentSession.md)[]\\>\n\n***\n\n### repositories()\n\n> **repositories**(): `Promise`\\<[`SelectableRepository`](../../agent-session/type-aliases/SelectableRepository.md)[]\\>\n\nThe GitHub repositories the caller can hand a managed session, with the\nbranch each one's sessions start on by default.\n\n#### Returns\n\n`Promise`\\<[`SelectableRepository`](../../agent-session/type-aliases/SelectableRepository.md)[]\\>\n\n***\n\n### repositoryBranches()\n\n> **repositoryBranches**(`repoUrl`): `Promise`\\<`string`[]\\>\n\nBranch names on one repository the caller can start a managed session\nfrom. `repoUrl` is one of the URLs [AgentSessionNamespace.repositories](#repositories)\nlists.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `repoUrl` | `string` |\n\n#### Returns\n\n`Promise`\\<`string`[]\\>\n\n***\n\n### setCodingPreferences()\n\n> **setCodingPreferences**(`preferences`): `Promise`\\<[`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md)\\>\n\nReplace the caller's coding preferences.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `preferences` | [`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md) |\n\n#### Returns\n\n`Promise`\\<[`CodingPreferencesBody`](../../../../../generated/agent-harness/types.gen/type-aliases/CodingPreferencesBody.md)\\>\n\n***\n\n### setDefaultSandboxSize()\n\n> **setDefaultSandboxSize**(`size`): `Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\>\n\nSet the caller's default sandbox size for the next `@coder` mention.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `size` | [`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md) |\n\n#### Returns\n\n`Promise`\\<[`SandboxSize`](../../../../../generated/agent-harness/types.gen/type-aliases/SandboxSize.md)\\>\n\n\n<!-- src/entities/agent-sessions/queued-action/classes/QueuedAction.md -->\n# Class: QueuedAction\n\nOne action waiting in an agent session's server-side queue: a prompt or a\ncompact accepted while a turn was running, dispatching when that turn\nends. Until then it can be edited (prompts only), steered, or removed; once\nit has dispatched, these actions answer 404 — there is no un-sending.\n\nList-sourced only - there is no per-action GET, only the queue snapshot -\nso this wraps whatever DTO the caller already has, the same shape\n`CrmComment` wraps a list-sourced record, rather than `MacroEntity`'s\nlazy-fetch-by-id.\n\n## Accessors\n\n### actionId\n\n#### Get Signature\n\n> **get** **actionId**(): `string`\n\nThe id the action was accepted under. Once it dispatches, this equals\n`requestId` on the folded message the action derives.\n\n##### Returns\n\n`string`\n\n***\n\n### actorUserId\n\n#### Get Signature\n\n> **get** **actorUserId**(): `string` \\| `undefined`\n\nThe user who queued it, absent when a bot acted on nobody's behalf.\n\n##### Returns\n\n`string` \\| `undefined`\n\n***\n\n### attachments\n\n#### Get Signature\n\n> **get** **attachments**(): [`PromptAttachment`](../../../../../generated/agent-harness/types.gen/type-aliases/PromptAttachment.md)[]\n\nFiles the prompt refers to; empty for a compact. Kept through an edit.\n\n##### Returns\n\n[`PromptAttachment`](../../../../../generated/agent-harness/types.gen/type-aliases/PromptAttachment.md)[]\n\n***\n\n### createdAt\n\n#### Get Signature\n\n> **get** **createdAt**(): `string`\n\nWhen the action was accepted, as an RFC 3339 timestamp.\n\n##### Returns\n\n`string`\n\n***\n\n### kind\n\n#### Get Signature\n\n> **get** **kind**(): `string`\n\n`prompt` or `compact`; only turn-occupying actions are ever queued.\n\n##### Returns\n\n`string`\n\n***\n\n### prompt\n\n#### Get Signature\n\n> **get** **prompt**(): `string` \\| `undefined`\n\nThe prompt's raw text, present for prompts only. What an edit replaces.\n\n##### Returns\n\n`string` \\| `undefined`\n\n## Methods\n\n### edit()\n\n> **edit**(`prompt`): `Promise`\\<`QueuedAction`\\>\n\nReplace this queued prompt's text before it dispatches. Returns this\nhandle for chaining; the edit endpoint answers 204, so `prompt` is\napplied locally rather than reread from a response body.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `prompt` | `string` |\n\n#### Returns\n\n`Promise`\\<`QueuedAction`\\>\n\n***\n\n### remove()\n\n> **remove**(): `Promise`\\<`void`\\>\n\nRemove this action from the queue before it dispatches.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### steer()\n\n> **steer**(): `Promise`\\<`void`\\>\n\nMove this action to the front and interrupt the current turn to run it next.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### from()\n\n> `static` **from**(`client`, `sessionId`, `dto`): `QueuedAction`\n\nWrap a queue entry already in hand (e.g. from `AgentSession.queue()`).\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `sessionId` | `string` |\n| `dto` | [`QueuedActionDto`](../../../../../generated/agent-harness/types.gen/type-aliases/QueuedActionDto.md) |\n\n#### Returns\n\n`QueuedAction`\n\n\n<!-- src/entities/agent-sessions/review/classes/ReviewItem.md -->\n# Class: ReviewItem\n\nAn item handle scopes edits and decisions to its persisted review.\n\n## Constructors\n\n### Constructor\n\n> **new ReviewItem**(`snapshot`, `actions`): `ReviewItem`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `snapshot` | [`ReviewItem`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewItem.md) |\n| `actions` | \\{ `dismiss`: () => `Promise`\\<`void`\\>; `edit`: (`draft`) => `Promise`\\<`void`\\>; `submit`: () => `Promise`\\<`void`\\>; \\} |\n| `actions.dismiss` | () => `Promise`\\<`void`\\> |\n| `actions.edit` | (`draft`) => `Promise`\\<`void`\\> |\n| `actions.submit` | () => `Promise`\\<`void`\\> |\n\n#### Returns\n\n`ReviewItem`\n\n## Accessors\n\n### draft\n\n#### Get Signature\n\n> **get** **draft**(): `unknown`\n\n##### Returns\n\n`unknown`\n\n***\n\n### id\n\n#### Get Signature\n\n> **get** **id**(): `string`\n\n##### Returns\n\n`string`\n\n***\n\n### result\n\n#### Get Signature\n\n> **get** **result**(): `unknown`\n\n##### Returns\n\n`unknown`\n\n***\n\n### status\n\n#### Get Signature\n\n> **get** **status**(): [`ReviewItemStatus`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewItemStatus.md)\n\n##### Returns\n\n[`ReviewItemStatus`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewItemStatus.md)\n\n## Methods\n\n### dismiss()\n\n> **dismiss**(): `Promise`\\<`void`\\>\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### edit()\n\n> **edit**(`draft`): `Promise`\\<`void`\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `draft` | `unknown` |\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### submit()\n\n> **submit**(): `Promise`\\<`void`\\>\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n\n<!-- src/entities/agent-sessions/review/classes/SessionReview.md -->\n# Class: SessionReview\n\nA persistent review remains actionable after the code execution ends.\n\n## Extends\n\n- [`MacroEntity`](../../../entity/classes/MacroEntity.md)\\<[`ReviewRecord`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewRecord.md)\\>\n\n## Properties\n\n| Property | Modifier | Type | Inherited from |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `public readonly` | `string` | [`MacroEntity`](../../../entity/classes/MacroEntity.md).[`id`](../../../entity/classes/MacroEntity.md#property-id) |\n| <a id=\"property-kind\"></a> `kind` | `readonly` | () => `Promise`\\<[`ReviewKind`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewKind.md)\\> | - |\n| <a id=\"property-title\"></a> `title` | `readonly` | () => `Promise`\\<`string`\\> | - |\n\n## Methods\n\n### dismissAll()\n\n> **dismissAll**(): `Promise`\\<`void`\\>\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### items()\n\n> **items**(): `Promise`\\<[`ReviewItem`](ReviewItem.md)[]\\>\n\n#### Returns\n\n`Promise`\\<[`ReviewItem`](ReviewItem.md)[]\\>\n\n***\n\n### reference()\n\n> **reference**(): `Promise`\\<\\{ `id`: `string`; `kind`: [`ReviewKind`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewKind.md); \\}\\>\n\nCompact reference for main()'s returned reviews array.\n\n#### Returns\n\n`Promise`\\<\\{ `id`: `string`; `kind`: [`ReviewKind`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewKind.md); \\}\\>\n\n***\n\n### refresh()\n\n> **refresh**(): `Promise`\\<`SessionReview`\\>\n\n#### Returns\n\n`Promise`\\<`SessionReview`\\>\n\n***\n\n### session()\n\n> **session**(): [`AgentSession`](../../agent-session/classes/AgentSession.md)\n\n#### Returns\n\n[`AgentSession`](../../agent-session/classes/AgentSession.md)\n\n***\n\n### submitAll()\n\n> **submitAll**(): `Promise`\\<`void`\\>\n\nSubmit the saved pending drafts. Never retries a conflict or ambiguous send.\n\n#### Returns\n\n`Promise`\\<`void`\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `detail?`: [`ReviewRecord`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewRecord.md); `id`: `string`; \\}\n\n#### Returns\n\n\\{ `detail?`: [`ReviewRecord`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewRecord.md); `id`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `detail?` | [`ReviewRecord`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewRecord.md) |\n| `id` | `string` |\n\n#### Inherited from\n\n[`MacroEntity`](../../../entity/classes/MacroEntity.md).[`toJSON`](../../../entity/classes/MacroEntity.md#tojson)\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `session`, `id`): `SessionReview`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `session` | [`AgentSession`](../../agent-session/classes/AgentSession.md) |\n| `id` | `string` |\n\n#### Returns\n\n`SessionReview`\n\n***\n\n### create()\n\n> `static` **create**(`client`, `execution`, `input`): `Promise`\\<`SessionReview`\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `execution` | [`CodeExecution`](../../code-execution/classes/CodeExecution.md) |\n| `input` | [`CreateReviewOptions`](../type-aliases/CreateReviewOptions.md) |\n\n#### Returns\n\n`Promise`\\<`SessionReview`\\>\n\n***\n\n### createForSession()\n\n> `static` **createForSession**(`client`, `session`, `input`, `execution?`): `Promise`\\<`SessionReview`\\>\n\nPresent a review in a session without requiring a code execution.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `session` | [`AgentSession`](../../agent-session/classes/AgentSession.md) |\n| `input` | [`CreateReviewOptions`](../type-aliases/CreateReviewOptions.md) |\n| `execution?` | [`CodeExecution`](../../code-execution/classes/CodeExecution.md) |\n\n#### Returns\n\n`Promise`\\<`SessionReview`\\>\n\n***\n\n### fromRecord()\n\n> `static` **fromRecord**(`client`, `session`, `record`): `SessionReview`\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `session` | [`AgentSession`](../../agent-session/classes/AgentSession.md) |\n| `record` | [`ReviewRecord`](../../../../../generated/agent-harness/types.gen/type-aliases/ReviewRecord.md) |\n\n#### Returns\n\n`SessionReview`\n\n***\n\n### list()\n\n> `static` **list**(`client`, `execution`): `Promise`\\<`SessionReview`[]\\>\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `execution` | [`CodeExecution`](../../code-execution/classes/CodeExecution.md) |\n\n#### Returns\n\n`Promise`\\<`SessionReview`[]\\>\n\n\n<!-- src/entities/agent-sessions/review/type-aliases/CreateReviewOptions.md -->\n# Type Alias: CreateReviewOptions\n\n> **CreateReviewOptions** = \\{ `drafts`: [`ReviewEmailDraft`](ReviewEmailDraft.md)[]; `kind`: `\"email\"`; `title`: `string`; \\} \\| \\{ `drafts`: [`ReviewCalendarDraft`](ReviewCalendarDraft.md)[]; `kind`: `\"calendar\"`; `title`: `string`; \\}\n\n\n<!-- src/entities/agent-sessions/review/type-aliases/ReviewCalendarDraft.md -->\n# Type Alias: ReviewCalendarDraft\n\n> **ReviewCalendarDraft** = \\{ `addGoogleMeet?`: `boolean`; `addMacroCall?`: `boolean`; `attendees?`: \\{ `email`: `string`; `isOptional?`: `boolean`; \\}[]; `calendarId?`: `string` \\| `null`; `description?`: `string` \\| `null`; `eventType?`: `\"default\"` \\| `\"out_of_office\"`; `location?`: `string` \\| `null`; `outOfOffice?`: \\{ `autoDeclineMode?`: `\"decline_none\"` \\| `\"decline_all\"` \\| `\"decline_new_only\"`; `declineMessage?`: `string` \\| `null`; \\} \\| `null`; `recurrenceLines?`: `string`[]; `reminders?`: \\{ `overrides?`: \\{ `method`: `string`; `minutes`: `number`; \\}[]; `useDefault`: `boolean`; \\} \\| `null`; `time`: [`EventTime`](../../../../../generated/calendar/types.gen/type-aliases/EventTime.md); `title`: `string`; \\}\n\nCalendar drafts use the existing calendar composer and creation action.\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-addgooglemeet\"></a> `addGoogleMeet?` | `boolean` |\n| <a id=\"property-addmacrocall\"></a> `addMacroCall?` | `boolean` |\n| <a id=\"property-attendees\"></a> `attendees?` | \\{ `email`: `string`; `isOptional?`: `boolean`; \\}[] |\n| <a id=\"property-calendarid\"></a> `calendarId?` | `string` \\| `null` |\n| <a id=\"property-description\"></a> `description?` | `string` \\| `null` |\n| <a id=\"property-eventtype\"></a> `eventType?` | `\"default\"` \\| `\"out_of_office\"` |\n| <a id=\"property-location\"></a> `location?` | `string` \\| `null` |\n| <a id=\"property-outofoffice\"></a> `outOfOffice?` | \\{ `autoDeclineMode?`: `\"decline_none\"` \\| `\"decline_all\"` \\| `\"decline_new_only\"`; `declineMessage?`: `string` \\| `null`; \\} \\| `null` |\n| <a id=\"property-recurrencelines\"></a> `recurrenceLines?` | `string`[] |\n| <a id=\"property-reminders\"></a> `reminders?` | \\{ `overrides?`: \\{ `method`: `string`; `minutes`: `number`; \\}[]; `useDefault`: `boolean`; \\} \\| `null` |\n| <a id=\"property-time\"></a> `time` | [`EventTime`](../../../../../generated/calendar/types.gen/type-aliases/EventTime.md) |\n| <a id=\"property-title\"></a> `title` | `string` |\n\n\n<!-- src/entities/agent-sessions/review/type-aliases/ReviewEmailDraft.md -->\n# Type Alias: ReviewEmailDraft\n\n> **ReviewEmailDraft** = \\{ `attachments?`: \\{ `documentId`: `string`; \\}[]; `bcc?`: \\{ `email`: `string`; `name?`: `string` \\| `null`; \\}[]; `body`: `string`; `cc?`: \\{ `email`: `string`; `name?`: `string` \\| `null`; \\}[]; `includeSignature?`: `boolean` \\| `null`; `replyingToId?`: `string` \\| `null`; `subject`: `string`; `to`: \\{ `email`: `string`; `name?`: `string` \\| `null`; \\}[]; \\}\n\nMarkdown is rendered by the ordinary email action; the UI can edit each draft.\n\n## Properties\n\n| Property | Type |\n| ------ | ------ |\n| <a id=\"property-attachments\"></a> `attachments?` | \\{ `documentId`: `string`; \\}[] |\n| <a id=\"property-bcc\"></a> `bcc?` | \\{ `email`: `string`; `name?`: `string` \\| `null`; \\}[] |\n| <a id=\"property-body\"></a> `body` | `string` |\n| <a id=\"property-cc\"></a> `cc?` | \\{ `email`: `string`; `name?`: `string` \\| `null`; \\}[] |\n| <a id=\"property-includesignature\"></a> `includeSignature?` | `boolean` \\| `null` |\n| <a id=\"property-replyingtoid\"></a> `replyingToId?` | `string` \\| `null` |\n| <a id=\"property-subject\"></a> `subject` | `string` |\n| <a id=\"property-to\"></a> `to` | \\{ `email`: `string`; `name?`: `string` \\| `null`; \\}[] |\n\n\n<!-- src/entities/agent-sessions/tool-approval/classes/ToolApproval.md -->\n# Class: ToolApproval\n\nA permission request scoped to its originating agent session.\n\n## Properties\n\n| Property | Modifier | Type | Description |\n| ------ | ------ | ------ | ------ |\n| <a id=\"property-id\"></a> `id` | `readonly` | `string` | Approval identity. |\n| <a id=\"property-session\"></a> `session` | `readonly` | [`AgentSession`](../../agent-session/classes/AgentSession.md) | Owning session. |\n\n## Methods\n\n### answer()\n\n> **answer**(`answer`): `Promise`\\<[`AnswerToolApprovalResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AnswerToolApprovalResponse.md)\\>\n\nAnswer the approval using the generated discriminated answer contract.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `answer` | [`ToolApprovalAnswerDto`](../../../../../generated/agent-harness/types.gen/type-aliases/ToolApprovalAnswerDto.md) |\n\n#### Returns\n\n`Promise`\\<[`AnswerToolApprovalResponse`](../../../../../generated/agent-harness/types.gen/type-aliases/AnswerToolApprovalResponse.md)\\>\n\n***\n\n### toJSON()\n\n> **toJSON**(): \\{ `id`: `string`; `sessionId`: `string`; \\}\n\nSerialize scoped identity only.\n\n#### Returns\n\n\\{ `id`: `string`; `sessionId`: `string`; \\}\n\n| Name | Type |\n| ------ | ------ |\n| `id` | `string` |\n| `sessionId` | `string` |\n\n***\n\n### byId()\n\n> `static` **byId**(`client`, `session`, `id`): `ToolApproval`\n\nConstruct a scoped approval handle.\n\n#### Parameters\n\n| Parameter | Type |\n| ------ | ------ |\n| `client` | `MacroClient` |\n| `session` | [`AgentSession`](../../agent-session/classes/AgentSession.md) |\n| `id` | `string` |\n\n#### Returns\n\n`ToolApproval`\n"
},
{
"name": "agents",
diff --git a/crates/agent_code_mode/src/domain/operations.json b/crates/agent_code_mode/src/domain/operations.json
index 89ddce9b59..62af1e5280 100644
--- a/crates/agent_code_mode/src/domain/operations.json
+++ b/crates/agent_code_mode/src/domain/operations.json
@@ -25,6 +25,7 @@
"agent-harness.listExecutionReviews": "List Execution Reviews",
"agent-harness.controlAgentSession": "Control Agent Session",
"agent-harness.getAgentSessionLog": "Get Agent Session Log",
+ "agent-harness.getAgentSessionFoldedLog": "Get Agent Session Folded Log",
"agent-harness.renameAgentSession": "Rename Agent Session",
"agent-harness.getAgentSessionPermissions": "Get Agent Session Permissions",
"agent-harness.updateAgentSessionPermissions": "Update Agent Session Permissions",
diff --git a/crates/agent_session/AGENTS.md b/crates/agent_session/AGENTS.md
index db4199347c..2383b4add9 100644
--- a/crates/agent_session/AGENTS.md
+++ b/crates/agent_session/AGENTS.md
@@ -14,7 +14,9 @@ consumer talks to.
- `src/domain/model.rs`: the `AgentSession` entity shape.
- `src/domain/turn_state.rs` + `src/domain/control.rs`: per-turn state and
the control-plane commands (used by held tool-call approvals).
-- `src/inbound/axum_router.rs`: the HTTP surface.
+- `src/inbound/axum_router.rs`: the HTTP surface. `GET /{id}/log` serves raw
+ frames for the web client's wasm fold; `GET /{id}/log/folded` serves the
+ same fold run server-side for the SDK and agents.
- `src/domain/read.rs` and `src/inbound/toolset/read_agent_session.rs`: bounded,
view-authorized conversation reads using the shared transcript fold.
- `src/outbound/postgres.rs`: the session repository.
diff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rs
index a5396047fd..86773bdd97 100644
--- a/crates/agent_session/src/domain/model.rs
+++ b/crates/agent_session/src/domain/model.rs
@@ -587,10 +587,9 @@ pub struct StoredAgentSessionLog {
/// With no successful load, history starts at the beginning. Failed attempts
/// remain in the stream and must be staged/discarded by fold consumers.
///
-/// Served rather than the messages it derives: the reader folds it. The web
-/// client runs the same fold compiled to WASM, so a streamed session and a
-/// reloaded one are rendered by one implementation rather than two that have
-/// to be kept agreeing.
+/// The web client folds it itself with the same fold compiled to WASM, so a
+/// streamed session and a reloaded one are rendered by one implementation.
+/// Readers without the fold get [`FoldedSessionLog`] instead.
#[derive(Debug, Clone)]
pub struct SessionLog {
/// The agent whose messages the log derives.
@@ -603,6 +602,16 @@ pub struct SessionLog {
pub entries: Vec<StoredAgentSessionLog>,
}
+/// A session's effective history folded into the messages a reader renders,
+/// oldest first: the same fold the web client runs over [`SessionLog`].
+#[derive(Debug, Clone)]
+pub struct FoldedSessionLog {
+ /// The agent whose messages these are; see [`SessionLog::bot`].
+ pub bot: SessionBot,
+ /// Every message, oldest first.
+ pub messages: Vec<agent_fold::domain::model::FoldedMessage>,
+}
+
/// How an incoming channel context relates to an agent session.
///
/// Only the originating thread can match: sessions no longer own a dedicated
diff --git a/crates/agent_session/src/domain/service.rs b/crates/agent_session/src/domain/service.rs
index 292f09fbfd..78b69618c5 100644
--- a/crates/agent_session/src/domain/service.rs
+++ b/crates/agent_session/src/domain/service.rs
@@ -62,10 +62,10 @@ use super::error::{AgentSessionError, Result};
use super::lifecycle::session_identity;
use super::model::{
AgentSession, AgentSessionId, AgentSessionLog, AgentSessionPreview, AgentSessionRenamed,
- AuthorKind, ClaimOutcome, CreateAgentSessionParams, LogAppended, MAX_AGENT_SESSION_NAME_CHARS,
- MAX_PREVIEW_SESSION_IDS, Message, MessageId, ReplicaId, SandboxSize, SessionClaim, SessionLog,
- SessionManagement, SessionPreviewCandidate, StoredAgentSessionLog, StoredQueuedAction,
- ThreadSession, cursor_run_checkpoint,
+ AuthorKind, ClaimOutcome, CreateAgentSessionParams, FoldedSessionLog, LogAppended,
+ MAX_AGENT_SESSION_NAME_CHARS, MAX_PREVIEW_SESSION_IDS, Message, MessageId, ReplicaId,
+ SandboxSize, SessionClaim, SessionLog, SessionManagement, SessionPreviewCandidate,
+ StoredAgentSessionLog, StoredQueuedAction, ThreadSession, cursor_run_checkpoint,
};
use super::model::{SessionBot, TurnPrompter};
use super::ports::{
@@ -345,12 +345,19 @@ pub trait AgentSessionService: Send + Sync + 'static {
/// The effective ACP history of one session, oldest first, with the agent
/// whose messages it derives.
///
- /// Served unfolded because nothing here folds for a reader any more: the
- /// web client runs the same fold compiled to WASM, so a streamed session
- /// and a reloaded one are rendered by one implementation rather than two
- /// that have to be kept agreeing. See [`SessionLog`].
+ /// Served unfolded for the web client, which runs the same fold compiled
+ /// to WASM so a streamed session and a reloaded one are rendered by one
+ /// implementation. See [`SessionLog`] and [`Self::folded_session_log`].
fn session_log(&self, id: AgentSessionId) -> impl Future<Output = Result<SessionLog>> + Send;
+ /// The same history as [`Self::session_log`], folded server-side into
+ /// renderable messages for readers that do not run the fold themselves,
+ /// such as SDK programs and agents reading other sessions.
+ fn folded_session_log(
+ &self,
+ id: AgentSessionId,
+ ) -> impl Future<Output = Result<FoldedSessionLog>> + Send;
+
/// Push a session's changed queue - the whole queue, every time - to its
/// viewers.
///
@@ -1168,6 +1175,15 @@ where
})
}
+ #[tracing::instrument(err, skip(self))]
+ async fn folded_session_log(&self, id: AgentSessionId) -> Result<FoldedSessionLog> {
+ let session = self.repo.get(id).await?;
+ Ok(FoldedSessionLog {
+ bot: self.repo.session_bot(session.bot_id).await?,
+ messages: self.folds.messages(id).await?,
+ })
+ }
+
async fn publish_queue_changed(&self, event: AgentSessionQueueChanged) -> Result<()> {
Ok(self.realtime.publish_queue_changed(event).await?)
}
diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rs
index 56903d3d05..864bccad39 100644
--- a/crates/agent_session/src/inbound/axum_router.rs
+++ b/crates/agent_session/src/inbound/axum_router.rs
@@ -197,6 +197,10 @@ where
"/{session_id}/log",
get(get_agent_session_log_handler::<T, Access, Auth>),
)
+ .route(
+ "/{session_id}/log/folded",
+ get(get_agent_session_folded_log_handler::<T, Access, Auth>),
+ )
.route(
"/{session_id}/name",
put(rename_agent_session_handler::<T, Access, Auth>),
@@ -1668,6 +1672,70 @@ pub async fn get_agent_session_log_handler<
}))
}
+/// Response body for one session's folded log.
+#[derive(Serialize, ToSchema)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentSessionFoldedLogResponse {
+ /// The agent whose messages these are; it sent every agent message.
+ pub bot: SessionBot,
+ /// The conversation, oldest first: prompts, replies, tool calls and their
+ /// results, plans, permission requests and how each turn ended. Each
+ /// element is a `FoldedMessage` from the fold's TypeScript contract,
+ /// which the SDK exports; the schema is opaque here because those types
+ /// are described with specta rather than utoipa.
+ #[schema(value_type = Vec<Object>)]
+ pub messages: Vec<agent_fold::inbound::wire::FoldedMessage>,
+}
+
+#[utoipa::path(
+ get,
+ path = "/agent-sessions/{session_id}/log/folded",
+ tag = "agent-sessions",
+ operation_id = "get_agent_session_folded_log",
+ params(("session_id" = Uuid, Path, description = "ID of the agent session")),
+ responses(
+ (status = 200, body = AgentSessionFoldedLogResponse),
+ (status = 401, body = String),
+ (status = 403, body = String),
+ (status = 500, body = String),
+ )
+)]
+/// One agent session's history folded into renderable messages: the same
+/// fold the web client runs over [`get_agent_session_log_handler`]'s frames.
+///
+/// For readers that do not run the fold themselves, such as SDK programs and
+/// agents reading another session's history.
+#[tracing::instrument(
+ skip_all,
+ fields(
+ session_id = %session_id,
+ agent.session.folded_log.messages = tracing::field::Empty,
+ ),
+ err(Debug)
+)]
+pub async fn get_agent_session_folded_log_handler<
+ T: AgentSessionService,
+ Access: EntityAccessService,
+ Auth: MacroAuthorizationService,
+>(
+ _access: AgentSessionAccessLevelExtractor<ViewAccessLevel, Access, Auth>,
+ State(state): State<AgentSessionRouterState<T, Access, Auth>>,
+ Path(session_id): Path<Uuid>,
+) -> Result<Json<AgentSessionFoldedLogResponse>, AgentSessionApiError> {
+ let session = AgentSessionId::new_from_uuid(session_id);
+ let log = state.service.folded_session_log(session).await?;
+ tracing::Span::current().record("agent.session.folded_log.messages", log.messages.len());
+
+ Ok(Json(AgentSessionFoldedLogResponse {
+ bot: log.bot,
+ messages: log
+ .messages
+ .into_iter()
+ .map(|message| agent_fold::inbound::wire::FoldedMessage::new(session, message))
+ .collect(),
+ }))
+}
+
/// Shared state for the create route: the opener that owns session-opening
/// semantics, the bot directory that gates it, and the authorization state the
/// extractor runs against.
diff --git a/crates/agent_session/src/inbound/axum_router/test/read.rs b/crates/agent_session/src/inbound/axum_router/test/read.rs
index 04d1c8a01a..dc5ffdb36e 100644
--- a/crates/agent_session/src/inbound/axum_router/test/read.rs
+++ b/crates/agent_session/src/inbound/axum_router/test/read.rs
@@ -7,7 +7,11 @@ use crate::domain::ports::{
use crate::domain::service::AgentSessionServiceImpl;
use crate::testing::InMemoryAgentSessionRepo;
async fn view_router() -> Router {
+ view_router_with_log(Vec::new()).await
+}
+async fn view_router_with_log(log: Vec<crate::domain::model::AgentSessionLog>) -> Router {
let repo = InMemoryAgentSessionRepo::new();
+ repo.extend_log(log);
repo.create(CreateAgentSessionParams {
purpose: crate::domain::model::SessionPurpose::Standalone,
repo_branch: None,
@@ -89,3 +93,40 @@ async fn detached_session_returns_saved_metadata() {
let value: serde_json::Value = serde_json::from_slice(&body).unwrap();
assert_eq!(value["id"], AgentSessionId::TEST_A.to_string());
}
+#[tokio::test]
+async fn folded_log_serves_the_folded_conversation() {
+ let recorded =
+ agent_fold::testing::parse_log_as(AgentSessionId::TEST_A, agent_fold::testing::TURN);
+ let expected = agent_fold::domain::fold::fold(recorded.clone());
+ let response = view_router_with_log(recorded)
+ .await
+ .oneshot(
+ Request::builder()
+ .uri(format!("/{}/log/folded", AgentSessionId::TEST_A))
+ .header(
+ macro_authorization::INTERNAL_API_KEY_HEADER,
+ "test-internal-key",
+ )
+ .body(Body::empty())
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status(), StatusCode::OK);
+ let body = axum::body::to_bytes(response.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
+ let expected = serde_json::to_value(
+ expected
+ .into_iter()
+ .map(|message| {
+ agent_fold::inbound::wire::FoldedMessage::new(AgentSessionId::TEST_A, message)
+ })
+ .collect::<Vec<_>>(),
+ )
+ .unwrap();
+ assert_eq!(body["messages"], expected);
+ assert!(!body["messages"].as_array().unwrap().is_empty());
+ assert!(body["bot"]["name"].is_string());
+}
diff --git a/crates/code_execution/src/outbound/deno/sdk.mjs b/crates/code_execution/src/outbound/deno/sdk.mjs
index 077252014f..eda899dd63 100644
--- a/crates/code_execution/src/outbound/deno/sdk.mjs
+++ b/crates/code_execution/src/outbound/deno/sdk.mjs
@@ -1,10 +1,10 @@
// Generated by packages/code-mode-sdk/scripts/generate.ts.
-async function bO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurrency limit must be a positive integer, got ${O}`);let x=Array($.length),S=0,K=async()=>{while(S<$.length){let X=S;S+=1,x[X]=await j($[X])}},Z=Array.from({length:Math.min(O,$.length)},K);return await Promise.all(Z),x}class J${loader;value;inflight;constructor($,O){this.loader=$;this.value=O}get(){if(this.value!==void 0)return Promise.resolve(this.value);return this.inflight??=this.loader().then(($)=>{return this.value=$,$}),this.inflight}peek(){return this.value}clear(){this.value=void 0,this.inflight=void 0}}async function*a($){let O;do{let j=await $(O),x=j.nextCursor??void 0;if(O!==void 0&&x!==void 0&&JSON.stringify(x)===JSON.stringify(O))throw Error("Pagination cursor did not advance");yield*j.items,O=x}while(O!==void 0)}class b extends Error{constructor($){super($);this.name="MacroError"}}class SO extends b{status;data;constructor($,O){super(`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class w extends b{constructor($){super($);this.name="MacroNotFoundError"}}function J($){if($.error!==void 0)throw new SO($.response?.status??0,$.error);return $.data}class A{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new J$(()=>this.fetch(),j)}field($){return async()=>(await this.detail.get())[$]??void 0}mappedField($,O){return async()=>O((await this.detail.get())[$]??void 0)}toJSON(){let $=this.detail.peek();return $===void 0?{id:this.id}:{id:this.id,detail:$}}async mutate($){let O=J(await $(this.client));return this.detail.clear(),O}}class F$ extends A{async permission(){return J(await this.client.storage.getEntityPermission({path:{entity_type:this.entityType,entity_id:this.id}}))}async favorite(){return J(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return J(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class S$ extends F${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=J(await this.client.properties.getEntityProperties({path:{entity_type:this.propertyEntityType,entity_id:this.id},query:$?.includeMetadata!==void 0?{include_metadata:$.includeMetadata}:void 0}));return O}async setProperty($,O){J(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return J(await this.client.properties.bulkUpdateEntityPropertyOptions({path:this.propertyReference(),body:{properties:$.map((O)=>({property_id:O.property.id,...O.add?{add_option_ids:O.add.map((j)=>j.id)}:{},...O.remove?{remove_option_ids:O.remove.map((j)=>j.id)}:{}}))}}))}async deleteProperty($){J(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}function l$($,O){return`<${$}>${JSON.stringify(O)}</${$}>`}function H6($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var R6={toMention:()=>({tag:l$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function D6($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(H6(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:C6(x)}}function C6($){let O=new Set;return $.filter((j)=>{let x=`${j.entity_type}:${j.entity_id}`;if(O.has(x))return!1;return O.add(x),!0})}function $$($){return typeof $==="string"?{content:$,mentions:[]}:$}class V$ extends A{static byId($,O){return new V$($,O)}static from($,O){return new V$($,O.id,O)}async fetch(){let $=J(await this.client.storage.listHarnesses()).find((O)=>O.id===this.id);if(!$)throw new w(`Harness ${this.id} is unavailable`);return $}name=this.field("name");connected=this.field("connected");kind=this.field("kind");async delete(){await this.mutate(($)=>$.storage.deleteHarness({path:{harness_id:this.id}}))}}class N$ extends A{static byId($,O){return new N$($,O)}static from($,O){return new N$($,O.bot.id,O)}async fetch(){let $=J(await this.client.storage.listAgents()).find((O)=>O.bot.id===this.id);if(!$)throw new w(`Agent ${this.id} is unavailable`);return $}name=this.mappedField("bot",($)=>$.name);instructions=this.field("instructions");defaultModel=this.field("default_model");channels=this.mappedField("channel_ids",($)=>$.map((O)=>f.byId(this.client,O)));host=this.mappedField("harness_id",($)=>$?V$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:Fx($)}))}}function Fx($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:G,...L}=$;return{...L,channel_ids:O?.map((Y)=>Y.id),team_id:j?.id,harness_id:x?.id,auto_accept_permissions:S,avatar_url:K,channel_scope:Z,default_model:X,is_coding:G}}async function Xj($,O,j){let{channelId:x,thread:S}=_6(O);if(await M6($)){let{id:Z}=J(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:x},body:{content:j.content,mentions:j.mentions,attachments:[],thread_id:S?.rootId??null,nonce:crypto.randomUUID()}}));return Z}if(S)throw new b("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support threads — use a team-owned bot, or requestedAs(user), "+"to reply in a thread");let{message_id:K}=J(await $.storage.postChannelBotWebhook({path:{channel_id:x},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return K}function _6($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function M6($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class g${client;channelId;rootId;constructor($,O,j){this.client=$;this.channelId=O;this.rootId=j}toJSON(){return{channelId:this.channelId,rootId:this.rootId}}channel(){return f.byId(this.client,this.channelId)}root(){return e.byId(this.client,this.channelId,this.rootId)}async replies(){let{replies:$}=J(await this.client.storage.entityMessageGetThread({path:{parent_type:"channel",parent_id:this.channelId,id:this.rootId}}));return $.map((O)=>e.from(this.client,this.channelId,O))}async reply($){let O=await Xj(this.client,this,$$($));return e.byId(this.client,this.channelId,O)}}class e extends F${channelId;mentions;entityType="channel_message";constructor($,O,j,x=[],S){super($,j,S);this.channelId=O;this.mentions=x}get path(){return{parent_type:"channel",parent_id:this.channelId,id:this.id}}async fetch(){return J(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j,x=[]){return new e($,O,j,x)}static from($,O,j){return new e($,O,j.id,j.mentions,j)}content=this.field("content");createdAt=this.field("created_at");editedAt=this.field("edited_at");updatedAt=this.field("updated_at");async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}channel(){return f.byId(this.client,this.channelId)}thread(){return new g$(this.client,this.channelId,this.id)}async react($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!0,emoji:$}})),this}async unreact($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!1,emoji:$}})),this}async edit($){let{content:O,mentions:j}=$$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}async reply($){return this.thread().reply($)}}class Gj{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}agent(){return N$.byId(this.client,this.record.botId)}sessions(){return this.record.sessions.map(($)=>({session:i.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new Ex(this.client,this,$))}async startFresh($){J(await this.client.agentHarness.startFreshAgentConversation({path:{channel_id:this.channel.id,bot_id:this.record.botId},body:{sessionId:$.id}}))}toJSON(){return{channelId:this.channel.id,agentId:this.record.botId}}}class Ex{client;conversation;record;constructor($,O,j){this.client=$;this.conversation=O;this.record=j}source(){return e.byId(this.client,this.conversation.channel.id,this.record.sourceMessageId)}session(){return i.byId(this.client,this.record.sessionId)}async retry($){J(await this.client.agentHarness.retryAgentConversationTurn({path:{channel_id:this.conversation.channel.id,bot_id:this.conversation.agent().id,source:this.record.sourceMessageId},body:{actionId:$}}))}toJSON(){return{channelId:this.conversation.channel.id,sourceMessageId:this.record.sourceMessageId}}}class W$ extends A{parent;toJSON(){return{...super.toJSON(),parentType:this.parent.type,parentId:this.parent.entity.id}}constructor($,O,j){super($,j);this.parent=O}static byId($,O,j){return new W$($,O,j)}get path(){return{parent_type:this.parent.type,parent_id:this.parent.entity.id,id:this.id}}async fetch(){return J(await this.client.storage.entityMessageGetThread({path:this.path})).state}resolved=this.field("resolved");async update($){let O={resolved:$.resolved,detach_anchor:$.detachAnchor,nonce:$.nonce};await this.mutate((j)=>j.storage.entityMessagePatchThread({path:this.path,body:O}))}async delete($){await this.mutate((O)=>O.storage.entityMessageDeleteThread({path:this.path,query:{nonce:$}}))}}async function E$($,O,j,x){for(let K of[...x?.messages??[],...x?.around?[x.around]:[]]){let Z="channelId"in K?{type:"channel",id:K.channelId}:("documentId"in K)?{type:"document",id:K.documentId}:("callId"in K)?{type:"call",id:K.callId}:K.parent;if(Z.type!==O.type||Z.id!==O.entity.id)throw Error("Timeline message belongs to another resource")}let S=J(await $.storage.messageTimelineEntries({path:{parent_type:O.type,parent_id:O.entity.id},query:{selection:x?JSON.stringify({cursor:x.cursor,around:x.around?.id,ids:x.messages?.map((K)=>K.id),activity_after:x.activityAfter,activity_before:x.activityBefore,anchored:x.anchored,direction:x.direction,include_deleted_threads:x.includeDeletedThreads,limit:x.limit}):void 0}}));return{entries:S.entries.map((K)=>{if(K.type==="activity")return{type:"activity",activity:{...K.activity,actor:M.byId($,K.activity.actor_id)}};return{type:"message",message:j(K.message)}}),nextCursor:S.next_cursor??void 0,previousCursor:S.previous_cursor??void 0}}var A6=50;function j$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(K,Z,X)=>{let G=X?.searchOn??"name_content",L=X?.pageSize??A6;return a(async(Y)=>{let{results:Q,next_cursor:T}=J(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:G,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...Y?{cursor:Y}:{}}}));return{items:Q.filter((W)=>W.type===j).map((W)=>x(K,W)),nextCursor:T}})}}class ZO{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}get id(){return this.record.id}user(){return M.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new ZO(this.client,this.channel,J(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.channel.id}})))}toJSON(){return this.record}}class f extends S${async recordActivity($){return new ZO(this.client,this,J(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.id}})))}async setPicture($){await this.mutate((O)=>O.storage.setChannelPicture({path:{channel_id:this.id},body:{profile_picture_id:$?.id??null}}))}messageThreadById($){return W$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return E$(this.client,{type:"channel",entity:this},(O)=>e.from(this.client,this.id,O),$)}async agentConversations(){return J(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Gj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return J(await this.client.storage.getChannel({path:{channel_id:this.id}}))}static byId($,O){return new f($,O)}static async dm($,O){let{channel_id:j}=J(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new f($,j)}static async private($,O){let{channel_id:j}=J(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new f($,j)}static async create($,O){let{id:j}=J(await $.storage.createChannel({body:{channel_type:O.type,name:O.name??null,participants:(O.participants??[]).map((x)=>x.id),team_id:O.team?.id??null}}));return new f($,j)}name=this.field("channel_name");type=this.field("channel_type");async send($,O){let j=await Xj(this.client,O?.thread??this,$$($));return e.byId(this.client,this.id,j)}messages($){return this.timeline({limit:$?.pageSize})}messagesAfter($,O){return this.timeline({activity_after:$ instanceof Date?$.toISOString():$,limit:O?.pageSize})}timeline($){return a(async(O)=>{let j=J(await this.client.storage.messageTimeline({path:{parent_type:"channel",parent_id:this.id},query:{selection:JSON.stringify({...$,cursor:O})}}));return{items:j.items.map((x)=>e.from(this.client,this.id,x)),nextCursor:j.next_cursor}})}message($){return e.byId(this.client,this.id,$)}async rename($){await this.mutate((O)=>O.storage.patchChannel({path:{channel_id:this.id},body:{channel_name:$}}))}async delete(){await this.mutate(($)=>$.storage.deleteChannel({path:{channel_id:this.id}}))}async join(){await this.mutate(($)=>$.storage.joinChannel({path:{channel_id:this.id}}))}async joinCode(){let{join_code:$}=J(await this.client.storage.getChannelJoinLink({path:{channel_id:this.id}}));return $}async leave(){await this.mutate(($)=>$.storage.leaveChannel({path:{channel_id:this.id}}))}async participants(){return J(await this.client.storage.getChannelParticipants({path:{channel_id:this.id}}))}async addParticipants($){await this.mutate((O)=>O.storage.addParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async removeParticipants($){await this.mutate((O)=>O.storage.removeParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async typing($,O){J(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return a(async(O)=>{let j=J(await this.client.storage.getChannelAttachments({path:{channel_id:this.id},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.type?{attachment_type:$.type}:{},...O?{cursor:O}:{}}}));return{items:j.items,nextCursor:j.next_cursor}})}webUrl(){return`${this.client.webAppUrl}/app/channel/${this.id}`}static search=j$({type:"channel",make:($,O)=>new f($,O.channel_id)})}class M extends S${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=J(await this.client.auth.getUserNamesWithEmail({body:{user_ids:[this.id]}})),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`user ${this.id} not found`);return O}static byId($,O){return new M($,O)}static async me($){let{user_id:O}=J(await $.auth.getUserInfo());return new M($,O)}async name(){let $=await this.detail.get();return[$.first_name,$.last_name].filter(Boolean).join(" ")||void 0}email(){let $=this.id.startsWith("macro|")?this.id.slice(6):void 0;return $?.includes("@")?$:void 0}dm(){return f.dm(this.client,this)}toMention(){return{tag:l$("m-user-mention",{userId:this.id}),mention:{entity_type:"user",entity_id:this.id}}}}class o{client;entityType;entity;constructor($,O,j){this.client=$;this.entityType=O;this.entity=j}get path(){return{entity_type:this.entityType,entity_id:this.entity.id}}async state($){let O=J(await this.client.storage.accessRequestsState({path:this.path,query:{offset:$}}));return{accessLevel:O.accessLevel??void 0,canReview:O.canReview,owner:O.owner?M.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?WO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>WO.from(this.client,this,j))}}async submit($,O){return WO.from(this.client,this,J(await this.client.storage.accessRequestsSubmit({path:this.path,body:{requestedLevel:$,revision:O}})))}async cancel($){J(await this.client.storage.accessRequestsCancel({path:this.path,query:{revision:$}}))}async direct(){return J(await this.client.storage.accessRequestsDirect({path:this.path})).map(($)=>({user:M.byId(this.client,$.userId),accessLevel:$.accessLevel}))}async grant($,O){J(await this.client.storage.accessRequestsSetDirect({path:{...this.path,user_id:$.id},body:{accessLevel:O}}))}async remove($){J(await this.client.storage.accessRequestsRemoveDirect({path:{...this.path,user_id:$.id}}))}async resolve($,O){let j=$.access.toJSON();if(j.entity_type!==this.entityType||j.entity_id!==this.entity.id)throw Error("Access request belongs to another entity");return J(await this.client.storage.accessRequestsResolve({path:{...this.path,request_id:$.id},body:O}))}toJSON(){return this.path}}class WO extends A{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new WO($,O,j)}async fetch(){if(this.resolvedRecord)return this.resolvedRecord;let $;do{let O=await this.access.state($),j=[O.mine,...O.requests].find((x)=>x?.id===this.id);if(j)return j.detail.get();$=O.nextOffset}while($!==void 0);throw new w(`Access request ${this.id} is unavailable`)}revision=this.field("revision");status=this.field("status");requestedLevel=this.field("requestedLevel");requester=this.mappedField("requesterId",($)=>M.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function r$($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}class B$ extends A{parent;constructor($,O,j,x){super($,j,x);this.parent=O}static byId($,O,j){return new B$($,O,j)}static fromRecord($,O,j){return new B$($,O,j.id,j)}static async create($,O,j){return B$.createForSession($,O.session(),j,O)}static async createForSession($,O,j,x){let S=J(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...j,executionId:x?.id??null}}));return B$.fromRecord($,O,S)}static async list($,O){return J(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>B$.fromRecord($,O.session(),x))}async fetch(){return J(await this.client.agentHarness.getSessionReview({path:{session_id:this.parent.id,review_id:this.id}}))}title=this.field("title");kind=this.field("kind");session(){return this.parent}async reference(){return{kind:await this.kind(),id:this.id}}async items(){return(await this.detail.get()).items.map(($)=>new wx($,{edit:(O)=>this.decide({action:"edit",item:$.id,draft:O}),submit:()=>this.decide({action:"submit",items:[$.id]}),dismiss:()=>this.decide({action:"dismiss",items:[$.id]})}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}async submitAll(){await this.decide({action:"submit",items:[]})}async dismissAll(){await this.decide({action:"dismiss",items:[]})}async decide($){let O=(await this.detail.get()).revision;await this.mutate((j)=>j.agentHarness.decideSessionReview({path:{session_id:this.parent.id,review_id:this.id},body:{...$,revision:O}}))}}class wx{snapshot;actions;constructor($,O){this.snapshot=$;this.actions=O}get id(){return this.snapshot.id}get status(){return this.snapshot.status}get draft(){return this.snapshot.draft}get result(){return this.snapshot.result}async edit($){await this.actions.edit($)}async submit(){await this.actions.submit()}async dismiss(){await this.actions.dismiss()}}class kO extends A{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new kO($,j,O)}async fetch(){return J(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>B$.create(this.client,this,$),list:()=>B$.list(this.client,this)};session(){return this.parent}status=this.field("status");source=this.field("source");calls=this.field("calls");error=this.field("error");async result(){return(await this.detail.get()).result}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class Kj{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new Kj($,O,j)}get actionId(){return this.dto.actionId}get kind(){return this.dto.kind}get prompt(){return this.dto.prompt??void 0}get attachments(){return this.dto.attachments??[]}get actorUserId(){return this.dto.actorUserId??void 0}get createdAt(){return this.dto.createdAt}async edit($){return J(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){J(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){J(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class gO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new gO($,O,j)}async answer($){return J(await this.client.agentHarness.answerAgentSessionToolApproval({path:{session_id:this.session.id,approval_id:this.id},body:{answer:$}}))}toJSON(){return{id:this.id,sessionId:this.session.id}}}class i extends A{access=new o(this.client,"agent_session",this);toolApprovalById($){return gO.byId(this.client,this,$)}async sharePermissions(){return J(await this.client.agentHarness.getAgentSessionPermissions({path:{session_id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.agentHarness.updateAgentSessionPermissions({path:{session_id:this.id},body:r$($)}))}static byId($,O){return new i($,O)}static async createManaged($,O){let{session:j}=J(await $.agentHarness.createAgentSession({body:{prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new i($,j.id,j)}static async repositories($){let{repositories:O}=J(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=J(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}async fetch(){return J(await this.client.agentHarness.getAgentSession({path:{session_id:this.id}}))}name=this.field("name");isArchived=this.field("isArchived");model=this.field("model");harness=this.field("harness");repoUrl=this.field("repoUrl");workspace=this.field("workspace");instructions=this.field("instructions");status=this.field("status");sandboxSize=this.field("sandboxSize");createdAt=this.field("createdAt");modifiedAt=this.field("modifiedAt");static async forPullRequest($,O){let{sessionIds:j}=J(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>i.byId($,x))}async pullRequests(){let{pullRequests:$}=J(await this.client.agentHarness.listAgentSessionPullRequests({path:{session_id:this.id}}));return $.map((O)=>({githubKey:O.githubKey,url:O.url,source:O.source,linkedBy:O.linkedBy?M.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){J(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){J(await this.client.agentHarness.unlinkAgentSessionPullRequest({path:{session_id:this.id},query:{url:$}}))}async rename($){await this.mutate((O)=>O.agentHarness.renameAgentSession({path:{session_id:this.id},body:{name:$}}))}async archive(){await this.setArchived(!0)}async unarchive(){await this.setArchived(!1)}async setArchived($){await this.mutate((O)=>O.agentHarness.setAgentSessionArchived({path:{session_id:this.id},body:{isArchived:$}}))}async setSandboxSize($){let{size:O}=await this.mutate((j)=>j.agentHarness.putAgentSessionSandboxSize({path:{session_id:this.id},body:{size:$}}));return O}static async defaultSandboxSize($){return J(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return J(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return J(await $.agentHarness.getAgentCodingPreferences())}static async setCodingPreferences($,O){return J(await $.agentHarness.putAgentCodingPreferences({body:O}))}async control($){return this.mutate((O)=>O.agentHarness.controlAgentSession({path:{session_id:this.id},body:$}))}prompt($,O){return this.control({type:"prompt",prompt:$,...O&&O.length>0?{attachments:O}:{}})}async queue(){let{entries:$}=J(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>Kj.from(this.client,this.id,O))}async changes(){return J(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return J(await this.client.agentHarness.getAgentSessionChangesPatch({path:{session_id:this.id}})).patch}async refreshChanges(){return this.mutate(($)=>$.agentHarness.refreshAgentSessionChanges({path:{session_id:this.id}}))}async log(){return J(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>B$.createForSession(this.client,this,$),byId:($)=>B$.byId(this.client,this,$)};codeExecutions={byId:($)=>kO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class qx{client;constructor($){this.client=$}byId($){return i.byId(this.client,$)}createManaged($){return i.createManaged(this.client,$)}repositories(){return i.repositories(this.client)}repositoryBranches($){return i.repositoryBranches(this.client,$)}forPullRequest($){return i.forPullRequest(this.client,$)}defaultSandboxSize(){return i.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return i.setDefaultSandboxSize(this.client,$)}codingPreferences(){return i.codingPreferences(this.client)}setCodingPreferences($){return i.setCodingPreferences(this.client,$)}}class fx{client;constructor($){this.client=$}byId($){return N$.byId(this.client,$)}async list(){return J(await this.client.storage.listAgents()).map(($)=>N$.from(this.client,$))}async create($){return N$.from(this.client,J(await this.client.storage.createAgent({body:Fx($)})))}}class bx{client;async usage($={}){let{users:O,...j}=$;return J(await this.client.cognition.getUsageHandler({body:{...j,include_users:O?.map((x)=>x.id)}}))}constructor($){this.client=$}async structuredCompletion($){return J(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return J(await this.client.cognition.decisions({body:$}))}}class p$ extends A{static byId($,O){return new p$($,O)}static from($,O){return new p$($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=J(await this.client.storage.listUserApiKeys()).keys.find((O)=>O.id===this.id);if(!$)throw new w(`API key ${this.id} is unavailable`);return $}name=this.field("name");createdAt=this.field("createdAt");async delete(){await this.mutate(($)=>$.storage.deleteUserApiKey({path:{id:this.id}}))}}class kx{client;constructor($){this.client=$}byId($){return p$.byId(this.client,$)}async list(){return J(await this.client.storage.listUserApiKeys()).keys.map(($)=>p$.from(this.client,$))}async create($){let O=J(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:p$.from(this.client,O),secret:O.key}}async tokenForEmail($){return J(await this.client.auth.macroApiToken({query:{email:$}}))}}class yO{client;constructor($){this.client=$}async me(){if(this.client.authConfig.type!=="bot")throw new b("bots.me() requires bot auth — a user API key has no bot identity");return J(await this.client.storage.getSelfBot())}async channels(){if(this.client.authConfig.type!=="bot")throw new b("bots.channels() requires bot auth — a user API key has no bot identity");let $=await this.me();return J(await this.client.storage.listBotChannels({path:{bot_id:$.id}}))}async myPrincipalId(){if(this.client.authConfig.type!=="bot")throw new b("bots.myPrincipalId() requires bot auth — a user API key has no bot identity");return this.client.myPrincipalId()}}class U$ extends A{async fetch(){let{links:$}=J(await this.client.email.listLinks()),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`email link ${this.id} not found`);return O}static byId($,O){return new U$($,O)}static async list($){let{links:O}=J(await $.email.listLinks());return O.map((j)=>new U$($,j.id,j))}emailAddress=this.field("email_address");provider=this.field("provider");isPrimary=this.field("is_primary");isSyncActive=this.field("is_sync_active");syncStatus=this.field("sync_status");needsReauth=this.field("needs_reauth");photoUrl=this.field("photo_url");async settingsOperations(){return J(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class y$ extends A{async setContributesToAvailability($){await this.mutate((O)=>O.calendar.setAvailabilityCalendar({path:{calendar_id:this.id},body:{contributesToAvailability:$}}))}async fetch(){let{calendars:$}=J(await this.client.calendar.listCalendars()),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`calendar ${this.id} not found`);return O}static byId($,O){return new y$($,O)}static async list($){let{calendars:O}=J(await $.calendar.listCalendars());return O.map((j)=>new y$($,j.id,j))}name=this.field("name");emailAddress=this.field("emailAddress");isPrimary=this.field("isPrimary");isWritable=this.field("isWritable");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>U$.byId(this.client,$))}class vO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return J(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return J(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){J(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class z$ extends A{async fetch(){throw new b(`calendar event ${this.id} has no fetch-by-id endpoint; read the record returned by calendar.createEvent / event.update / event.rsvp instead`)}static byId($,O){return new z$($,O)}static fromRecord($,O){return new z$($,O.id,O)}title=this.field("title");description=this.field("description");location=this.field("location");time=this.field("time");status=this.field("status");attendees=this.field("attendees");transparency=this.field("transparency");isReadOnly=this.field("isReadOnly");recurrenceLines=this.field("recurrenceLines");calendar=this.mappedField("calendarId",($)=>$?y$.byId(this.client,$):void 0);record(){return this.detail.get()}async update($){let O=await this.mutate((j)=>j.calendar.updateCalendarEvent({path:{event_id:this.id},body:P6($)}));return z$.fromRecord(this.client,O)}async delete($={}){await this.mutate((O)=>O.calendar.deleteCalendarEvent({path:{event_id:this.id},query:{calendarId:$.calendar?.id,scope:$.scope,recurrenceId:$.recurrenceId}}))}async prepareReplacement($){let O=J(await this.client.calendar.prepareCalendarReplacement({path:{event_id:this.id},body:{removeConference:$.removeConference,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return new vO(this.client,O.operationId)}async providerUrl($={}){return J(await this.client.calendar.calendarEventProviderUrl({path:{event_id:this.id},query:{recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}})).url??void 0}async rsvp($){let O=await this.mutate((j)=>j.calendar.rsvpCalendarEvent({path:{event_id:this.id},body:{response:$.response,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return z$.fromRecord(this.client,O)}}function P6($){return{title:$.title,description:$.description,location:$.location,time:$.time,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,outOfOffice:$.outOfOffice,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}class gx{client;async availabilityCalendars(){return J(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:y$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return J(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return J(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){return a(async(O)=>{let j=J(await this.client.storage.listOccurrences({query:{...$,cursor:O}}));return{items:j.items.map((x)=>({event:z$.fromRecord(this.client,x.event),occurrence:x.occurrence})),nextCursor:j.nextCursor}})}async teamPage($){let O=J(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:M.byId(this.client,j)})),members:O.members.map((j)=>({user:M.byId(this.client,j.userId),sharing:j.sharing,coverage:j.coverage})),nextCursor:O.nextCursor??void 0}}async teamOutOfOffice($){let O=J(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:z$.byId(this.client,j.eventId),owner:M.byId(this.client,j.ownerId),occurrenceKey:j.occurrenceKey,time:j.time,title:j.title??void 0})),hasMore:O.hasMore}}constructor($){this.client=$}calendars(){return y$.list(this.client)}calendar($){return y$.byId(this.client,$)}event($){return z$.byId(this.client,$)}replacement($){return new vO(this.client,$)}async createEvent($){let O=J(await this.client.calendar.createCalendarEvent({body:F6($)}));return z$.fromRecord(this.client,O)}}function F6($){return{title:$.title,time:$.time,description:$.description,location:$.location,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,macroCall:$.macroCall,outOfOffice:$.outOfOffice,calendarId:$.calendar?.id,emailLinkId:$.emailLink?.id}}class I$ extends A{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new I$($,O)}static from($,O){return new I$($,O.id,O)}async fetch(){if(this.lookupToken)return J(await this.client.storage.meetingLookup({path:{token:this.lookupToken}}));let $=J(await this.client.storage.meetingList()).meetings.find((O)=>O.id===this.id);if(!$)throw new w(`Meeting ${this.id} is unavailable`);return this.lookupToken=$.shareToken,$}title=this.field("title");scheduledStart=this.field("scheduledStart");scheduledEnd=this.field("scheduledEnd");channel=this.mappedField("channelId",($)=>$?f.byId(this.client,$):void 0);call=this.mappedField("callId",($)=>$?K$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.meetingUpdate({path:{meeting_id:this.id},body:$}))}async cancel(){await this.mutate(($)=>$.storage.meetingCancel({path:{meeting_id:this.id}}))}async invitePermissions(){return J(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){J(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){J(await this.client.storage.meetingInviteUsers({path:{token:(await this.detail.get()).shareToken},body:{userIds:$.map((O)=>O.id)}}))}async webUrl(){return`${this.client.webAppUrl}/app/meet/join/${encodeURIComponent((await this.detail.get()).shareToken)}`}}class v$ extends A{callId;constructor($,O,j,x){super($,j,x);this.callId=O}get path(){return{parent_type:"call",parent_id:this.callId,id:this.id}}async fetch(){return J(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new v$($,O,j)}static from($,O,j){return new v$($,O,j.id,j)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return K$.byId(this.client,this.callId)}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=J(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...$$($),thread_id:this.callId}}));return v$.from(this.client,this.callId,O)}async edit($){let{content:O,mentions:j}=$$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class K$ extends F${messageThreadById($){return W$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return E$(this.client,{type:"call",entity:this},(O)=>v$.from(this.client,this.id,O),$)}access=new o(this.client,"call",this);async meeting(){return I$.from(this.client,J(await this.client.storage.meetingShare({path:{call_id:this.id}})))}async editTranscript($){await this.mutate((O)=>O.storage.editCallTranscript({path:{call_id:this.id},body:{assignments:$}}))}async toggleTeamShare(){return this.mutate(($)=>$.storage.toggleShareWithTeam({path:{call_id:this.id}}))}entityType="call";async fetch(){return J(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new K$($,O)}message($){return v$.byId(this.client,this.id,$)}name=this.field("customName");channel=this.mappedField("channelId",($)=>$?f.byId(this.client,$):void 0);channelName=this.field("channelName");creator=this.mappedField("createdBy",($)=>M.byId(this.client,$));isActive=this.field("isActive");status=this.field("status");roomName=this.field("roomName");startedAt=this.field("startedAt");endedAt=this.field("endedAt");durationMs=this.field("durationMs");summary=this.field("summary");transcript=this.field("transcript");participants=this.field("participants");guests=this.field("guests");teamShareAccessLevel=this.field("teamShareAccessLevel");shareWithTeam=this.field("shareWithTeam");recordingUrl=this.field("recordingUrl");recordingPreviewUrl=this.field("recordingPreviewUrl");recordingStartedAt=this.field("recordingStartedAt");async rename($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{customName:$??""}}))}async setTeamShare($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{sharePermission:{teamShareAccessLevel:$?"view":null}}}))}async delete(){await this.mutate(($)=>$.storage.deleteCallRecord({path:{call_id:this.id}}))}static search=j$({filters:{call_filters:{}},type:"call",make:($,O)=>new K$($,O.call_id)})}class yx{client;constructor($){this.client=$}byId($){return K$.byId(this.client,$)}search($,O){return K$.search(this.client,$,O)}}class vx{client;constructor($){this.client=$}async list(){let{labels:$}=J(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return J(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return J(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return J(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return J(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return J(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){J(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){J(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}class hx{client;async activity(){return J(await this.client.storage.getActivity()).map(($)=>new ZO(this.client,f.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new vx($)}byId($){return f.byId(this.client,$)}async dm($){return f.dm(this.client,$)}async private($){return f.private(this.client,$)}async create($){return f.create(this.client,$)}async list(){let{items:$}=J(await this.client.storage.getChannels());return $.map((O)=>f.byId(this.client,O.id.toString()))}async*search($,O){if(!O?.searchOn||O.searchOn==="name"){let{items:j}=J(await this.client.storage.getChannels()),x=$.toLowerCase();for(let S of j)if(S.name?.toLowerCase().includes(x))yield f.byId(this.client,S.id.toString())}else yield*f.search(this.client,$,O)}}class n extends S${async sharePermissions(){return J(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return J(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new o(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=J(await this.client.storage.getProjectHandler({path:{id:this.id}}));return $.projectMetadata}static byId($,O){return new n($,O)}static async create($,O){let{data:j}=J(await $.storage.createProjectHandler({body:{name:O.name,projectParentId:O.parent?.id??null}}));return new n($,j.id,j)}name=this.field("name");parent=this.mappedField("parentId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");async items(){let{data:$}=J(await this.client.storage.getProjectContentHandler({path:{id:this.id}}));return $.map((O)=>O.item)}async rename($){await this.mutate((O)=>O.storage.editProjectV2({path:{id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteProject({path:{id:this.id}}):O.storage.deleteProjectHandler({path:{id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteProject({path:{id:this.id}}))}static search=j$({filters:{project_filters:{}},type:"project",make:($,O)=>new n($,O.id)})}class hO{client;chat;id;message;constructor($,O,j,x){this.client=$;this.chat=O;this.id=j;this.message=x}static byId($,O,j,x){return new hO($,O,j,x)}async stop(){J(await this.client.cognition.stopChatStream({body:{chat_id:this.chat.id,stream_id:this.id}}))}toJSON(){return{id:this.id,chatId:this.chat.id,messageId:this.message.id}}}class mO extends A{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new mO($,O,j)}async fetch(){let $=J(await this.client.cognition.getChat({path:{chat_id:this.chat.id}})).chat.messages.find((O)=>O.id===this.id);if(!$)throw new w(`Chat message ${this.id} is not yet available`);return $}content=this.field("content");role=this.field("role");async refresh(){this.detail.clear(),await this.detail.get()}toJSON(){return{...super.toJSON(),chatId:this.chat.id}}}class Z$ extends S${async send($){let{attachments:O,additionalInstructions:j,...x}=$,S=await this.mutate((Z)=>Z.cognition.sendChatMessage({body:{...x,chat_id:this.id,additional_instructions:j,attachments:O?.map((X)=>({entity_id:X.entity.id,entity_type:X.type}))}})),K=Z$.byId(this.client,S.chat_id);return hO.byId(this.client,K,S.stream_id,mO.byId(this.client,K,S.message_id))}access=new o(this.client,"chat",this);entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=J(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new Z$($,O)}static async create($,O){let{id:j}=J(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new Z$($,j)}name=this.field("name");model=this.field("model");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");messages=this.field("messages");async rename($){await this.mutate((O)=>O.cognition.patchChat({path:{chat_id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.cognition.permanentlyDeleteChat({path:{chat_id:this.id}}):O.cognition.deleteChat({path:{chat_id:this.id}}))}async copy(){let{id:$}=await this.mutate((O)=>O.cognition.copyChat({path:{chat_id:this.id}}));return new Z$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=J(await this.client.cognition.getChatHistoryHandler({path:{chat_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/chat/${this.id}`}static search=j$({filters:{chat_filters:{}},type:"chat",make:($,O)=>new Z$($,O.chat_id)});toMention(){return{tag:l$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class mx{client;constructor($){this.client=$}byId($){return Z$.byId(this.client,$)}create($){return Z$.create(this.client,$)}search($,O){return Z$.search(this.client,$,O)}}class T$ extends A{async fetch(){let O=J(await this.client.auth.getUserTeams()).find((j)=>j.id===this.id);if(!O)throw new w(`team ${this.id} not found`);return O}static byId($,O){return new T$($,O)}static async current($){let O=J(await $.auth.getTeam());if(!O)throw new w("caller has no current team");return new T$($,O.team.id,O.team)}static async list($){return J(await $.auth.getUserTeams()).map((j)=>new T$($,j.id,j))}name=this.field("name");slug=this.field("slug");defaultLinkShare=this.field("default_link_share");owner=this.mappedField("owner_id",($)=>M.byId(this.client,$));async members(){let $=J(await this.client.auth.getTeam());if(!$||$.team.id!==this.id)throw new b("members are only available for the current team (see Team.current)");return $.members.map((O)=>({user:M.byId(this.client,O.user_id),role:O.role}))}}var E6=8;class _$ extends A{parent;constructor($,O,j,x){super($,j,x);this.parent=O}get path(){return{parent_type:this.parent.type,parent_id:this.parent.id,id:this.id}}async fetch(){return J(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new _$($,O,j)}static from($,O,j){return new _$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");deletedAt=this.field("deleted_at");async threadId(){return(await this.detail.get()).thread_id??this.id}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return cO(this.client,this.parent,$,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=$$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}async function Yj($,O){let j={parent_type:O.type,parent_id:O.id},x=a(async(K)=>{let Z=J(await $.storage.messageTimeline({path:j,query:{selection:JSON.stringify({limit:100,cursor:K})}}));return{items:Z.items,nextCursor:Z.next_cursor}}),S=[];for await(let K of x)S.push(K);return bO(S,E6,async(K)=>{let{state:Z,root:X,replies:G}=J(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...G].map((L)=>_$.from($,O,L))}})}async function cO($,O,j,x){let S=J(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...$$(j),thread_id:x?.threadId??null}}));return _$.from($,O,S)}class w$ extends F${messageThreadById($){return W$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return E$(this.client,{type:"crm_contact",entity:this},(O)=>_$.from(this.client,{type:"crm_contact",id:this.id},O),$)}entityType="crm_contact";async fetch(){return J(await this.client.storage.getContact({path:{contact_id:this.id}}))}static byId($,O){return new w$($,O)}static from($,O){return new w$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>q$.byId(this.client,$));hidden=this.field("hidden");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");firstInteraction=this.field("firstInteraction");lastInteraction=this.field("lastInteraction");async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setContactHidden({path:{contact_id:this.id},body:{hidden:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmContactName({path:{contact_id:this.id},body:{name:$}}))}get commentParent(){return{type:"crm_contact",id:this.id}}async comments(){return Yj(this.client,this.commentParent)}async comment($,O){return cO(this.client,this.commentParent,$,O)}commentById($){return _$.byId(this.client,this.commentParent,$)}}class q$ extends S${messageThreadById($){return W$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return E$(this.client,{type:"crm_company",entity:this},(O)=>_$.from(this.client,{type:"crm_company",id:this.id},O),$)}entityType="crm_company";propertyEntityType="COMPANY";async fetch(){return J(await this.client.storage.getCompany({path:{company_id:this.id}}))}static byId($,O){return new q$($,O)}static from($,O){return new q$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>T$.byId(this.client,$));createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async domain(){let{domains:$}=await this.detail.get();return $[0]?.domain}async domains(){let{domains:$}=await this.detail.get();return $.map((O)=>O.domain)}async contacts(){return J(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>w$.from(this.client,O))}static search=j$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new q$($,O.id)});async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setCompanyHidden({path:{company_id:this.id},body:{hidden:$}}))}async setEmailSync($){await this.mutate((O)=>O.storage.setEmailSync({path:{company_id:this.id},body:{email_sync:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmCompanyName({path:{company_id:this.id},body:{name:$}}))}async createContact($){let O=await this.mutate((j)=>j.storage.createCrmContact({path:{company_id:this.id},body:$}));return w$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Yj(this.client,this.commentParent)}async comment($,O){return cO(this.client,this.commentParent,$,O)}commentById($){return _$.byId(this.client,this.commentParent,$)}}class a$ extends A{tableDetail=new J$(async()=>J(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new a$($,O)}static from($,O){return new a$($,O.id,O)}async fetch(){return J(await this.client.storage.getCrmPipeline({path:{id:this.id}}))}name=this.field("name");recordType=this.field("recordType");accessLevel=this.field("grant");sharing=this.field("sharing");owner=this.mappedField("userId",($)=>M.byId(this.client,$));team=this.mappedField("teamId",($)=>T$.byId(this.client,$));async rename($){await this.mutate((O)=>O.storage.renameCrmPipeline({path:{id:this.id},body:{name:$}}))}async setSharing($){if($===void 0)throw Error("Sharing is required");await this.mutate((O)=>O.storage.shareCrmPipeline({path:{id:this.id},body:{sharing:$}}))}async setTrashed($){await this.mutate((O)=>O.storage.trashCrmPipeline({path:{id:this.id},body:{trashed:$}}))}async sharePermissions(){return J(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:r$($)}))}async table(){return Qj.from(this.client,this,await this.tableRecord())}tableRecord(){return this.tableDetail.get()}rows(){return a(async($)=>{let O=J(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>XO.from(this.client,this,j)),nextCursor:O.next}})}queryRows($={}){if($.rows?.some((O)=>O.pipeline.id!==this.id))throw Error("Rows belong to another pipeline");return a(async(O)=>{let j=J(await this.client.storage.queryCrmPipelineRows({path:{id:this.id},body:{after:O,query:$.query,rowIds:$.rows?.map((x)=>x.id)}}));return{items:j.rows.map((x)=>XO.from(this.client,this,x)),nextCursor:j.next}})}async applyOps($,O){if(O?.baseVersions?.some((S)=>S.table.pipeline.id!==this.id))throw Error("Table belongs to another pipeline");let j={ops:$,baseVersions:O?.baseVersions?Object.fromEntries(O.baseVersions.map((S)=>[S.table.id,S.version])):void 0},x=await this.mutate((S)=>S.storage.applyCrmPipelineOps({path:{id:this.id},body:j}));return this.tableDetail.clear(),x}}class Qj extends A{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j){super($,j.table.id,j);this.pipeline=O}static from($,O,j){return new Qj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>Jj.from(this.client,this,$))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return XO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class XO extends A{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j,x){super($,j,x);this.pipeline=O}static byId($,O,j){return new XO($,O,j)}static from($,O,j){return new XO($,O,j.rowId,j)}async fetch(){for await(let $ of this.pipeline.queryRows({rows:[this]}))if($.id===this.id)return $.detail.get();throw new w(`Pipeline row ${this.id} is unavailable`)}cells=this.field("cells");async refresh(){this.detail.clear(),await this.detail.get()}}class Jj extends A{table;toJSON(){return{...super.toJSON(),pipelineId:this.table.pipeline.id,tableId:this.table.id}}constructor($,O,j){super($,j.column.id,j);this.table=O}static from($,O,j){return new Jj($,O,j)}async fetch(){let $=(await this.table.pipeline.tableRecord()).columns.find((O)=>O.column.id===this.id);if(!$)throw new w(`Pipeline column ${this.id} is unavailable`);return $}async writable(){return(await this.fetch()).writable}async name(){return(await this.fetch()).column.display_name??(await this.fetch()).definition.definition.display_name}}class cx{client;constructor($){this.client=$}byId($){return a$.byId(this.client,$)}async list(){return J(await this.client.storage.listCrmPipelines()).map(($)=>a$.from(this.client,$))}async create($){return a$.from(this.client,J(await this.client.storage.createCrmPipeline({body:$})))}}class ux{client;pipelines;constructor($){this.client=$;this.pipelines=new cx($)}companyById($){return q$.byId(this.client,$)}contactById($){return w$.byId(this.client,$)}async contactByEmail($){let{contact:O}=J(await this.client.storage.getContactByEmail({query:{email:$}}));return O?w$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=J(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return j.map((x)=>w$.from(this.client,x))}async createCompany($){return q$.from(this.client,J(await this.client.storage.createCrmCompany({body:$})))}async settings(){return J(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return J(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return J(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){J(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return q$.search(this.client,$)}}var G$=Symbol.for("@ts-pattern/matcher"),P1=Symbol.for("@ts-pattern/isVariadic");var dx=($)=>Boolean($&&typeof $=="object"),Vj=($)=>$&&!!$[G$],s=($,O,j)=>{if(Vj($)){let x=$[G$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if(dx($)){if(!dx(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Vj(X)&&X[P1]?K.push(X):K.length?S.push(X):x.push(X)}if(K.length){if(K.length>1)throw Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(O.length<x.length+S.length)return!1;let Z=O.slice(0,x.length),X=S.length===0?[]:O.slice(-S.length),G=O.slice(x.length,S.length===0?1/0:-S.length);return x.every((L,Y)=>s(L,Z[Y],j))&&S.every((L,Y)=>s(L,X[Y],j))&&(K.length===0||s(K[0],G,j))}return $.length===O.length&&$.every((Z,X)=>s(Z,O[X],j))}return Reflect.ownKeys($).every((x)=>{let S=$[x];return((x in O)||Vj(K=S)&&K[G$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},X$=($)=>{var O,j,x;return dx($)?Vj($)?(O=(j=(x=$[G$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?uO($,X$):uO(Object.values($),X$):[]},uO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function w6(...$){if($.length===1){let[O]=$;return(j)=>s(O,j,()=>{})}if($.length===2){let[O,j]=$;return s(O,j,()=>{})}throw Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${$.length}.`)}function t($){return Object.assign($,{optional:()=>px($),and:(O)=>u($,O),or:(O)=>F1($,O),select:(O)=>O===void 0?dO($):dO(O,$)})}function lx($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[P1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>lx(px($)),select:(O)=>lx(O===void 0?dO($):dO(O,$))})}function px($){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(X$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>X$($),matcherType:"optional"})})}var q6=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},f6=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},b6=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function u(...$){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>uO($,X$),matcherType:"and"})})}function F1(...$){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return uO($,X$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>uO($,X$),matcherType:"or"})})}function m($){return{[G$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function dO(...$){let O=typeof $[0]=="string"?$[0]:void 0,j=$.length===2?$[1]:typeof $[0]=="string"?void 0:$[0];return t({[G$]:()=>({match:(x)=>{let S={[O!=null?O:"@ts-pattern/anonymous-select-key"]:x};return{matched:j===void 0||s(j,x,(K,Z)=>{S[K]=Z}),selections:S}},getSelectionKeys:()=>[O!=null?O:"@ts-pattern/anonymous-select-key"].concat(j===void 0?[]:X$(j))})})}function E1($){return!0}function f$($){return typeof $=="number"}function i$($){return typeof $=="string"}function n$($){return typeof $=="bigint"}var w1=t(m(E1)),k6=t(m(E1)),g6=w1,s$=($)=>Object.assign(t($),{startsWith:(O)=>{return s$(u($,(j=O,m((x)=>i$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return s$(u($,(j=O,m((x)=>i$(x)&&x.endsWith(j)))));var j},minLength:(O)=>s$(u($,((j)=>m((x)=>i$(x)&&x.length>=j))(O))),length:(O)=>s$(u($,((j)=>m((x)=>i$(x)&&x.length===j))(O))),maxLength:(O)=>s$(u($,((j)=>m((x)=>i$(x)&&x.length<=j))(O))),includes:(O)=>{return s$(u($,(j=O,m((x)=>i$(x)&&x.includes(j)))));var j},regex:(O)=>{return s$(u($,(j=O,m((x)=>i$(x)&&Boolean(x.match(j))))));var j}}),A1=s$(m(i$)),b$=($)=>Object.assign(t($),{between:(O,j)=>b$(u($,((x,S)=>m((K)=>f$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>b$(u($,((j)=>m((x)=>f$(x)&&x<j))(O))),gt:(O)=>b$(u($,((j)=>m((x)=>f$(x)&&x>j))(O))),lte:(O)=>b$(u($,((j)=>m((x)=>f$(x)&&x<=j))(O))),gte:(O)=>b$(u($,((j)=>m((x)=>f$(x)&&x>=j))(O))),int:()=>b$(u($,m((O)=>f$(O)&&Number.isInteger(O)))),finite:()=>b$(u($,m((O)=>f$(O)&&Number.isFinite(O)))),positive:()=>b$(u($,m((O)=>f$(O)&&O>0))),negative:()=>b$(u($,m((O)=>f$(O)&&O<0)))}),y6=b$(m(f$)),t$=($)=>Object.assign(t($),{between:(O,j)=>t$(u($,((x,S)=>m((K)=>n$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>t$(u($,((j)=>m((x)=>n$(x)&&x<j))(O))),gt:(O)=>t$(u($,((j)=>m((x)=>n$(x)&&x>j))(O))),lte:(O)=>t$(u($,((j)=>m((x)=>n$(x)&&x<=j))(O))),gte:(O)=>t$(u($,((j)=>m((x)=>n$(x)&&x>=j))(O))),positive:()=>t$(u($,m((O)=>n$(O)&&O>0))),negative:()=>t$(u($,m((O)=>n$(O)&&O<0)))}),v6=t$(m(n$)),h6=t(m(function($){return typeof $=="boolean"})),m6=t(m(function($){return typeof $=="symbol"})),c6=t(m(function($){return $==null})),u6=t(m(function($){return $!=null})),x$={__proto__:null,matcher:G$,optional:px,array:function(...$){return lx({[G$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let j=$[0],x={};if(O.length===0)return X$(j).forEach((K)=>{x[K]=[]}),{matched:!0,selections:x};let S=(K,Z)=>{x[K]=(x[K]||[]).concat([Z])};return{matched:O.every((K)=>s(j,K,S)),selections:x}},getSelectionKeys:()=>$.length===0?[]:X$($[0])})})},set:function(...$){return t({[G$]:()=>({match:(O)=>{if(!(O instanceof Set))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};if($.length===0)return{matched:!0};let x=(K,Z)=>{j[K]=(j[K]||[]).concat([Z])},S=$[0];return{matched:q6(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:X$($[0])})})},map:function(...$){return t({[G$]:()=>({match:(O)=>{if(!(O instanceof Map))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};let x=(X,G)=>{j[X]=(j[X]||[]).concat([G])};if($.length===0)return{matched:!0};var S;if($.length===1)throw Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${(S=$[0])==null?void 0:S.toString()}`);let[K,Z]=$;return{matched:f6(O,(X,G)=>{let L=s(K,G,x),Y=s(Z,X,x);return L&&Y}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...X$($[0]),...X$($[1])]})})},record:function(...$){return t({[G$]:()=>({match:(O)=>{if(O===null||typeof O!="object"||Array.isArray(O))return{matched:!1};var j;if($.length===0)throw Error(`\`P.record\` wasn't given enough arguments. Expected (value) or (key, value), received ${(j=$[0])==null?void 0:j.toString()}`);let x={},S=(X,G)=>{x[X]=(x[X]||[]).concat([G])},[K,Z]=$.length===1?[A1,$[0]]:$;return{matched:b6(O,(X,G)=>{let L=typeof X!="string"||Number.isNaN(Number(X))?null:Number(X),Y=L!==null&&s(K,L,S),Q=s(K,X,S),T=s(Z,G,S);return(Q||Y)&&T}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...X$($[0]),...X$($[1])]})})},intersection:u,union:F1,not:function($){return t({[G$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:m,select:dO,any:w1,unknown:k6,_:g6,string:A1,number:y6,bigint:v6,boolean:h6,symbol:m6,nullish:c6,nonNullable:u6,instanceOf:function($){return t(m(function(O){return(j)=>j instanceof O}($)))},shape:function($){return t(m(w6($)))}};class q1 extends Error{constructor($){let O;try{O=JSON.stringify($)}catch(j){O=$}super(`Pattern matching error: no pattern matches value ${O}`),this.input=void 0,this.input=$}}var rx={matched:!1,value:void 0};function c($){return new Wj($,rx)}class Wj{constructor($,O){this.input=void 0,this.state=void 0,this.input=$,this.state=O}with(...$){if(this.state.matched)return this;let O=$[$.length-1],j=[$[0]],x;$.length===3&&typeof $[1]=="function"?x=$[1]:$.length>2&&j.push(...$.slice(1,$.length-1));let S=!1,K={},Z=(G,L)=>{S=!0,K[G]=L},X=!j.some((G)=>s(G,this.input,Z))||x&&!Boolean(x(this.input))?rx:{matched:!0,value:O(S?"@ts-pattern/anonymous-select-key"in K?K["@ts-pattern/anonymous-select-key"]:K:this.input,this.input)};return new Wj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Wj(this.input,j?{matched:!0,value:O(this.input,this.input)}:rx)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=d6){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function d6($){throw new q1($)}var ax,l6=new Uint8Array(16);function Bj(){if(!ax){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ax=crypto.getRandomValues.bind(crypto)}return ax(l6)}var O$=[];for(let $=0;$<256;++$)O$.push(($+256).toString(16).slice(1));function f1($,O=0){return(O$[$[O+0]]+O$[$[O+1]]+O$[$[O+2]]+O$[$[O+3]]+"-"+O$[$[O+4]]+O$[$[O+5]]+"-"+O$[$[O+6]]+O$[$[O+7]]+"-"+O$[$[O+8]]+O$[$[O+9]]+"-"+O$[$[O+10]]+O$[$[O+11]]+O$[$[O+12]]+O$[$[O+13]]+O$[$[O+14]]+O$[$[O+15]]).toLowerCase()}var ix={};function r6($,O,j){let x;if($)x=b1($.random??$.rng?.()??Bj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Bj();p6(ix,S,K),x=b1(K,ix.msecs,ix.seq,O,j)}return O??f1(x)}function p6($,O,j){if($.msecs??=-1/0,$.seq??=0,O>$.msecs)$.seq=j[6]<<23|j[7]<<16|j[8]<<8|j[9],$.msecs=O;else if($.seq=$.seq+1|0,$.seq===0)$.msecs++;return $}function b1($,O,j,x,S=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!x)x=new Uint8Array(16),S=0;else if(S<0||S+16>x.length)throw RangeError(`UUID byte range ${S}:${S+15} is out of buffer bounds`);return O??=Date.now(),j??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],x[S++]=O/1099511627776&255,x[S++]=O/4294967296&255,x[S++]=O/16777216&255,x[S++]=O/65536&255,x[S++]=O/256&255,x[S++]=O&255,x[S++]=112|j>>>28&15,x[S++]=j>>>20&255,x[S++]=128|j>>>14&63,x[S++]=j>>>6&255,x[S++]=j<<2&255|$[10]&3,x[S++]=$[11],x[S++]=$[12],x[S++]=$[13],x[S++]=$[14],x[S++]=$[15],x}var h$=r6;class M${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new M$($,O)}async detail(){let{columns:$}=await this.table.detail(),O=$.find((j)=>j.column.id===this.id);if(!O)throw new w(`column ${this.id} is not on table ${this.table.id}`);return O}async name(){let $=await this.detail();return $.column.display_name??$.definition.definition.display_name}async rename($){return await this.table.database.renameColumn(this,$),this}async inferType($){return await this.table.database.inferColumnType(this,$),this}changeType($){return this.table.database.changeColumnType(this,$)}convertIntoNewColumn($){return this.table.database.convertColumnIntoNewColumn(this,$)}casts(){return this.table.database.columnCasts(this)}async delete(){await this.table.database.deleteColumn(this)}async dataType(){return(await this.detail()).definition.definition.data_type}async isMultiSelect(){return(await this.detail()).definition.definition.is_multi_select}async position(){return(await this.detail()).column.position}async definition(){return(await this.detail()).definition}async config(){return(await this.detail()).column.config??void 0}async addOptions($){return await this.table.database.addColumnOptions(this,$),this}toJSON(){return{id:this.id,tableId:this.table.id}}}class A${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new A$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Lj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Lj($,O)}async detail(){let{views:$}=await this.table.detail(),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`view ${this.id} is not on table ${this.table.id}`);return O}async name(){return(await this.detail()).name}async position(){return(await this.detail()).position}async layout(){return(await this.detail()).layout}async query(){return(await this.detail()).query}positions(){return this.table.database.viewPositions(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Y${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new Y$($,O)}async detail(){let{tables:$}=await this.database.schema(),O=$.find((j)=>j.table.id===this.id);if(!O)throw new w(`table ${this.id} is not in database ${this.database.id}`);return O}async name(){return(await this.detail()).table.name}async rename($){return await this.database.renameTable(this,$),this}async version(){return(await this.detail()).table.version}async position(){return(await this.detail()).table.position}async columns(){let{columns:$}=await this.detail();return $.map((O)=>M$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return A$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>Lj.byId(this,O.id))}createWebhook(){return this.database.createWebhook(this)}async delete(){await this.database.deleteTable(this)}toJSON(){return{id:this.id,databaseId:this.database.id}}}async function Nj($,O,j,x={}){let S=J(await $.storage.queryDatabases({body:{sql:j,databaseId:x.database?.id,baseVersions:Object.fromEntries((x.baseVersions??[]).map(({table:Y,version:Q})=>[Y.id,Q]))}})),K=new Map;for(let Y of[x.database,...(x.baseVersions??[]).map(({table:Q})=>Q.database)]){if(!Y)continue;let Q=K.get(Y.id);if(Q)Q.add(Y);else K.set(Y.id,new Set([Y]))}let Z=(Y)=>{let Q=K.get(Y)?.values().next().value;if(Q)return Q;let T=O($,Y);return K.set(Y,new Set([T])),T},X=(Y)=>{let Q=S.tableDatabases[Y];if(!Q)throw Error(`SQL response is missing the owner of table ${Y}`);return Y$.byId(Z(Q),Y)},G=new Set(Object.keys(S.newVersions).map((Y)=>X(Y).database.id));if(S.statement.kind==="schema")G.add(S.statement.databaseId);for(let Y of G)for(let Q of K.get(Y)??[])Q.invalidateSchema();let L=c(S.statement).with({kind:"select"},(Y)=>Y).with({kind:"schema"},({databaseId:Y,summary:Q})=>({kind:"schema",database:Z(Y),summary:Q})).with({kind:"insert"},{kind:"update"},{kind:"delete"},({kind:Y,tableId:Q,tableName:T})=>({kind:Y,table:X(Q),tableName:T})).with({kind:"alterColumnType"},({tableId:Y,tableName:Q,columnId:T,columnName:z,to:W})=>{let V=X(Y);return{kind:"alterColumnType",table:V,tableName:Q,column:M$.byId(V,T),columnName:z,to:W}}).exhaustive();return{result:S.result?a6(S.result,X,S.tableDatabases):void 0,changesApplied:S.changesApplied,insertedRows:L.kind==="insert"?S.insertedRowIds.map((Y)=>A$.byId(L.table,Y)):[],newVersions:Object.entries(S.newVersions).map(([Y,Q])=>({table:X(Y),version:Q})),readVersions:Object.entries(S.readVersions).map(([Y,Q])=>({table:X(Y),version:Q})),truncatedTables:S.truncatedTables,statement:L}}function a6($,O,j){let x=$.sourceTable&&j[$.sourceTable]?O($.sourceTable):void 0;return{columns:$.columns.map(({relatedTable:S,...K})=>({...K,relatedTable:S&&j[S]?O(S):void 0})),rows:$.rows,sourceTable:x,rowHandles:x?$.rowIds.map((S)=>A$.byId(x,S)):[]}}class Uj{table;id;createdBy;record;constructor($,O,j,x){this.table=$;this.id=O;this.createdBy=j;this.record=x}static fromRecord($,O,j){return new Uj($,j.id,O,j)}get tokenPrefix(){return this.record.tokenPrefix}get createdAt(){return this.record.createdAt}delete(){return this.table.database.deleteWebhook(this)}toJSON(){return{id:this.id,tableId:this.table.id,tokenPrefix:this.tokenPrefix}}}class tx extends SO{op;row;column;taken;constructor($,O){super($,O);this.name="MacroOpRefusedError",this.message=O.message,this.op=O.op,this.row=O.row,this.column=O.column,this.taken=O.taken}}function zj($){return c($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:x$.not("relation")},(O)=>O).exhaustive()}var i6={USER:"People",DOCUMENT:"Documents",TASK:"Tasks",COMPANY:"Companies",CONTACT:"Contacts",CALL_RECORD:"Calls",CHANNEL:"Channels",CHAT:"Chats",PROJECT:"Projects",THREAD:"Emails",CALENDAR_EVENT:"Events",INITIATIVE:"Initiatives"};function n6($){return c($).with({type:"text"},()=>"Text").with({type:"number"},()=>"Number").with({type:"boolean"},()=>"Checkbox").with({type:"date"},()=>"Date").with({type:"link"},()=>"URL").with({type:"select",multi:!0},()=>"Multi-select").with({type:"select",multi:!1},()=>"Select").with({type:"select_number",multi:!0},()=>"Multi-number select").with({type:"select_number",multi:!1},()=>"Number select").with({type:"tag"},()=>"Tag").with({type:"entity"},({target:O})=>i6[O]).with({type:"relation"},()=>"Relation").exhaustive()}function nx($){return $.map((O)=>({id:h$(),label:O}))}function k1($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function sx($){return c($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:x$.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive()}function m$($,O,j){let[x]=$;if($.length!==1||!k1(x,O,j))throw new b(`expected one ${O}.${j} result, got ${$.map(sx).join(", ")||"none"}`);return x}class Q$ extends A{access=new o(this.client,"database",this);async fetch(){return J(await this.client.storage.getDatabase({path:{id:this.id}}))}assertOwns($,O){if(O.id!==this.id)throw new b(`${$} does not belong to database ${this.id}`)}static byId($,O){return new Q$($,O)}static async create($,O){let j=J(await $.storage.createDatabase({body:{name:O.name}}));return new Q$($,j.id)}static async list($){return J(await $.storage.listDatabases()).map((j)=>new Q$($,j.database.id))}query($,O){return Nj(this.client,Q$.byId,$,{...O,database:this})}invalidateSchema(){this.detail.clear()}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>M.byId(this.client,$.owner_id));createdAt=this.mappedField("database",($)=>$.created_at);trashedAt=this.mappedField("database",($)=>$.trashed_at??void 0);grant=this.field("grant");tables=this.mappedField("tables",($)=>$.map((O)=>Y$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?Y$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=m$(await this.applyOps([{kind:"table",table:h$(),change:{kind:"create",name:$.name}}]),"table","created");return Y$.byId(this,O)}async applyOps($,O={}){let j={ops:$};if(O.baseVersions!==void 0){for(let{table:S}of O.baseVersions)this.assertOwns(`table ${S.id}`,S.database);j.baseVersions=Object.fromEntries(O.baseVersions.map(({table:S,version:K})=>[S.id,K]))}let{results:x}=await this.mutate(async(S)=>{let K=await S.storage.applyDatabaseOps({path:{id:this.id},body:j});if(K.error!==void 0&&"op"in K.error)throw new tx(K.response?.status??0,K.error);return K});return x}async reorderTables($){for(let x of $)this.assertOwns(`table ${x.id}`,x.database);let O=await this.applyOps([{kind:"reorder_tables",order:$.map((x)=>x.id)}]),[j]=O;if(O.length!==1||j?.kind!=="reorder_tables")throw new b(`expected one reorder_tables result, got ${O.map(sx).join(", ")||"none"}`);return j.tables.map(({table:x})=>Y$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),m$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),J(await this.client.storage.listDatabaseColumnCasts({path:{id:this.id,table_id:$.table.id,column_id:$.id}}))}async viewPositions($){this.assertOwns(`view ${$.id}`,$.table.database);let{positions:O}=J(await this.client.storage.getDatabaseViewPositions({path:{id:this.id,view_id:$.id}}));return O}async rowHistory($){this.assertOwns(`row ${$.id}`,$.table.database);let{changes:O}=J(await this.client.storage.getDatabaseRowHistory({path:{id:this.id,table_id:$.table.id,row_id:$.id}}));return O}async importTable($){let O=await this.mutate((j)=>j.storage.importDatabaseTable({path:{id:this.id},body:$}));return Y$.byId(this,O.id)}webhookOf($){return Uj.fromRecord(Y$.byId(this,$.tableId),M.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=J(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=J(await this.client.storage.createDatabaseWebhook({path:{id:this.id},body:{tableId:$.id}}));return{webhook:this.webhookOf(O.webhook),token:O.token}}async deleteWebhook($){this.assertOwns("webhook",$.table.database),J(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return J(await this.client.storage.getDatabasePermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateDatabasePermissions({path:{id:this.id},body:$}))}async changeColumnType($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.table.version();return m$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:zj(O.to)}}],{baseVersions:[{table:$.table,version:j}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),J(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:zj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${n6(O.to)})`,S=h$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:zj(O.to),options:nx(j.options)},after:$.id}}];if(j.cells.length>0)K.push({kind:"rows",table:$.table.id,change:{kind:"update",changes:{kind:"per_row",rows:j.cells.map(({row:X,value:G})=>({row:X,cells:[{column:S,value:G}]}))}}});let[Z]=await this.applyOps(K,{baseVersions:[{table:$.table,version:j.tableVersion}]});if(!k1(Z,"column","created"))throw new b(`expected a column.created result, got ${Z?sx(Z):"none"}`);return M$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=m$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"delete"}}],{baseVersions:[{table:$.table,version:O}]}),"column","deleted");return j}async reorderColumns($,O){this.assertOwns(`table ${$.id}`,$.database);for(let S of O)if(S.table.id!==$.id)throw new b(`column ${S.id} does not belong to table ${$.id}`);let j=await $.version(),{tableVersion:x}=m$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"reorder_columns",order:O.map((S)=>S.id)}}],{baseVersions:[{table:$,version:j}]}),"table","columns_reordered");if(x===void 0)throw new b(`table ${$.id} reordered its columns without a version`);return x}async renameTable($,O){this.assertOwns(`table ${$.id}`,$.database);let j=await $.name(),{tableVersion:x}=m$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"rename",name:O,previousName:j}}]),"table","renamed");if(x===void 0)throw new b(`table ${$.id} was renamed without a version`);return x}async renameColumn($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.name(),{tableVersion:x}=m$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"rename",name:O,previousName:j}}]),"column","renamed");return x}async inferColumnType($,O){return this.assertOwns(`column ${$.id}`,$.table.database),this.mutate((j)=>j.storage.inferDatabaseColumnType({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{dataType:O.dataType,baseVersion:O.baseVersion,...O.specificEntityType!==void 0?{specificEntityType:O.specificEntityType}:{}}}))}async addColumn($,O){if(this.assertOwns(`table ${$.id}`,$.database),O.after!==void 0&&O.after.table.id!==$.id)throw new b(`column ${O.after.id} does not belong to table ${$.id}`);let j="property"in O?{source:"existing",property:O.property.id}:{source:"new",name:O.name,type:zj(O.type),...O.options!==void 0?{options:nx(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=m$(await this.applyOps([{kind:"column",table:$.id,column:h$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return M$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),m$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:nx(O)}}]),"column","options_added")}}class ex{client;constructor($){this.client=$}query($,O){return Nj(this.client,Q$.byId,$,O)}byId($){return Q$.byId(this.client,$)}create($){return Q$.create(this.client,$)}list(){return Q$.list(this.client)}}class GO extends A{document;toJSON(){return{...super.toJSON(),documentId:this.document.id}}constructor($,O,j,x){super($,j,x);this.document=O}static byId($,O,j){return new GO($,O,j)}static from($,O,j){return new GO($,O,j.uuid,j)}async fetch(){let $=J(await this.client.storage.getDocumentAnchors({path:{document_id:this.document.id}})).data.find((O)=>O.uuid===this.id);if(!$)throw new w(`Annotation ${this.id} is unavailable`);return $}kind=this.field("anchorType");page=this.field("page");async edit($){if(await this.kind()!=="placeable")throw Error("Only placeable comment annotations can be edited");await this.mutate((O)=>O.storage.editAnchor({body:{...$,uuid:this.id,anchorType:"free-comment",fileType:"pdf"}}))}async delete(){if(await this.kind()!=="highlight")throw Error("Only standalone highlights can be deleted with this endpoint");await this.mutate(($)=>$.storage.deleteAnchor({body:{uuid:this.id,anchorType:"highlight",fileType:"pdf"}}))}}class c$ extends A{documentId;constructor($,O,j,x){super($,j,x);this.documentId=O}get path(){return{parent_type:"document",parent_id:this.documentId,id:this.id}}async fetch(){return J(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new c$($,O,j)}static from($,O,j){return new c$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");async threadId(){return(await this.detail.get()).thread_id??this.id}document(){return q.byId(this.client,this.documentId)}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return this.document().comment($,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=$$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class lO{client;document;id;detail;constructor($,O,j){this.client=$;this.document=O;this.id=j;this.detail=new J$(async()=>J(await this.client.storage.getDocumentVersion({path:{document_id:O.id,document_version_id:j}})).data)}static byId($,O,j){return new lO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var s6=8;class q extends S${async anchors(){return J(await this.client.storage.getDocumentAnchors({path:{document_id:this.id}})).data.map(($)=>GO.from(this.client,this,$))}async createHighlight($){return GO.from(this.client,this,J(await this.client.storage.createAnchor({path:{document_id:this.id},body:{...$,fileType:"pdf",anchorType:"highlight"}})))}version($){return lO.byId(this.client,this,$)}async sharePermissions(){return J(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return J(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return J(await this.client.storage.presaveDocumentHandler({path:{document_id:this.id},body:{newBom:$}})).data}async save($){return(await this.mutate((O)=>O.storage.saveDocumentHandler({path:{document_id:this.id},body:$}))).data}async simpleSave(){return(await this.mutate(($)=>$.storage.simpleSave({path:{document_id:this.id}}))).data}messageThreadById($){return W$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return E$(this.client,{type:"document",entity:this},(O)=>c$.from(this.client,this.id,O),$)}access=new o(this.client,"document",this);async fetch(){let{data:$}=J(await this.client.storage.getDocument({path:{document_id:this.id}}));return $.documentMetadata}static byId($,O){return new q($,O)}static async create($,O){let{documentId:j}=J(await $.storage.createMarkdownHandler({body:{documentName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new q($,j)}static async createSnippet($,O){let{documentId:j}=J(await $.storage.createSnippetHandler({body:{snippetName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new q($,j)}static async createSkill($,O){let{documentId:j}=J(await $.storage.createSkillHandler({body:{skillName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new q($,j)}static recent($,O){let j=O?.pageSize??50;return a(async(x)=>{let S=J(await $.storage.getUserDocumentsHandler({query:{limit:j,offset:x?Number(x):0,...O?.fileType!==void 0?{file_type:O.fileType}:{}}})),K=S.data?.next_offset;return{items:(S.data?.documents??[]).map((Z)=>new q($,Z.documentId)),nextCursor:K!=null?String(K):null}})}static async recentlyDeleted($){let{data:O}=J(await $.storage.recentlyDeleted({}));return O.items.filter((j)=>j.type==="document").map((j)=>new q($,j.id))}entityType="document";propertyEntityType="DOCUMENT";name=this.field("documentName");fileType=this.field("fileType");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);owner=this.mappedField("owner",($)=>M.byId(this.client,$));branchedFrom=this.mappedField("branchedFromId",($)=>$?q.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");deletedAt=this.field("deletedAt");async content(){let{text:$}=J(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=J(await this.client.storage.exportDocument({path:{document_id:this.id}})),j=await fetch(O);if(!j.ok)throw new SO(j.status,{message:"failed to download document content"});return j.text()}async rename($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{documentName:$}}))}async move($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{projectId:$?.id??""}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteDocument({path:{document_id:this.id}}):O.storage.deleteDocument({path:{document_id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteDocument({path:{document_id:this.id}}))}async copy($){let{data:O}=J(await this.client.storage.copyDocument({path:{document_id:this.id},query:$.versionId!==void 0?{version_id:$.versionId}:void 0,body:{documentName:$.name}}));return new q(this.client,O.documentMetadata.documentId)}async comments(){let $={parent_type:"document",parent_id:this.id},O=a(async(x)=>{let S=J(await this.client.storage.messageTimeline({path:$,query:{selection:JSON.stringify({limit:100,cursor:x})}}));return{items:S.items,nextCursor:S.next_cursor}}),j=[];for await(let x of O)j.push(x);return bO(j,s6,async(x)=>{let{state:S,root:K,replies:Z}=J(await this.client.storage.entityMessageGetThread({path:{...$,id:x.id}}));return{thread:S,comments:[K,...Z].map((X)=>c$.from(this.client,this.id,X))}})}async comment($,O){let j=await this.mutate((x)=>x.storage.entityMessageCreate({path:{parent_type:"document",parent_id:this.id},body:{...$$($),thread_id:O?.threadId??null}}));return c$.from(this.client,this.id,j)}async shortId(){return J(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return J(await this.client.storage.getDocumentTeamShare({path:{document_id:this.id}}))}async setTeamShare($){await this.mutate((O)=>O.storage.setDocumentTeamShare({path:{document_id:this.id},body:{shareWithTeam:$}}))}async githubPullRequests(){let{pullRequests:$}=J(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=J(await this.client.storage.getDocumentBranchName({path:{document_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/md/${this.id}`}static search=j$({filters:{document_filters:{}},type:"document",make:($,O)=>new q($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:l$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class Ij{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=J(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Ij(j.id,j.name))}}class ox{client;async byTeamSlug($){let O=J(await this.client.storage.getDocumentByTeamSlug({path:{slug:$}}));if(typeof O!=="object"||O===null||!("data"in O)||typeof O.data!=="object"||O.data===null||!("documentMetadata"in O.data)||typeof O.data.documentMetadata!=="object"||O.data.documentMetadata===null||!("documentId"in O.data.documentMetadata)||typeof O.data.documentMetadata.documentId!=="string")throw Error("Invalid team task document response");return q.byId(this.client,O.data.documentMetadata.documentId)}async validatePermissionsToken($){let O=J(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:q.byId(this.client,O.document_id),user:O.user_id?M.byId(this.client,O.user_id):void 0,accessLevel:O.access_level,expiresAt:O.exp,issuer:O.iss}}async createUpload($){let O={documentName:$.name,sha:$.sha,fileType:$.fileType,mimeType:$.mimeType,projectId:$.project?.id,teamId:$.team?.id,branchedFromId:$.branchedFrom?.id,emailAttachmentId:$.attachment?.id,isTask:$.isTask},j=J(await this.client.storage.createDocument({body:O})).data;return{document:q.byId(this.client,j.documentMetadata.documentId),uploadUrl:j.presignedUrl??void 0,contentType:j.contentType,content:j.documentMetadata.content}}constructor($){this.client=$}byId($){return q.byId(this.client,$)}create($){return q.create(this.client,$)}createSnippet($){return q.createSnippet(this.client,$)}createSkill($){return q.createSkill(this.client,$)}systemSkills(){return Ij.list(this.client)}search($,O){return q.search(this.client,$,O)}recent($){return q.recent(this.client,$)}recentlyDeleted(){return q.recentlyDeleted(this.client)}}class KO extends A{async fetch(){let{attachment:$}=J(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new KO($,O)}static from($,O){return new KO($,O.db_id,O)}filename=this.field("filename");mimeType=this.field("mime_type");size=this.field("size_bytes");dataUrl=this.field("data_url");sfsId=this.field("sfs_id");contentId=this.field("content_id");async toDocument(){let{document_id:$}=J(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return q.byId(this.client,$)}}class H$ extends S${access=new o(this.client,"email_thread",this);async followup(){return J(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return J(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return J(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}async update($){await this.mutate((O)=>O.storage.editThreadV2({path:{thread_id:this.id},body:{projectId:$.project===void 0?void 0:$.project?.id??null,sharePermission:$.sharePermission?r$($.sharePermission):void 0}}))}entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=J(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new H$($,O)}createdAt=this.field("created_at");updatedAt=this.field("updated_at");isRead=this.field("is_read");inboxVisible=this.field("inbox_visible");accessLevel=this.field("access_level");providerId=this.field("provider_id");link=this.mappedField("link_id",($)=>U$.byId(this.client,$));project=this.mappedField("project_id",($)=>$?n.byId(this.client,$):void 0);latestInboundAt=this.field("latest_inbound_message_ts");latestOutboundAt=this.field("latest_outbound_message_ts");latestNonSpamAt=this.field("latest_non_spam_message_ts");async subject(){let{messages:$}=await this.detail.get();for(let O of $)if(O.subject)return O.subject;return}async participants(){let{messages:$}=await this.detail.get(),O=new Map;for(let j of $)for(let x of[j.from,...j.to,...j.cc,...j.bcc])if(x&&!O.has(x.email))O.set(x.email,x);return[...O.values()]}async messages($){return J(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((j)=>R$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>KO.from(this.client,j)))}async reply($){let O=$.subject??await this.subject()??"",{message:j}=await this.mutate((x)=>x.email.sendMessage({body:{message:{thread_db_id:this.id,replying_to_id:$.replyingTo?.id??null,to:$.to,cc:$.cc??null,bcc:$.bcc??null,subject:O,body_text:$.bodyText}}}));return j.db_id?R$.byId(this.client,j.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}async updateState($){await this.mutate((O)=>O.email.updateThreadState({path:{id:this.id},body:$}))}async operations(){return J(await this.client.email.threadOperations({path:{id:this.id}}))}async markSeen(){await this.mutate(($)=>$.email.threadSeen({path:{id:this.id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!1}}))}async moveToProject($){await this.mutate((O)=>O.email.updateThreadProject({path:{thread_id:this.id},body:{projectId:$?.id??null}}))}static search=j$({filters:{email_filters:{}},type:"email",make:($,O)=>new H$($,O.thread_id)})}class R$ extends A{async fetch(){return J(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new R$($,O)}static from($,O){return new R$($,O.db_id,O)}static async send($,O){let{message:j}=J(await $.email.sendMessage({body:{message:{to:O.to,cc:O.cc??null,bcc:O.bcc??null,subject:O.subject,body_text:O.bodyText}}}));return j.db_id?R$.byId($,j.db_id):void 0}subject=this.field("subject");from=this.field("from");to=this.field("to");cc=this.field("cc");bcc=this.field("bcc");body=this.field("body_parsed");sentAt=this.field("internal_date_ts");labels=this.field("labels");link=this.mappedField("link_id",($)=>U$.byId(this.client,$));async operationStatus(){return J(await this.client.email.messageOperationStatus({path:{id:this.id}}))}async resolveOperation($){await this.mutate((O)=>O.email.resolveMessageOperation({path:{id:this.id},body:$}))}async completeDraftAttachment($){let O=await this.link();await this.mutate((j)=>j.email.completeDraftAttachment({path:{id:this.id,attachment_id:$},headers:{"X-Email-Link-Id":O.id}}))}async transferDraft($){let O=await this.link();return this.mutate((j)=>j.email.transferDraft({path:{id:this.id},body:$,headers:{"X-Email-Link-Id":O.id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!1}}))}async thread(){return H$.byId(this.client,(await this.detail.get()).thread_db_id)}}class YO extends R${async inboxHeaders(){return{"X-Email-Link-Id":(await this.link()).id}}static byId($,O){return new YO($,O)}async update($){let O=await this.inboxHeaders();await this.mutate((j)=>j.email.createDraft({headers:O,body:{draft:{...$0($),db_id:this.id}}}))}async delete(){let $=await this.inboxHeaders();await this.mutate((O)=>O.email.deleteDraft({path:{id:this.id},headers:$}))}async schedule($,O){let j=await this.inboxHeaders();await this.mutate((x)=>x.email.upsertScheduledMessage({path:{id:this.id},headers:j,body:{send_time:$,include_signature:O?.includeSignature}}))}async unschedule(){let $=await this.inboxHeaders();await this.mutate((O)=>O.email.deleteScheduledDraft({path:{message_id:this.id},headers:$}))}async addAttachment($){let O={file_name:$.fileName,sha:$.sha,size:$.size,upload_id:$.uploadId},j=await this.inboxHeaders(),x=await this.mutate((S)=>S.email.addDraftAttachment({path:{id:this.id},headers:j,body:O}));return{attachment:rO.byId(this.client,this,x.attachment_id),uploadUrl:x.upload_url,contentType:x.content_type}}async forwardAttachment($){let O=await this.inboxHeaders(),j=await this.mutate((x)=>x.email.addForwardedAttachment({path:{id:this.id},headers:O,body:{attachment_id:$.id}}));return rO.byId(this.client,this,j.attachment_id,!0)}async removeAttachment($){if($.draft.id!==this.id)throw Error("Attachment belongs to another draft");let O=await this.inboxHeaders();if($.forwarded)await this.mutate((j)=>j.email.removeForwardedAttachment({path:{id:this.id,attachment_id:$.id},headers:O}));else await this.mutate((j)=>j.email.removeDraftAttachment({path:{id:this.id,attachment_id:$.id},headers:O}))}async verifyAttachment($){if($.draft.id!==this.id||$.forwarded)throw Error("Expected an uploaded attachment on this draft");await this.completeDraftAttachment($.id)}}class rO{draft;id;forwarded;constructor($,O,j){this.draft=$;this.id=O;this.forwarded=j}static byId($,O,j,x=!1){return new rO(O,j,x)}complete(){return this.draft.verifyAttachment(this)}remove(){return this.draft.removeAttachment(this)}toJSON(){return{id:this.id,draftId:this.draft.id,forwarded:this.forwarded}}}function $0($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:K,thread:Z,replyingTo:X,...G}=$;return{...G,body_text:O,body_html:j===void 0?void 0:btoa(Array.from(new TextEncoder().encode(j),(L)=>String.fromCharCode(L)).join("")).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),body_macro:x,headers_json:S,include_signature:K,thread_db_id:Z?.id,replying_to_id:X?.id}}class QO extends A{inbox;constructor($,O,j,x){super($,O,j);this.inbox=x}get headers(){return this.inbox?{"X-Email-Link-Id":this.inbox.id}:void 0}static byId($,O,j){return new QO($,O,void 0,j)}static from($,O,j){return new QO($,O.id,O,j)}async fetch(){let $=J(await this.client.email.listEmailFilters({headers:this.headers})).filters.find((O)=>O.id===this.id);if(!$)throw new w(`Email filter ${this.id} is unavailable`);return $}emailAddress=this.field("email_address");emailDomain=this.field("email_domain");isImportant=this.field("is_important");async setImportant($){let O=await this.detail.get();await this.mutate((j)=>j.email.upsertEmailFilter({headers:this.headers,body:{email_address:O.email_address,email_domain:O.email_domain,is_important:$}}))}async delete(){await this.mutate(($)=>$.email.deleteEmailFilter({path:{id:this.id},headers:this.headers}))}}class e$ extends A{async fetch(){let{labels:$}=J(await this.client.email.listLabels()),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`label ${this.id} not found`);return O}static byId($,O){return new e$($,O)}static async list($){let{labels:O}=J(await $.email.listLabels());return O.map((j)=>new e$($,j.id,j))}static async create($,O){let{label:j}=J(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new b("created label has no id");return new e$($,j.id)}async delete(){J(await this.client.email.deleteLabel({path:{id:this.id}}))}name=this.field("name");linkId=this.field("linkId");type=this.field("type");createdAt=this.field("createdAt");labelListVisibility=this.field("labelListVisibility");messageListVisibility=this.field("messageListVisibility")}class O0{client;async createDraft($,O){let j=J(await this.client.email.createDraft({body:{draft:$0($)},headers:O?{"X-Email-Link-Id":O.id}:void 0}));if(!j.draft.db_id)throw Error("Draft response has no message id");return YO.byId(this.client,j.draft.db_id)}draftById($){return YO.byId(this.client,$)}async*scheduled($){let O=$?.pageSize??100;if(!Number.isInteger(O)||O<1)throw Error("pageSize must be positive");let j=Math.min(O,1000);for(let x=0;;x+=j){let S=J(await this.client.email.getScheduledMessages({query:{offset:x,limit:j},headers:$?.inbox?{"X-Email-Link-Id":$.inbox.id}:void 0}));for(let K of S.messages)yield YO.byId(this.client,K.db_id);if(S.messages.length<j)return}}async filters($){return J(await this.client.email.listEmailFilters({headers:$?{"X-Email-Link-Id":$.id}:void 0})).filters.map((O)=>QO.from(this.client,O,$))}async upsertFilter($,O){return QO.from(this.client,J(await this.client.email.upsertEmailFilter({headers:O?{"X-Email-Link-Id":O.id}:void 0,body:{email_address:$.emailAddress,email_domain:$.emailDomain,is_important:$.isImportant}})).filter,O)}async contacts(){return J(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return a(async(x)=>{let S=J(await this.client.storage.listEmailReminders({query:{...j,inboxIds:O?.map((K)=>K.id),cursor:x}}));return{items:S.items.map(({threadId:K,...Z})=>({...Z,thread:H$.byId(this.client,K)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return H$.byId(this.client,$)}message($){return R$.byId(this.client,$)}attachment($){return KO.byId(this.client,$)}link($){return U$.byId(this.client,$)}links(){return U$.list(this.client)}async connectionProviders(){return J(await this.client.auth.emailConnectionProviders())}async recoverDraftTransfer($){return J(await this.client.email.recoverDraftTransfer({path:{id:$}}))}send($){return R$.send(this.client,$)}search($,O){return H$.search(this.client,$,O)}inbox($){return a(async(O)=>{let j=J(await this.client.email.previewsInboxCursor({path:{view:"inbox"},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.sort?{sort_method:$.sort}:{},...O?{cursor:O}:{}}}));return{items:j.items.map((x)=>H$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return e$.byId(this.client,$)}labels(){return e$.list(this.client)}createLabel($){return e$.create(this.client,$)}async deleteLabel($){J(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){J(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){J(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return J(await this.client.email.listBlockedSenders()).blocked_emails}}class BO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new BO($,O)}async delete(){J(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class j0{client;constructor($){this.client=$}byId($){return BO.byId(this.client,$)}async create($,O){let j=J(await this.client.storage.createEntityMention({body:{source_entity_id:$.entity.id,source_entity_type:$.type,entity_id:O.entity.id,entity_type:O.type}}));return BO.byId(this.client,j.id)}}class x0{client;constructor($){this.client=$}async list($={}){let{favorites:O}=J(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return J(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){J(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){J(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class o$ extends F${entityType="foreign_entity";async fetch(){return J(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new o$($,O)}static fromRecord($,O){return new o$($,O.id,O)}foreignEntityId=this.field("foreignEntityId");source=this.field("foreignEntitySource");storedForId=this.field("storedForId");storedForAuthEntity=this.field("storedForAuthEntity");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async metadata(){return(await this.detail.get()).metadata}}function g1({login:$,...O}){return{...O,login:$??void 0}}class S0{client;constructor($){this.client=$}byId($){return o$.byId(this.client,$)}async bySource($,O){return o$.fromRecord(this.client,J(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:j,labels:x}=J(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map(g1),assignees:j.map(g1),labels:x.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class u${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new u$($,O)}async detail(){let O=(await this.form.schema()).sections.flatMap((j)=>j.kind==="questions"?j.questions:[]).find((j)=>j.id===this.id);if(!O)throw new w(`question ${this.id} is not on form ${this.form.id}`);return O}async title(){return(await this.detail()).title}async column(){return M$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>JO.byId(this,$.id))}}class JO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new JO($,O)}async detail(){let $=(await this.question.detail()).options.find((O)=>O.id===this.id);if(!$)throw new w(`option ${this.id} is not on question ${this.question.id}`);return $}async label(){return(await this.detail()).label}async color(){return(await this.detail()).color??void 0}}class LO{form;id;detail;constructor($,O,j){this.form=$;this.id=O;this.detail=new J$(()=>this.load(),j)}async load(){let $=await this.form.myResponse();if($.response.id!==this.id)throw new w(`response ${this.id} is not your current response`);return $}static byId($,O,j){return new LO($,O,j)}async status(){return(await this.detail.get()).status}async row(){return(await this.detail.get()).row}async answers(){return(await this.detail.get()).answers}async booking(){return(await this.detail.get()).booking}async refresh(){let $=await this.load();return this.detail=new J$(()=>this.load(),$),this}}class d${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new d$($,O)}async detail(){let $=(await this.form.schema()).sections.find((O)=>O.id===this.id);if(!$)throw new w(`section ${this.id} is not on form ${this.form.id}`);return $}async title(){return(await this.detail()).title}async questions(){let $=await this.detail();return $.kind==="questions"?$.questions.map((O)=>u$.byId(this.form,O.id)):[]}}class Tj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Tj($,O)}}class k$ extends A{async fetch(){return J(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new k$($,O)}static async create($,O){let j=J(await $.storage.createForm({body:{name:O.name,source:O.table?{kind:"table",databaseId:O.table.database.id,tableId:O.table.id}:{kind:"new"}}}));return new k$($,j.form.id,j)}static async list($,O){if(!O)return J(await $.storage.listAccessibleForms()).map(({form:S})=>new k$($,S.id));return J(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new k$($,x.id))}schema(){return this.detail.get()}name=this.mappedField("form",($)=>$.name);description=this.mappedField("form",($)=>$.description);owner=this.mappedField("form",($)=>M.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>Q$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>Y$.byId(Q$.byId(this.client,$.databaseId),$.tableId));audience=this.mappedField("form",($)=>$.audience);status=this.mappedField("form",($)=>$.status);closesAt=this.mappedField("form",($)=>$.closesAt??void 0);access=this.field("access");async sections(){return(await this.detail.get()).sections.map(($)=>d$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>u$.byId(this,O.id)):[])}async update($){return await this.mutate((O)=>O.storage.updateForm({path:{id:this.id},body:$})),this}assertOwns($){if($.form.id!==this.id)throw new b(`question or section does not belong to form ${this.id}`)}async replaceLayout($){let O=await this.table(),j=(Z)=>{if(Z.table.id!==O.id||Z.table.database.id!==O.database.id)throw new b(`column does not belong to form ${this.id}'s table`);return Z.id},x=(Z)=>({conjunction:Z.conjunction,conditions:Z.conditions.map((X)=>c(X).with({kind:"group"},(G)=>({kind:"group",...x(G)})).with({kind:"condition"},(G)=>({kind:"condition",column:j(G.column),test:c(G.test).with({kind:"options"},(L)=>({...L,options:L.options.map((Y)=>Y.id)})).with({kind:"entities"},(L)=>({...L,entities:L.entities.map((Y)=>Y.id)})).with({kind:x$.union("presence","text","number","date","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((Z)=>{if(Z.section)this.assertOwns(Z.section);let X={id:Z.section?.id??h$(),title:Z.title,description:Z.description??""};return c(Z).with({kind:"booking"},(G)=>({...X,kind:"booking",target:G.target})).with({kind:"gate"},(G)=>({...X,kind:"gate",rules:x(G.rules),message:G.message})).with({kind:"questions"},(G)=>({...X,kind:"questions",questions:G.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??h$(),column:j(L.column),helpText:L.helpText??"",required:L.required??!1,widget:L.widget??null}})})).exhaustive()})},K=await this.mutate((Z)=>Z.storage.putFormLayout({path:{id:this.id},body:S}));return{form:this,publicationError:K.publicationError}}wireAnswers($){return $.map(({question:O,value:j})=>{this.assertOwns(O);let x=c(j).with({type:"rows"},(S)=>({type:"rows",value:S.value.map((K)=>K.id)})).with({type:"options"},(S)=>({type:"options",value:S.value.map((K)=>{if(K.question.id!==O.id||K.question.form.id!==this.id)throw new b("option does not belong to the answered question");return{id:K.id}})})).with({type:"entities"},(S)=>({type:"entities",value:S.value.map(({entityType:K,entity:Z})=>({entityType:K,entityId:Z.id}))})).with({type:x$.union("text","number","boolean","date","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:d$.byId(this,$.section)}:void 0}async outcome($,O){return c($).with({outcome:"stopped"},(j)=>({...j,section:d$.byId(this,j.section)})).with({outcome:"submitted"},async(j)=>{let x=A$.byId(await this.table(),j.row),S=this.unlockedBooking(j.booking);return{outcome:"submitted",response:LO.byId(this,j.response,{status:"submitted",row:x,answers:O,booking:S}),row:x,...S?{booking:S}:{}}}).exhaustive()}async submit($){let O={answers:this.wireAnswers($)};return this.outcome(J(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(J(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=J(await this.client.storage.getMyFormResponse({path:{id:this.id}})),O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=u$.byId(this,K.question),X=await c(K.value).with({type:"options"},(G)=>({type:"options",value:G.value.map((L)=>{if(!("id"in L))throw new b("stored form answers must reference options by id");return JO.byId(Z,L.id)})})).with({type:"entities"},(G)=>({type:"entities",value:G.value.map((L)=>({entityType:L.entityType,entity:Tj.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(G)=>{let L=await Z.detail();if(L.kind.type!=="relation")throw new b("row answer requires a relation question");let Y=Y$.byId(Q$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:G.value.map((Q)=>A$.byId(Y,Q))}}).with({type:x$.union("text","number","boolean","date","link","clear")},(G)=>G).exhaustive();return{question:Z,value:X}})),x=$.response.row?A$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{...S?{booking:S}:{},response:LO.byId(this,$.response.id,{status:$.response.status,row:x,answers:j,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?d$.byId(this,$.response.stoppedAtSection):void 0,row:x,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:j}}async responseSummary(){let $=J(await this.client.storage.getFormResponseSummary({path:{id:this.id}}));return{...$,stoppedBySection:$.stoppedBySection.map((O)=>({section:d$.byId(this,O.section),count:O.count}))}}async tally(){return J(await this.client.storage.getFormTally({path:{id:this.id}})).questions.map((O)=>{let j=u$.byId(this,O.question);return{question:j,responses:O.responses,buckets:O.buckets.map((x)=>({count:x.count,value:c(x.value).with({kind:"option"},(S)=>({kind:"option",option:JO.byId(j,S.option)})).with({kind:"checkbox"},(S)=>S).exhaustive()}))}})}async sharePermissions(){return J(await this.client.storage.getFormPermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateFormPermissions({path:{id:this.id},body:$}))}webUrl(){return`${this.client.webAppUrl}/app/form/${this.id}`}respondUrl(){return`${this.client.webAppUrl}/app/form/${this.id}/respond`}}class Z0{client;constructor($){this.client=$}byId($){return k$.byId(this.client,$)}create($){return k$.create(this.client,$)}list($){return k$.list(this.client,$)}}class NO extends A{static byId($,O){return new NO($,O)}async fetch(){return J(await this.client.storage.getGithubPullRequest({path:{id:this.id}}))}title=this.field("title");url=this.field("url");status=this.field("status");async changes(){let $=J(await this.client.storage.getGithubPullRequestChanges({path:{id:this.id}}));return{changeset:$.changeset?new X0(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class X0{client;pullRequest;record;constructor($,O,j){this.client=$;this.pullRequest=O;this.record=j}get id(){return this.record.id}async patch(){return J(await this.client.storage.getGithubPullRequestChangesPatch({path:{id:this.pullRequest.id},query:{changeset:this.id}})).patch}toJSON(){return{pullRequestId:this.pullRequest.id,...this.record}}}class G0{client;constructor($){this.client=$}byId($){return NO.byId(this.client,$)}forEntity($){return NO.byId(this.client,$.id)}}class UO extends A{static byId($,O){return new UO($,O)}async fetch(){return J(await this.client.storage.getHarnessPairing({path:{code:this.id}}))}name=this.field("requested_name");expiresAt=this.field("expires_at");async approve($){let O={name:$?.name,team_id:$?.team?.id,allow_permission_bypass:$?.allowPermissionBypass};return V$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class pO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new pO($,O)}async claim($){let O=J(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:V$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class K0{client;constructor($){this.client=$}byId($){return V$.byId(this.client,$)}async list(){return J(await this.client.storage.listHarnesses()).map(($)=>V$.from(this.client,$))}async me(){return V$.from(this.client,J(await this.client.storage.getSelfHarness()))}async deleteSelf(){J(await this.client.storage.deleteSelfHarness())}async agents(){return J(await this.client.storage.listHarnessAgents()).map(($)=>N$.byId(this.client,$.bot_id))}async sessions(){return J(await this.client.storage.listHarnessSessions()).map(($)=>i.byId(this.client,$.session_id))}pairing($){return UO.byId(this.client,$)}async createPairing($){let O=J(await this.client.storage.createHarnessPairing({body:$}));return{pairing:UO.byId(this.client,O.code),device:pO.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}var t6="00000001-0000-0000-0000-000000000002",e6="00000001-0000-0000-0002-000000000004";function o6($){let O=$.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/([1-9][0-9]*)\/?(?:[?#].*)?$/i);if(!O)throw Error(`Expected a GitHub pull request URL like https://github.com/owner/repo/pull/1, got ${$}`);return`${O[1]}/${O[2]}/pull/${O[3]}`}class D$ extends q{static byId($,O){return new D$($,O)}static async create($,O){let{documentId:j}=J(await $.storage.createTaskHandler({body:{taskName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null,teamId:O.team?.id??null,shareWithTeam:O.shareWithTeam??!0}}));return new D$($,j)}static async forPullRequest($,O){let j=o6(O),{pullRequests:x}=J(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new D$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===t6)?.value;return j?.type==="SelectOption"&&j.value.includes(e6)}webUrl(){return`${this.client.webAppUrl}/app/task/${this.id}`}static search=j$({filters:{document_filters:{sub_types:["task"],task_filters:{}}},type:"document",make:($,O)=>new D$($,O.document_id)})}class $O extends A{access=new o(this.client,"initiative",this);static byId($,O){return new $O($,O)}static from($,O){return new $O($,O.id,O)}async fetch(){return J(await this.client.storage.getInitiative({path:{initiative_id:this.id}}))}name=this.field("name");owner=this.mappedField("ownerId",($)=>M.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>M.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>D$.byId(this.client,O)));accessLevel=this.field("userAccessLevel");sharePermissions=this.field("sharePermission");async update($){await this.mutate((O)=>O.storage.updateInitiative({path:{initiative_id:this.id},body:{name:$.name,memberIds:$.members?.map((j)=>j.id),sharePermission:$.sharePermission?r$($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class Y0{client;constructor($){this.client=$}byId($){return $O.byId(this.client,$)}async list(){return J(await this.client.storage.listInitiatives()).initiatives.map(($)=>$O.byId(this.client,$.id))}async create($){return $O.from(this.client,J(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class Q0{client;constructor($){this.client=$}byId($){return I$.byId(this.client,$)}async create($){return I$.from(this.client,J(await this.client.storage.meetingCreate({body:$})))}async list(){return J(await this.client.storage.meetingList()).meetings.map(($)=>I$.from(this.client,$))}async active(){return J(await this.client.storage.meetingListActive()).meetings.map(($)=>I$.from(this.client,$))}async lookup($){return I$.from(this.client,J(await this.client.storage.meetingLookup({path:{token:$}})))}}class VO extends A{async fetch(){return J(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new VO($,O)}static from($,O){return new VO($,O.id,O)}static list($,O){return a(async(j)=>{let x=J(await $.notification.listTypedNotifications({query:{...O?.pageSize?{limit:O.pageSize}:{},...O?.states!==void 0?{states:O.states.join(",")}:{},...j?{cursor:j}:{}}}));return{items:x.items.map((S)=>VO.from($,S)),nextCursor:x.next_cursor}})}type=this.field("notification_event_type");createdAt=this.field("created_at");updatedAt=this.field("updated_at");state=this.field("state");done=this.mappedField("state",($)=>$==="done");sent=this.field("sent");viewedAt=this.field("viewed_at");deletedAt=this.field("deleted_at");owner=this.mappedField("owner_id",($)=>M.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?M.byId(this.client,$):void 0);metadata=this.field("notification_metadata");async seen(){return await this.state()!=="unseen"}async markSeen(){await this.mutate(($)=>$.notification.bulkMarkNotificationsSeen({body:{notificationIds:[this.id]}}))}async markDone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsDone({body:{notificationIds:[this.id]}}))}async markUndone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsUndone({body:{notificationIds:[this.id]}}))}async delete(){await this.mutate(($)=>$.notification.deleteUserNotificationV2({path:{notification_id:this.id}}))}}class J0{client;constructor($){this.client=$}byId($){return VO.byId(this.client,$)}list($){return VO.list(this.client,$)}async markSeen($){J(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){J(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){J(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return J(await this.client.notification.getNotificationTypePreferences())}async enableType($){J(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){J(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class V0{client;constructor($){this.client=$}async list(){let{data:$}=J(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){J(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){J(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){J(await this.client.storage.reorderPinsHandler({body:$}))}}class W0{client;constructor($){this.client=$}byId($){return n.byId(this.client,$)}create($){return n.create(this.client,$)}search($,O){return n.search(this.client,$,O)}}class zO{client;definitionId;id;record;constructor($,O,j,x){this.client=$;this.definitionId=O;this.id=j;this.record=x}static from($,O,j){return new zO($,O,j.id,j)}get value(){return this.record.value}get color(){return this.record.color??void 0}get displayOrder(){return this.record.display_order}get createdAt(){return this.record.created_at}get updatedAt(){return this.record.updated_at}async update($){return this.record=J(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){J(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class OO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new J$(()=>this.fetch(),j)}async fetch(){return J(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let j=J(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new OO($,j.id,j)}static byId($,O){return new OO($,O)}static fromRecord($,O){return new OO($,O.id,O)}get displayName(){return this.detail.get().then(($)=>$.display_name)}get dataType(){return this.detail.get().then(($)=>$.data_type)}get owner(){return this.detail.get().then(($)=>$.owner)}get isSystem(){return this.detail.get().then(($)=>$.is_system)}get isMultiSelect(){return this.detail.get().then(($)=>$.is_multi_select)}get createdAt(){return this.detail.get().then(($)=>$.created_at)}get updatedAt(){return this.detail.get().then(($)=>$.updated_at)}async delete(){return J(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return J(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>zO.from(this.client,this.id,O))}async addOption($){let O=J(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return zO.from(this.client,this.id,O)}async updateOption($,O){let j=J(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return zO.from(this.client,this.id,j)}async deleteOption($){return J(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class B0{client;constructor($){this.client=$}async list($){return J(await this.client.properties.listProperties({query:{scope:$?.scope??"all",...$?.forEntityType!==void 0?{for_entity_type:$.forEntityType}:{}}})).map((j)=>{let x="definition"in j?j.definition:j;return OO.fromRecord(this.client,x)})}create($){return OO.create(this.client,$)}definition($){return OO.byId(this.client,$)}async bulkEntityProperties($){return J(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return J(await this.client.properties.bulkUpdateEntitiesPropertyOptions({body:{entities:$.map((x)=>x.propertyReference()),property_id:O.property.id,...O.add?{add_option_ids:O.add.map((x)=>x.id)}:{},...O.remove?{remove_option_ids:O.remove.map((x)=>x.id)}:{}}})).results}async addEntityPropertyOption($){return J(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return J(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return J(await this.client.properties.listTags({}))}}function L0($){return c($).with({type:"cron"},(O)=>O).with({type:"events"},(O)=>({type:"events",filters:O.filters.map(({entities:j,...x})=>({...x,ids:j?.map((S)=>S.entity.id)}))})).exhaustive()}function $7($){return c($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(L0)})).with({type:"cron"},L0).with({type:"events"},L0).exhaustive()}class jO extends A{static byId($,O){return new jO($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new jO($,O.id,O)}async fetch(){return J(await this.client.scheduledAction.getScheduledAction({path:{id:this.id}}))}name=this.field("name");trigger=this.field("trigger");enabled=this.field("enabled");nextRunAt=this.field("next_run_at");revision=this.field("configuration_revision");owner=this.mappedField("owner",($)=>M.byId(this.client,$));async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:U0($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=J(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return c($.resource).with({type:"agent"},(O)=>i.byId(this.client,O.id)).with({type:"chat"},(O)=>Z$.byId(this.client,O.id)).exhaustive();return $.chat_id?Z$.byId(this.client,$.chat_id):void 0}async history(){return J(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new N0(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class N0{routine;record;constructor($,O){this.routine=$;this.record=O}get id(){return this.record.id??void 0}toJSON(){return{routine:this.routine.id,...this.record}}}function U0($){let O={prompt:$.prompt,user_prompt:$.userPrompt,model:$.model,agent:$.agent?{bot_id:$.agent.id}:void 0};return{kind:"Agent",name:$.name,enabled:$.enabled,trigger:$7($.trigger),task:{...O}}}class z0{client;constructor($){this.client=$}byId($){return jO.byId(this.client,$)}async create($){return jO.from(this.client,J(await this.client.scheduledAction.createScheduledAction({body:{...U0($),enabled:$.enabled??!0}})))}async list($){return J(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>jO.from(this.client,O))}}class I0{client;constructor($){this.client=$}byId($){return D$.byId(this.client,$)}create($){return D$.create(this.client,$)}forPullRequest($){return D$.forPullRequest(this.client,$)}search($,O){return D$.search(this.client,$,O)}}class T0{client;constructor($){this.client=$}byId($){return T$.byId(this.client,$)}current(){return T$.current(this.client)}list(){return T$.list(this.client)}}class H0{client;constructor($){this.client=$}async get($){return J(await this.client.unfurl.getUnfurl({query:{url:$}}))}async bulk($){return J(await this.client.unfurl.getUnfurlBulk({body:{url_list:$}}))}}class R0{client;constructor($){this.client=$}byId($){return M.byId(this.client,$)}me(){return M.me(this.client)}}class xO extends A{signingSecret;constructor($,O,j,x){super($,O,j);this.signingSecret=x}async fetch(){return J(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let j=J(await $.storage.createWebhook({body:{endpoint_url:O.url,namespace:O.namespace,name:O.name,filters:O.filters,scope:O.scope??"user",...O.headers!==void 0?{headers:O.headers}:{}}}));return new xO($,j.id,j,j.signing_secret)}static byId($,O){return new xO($,O)}static fromRecord($,O){return new xO($,O.id,O)}name=this.field("name");namespace=this.field("namespace");endpointUrl=this.field("endpoint_url");status=this.field("status");isValid=this.field("is_valid");filters=this.field("filters");createdAt=this.field("created_at");workspaceId=this.field("workspace_id");createdBy=this.mappedField("created_by_user_id",($)=>M.byId(this.client,$));async scope(){let $=await this.detail.get();return $.workspace_id===$.created_by_user_id?"user":"team"}async update($){await this.mutate((O)=>O.storage.patchWebhook({path:{webhook_id:this.id},body:$}))}async rename($){await this.update({name:$})}async setUrl($){await this.update({endpoint_url:$})}async setFilters($){await this.update({filters:$})}async pause(){await this.update({status:"paused"})}async resume(){await this.update({status:"active"})}async delete(){await this.mutate(($)=>$.storage.deleteWebhook({path:{webhook_id:this.id}}))}async validate(){return this.mutate(($)=>$.storage.validateWebhook({path:{webhook_id:this.id}}))}}class D0{client;constructor($){this.client=$}create($){return xO.create(this.client,$)}byId($){return xO.byId(this.client,$)}async list(){let{webhooks:$}=J(await this.client.storage.listWebhooks());return $.map((O)=>xO.fromRecord(this.client,O))}}function C0($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function y1($,O,j){let x=[];for(let S of C0(O)){if(S.definition.data_type!=="TAG"||S.value?.type!=="SelectOption")continue;for(let K of S.value.value){let Z=j.get(K);if(Z&&!x.some((X)=>X.label===Z.label&&X.scope===Z.scope))x.push(Z)}}switch(O.tag){case"document":return{type:"document",id:O.data.id,entity:q.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name,fileType:O.data.fileType,subType:O.data.subType?.type};case"chat":return{type:"ai_chat",id:O.data.id,entity:Z$.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"project":return{type:"project",id:O.data.id,entity:n.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"emailThread":return{type:"email",id:O.data.id,entity:H$.byId($,O.data.id),snapshot:O,tags:x,subject:O.data.name,snippet:O.data.snippet,senderName:O.data.senderName,senderEmail:O.data.senderEmail,inboxVisible:O.data.inboxVisible,isRead:O.data.isRead,isDraft:O.data.isDraft};case"channel":return{type:"channel",id:O.data.channel.id,entity:f.byId($,O.data.channel.id),snapshot:O,tags:x,name:O.data.channel.name};case"channelThread":return{type:"channel_thread",id:O.data.id,entity:new g$($,O.data.channel_id,O.data.id),snapshot:O,tags:x,channelId:O.data.channel_id};case"call":return{type:"call",id:O.data.callId,entity:K$.byId($,O.data.callId),snapshot:O,tags:x,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:z$.byId($,O.data.id),snapshot:O,tags:x,title:O.data.title,status:O.data.status,location:O.data.location,conferenceUrl:O.data.conferenceUrl,conferenceProvider:O.data.conferenceProvider,time:O.data.time};case"foreignEntity":return{type:"foreign_entity",id:O.data.id,entity:o$.byId($,O.data.id),snapshot:O,tags:x,foreignEntityId:O.data.foreignEntityId,foreignEntitySource:O.data.foreignEntitySource,metadata:O.data.metadata};default:throw Error(`Unexpected workspace entity type: ${O.tag}`)}}var v1="00000000-0000-0000-0000-000000000000",_0={document:["df","id"],project:["pf","pid"],ai_chat:["cf","cid"],email:["ef","ThreadId"],channel:["chanf","ChannelId"],channel_thread:["cthf","ThreadId"],call:["callf","CallId"],calendar_event:["calf","id"],foreign_entity:["fef","id"]},Hj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),h1=($,O)=>$==null?O:{"&":[$,O]};function M0($,O){if(!$||typeof $!=="object"||Array.isArray($))throw Error(`Invalid workspace ${O}: expected a filter expression.`);let j=Object.entries($),x=j[0];if(j.length!==1||x===void 0)throw Error(`Invalid workspace ${O}: use exactly one of l, &, |, !.`);let[S,K]=x;if(S==="l")return;if(S==="!"){M0(K,`${O}.!`);return}if(S!=="&"&&S!=="|")throw Error(`Invalid workspace ${O}: use l, &, | or !.`);if(!Array.isArray(K)||K.length!==2)throw Error(`Invalid workspace ${O}.${S}: expected exactly two expressions. Use {l: {...}} for a single condition; nest binary operators for three or more.`);K.forEach((Z,X)=>{M0(Z,`${O}.${S}[${X}]`)})}class Rj{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(J),this.tagSets}async tagMap(){let $=new Map;for(let O of await this.sets())for(let j of O.options)if(j.value.type==="string")$.set(j.id,{label:j.value.value,scope:O.scope==="user"?"personal":"team"});return $}async body($){for(let[S,K,Z]of[["sortBy",$.sortBy,["recently_viewed","recently_updated","recently_created"]],["emailPreset",$.emailPreset,["signal"]],["tagsMatch",$.tagsMatch,["any","all"]]])if(K!==void 0&&!Z.includes(K))throw Error(`Invalid workspace ${S}: ${K}`);if($.includeTypes!==void 0&&(!Array.isArray($.includeTypes)||$.includeTypes.some((S)=>!Object.hasOwn(_0,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(_0).join(", ")}. Tasks use document with df: {l: {dst: 'task'}}.`);for(let S of["df","pf","cf","ef","chanf","cthf","callf","fef","calf","propf"])if($[S]!=null)M0($[S],S);if($.tags?.some((S)=>S.scope!==void 0&&S.scope!=="personal"&&S.scope!=="team"))throw Error("Invalid workspace tag scope");if($.limit!==void 0&&!Number.isFinite($.limit))throw Error("Workspace limit must be finite");let O={df:$.df,pf:$.pf,cf:$.cf,ef:$.ef,chanf:$.chanf,cthf:$.cthf,callf:$.callf,fef:$.fef,calf:$.calf,propf:$.propf,ccf:{l:{id:v1}},favorites_only:$.favoritesOnly,expand:!0,limit:Math.max(1,Math.min(500,Math.trunc($.limit??50))),sort_method:$.sortBy==="recently_viewed"?"viewed_at":$.sortBy==="recently_created"?"created_at":"updated_at",sort_direction:"desc",emailView:$.emailView??"inbox"};if($.emailPreset==="signal")O.ef={"&":[{l:{Importance:!0}},{l:{Shared:"exclude"}}]};let j=$.inbox?.trim();if(j){let{links:S}=J(await this.client.email.listLinks()),K=S.filter((X)=>Hj(X.email_address)===Hj(j)),Z=K[0];if(!Z)throw Error(`No connected inbox matches "${j}". Connected inboxes: ${S.map((X)=>X.email_address).join(", ")}.`);if(K.length>1)throw Error(`Multiple connected inboxes match "${j}"; cannot pick one.`);O.ef=h1(O.ef,{l:{Owner:Z.id}})}let x=$.includeTypes??($.emailPreset==="signal"?["email"]:void 0);if(x?.length){for(let[S,[K,Z]]of Object.entries(_0))if(!x.includes(S))O[K]={l:{[Z]:v1}}}if($.tags?.length){let S=(await this.sets()).flatMap((G)=>{let L=G.definition;if(!L)return[];return G.options.flatMap((Y)=>Y.value.type==="string"?[{id:Y.id,definitionId:L.id,label:Y.value.value,scope:G.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let G of $.tags){let L=S.filter((Y)=>Hj(Y.label)===Hj(G.label.trim())&&(!G.scope||Y.scope===G.scope));if(!L.length)throw Error(`Unknown tag "${G.label}". Available tags: ${S.map((Y)=>`${Y.label} (${Y.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${G.label}" is ambiguous; specify personal or team scope.`);for(let Y of L)K.set(Y.id,Y)}let X=[...K.values()].map((G)=>({l:{pd:G.definitionId,v:{so:G.id}}})).reduce((G,L)=>G===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[G,L]},void 0);O.propf=h1(O.propf,X)}return O}}class A0{client;constructor($){this.client=$}async page($={}){let O=new Rj(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new Rj(this.client),j=await O.body($);yield*a((x)=>this.fetch(O,j,x))}async fetch($,O,j){let x=J(await this.client.storage.postItemsSoupAst({body:O,query:j?{cursor:j}:void 0})),K=x.items.some((Z)=>C0(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>y1(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function m1({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let Q,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,I=Y.signal??new AbortController().signal;while(!0){if(I.aborted)break;B++;let P=Y.headers instanceof Headers?Y.headers:new Headers(Y.headers);if(Q!==void 0)P.set("Last-Event-ID",Q);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);let N=await(Y.fetch??globalThis.fetch)(C);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",k);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;U+=l,U=U.replace(/\r\n?/g,`
+async function bO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurrency limit must be a positive integer, got ${O}`);let x=Array($.length),S=0,K=async()=>{while(S<$.length){let X=S;S+=1,x[X]=await j($[X])}},Z=Array.from({length:Math.min(O,$.length)},K);return await Promise.all(Z),x}class J${loader;value;inflight;constructor($,O){this.loader=$;this.value=O}get(){if(this.value!==void 0)return Promise.resolve(this.value);return this.inflight??=this.loader().then(($)=>{return this.value=$,$}),this.inflight}peek(){return this.value}clear(){this.value=void 0,this.inflight=void 0}}async function*a($){let O;do{let j=await $(O),x=j.nextCursor??void 0;if(O!==void 0&&x!==void 0&&JSON.stringify(x)===JSON.stringify(O))throw Error("Pagination cursor did not advance");yield*j.items,O=x}while(O!==void 0)}class b extends Error{constructor($){super($);this.name="MacroError"}}class SO extends b{status;data;constructor($,O){super(`Macro API error ${$}`);this.status=$;this.data=O;this.name="MacroApiError"}}class w extends b{constructor($){super($);this.name="MacroNotFoundError"}}function J($){if($.error!==void 0)throw new SO($.response?.status??0,$.error);return $.data}class A{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new J$(()=>this.fetch(),j)}field($){return async()=>(await this.detail.get())[$]??void 0}mappedField($,O){return async()=>O((await this.detail.get())[$]??void 0)}toJSON(){let $=this.detail.peek();return $===void 0?{id:this.id}:{id:this.id,detail:$}}async mutate($){let O=J(await $(this.client));return this.detail.clear(),O}}class F$ extends A{async permission(){return J(await this.client.storage.getEntityPermission({path:{entity_type:this.entityType,entity_id:this.id}}))}async favorite(){return J(await this.client.storage.addFavorite({body:{entityId:this.id,entityType:this.entityType}})),this}async unfavorite(){return J(await this.client.storage.removeFavoriteByEntity({path:{entity_type:this.entityType,entity_id:this.id}})),this}}class S$ extends F${propertyReference(){return{entity_type:this.propertyEntityType,entity_id:this.id}}async properties($){let{properties:O}=J(await this.client.properties.getEntityProperties({path:{entity_type:this.propertyEntityType,entity_id:this.id},query:$?.includeMetadata!==void 0?{include_metadata:$.includeMetadata}:void 0}));return O}async setProperty($,O){J(await this.client.properties.setEntityProperty({path:{...this.propertyReference(),property_id:$.id},body:{value:O??null}}))}async updatePropertyOptions($){return J(await this.client.properties.bulkUpdateEntityPropertyOptions({path:this.propertyReference(),body:{properties:$.map((O)=>({property_id:O.property.id,...O.add?{add_option_ids:O.add.map((j)=>j.id)}:{},...O.remove?{remove_option_ids:O.remove.map((j)=>j.id)}:{}}))}}))}async deleteProperty($){J(await this.client.properties.deleteEntityProperty({path:{entity_property_id:$.property.id}}))}}function l$($,O){return`<${$}>${JSON.stringify(O)}</${$}>`}function H6($){return typeof $==="object"&&$!==null&&typeof $.toMention==="function"}var R6={toMention:()=>({tag:l$("m-group-mention",{groupAlias:"here"}),mention:{entity_type:"group",entity_id:"here"}})};function D6($,...O){let j="",x=[];for(let[S,K]of $.entries()){j+=K;let Z=O[S];if(Z===void 0)continue;if(H6(Z)){let X=Z.toMention();j+=X.tag,x.push(X.mention)}else j+=String(Z)}return{content:j,mentions:C6(x)}}function C6($){let O=new Set;return $.filter((j)=>{let x=`${j.entity_type}:${j.entity_id}`;if(O.has(x))return!1;return O.add(x),!0})}function $$($){return typeof $==="string"?{content:$,mentions:[]}:$}class V$ extends A{static byId($,O){return new V$($,O)}static from($,O){return new V$($,O.id,O)}async fetch(){let $=J(await this.client.storage.listHarnesses()).find((O)=>O.id===this.id);if(!$)throw new w(`Harness ${this.id} is unavailable`);return $}name=this.field("name");connected=this.field("connected");kind=this.field("kind");async delete(){await this.mutate(($)=>$.storage.deleteHarness({path:{harness_id:this.id}}))}}class N$ extends A{static byId($,O){return new N$($,O)}static from($,O){return new N$($,O.bot.id,O)}async fetch(){let $=J(await this.client.storage.listAgents()).find((O)=>O.bot.id===this.id);if(!$)throw new w(`Agent ${this.id} is unavailable`);return $}name=this.mappedField("bot",($)=>$.name);instructions=this.field("instructions");defaultModel=this.field("default_model");channels=this.mappedField("channel_ids",($)=>$.map((O)=>f.byId(this.client,O)));host=this.mappedField("harness_id",($)=>$?V$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.updateAgent({path:{agent_id:this.id},body:Fx($)}))}}function Fx($){let{channels:O,team:j,host:x,autoAcceptPermissions:S,avatarUrl:K,channelScope:Z,defaultModel:X,isCoding:G,...L}=$;return{...L,channel_ids:O?.map((Y)=>Y.id),team_id:j?.id,harness_id:x?.id,auto_accept_permissions:S,avatar_url:K,channel_scope:Z,default_model:X,is_coding:G}}async function Xj($,O,j){let{channelId:x,thread:S}=_6(O);if(await M6($)){let{id:Z}=J(await $.storage.entityMessageCreate({path:{parent_type:"channel",parent_id:x},body:{content:j.content,mentions:j.mentions,attachments:[],thread_id:S?.rootId??null,nonce:crypto.randomUUID()}}));return Z}if(S)throw new b("a user-owned bot can only post via the channel webhook endpoint, which "+"does not support threads — use a team-owned bot, or requestedAs(user), "+"to reply in a thread");let{message_id:K}=J(await $.storage.postChannelBotWebhook({path:{channel_id:x},body:{content:j.content},headers:{"x-macro-bot-scope":"user"}}));return K}function _6($){return"rootId"in $?{channelId:$.channelId,thread:$}:{channelId:$.id}}async function M6($){if($.authConfig.type!=="bot"||$.hasActingUser())return!0;let{owner:O}=await $.selfBot();return O?.type==="team"}class g${client;channelId;rootId;constructor($,O,j){this.client=$;this.channelId=O;this.rootId=j}toJSON(){return{channelId:this.channelId,rootId:this.rootId}}channel(){return f.byId(this.client,this.channelId)}root(){return e.byId(this.client,this.channelId,this.rootId)}async replies(){let{replies:$}=J(await this.client.storage.entityMessageGetThread({path:{parent_type:"channel",parent_id:this.channelId,id:this.rootId}}));return $.map((O)=>e.from(this.client,this.channelId,O))}async reply($){let O=await Xj(this.client,this,$$($));return e.byId(this.client,this.channelId,O)}}class e extends F${channelId;mentions;entityType="channel_message";constructor($,O,j,x=[],S){super($,j,S);this.channelId=O;this.mentions=x}get path(){return{parent_type:"channel",parent_id:this.channelId,id:this.id}}async fetch(){return J(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j,x=[]){return new e($,O,j,x)}static from($,O,j){return new e($,O,j.id,j.mentions,j)}content=this.field("content");createdAt=this.field("created_at");editedAt=this.field("edited_at");updatedAt=this.field("updated_at");async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}channel(){return f.byId(this.client,this.channelId)}thread(){return new g$(this.client,this.channelId,this.id)}async react($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!0,emoji:$}})),this}async unreact($){return await this.mutate((O)=>O.storage.entityMessageReact({path:this.path,body:{add:!1,emoji:$}})),this}async edit($){let{content:O,mentions:j}=$$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}async reply($){return this.thread().reply($)}}class Gj{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}agent(){return N$.byId(this.client,this.record.botId)}sessions(){return this.record.sessions.map(($)=>({session:i.byId(this.client,$.sessionId),isCurrent:$.isCurrent,createdAt:$.createdAt}))}turns(){return this.record.turns.map(($)=>new Ex(this.client,this,$))}async startFresh($){J(await this.client.agentHarness.startFreshAgentConversation({path:{channel_id:this.channel.id,bot_id:this.record.botId},body:{sessionId:$.id}}))}toJSON(){return{channelId:this.channel.id,agentId:this.record.botId}}}class Ex{client;conversation;record;constructor($,O,j){this.client=$;this.conversation=O;this.record=j}source(){return e.byId(this.client,this.conversation.channel.id,this.record.sourceMessageId)}session(){return i.byId(this.client,this.record.sessionId)}async retry($){J(await this.client.agentHarness.retryAgentConversationTurn({path:{channel_id:this.conversation.channel.id,bot_id:this.conversation.agent().id,source:this.record.sourceMessageId},body:{actionId:$}}))}toJSON(){return{channelId:this.conversation.channel.id,sourceMessageId:this.record.sourceMessageId}}}class W$ extends A{parent;toJSON(){return{...super.toJSON(),parentType:this.parent.type,parentId:this.parent.entity.id}}constructor($,O,j){super($,j);this.parent=O}static byId($,O,j){return new W$($,O,j)}get path(){return{parent_type:this.parent.type,parent_id:this.parent.entity.id,id:this.id}}async fetch(){return J(await this.client.storage.entityMessageGetThread({path:this.path})).state}resolved=this.field("resolved");async update($){let O={resolved:$.resolved,detach_anchor:$.detachAnchor,nonce:$.nonce};await this.mutate((j)=>j.storage.entityMessagePatchThread({path:this.path,body:O}))}async delete($){await this.mutate((O)=>O.storage.entityMessageDeleteThread({path:this.path,query:{nonce:$}}))}}async function E$($,O,j,x){for(let K of[...x?.messages??[],...x?.around?[x.around]:[]]){let Z="channelId"in K?{type:"channel",id:K.channelId}:("documentId"in K)?{type:"document",id:K.documentId}:("callId"in K)?{type:"call",id:K.callId}:K.parent;if(Z.type!==O.type||Z.id!==O.entity.id)throw Error("Timeline message belongs to another resource")}let S=J(await $.storage.messageTimelineEntries({path:{parent_type:O.type,parent_id:O.entity.id},query:{selection:x?JSON.stringify({cursor:x.cursor,around:x.around?.id,ids:x.messages?.map((K)=>K.id),activity_after:x.activityAfter,activity_before:x.activityBefore,anchored:x.anchored,direction:x.direction,include_deleted_threads:x.includeDeletedThreads,limit:x.limit}):void 0}}));return{entries:S.entries.map((K)=>{if(K.type==="activity")return{type:"activity",activity:{...K.activity,actor:M.byId($,K.activity.actor_id)}};return{type:"message",message:j(K.message)}}),nextCursor:S.next_cursor??void 0,previousCursor:S.previous_cursor??void 0}}var A6=50;function j$($){let{filters:O,type:j,make:x,includeCrm:S}=$;return(K,Z,X)=>{let G=X?.searchOn??"name_content",L=X?.pageSize??A6;return a(async(Y)=>{let{results:Q,next_cursor:T}=J(await K.search.unifiedSearch({body:{query:Z,match_type:"partial",search_on:G,...O?{filters:O}:{},...S?{include_crm:!0}:{}},query:{page_size:L,...Y?{cursor:Y}:{}}}));return{items:Q.filter((W)=>W.type===j).map((W)=>x(K,W)),nextCursor:T}})}}class ZO{client;channel;record;constructor($,O,j){this.client=$;this.channel=O;this.record=j}get id(){return this.record.id}user(){return M.byId(this.client,this.record.user_id)}createdAt(){return this.record.created_at}async recordInteraction($){return new ZO(this.client,this.channel,J(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.channel.id}})))}toJSON(){return this.record}}class f extends S${async recordActivity($){return new ZO(this.client,this,J(await this.client.storage.postActivity({body:{activity_type:$,channel_id:this.id}})))}async setPicture($){await this.mutate((O)=>O.storage.setChannelPicture({path:{channel_id:this.id},body:{profile_picture_id:$?.id??null}}))}messageThreadById($){return W$.byId(this.client,{type:"channel",entity:this},$)}timelinePage($){return E$(this.client,{type:"channel",entity:this},(O)=>e.from(this.client,this.id,O),$)}async agentConversations(){return J(await this.client.agentHarness.listAgentConversations({path:{channel_id:this.id}})).conversations.map(($)=>new Gj(this.client,this,$))}entityType="channel";propertyEntityType="CHANNEL";async fetch(){return J(await this.client.storage.getChannel({path:{channel_id:this.id}}))}static byId($,O){return new f($,O)}static async dm($,O){let{channel_id:j}=J(await $.storage.getOrCreateDm({body:{recipient_id:O.id}}));return new f($,j)}static async private($,O){let{channel_id:j}=J(await $.storage.getOrCreatePrivate({body:{recipients:O.map((x)=>x.id)}}));return new f($,j)}static async create($,O){let{id:j}=J(await $.storage.createChannel({body:{channel_type:O.type,name:O.name??null,participants:(O.participants??[]).map((x)=>x.id),team_id:O.team?.id??null}}));return new f($,j)}name=this.field("channel_name");type=this.field("channel_type");async send($,O){let j=await Xj(this.client,O?.thread??this,$$($));return e.byId(this.client,this.id,j)}messages($){return this.timeline({limit:$?.pageSize})}messagesAfter($,O){return this.timeline({activity_after:$ instanceof Date?$.toISOString():$,limit:O?.pageSize})}timeline($){return a(async(O)=>{let j=J(await this.client.storage.messageTimeline({path:{parent_type:"channel",parent_id:this.id},query:{selection:JSON.stringify({...$,cursor:O})}}));return{items:j.items.map((x)=>e.from(this.client,this.id,x)),nextCursor:j.next_cursor}})}message($){return e.byId(this.client,this.id,$)}async rename($){await this.mutate((O)=>O.storage.patchChannel({path:{channel_id:this.id},body:{channel_name:$}}))}async delete(){await this.mutate(($)=>$.storage.deleteChannel({path:{channel_id:this.id}}))}async join(){await this.mutate(($)=>$.storage.joinChannel({path:{channel_id:this.id}}))}async joinCode(){let{join_code:$}=J(await this.client.storage.getChannelJoinLink({path:{channel_id:this.id}}));return $}async leave(){await this.mutate(($)=>$.storage.leaveChannel({path:{channel_id:this.id}}))}async participants(){return J(await this.client.storage.getChannelParticipants({path:{channel_id:this.id}}))}async addParticipants($){await this.mutate((O)=>O.storage.addParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async removeParticipants($){await this.mutate((O)=>O.storage.removeParticipants({path:{channel_id:this.id},body:{participants:$.map((j)=>j.id)}}))}async typing($,O){J(await this.client.storage.entityMessageTyping({path:{parent_type:"channel",parent_id:this.id},body:{active:$==="start",thread_id:O?.thread?.rootId??null}}))}attachments($){return a(async(O)=>{let j=J(await this.client.storage.getChannelAttachments({path:{channel_id:this.id},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.type?{attachment_type:$.type}:{},...O?{cursor:O}:{}}}));return{items:j.items,nextCursor:j.next_cursor}})}webUrl(){return`${this.client.webAppUrl}/app/channel/${this.id}`}static search=j$({type:"channel",make:($,O)=>new f($,O.channel_id)})}class M extends S${entityType="user";propertyEntityType="USER";async fetch(){let{names:$}=J(await this.client.auth.getUserNamesWithEmail({body:{user_ids:[this.id]}})),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`user ${this.id} not found`);return O}static byId($,O){return new M($,O)}static async me($){let{user_id:O}=J(await $.auth.getUserInfo());return new M($,O)}async name(){let $=await this.detail.get();return[$.first_name,$.last_name].filter(Boolean).join(" ")||void 0}email(){let $=this.id.startsWith("macro|")?this.id.slice(6):void 0;return $?.includes("@")?$:void 0}dm(){return f.dm(this.client,this)}toMention(){return{tag:l$("m-user-mention",{userId:this.id}),mention:{entity_type:"user",entity_id:this.id}}}}class o{client;entityType;entity;constructor($,O,j){this.client=$;this.entityType=O;this.entity=j}get path(){return{entity_type:this.entityType,entity_id:this.entity.id}}async state($){let O=J(await this.client.storage.accessRequestsState({path:this.path,query:{offset:$}}));return{accessLevel:O.accessLevel??void 0,canReview:O.canReview,owner:O.owner?M.byId(this.client,O.owner):void 0,pendingCount:O.pendingCount,supportedLevels:O.supportedLevels,nextOffset:O.nextOffset??void 0,mine:O.mine?WO.from(this.client,this,O.mine):void 0,requests:O.requests.map((j)=>WO.from(this.client,this,j))}}async submit($,O){return WO.from(this.client,this,J(await this.client.storage.accessRequestsSubmit({path:this.path,body:{requestedLevel:$,revision:O}})))}async cancel($){J(await this.client.storage.accessRequestsCancel({path:this.path,query:{revision:$}}))}async direct(){return J(await this.client.storage.accessRequestsDirect({path:this.path})).map(($)=>({user:M.byId(this.client,$.userId),accessLevel:$.accessLevel}))}async grant($,O){J(await this.client.storage.accessRequestsSetDirect({path:{...this.path,user_id:$.id},body:{accessLevel:O}}))}async remove($){J(await this.client.storage.accessRequestsRemoveDirect({path:{...this.path,user_id:$.id}}))}async resolve($,O){let j=$.access.toJSON();if(j.entity_type!==this.entityType||j.entity_id!==this.entity.id)throw Error("Access request belongs to another entity");return J(await this.client.storage.accessRequestsResolve({path:{...this.path,request_id:$.id},body:O}))}toJSON(){return this.path}}class WO extends A{access;resolvedRecord;constructor($,O,j){super($,j.id,j);this.access=O}static from($,O,j){return new WO($,O,j)}async fetch(){if(this.resolvedRecord)return this.resolvedRecord;let $;do{let O=await this.access.state($),j=[O.mine,...O.requests].find((x)=>x?.id===this.id);if(j)return j.detail.get();$=O.nextOffset}while($!==void 0);throw new w(`Access request ${this.id} is unavailable`)}revision=this.field("revision");status=this.field("status");requestedLevel=this.field("requestedLevel");requester=this.mappedField("requesterId",($)=>M.byId(this.client,$));async resolve($){this.resolvedRecord=await this.access.resolve(this,{revision:await this.revision(),grantedLevel:$}),this.detail.clear()}}function r$($){return{...$,channelSharePermissions:$.channelSharePermissions===void 0||$.channelSharePermissions===null?$.channelSharePermissions:$.channelSharePermissions.map((O)=>({channelId:O.channel.id,accessLevel:O.accessLevel,operation:O.operation}))}}class B$ extends A{parent;constructor($,O,j,x){super($,j,x);this.parent=O}static byId($,O,j){return new B$($,O,j)}static fromRecord($,O,j){return new B$($,O,j.id,j)}static async create($,O,j){return B$.createForSession($,O.session(),j,O)}static async createForSession($,O,j,x){let S=J(await $.agentHarness.createSessionReview({path:{session_id:O.id},body:{...j,executionId:x?.id??null}}));return B$.fromRecord($,O,S)}static async list($,O){return J(await $.agentHarness.listExecutionReviews({path:{session_id:O.session().id,execution_id:O.id}})).map((x)=>B$.fromRecord($,O.session(),x))}async fetch(){return J(await this.client.agentHarness.getSessionReview({path:{session_id:this.parent.id,review_id:this.id}}))}title=this.field("title");kind=this.field("kind");session(){return this.parent}async reference(){return{kind:await this.kind(),id:this.id}}async items(){return(await this.detail.get()).items.map(($)=>new wx($,{edit:(O)=>this.decide({action:"edit",item:$.id,draft:O}),submit:()=>this.decide({action:"submit",items:[$.id]}),dismiss:()=>this.decide({action:"dismiss",items:[$.id]})}))}async refresh(){return this.detail.clear(),await this.detail.get(),this}async submitAll(){await this.decide({action:"submit",items:[]})}async dismissAll(){await this.decide({action:"dismiss",items:[]})}async decide($){let O=(await this.detail.get()).revision;await this.mutate((j)=>j.agentHarness.decideSessionReview({path:{session_id:this.parent.id,review_id:this.id},body:{...$,revision:O}}))}}class wx{snapshot;actions;constructor($,O){this.snapshot=$;this.actions=O}get id(){return this.snapshot.id}get status(){return this.snapshot.status}get draft(){return this.snapshot.draft}get result(){return this.snapshot.result}async edit($){await this.actions.edit($)}async submit(){await this.actions.submit()}async dismiss(){await this.actions.dismiss()}}class kO extends A{parent;constructor($,O,j){super($,O);this.parent=j}static byId($,O,j){return new kO($,j,O)}async fetch(){return J(await this.client.agentHarness.getCodeExecution({path:{session_id:this.parent.id,execution_id:this.id}}))}reviews={create:($)=>B$.create(this.client,this,$),list:()=>B$.list(this.client,this)};session(){return this.parent}status=this.field("status");source=this.field("source");calls=this.field("calls");error=this.field("error");async result(){return(await this.detail.get()).result}async refresh(){return this.detail.clear(),await this.detail.get(),this}}class Kj{client;sessionId;dto;constructor($,O,j){this.client=$;this.sessionId=O;this.dto=j}static from($,O,j){return new Kj($,O,j)}get actionId(){return this.dto.actionId}get kind(){return this.dto.kind}get prompt(){return this.dto.prompt??void 0}get attachments(){return this.dto.attachments??[]}get actorUserId(){return this.dto.actorUserId??void 0}get createdAt(){return this.dto.createdAt}async edit($){return J(await this.client.agentHarness.editQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId},body:{prompt:$}})),this.dto={...this.dto,prompt:$},this}async steer(){J(await this.client.agentHarness.steerQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}async remove(){J(await this.client.agentHarness.removeQueuedAction({path:{session_id:this.sessionId,action_id:this.actionId}}))}}class gO{client;session;id;constructor($,O,j){this.client=$;this.session=O;this.id=j}static byId($,O,j){return new gO($,O,j)}async answer($){return J(await this.client.agentHarness.answerAgentSessionToolApproval({path:{session_id:this.session.id,approval_id:this.id},body:{answer:$}}))}toJSON(){return{id:this.id,sessionId:this.session.id}}}class i extends A{access=new o(this.client,"agent_session",this);toolApprovalById($){return gO.byId(this.client,this,$)}async sharePermissions(){return J(await this.client.agentHarness.getAgentSessionPermissions({path:{session_id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.agentHarness.updateAgentSessionPermissions({path:{session_id:this.id},body:r$($)}))}static byId($,O){return new i($,O)}static async createManaged($,O){let{session:j}=J(await $.agentHarness.createAgentSession({body:{prompt:O?.prompt,instructions:O?.instructions,model:O?.model,repoUrl:O?.repoUrl,repoBranch:O?.repoBranch}}));return new i($,j.id,j)}static async repositories($){let{repositories:O}=J(await $.agentHarness.listAgentRepositories());return O.map((j)=>({url:j.url,defaultBranch:j.defaultBranch??void 0}))}static async repositoryBranches($,O){let{branches:j}=J(await $.agentHarness.listAgentRepositoryBranches({query:{repoUrl:O}}));return j}async fetch(){return J(await this.client.agentHarness.getAgentSession({path:{session_id:this.id}}))}name=this.field("name");isArchived=this.field("isArchived");model=this.field("model");harness=this.field("harness");repoUrl=this.field("repoUrl");workspace=this.field("workspace");instructions=this.field("instructions");status=this.field("status");sandboxSize=this.field("sandboxSize");createdAt=this.field("createdAt");modifiedAt=this.field("modifiedAt");static async forPullRequest($,O){let{sessionIds:j}=J(await $.agentHarness.agentSessionsForPullRequest({body:{url:O}}));return j.map((x)=>i.byId($,x))}async pullRequests(){let{pullRequests:$}=J(await this.client.agentHarness.listAgentSessionPullRequests({path:{session_id:this.id}}));return $.map((O)=>({githubKey:O.githubKey,url:O.url,source:O.source,linkedBy:O.linkedBy?M.byId(this.client,O.linkedBy):void 0,createdAt:O.createdAt}))}async linkPullRequest($){J(await this.client.agentHarness.linkAgentSessionPullRequest({path:{session_id:this.id},body:{url:$}}))}async unlinkPullRequest($){J(await this.client.agentHarness.unlinkAgentSessionPullRequest({path:{session_id:this.id},query:{url:$}}))}async rename($){await this.mutate((O)=>O.agentHarness.renameAgentSession({path:{session_id:this.id},body:{name:$}}))}async archive(){await this.setArchived(!0)}async unarchive(){await this.setArchived(!1)}async setArchived($){await this.mutate((O)=>O.agentHarness.setAgentSessionArchived({path:{session_id:this.id},body:{isArchived:$}}))}async setSandboxSize($){let{size:O}=await this.mutate((j)=>j.agentHarness.putAgentSessionSandboxSize({path:{session_id:this.id},body:{size:$}}));return O}static async defaultSandboxSize($){return J(await $.agentHarness.getAgentSandboxSize()).size}static async setDefaultSandboxSize($,O){return J(await $.agentHarness.putAgentSandboxSize({body:{size:O}})).size}static async codingPreferences($){return J(await $.agentHarness.getAgentCodingPreferences())}static async setCodingPreferences($,O){return J(await $.agentHarness.putAgentCodingPreferences({body:O}))}async control($){return this.mutate((O)=>O.agentHarness.controlAgentSession({path:{session_id:this.id},body:$}))}prompt($,O){return this.control({type:"prompt",prompt:$,...O&&O.length>0?{attachments:O}:{}})}async queue(){let{entries:$}=J(await this.client.agentHarness.getAgentSessionQueue({path:{session_id:this.id}}));return $.map((O)=>Kj.from(this.client,this.id,O))}async changes(){return J(await this.client.agentHarness.getAgentSessionChanges({path:{session_id:this.id}}))}async changesPatch(){return J(await this.client.agentHarness.getAgentSessionChangesPatch({path:{session_id:this.id}})).patch}async refreshChanges(){return this.mutate(($)=>$.agentHarness.refreshAgentSessionChanges({path:{session_id:this.id}}))}async foldedLog(){let{bot:$,messages:O}=J(await this.client.agentHarness.getAgentSessionFoldedLog({path:{session_id:this.id}}));return{bot:$,messages:O}}async log(){return J(await this.client.agentHarness.getAgentSessionLog({path:{session_id:this.id}}))}reviews={create:($)=>B$.createForSession(this.client,this,$),byId:($)=>B$.byId(this.client,this,$)};codeExecutions={byId:($)=>kO.byId(this.client,this,$)};async delete(){await this.mutate(($)=>$.agentHarness.deleteAgentSession({path:{session_id:this.id}}))}}class qx{client;constructor($){this.client=$}byId($){return i.byId(this.client,$)}createManaged($){return i.createManaged(this.client,$)}repositories(){return i.repositories(this.client)}repositoryBranches($){return i.repositoryBranches(this.client,$)}forPullRequest($){return i.forPullRequest(this.client,$)}defaultSandboxSize(){return i.defaultSandboxSize(this.client)}setDefaultSandboxSize($){return i.setDefaultSandboxSize(this.client,$)}codingPreferences(){return i.codingPreferences(this.client)}setCodingPreferences($){return i.setCodingPreferences(this.client,$)}}class fx{client;constructor($){this.client=$}byId($){return N$.byId(this.client,$)}async list(){return J(await this.client.storage.listAgents()).map(($)=>N$.from(this.client,$))}async create($){return N$.from(this.client,J(await this.client.storage.createAgent({body:Fx($)})))}}class bx{client;async usage($={}){let{users:O,...j}=$;return J(await this.client.cognition.getUsageHandler({body:{...j,include_users:O?.map((x)=>x.id)}}))}constructor($){this.client=$}async structuredCompletion($){return J(await this.client.cognition.structuredCompletion({body:$}))}async decide($){return J(await this.client.cognition.decisions({body:$}))}}class p$ extends A{static byId($,O){return new p$($,O)}static from($,O){return new p$($,O.id,{id:O.id,name:O.name,createdAt:O.createdAt})}async fetch(){let $=J(await this.client.storage.listUserApiKeys()).keys.find((O)=>O.id===this.id);if(!$)throw new w(`API key ${this.id} is unavailable`);return $}name=this.field("name");createdAt=this.field("createdAt");async delete(){await this.mutate(($)=>$.storage.deleteUserApiKey({path:{id:this.id}}))}}class kx{client;constructor($){this.client=$}byId($){return p$.byId(this.client,$)}async list(){return J(await this.client.storage.listUserApiKeys()).keys.map(($)=>p$.from(this.client,$))}async create($){let O=J(await this.client.storage.createUserApiKey({body:{name:$}}));return{key:p$.from(this.client,O),secret:O.key}}async tokenForEmail($){return J(await this.client.auth.macroApiToken({query:{email:$}}))}}class yO{client;constructor($){this.client=$}async me(){if(this.client.authConfig.type!=="bot")throw new b("bots.me() requires bot auth — a user API key has no bot identity");return J(await this.client.storage.getSelfBot())}async channels(){if(this.client.authConfig.type!=="bot")throw new b("bots.channels() requires bot auth — a user API key has no bot identity");let $=await this.me();return J(await this.client.storage.listBotChannels({path:{bot_id:$.id}}))}async myPrincipalId(){if(this.client.authConfig.type!=="bot")throw new b("bots.myPrincipalId() requires bot auth — a user API key has no bot identity");return this.client.myPrincipalId()}}class U$ extends A{async fetch(){let{links:$}=J(await this.client.email.listLinks()),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`email link ${this.id} not found`);return O}static byId($,O){return new U$($,O)}static async list($){let{links:O}=J(await $.email.listLinks());return O.map((j)=>new U$($,j.id,j))}emailAddress=this.field("email_address");provider=this.field("provider");isPrimary=this.field("is_primary");isSyncActive=this.field("is_sync_active");syncStatus=this.field("sync_status");needsReauth=this.field("needs_reauth");photoUrl=this.field("photo_url");async settingsOperations(){return J(await this.client.email.mailboxSettingsOperations({headers:{"X-Email-Link-Id":this.id}}))}}class y$ extends A{async setContributesToAvailability($){await this.mutate((O)=>O.calendar.setAvailabilityCalendar({path:{calendar_id:this.id},body:{contributesToAvailability:$}}))}async fetch(){let{calendars:$}=J(await this.client.calendar.listCalendars()),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`calendar ${this.id} not found`);return O}static byId($,O){return new y$($,O)}static async list($){let{calendars:O}=J(await $.calendar.listCalendars());return O.map((j)=>new y$($,j.id,j))}name=this.field("name");emailAddress=this.field("emailAddress");isPrimary=this.field("isPrimary");isWritable=this.field("isWritable");isSubscription=this.field("isSubscription");color=this.field("color");syncError=this.field("syncError");emailLink=this.mappedField("emailLinkId",($)=>U$.byId(this.client,$))}class vO{client;id;constructor($,O){this.client=$;this.id=O}async status(){return J(await this.client.calendar.calendarReplacementStatus({path:{operation_id:this.id}}))}async confirm(){return J(await this.client.calendar.confirmCalendarReplacement({path:{operation_id:this.id}}))}async discard(){J(await this.client.calendar.discardCalendarReplacement({path:{operation_id:this.id}}))}}class z$ extends A{async fetch(){throw new b(`calendar event ${this.id} has no fetch-by-id endpoint; read the record returned by calendar.createEvent / event.update / event.rsvp instead`)}static byId($,O){return new z$($,O)}static fromRecord($,O){return new z$($,O.id,O)}title=this.field("title");description=this.field("description");location=this.field("location");time=this.field("time");status=this.field("status");attendees=this.field("attendees");transparency=this.field("transparency");isReadOnly=this.field("isReadOnly");recurrenceLines=this.field("recurrenceLines");calendar=this.mappedField("calendarId",($)=>$?y$.byId(this.client,$):void 0);record(){return this.detail.get()}async update($){let O=await this.mutate((j)=>j.calendar.updateCalendarEvent({path:{event_id:this.id},body:P6($)}));return z$.fromRecord(this.client,O)}async delete($={}){await this.mutate((O)=>O.calendar.deleteCalendarEvent({path:{event_id:this.id},query:{calendarId:$.calendar?.id,scope:$.scope,recurrenceId:$.recurrenceId}}))}async prepareReplacement($){let O=J(await this.client.calendar.prepareCalendarReplacement({path:{event_id:this.id},body:{removeConference:$.removeConference,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return new vO(this.client,O.operationId)}async providerUrl($={}){return J(await this.client.calendar.calendarEventProviderUrl({path:{event_id:this.id},query:{recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}})).url??void 0}async rsvp($){let O=await this.mutate((j)=>j.calendar.rsvpCalendarEvent({path:{event_id:this.id},body:{response:$.response,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}));return z$.fromRecord(this.client,O)}}function P6($){return{title:$.title,description:$.description,location:$.location,time:$.time,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,outOfOffice:$.outOfOffice,scope:$.scope,recurrenceId:$.recurrenceId,calendarId:$.calendar?.id}}class gx{client;async availabilityCalendars(){return J(await this.client.calendar.getAvailabilityCalendars()).calendars.map(($)=>({calendar:y$.byId(this.client,$.calendarId),name:$.name,isPrimary:$.isPrimary,contributesToAvailability:$.contributesToAvailability}))}async teamSharing(){return J(await this.client.calendar.getTeamSharing()).sharing}async setTeamSharing($){return J(await this.client.calendar.setTeamSharing({body:{sharing:$}})).sharing}occurrences($){return a(async(O)=>{let j=J(await this.client.storage.listOccurrences({query:{...$,cursor:O}}));return{items:j.items.map((x)=>({event:z$.fromRecord(this.client,x.event),occurrence:x.occurrence})),nextCursor:j.nextCursor}})}async teamPage($){let O=J(await this.client.storage.listTeamCalendar({query:$}));return{items:O.items.map(({ownerId:j,...x})=>({...x,owner:M.byId(this.client,j)})),members:O.members.map((j)=>({user:M.byId(this.client,j.userId),sharing:j.sharing,coverage:j.coverage})),nextCursor:O.nextCursor??void 0}}async teamOutOfOffice($){let O=J(await this.client.storage.listTeamOutOfOffice({query:$}));return{items:O.items.map((j)=>({event:z$.byId(this.client,j.eventId),owner:M.byId(this.client,j.ownerId),occurrenceKey:j.occurrenceKey,time:j.time,title:j.title??void 0})),hasMore:O.hasMore}}constructor($){this.client=$}calendars(){return y$.list(this.client)}calendar($){return y$.byId(this.client,$)}event($){return z$.byId(this.client,$)}replacement($){return new vO(this.client,$)}async createEvent($){let O=J(await this.client.calendar.createCalendarEvent({body:F6($)}));return z$.fromRecord(this.client,O)}}function F6($){return{title:$.title,time:$.time,description:$.description,location:$.location,attendees:$.attendees,recurrenceLines:$.recurrenceLines,visibility:$.visibility,transparency:$.transparency,reminders:$.reminders,conference:$.conference,macroCall:$.macroCall,outOfOffice:$.outOfOffice,calendarId:$.calendar?.id,emailLinkId:$.emailLink?.id}}class I$ extends A{lookupToken;constructor($,O,j){super($,O,j);this.lookupToken=j?.shareToken}static byId($,O){return new I$($,O)}static from($,O){return new I$($,O.id,O)}async fetch(){if(this.lookupToken)return J(await this.client.storage.meetingLookup({path:{token:this.lookupToken}}));let $=J(await this.client.storage.meetingList()).meetings.find((O)=>O.id===this.id);if(!$)throw new w(`Meeting ${this.id} is unavailable`);return this.lookupToken=$.shareToken,$}title=this.field("title");scheduledStart=this.field("scheduledStart");scheduledEnd=this.field("scheduledEnd");channel=this.mappedField("channelId",($)=>$?f.byId(this.client,$):void 0);call=this.mappedField("callId",($)=>$?K$.byId(this.client,$):void 0);async update($){await this.mutate((O)=>O.storage.meetingUpdate({path:{meeting_id:this.id},body:$}))}async cancel(){await this.mutate(($)=>$.storage.meetingCancel({path:{meeting_id:this.id}}))}async invitePermissions(){return J(await this.client.storage.meetingInvitePermissions({path:{token:(await this.detail.get()).shareToken}}))}async invite($){J(await this.client.storage.meetingInvite({path:{token:(await this.detail.get()).shareToken},body:{email:$}}))}async inviteUsers($){J(await this.client.storage.meetingInviteUsers({path:{token:(await this.detail.get()).shareToken},body:{userIds:$.map((O)=>O.id)}}))}async webUrl(){return`${this.client.webAppUrl}/app/meet/join/${encodeURIComponent((await this.detail.get()).shareToken)}`}}class v$ extends A{callId;constructor($,O,j,x){super($,j,x);this.callId=O}get path(){return{parent_type:"call",parent_id:this.callId,id:this.id}}async fetch(){return J(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new v$($,O,j)}static from($,O,j){return new v$($,O,j.id,j)}content=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");call(){return K$.byId(this.client,this.callId)}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){let O=J(await this.client.storage.entityMessageCreate({path:{parent_type:"call",parent_id:this.callId},body:{...$$($),thread_id:this.callId}}));return v$.from(this.client,this.callId,O)}async edit($){let{content:O,mentions:j}=$$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class K$ extends F${messageThreadById($){return W$.byId(this.client,{type:"call",entity:this},$)}timelinePage($){return E$(this.client,{type:"call",entity:this},(O)=>v$.from(this.client,this.id,O),$)}access=new o(this.client,"call",this);async meeting(){return I$.from(this.client,J(await this.client.storage.meetingShare({path:{call_id:this.id}})))}async editTranscript($){await this.mutate((O)=>O.storage.editCallTranscript({path:{call_id:this.id},body:{assignments:$}}))}async toggleTeamShare(){return this.mutate(($)=>$.storage.toggleShareWithTeam({path:{call_id:this.id}}))}entityType="call";async fetch(){return J(await this.client.storage.getCallRecord({path:{call_id:this.id}}))}static byId($,O){return new K$($,O)}message($){return v$.byId(this.client,this.id,$)}name=this.field("customName");channel=this.mappedField("channelId",($)=>$?f.byId(this.client,$):void 0);channelName=this.field("channelName");creator=this.mappedField("createdBy",($)=>M.byId(this.client,$));isActive=this.field("isActive");status=this.field("status");roomName=this.field("roomName");startedAt=this.field("startedAt");endedAt=this.field("endedAt");durationMs=this.field("durationMs");summary=this.field("summary");transcript=this.field("transcript");participants=this.field("participants");guests=this.field("guests");teamShareAccessLevel=this.field("teamShareAccessLevel");shareWithTeam=this.field("shareWithTeam");recordingUrl=this.field("recordingUrl");recordingPreviewUrl=this.field("recordingPreviewUrl");recordingStartedAt=this.field("recordingStartedAt");async rename($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{customName:$??""}}))}async setTeamShare($){await this.mutate((O)=>O.storage.editCallRecord({path:{call_id:this.id},body:{sharePermission:{teamShareAccessLevel:$?"view":null}}}))}async delete(){await this.mutate(($)=>$.storage.deleteCallRecord({path:{call_id:this.id}}))}static search=j$({filters:{call_filters:{}},type:"call",make:($,O)=>new K$($,O.call_id)})}class yx{client;constructor($){this.client=$}byId($){return K$.byId(this.client,$)}search($,O){return K$.search(this.client,$,O)}}class vx{client;constructor($){this.client=$}async list(){let{labels:$}=J(await this.client.storage.listChannelLabels());return $}async create($,O=[]){return J(await this.client.storage.createChannelLabel({body:{name:$,channelIds:O.map((j)=>j.id)}}))}async createSmartTag($,O){return J(await this.client.storage.createChannelLabel({body:{name:$,rule:O}}))}async previewSmartTag($){return J(await this.client.storage.previewSmartTag({body:$}))}async updateSmartTag($,O,j){return J(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O,rule:j}}))}async rename($,O){return J(await this.client.storage.renameChannelLabel({path:{label_id:$.id},body:{name:O}}))}async delete($){J(await this.client.storage.deleteChannelLabel({path:{label_id:$.id}}))}async setLabel($,O){J(await this.client.storage.setChannelLabel({path:{channel_id:$.id},body:{labelId:O?.id??null}}))}}class hx{client;async activity(){return J(await this.client.storage.getActivity()).map(($)=>new ZO(this.client,f.byId(this.client,$.channel_id),$))}labels;constructor($){this.client=$;this.labels=new vx($)}byId($){return f.byId(this.client,$)}async dm($){return f.dm(this.client,$)}async private($){return f.private(this.client,$)}async create($){return f.create(this.client,$)}async list(){let{items:$}=J(await this.client.storage.getChannels());return $.map((O)=>f.byId(this.client,O.id.toString()))}async*search($,O){if(!O?.searchOn||O.searchOn==="name"){let{items:j}=J(await this.client.storage.getChannels()),x=$.toLowerCase();for(let S of j)if(S.name?.toLowerCase().includes(x))yield f.byId(this.client,S.id.toString())}else yield*f.search(this.client,$,O)}}class n extends S${async sharePermissions(){return J(await this.client.storage.getProjectPermissionsV2({path:{id:this.id}}))}async accessLevel(){return J(await this.client.storage.getProjectUserAccessLevel({path:{id:this.id}}))}access=new o(this.client,"project",this);entityType="project";propertyEntityType="PROJECT";async fetch(){let{data:$}=J(await this.client.storage.getProjectHandler({path:{id:this.id}}));return $.projectMetadata}static byId($,O){return new n($,O)}static async create($,O){let{data:j}=J(await $.storage.createProjectHandler({body:{name:O.name,projectParentId:O.parent?.id??null}}));return new n($,j.id,j)}name=this.field("name");parent=this.mappedField("parentId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");async items(){let{data:$}=J(await this.client.storage.getProjectContentHandler({path:{id:this.id}}));return $.map((O)=>O.item)}async rename($){await this.mutate((O)=>O.storage.editProjectV2({path:{id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteProject({path:{id:this.id}}):O.storage.deleteProjectHandler({path:{id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteProject({path:{id:this.id}}))}static search=j$({filters:{project_filters:{}},type:"project",make:($,O)=>new n($,O.id)})}class hO{client;chat;id;message;constructor($,O,j,x){this.client=$;this.chat=O;this.id=j;this.message=x}static byId($,O,j,x){return new hO($,O,j,x)}async stop(){J(await this.client.cognition.stopChatStream({body:{chat_id:this.chat.id,stream_id:this.id}}))}toJSON(){return{id:this.id,chatId:this.chat.id,messageId:this.message.id}}}class mO extends A{chat;constructor($,O,j){super($,j);this.chat=O}static byId($,O,j){return new mO($,O,j)}async fetch(){let $=J(await this.client.cognition.getChat({path:{chat_id:this.chat.id}})).chat.messages.find((O)=>O.id===this.id);if(!$)throw new w(`Chat message ${this.id} is not yet available`);return $}content=this.field("content");role=this.field("role");async refresh(){this.detail.clear(),await this.detail.get()}toJSON(){return{...super.toJSON(),chatId:this.chat.id}}}class Z$ extends S${async send($){let{attachments:O,additionalInstructions:j,...x}=$,S=await this.mutate((Z)=>Z.cognition.sendChatMessage({body:{...x,chat_id:this.id,additional_instructions:j,attachments:O?.map((X)=>({entity_id:X.entity.id,entity_type:X.type}))}})),K=Z$.byId(this.client,S.chat_id);return hO.byId(this.client,K,S.stream_id,mO.byId(this.client,K,S.message_id))}access=new o(this.client,"chat",this);entityType="chat";propertyEntityType="CHAT";async fetch(){let{chat:$}=J(await this.client.cognition.getChat({path:{chat_id:this.id}}));return $}static byId($,O){return new Z$($,O)}static async create($,O){let{id:j}=J(await $.cognition.createChat({body:{name:O?.name??null,projectId:O?.project?.id??null}}));return new Z$($,j)}name=this.field("name");model=this.field("model");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");messages=this.field("messages");async rename($){await this.mutate((O)=>O.cognition.patchChat({path:{chat_id:this.id},body:{name:$}}))}async delete($){await this.mutate((O)=>$?.permanent?O.cognition.permanentlyDeleteChat({path:{chat_id:this.id}}):O.cognition.deleteChat({path:{chat_id:this.id}}))}async copy(){let{id:$}=await this.mutate((O)=>O.cognition.copyChat({path:{chat_id:this.id}}));return new Z$(this.client,$)}async restore(){await this.mutate(($)=>$.cognition.revertDeleteChat({path:{chat_id:this.id}}))}async history(){let{conversation:$}=J(await this.client.cognition.getChatHistoryHandler({path:{chat_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/chat/${this.id}`}static search=j$({filters:{chat_filters:{}},type:"chat",make:($,O)=>new Z$($,O.chat_id)});toMention(){return{tag:l$("m-document-mention",{documentId:this.id,documentName:this.detail.peek()?.name??"",blockName:"chat",blockParams:{}}),mention:{entity_type:"chat",entity_id:this.id}}}}class mx{client;constructor($){this.client=$}byId($){return Z$.byId(this.client,$)}create($){return Z$.create(this.client,$)}search($,O){return Z$.search(this.client,$,O)}}class T$ extends A{async fetch(){let O=J(await this.client.auth.getUserTeams()).find((j)=>j.id===this.id);if(!O)throw new w(`team ${this.id} not found`);return O}static byId($,O){return new T$($,O)}static async current($){let O=J(await $.auth.getTeam());if(!O)throw new w("caller has no current team");return new T$($,O.team.id,O.team)}static async list($){return J(await $.auth.getUserTeams()).map((j)=>new T$($,j.id,j))}name=this.field("name");slug=this.field("slug");defaultLinkShare=this.field("default_link_share");owner=this.mappedField("owner_id",($)=>M.byId(this.client,$));async members(){let $=J(await this.client.auth.getTeam());if(!$||$.team.id!==this.id)throw new b("members are only available for the current team (see Team.current)");return $.members.map((O)=>({user:M.byId(this.client,O.user_id),role:O.role}))}}var E6=8;class _$ extends A{parent;constructor($,O,j,x){super($,j,x);this.parent=O}get path(){return{parent_type:this.parent.type,parent_id:this.parent.id,id:this.id}}async fetch(){return J(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new _$($,O,j)}static from($,O,j){return new _$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");deletedAt=this.field("deleted_at");async threadId(){return(await this.detail.get()).thread_id??this.id}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return cO(this.client,this.parent,$,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=$$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}async function Yj($,O){let j={parent_type:O.type,parent_id:O.id},x=a(async(K)=>{let Z=J(await $.storage.messageTimeline({path:j,query:{selection:JSON.stringify({limit:100,cursor:K})}}));return{items:Z.items,nextCursor:Z.next_cursor}}),S=[];for await(let K of x)S.push(K);return bO(S,E6,async(K)=>{let{state:Z,root:X,replies:G}=J(await $.storage.entityMessageGetThread({path:{...j,id:K.id}}));return{thread:Z,comments:[X,...G].map((L)=>_$.from($,O,L))}})}async function cO($,O,j,x){let S=J(await $.storage.entityMessageCreate({path:{parent_type:O.type,parent_id:O.id},body:{...$$(j),thread_id:x?.threadId??null}}));return _$.from($,O,S)}class w$ extends F${messageThreadById($){return W$.byId(this.client,{type:"crm_contact",entity:this},$)}timelinePage($){return E$(this.client,{type:"crm_contact",entity:this},(O)=>_$.from(this.client,{type:"crm_contact",id:this.id},O),$)}entityType="crm_contact";async fetch(){return J(await this.client.storage.getContact({path:{contact_id:this.id}}))}static byId($,O){return new w$($,O)}static from($,O){return new w$($,O.id,O)}name=this.field("name");email=this.field("email");company=this.mappedField("companyId",($)=>q$.byId(this.client,$));hidden=this.field("hidden");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");firstInteraction=this.field("firstInteraction");lastInteraction=this.field("lastInteraction");async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setContactHidden({path:{contact_id:this.id},body:{hidden:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmContactName({path:{contact_id:this.id},body:{name:$}}))}get commentParent(){return{type:"crm_contact",id:this.id}}async comments(){return Yj(this.client,this.commentParent)}async comment($,O){return cO(this.client,this.commentParent,$,O)}commentById($){return _$.byId(this.client,this.commentParent,$)}}class q$ extends S${messageThreadById($){return W$.byId(this.client,{type:"crm_company",entity:this},$)}timelinePage($){return E$(this.client,{type:"crm_company",entity:this},(O)=>_$.from(this.client,{type:"crm_company",id:this.id},O),$)}entityType="crm_company";propertyEntityType="COMPANY";async fetch(){return J(await this.client.storage.getCompany({path:{company_id:this.id}}))}static byId($,O){return new q$($,O)}static from($,O){return new q$($,O.id,O)}name=this.field("name");description=this.field("description");hidden=this.field("hidden");emailSync=this.field("emailSync");team=this.mappedField("teamId",($)=>T$.byId(this.client,$));createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async domain(){let{domains:$}=await this.detail.get();return $[0]?.domain}async domains(){let{domains:$}=await this.detail.get();return $.map((O)=>O.domain)}async contacts(){return J(await this.client.storage.listCompanyContacts({path:{company_id:this.id}})).map((O)=>w$.from(this.client,O))}static search=j$({filters:{crm_company_filters:{}},type:"company",includeCrm:!0,make:($,O)=>new q$($,O.id)});async hide(){await this.setHidden(!0)}async unhide(){await this.setHidden(!1)}async setHidden($){await this.mutate((O)=>O.storage.setCompanyHidden({path:{company_id:this.id},body:{hidden:$}}))}async setEmailSync($){await this.mutate((O)=>O.storage.setEmailSync({path:{company_id:this.id},body:{email_sync:$}}))}async rename($){await this.mutate((O)=>O.storage.setCrmCompanyName({path:{company_id:this.id},body:{name:$}}))}async createContact($){let O=await this.mutate((j)=>j.storage.createCrmContact({path:{company_id:this.id},body:$}));return w$.from(this.client,O)}get commentParent(){return{type:"crm_company",id:this.id}}async comments(){return Yj(this.client,this.commentParent)}async comment($,O){return cO(this.client,this.commentParent,$,O)}commentById($){return _$.byId(this.client,this.commentParent,$)}}class a$ extends A{tableDetail=new J$(async()=>J(await this.client.storage.getCrmPipelineTable({path:{id:this.id}})));static byId($,O){return new a$($,O)}static from($,O){return new a$($,O.id,O)}async fetch(){return J(await this.client.storage.getCrmPipeline({path:{id:this.id}}))}name=this.field("name");recordType=this.field("recordType");accessLevel=this.field("grant");sharing=this.field("sharing");owner=this.mappedField("userId",($)=>M.byId(this.client,$));team=this.mappedField("teamId",($)=>T$.byId(this.client,$));async rename($){await this.mutate((O)=>O.storage.renameCrmPipeline({path:{id:this.id},body:{name:$}}))}async setSharing($){if($===void 0)throw Error("Sharing is required");await this.mutate((O)=>O.storage.shareCrmPipeline({path:{id:this.id},body:{sharing:$}}))}async setTrashed($){await this.mutate((O)=>O.storage.trashCrmPipeline({path:{id:this.id},body:{trashed:$}}))}async sharePermissions(){return J(await this.client.storage.getCrmPipelinePermissions({path:{id:this.id}}))}async updateSharePermissions($){return this.mutate((O)=>O.storage.updateCrmPipelinePermissions({path:{id:this.id},body:r$($)}))}async table(){return Qj.from(this.client,this,await this.tableRecord())}tableRecord(){return this.tableDetail.get()}rows(){return a(async($)=>{let O=J(await this.client.storage.getCrmPipelineRows({path:{id:this.id},query:{after:$}}));return{items:O.rows.map((j)=>XO.from(this.client,this,j)),nextCursor:O.next}})}queryRows($={}){if($.rows?.some((O)=>O.pipeline.id!==this.id))throw Error("Rows belong to another pipeline");return a(async(O)=>{let j=J(await this.client.storage.queryCrmPipelineRows({path:{id:this.id},body:{after:O,query:$.query,rowIds:$.rows?.map((x)=>x.id)}}));return{items:j.rows.map((x)=>XO.from(this.client,this,x)),nextCursor:j.next}})}async applyOps($,O){if(O?.baseVersions?.some((S)=>S.table.pipeline.id!==this.id))throw Error("Table belongs to another pipeline");let j={ops:$,baseVersions:O?.baseVersions?Object.fromEntries(O.baseVersions.map((S)=>[S.table.id,S.version])):void 0},x=await this.mutate((S)=>S.storage.applyCrmPipelineOps({path:{id:this.id},body:j}));return this.tableDetail.clear(),x}}class Qj extends A{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j){super($,j.table.id,j);this.pipeline=O}static from($,O,j){return new Qj($,O,j)}fetch(){return this.pipeline.tableRecord()}async columns(){return(await this.pipeline.tableRecord()).columns.map(($)=>Jj.from(this.client,this,$))}async version(){return(await this.pipeline.tableRecord()).table.version}rowById($){return XO.byId(this.client,this.pipeline,$)}rows(){return this.pipeline.rows()}}class XO extends A{pipeline;toJSON(){return{...super.toJSON(),pipelineId:this.pipeline.id}}constructor($,O,j,x){super($,j,x);this.pipeline=O}static byId($,O,j){return new XO($,O,j)}static from($,O,j){return new XO($,O,j.rowId,j)}async fetch(){for await(let $ of this.pipeline.queryRows({rows:[this]}))if($.id===this.id)return $.detail.get();throw new w(`Pipeline row ${this.id} is unavailable`)}cells=this.field("cells");async refresh(){this.detail.clear(),await this.detail.get()}}class Jj extends A{table;toJSON(){return{...super.toJSON(),pipelineId:this.table.pipeline.id,tableId:this.table.id}}constructor($,O,j){super($,j.column.id,j);this.table=O}static from($,O,j){return new Jj($,O,j)}async fetch(){let $=(await this.table.pipeline.tableRecord()).columns.find((O)=>O.column.id===this.id);if(!$)throw new w(`Pipeline column ${this.id} is unavailable`);return $}async writable(){return(await this.fetch()).writable}async name(){return(await this.fetch()).column.display_name??(await this.fetch()).definition.definition.display_name}}class cx{client;constructor($){this.client=$}byId($){return a$.byId(this.client,$)}async list(){return J(await this.client.storage.listCrmPipelines()).map(($)=>a$.from(this.client,$))}async create($){return a$.from(this.client,J(await this.client.storage.createCrmPipeline({body:$})))}}class ux{client;pipelines;constructor($){this.client=$;this.pipelines=new cx($)}companyById($){return q$.byId(this.client,$)}contactById($){return w$.byId(this.client,$)}async contactByEmail($){let{contact:O}=J(await this.client.storage.getContactByEmail({query:{email:$}}));return O?w$.from(this.client,O):void 0}async searchContacts($,O={}){let{contacts:j}=J(await this.client.storage.searchContacts({query:{query:$,limit:O.limit}}));return j.map((x)=>w$.from(this.client,x))}async createCompany($){return q$.from(this.client,J(await this.client.storage.createCrmCompany({body:$})))}async settings(){return J(await this.client.storage.getCrmTeamSettings())}async updateSettings($){return J(await this.client.storage.putCrmTeamSettings({body:$}))}async setStages($){return J(await this.client.storage.putCrmTeamStages({body:$}))}async resetStages(){J(await this.client.storage.resetCrmTeamStages())}searchCompanies($){return q$.search(this.client,$)}}var G$=Symbol.for("@ts-pattern/matcher"),P1=Symbol.for("@ts-pattern/isVariadic");var dx=($)=>Boolean($&&typeof $=="object"),Vj=($)=>$&&!!$[G$],s=($,O,j)=>{if(Vj($)){let x=$[G$](),{matched:S,selections:K}=x.match(O);return S&&K&&Object.keys(K).forEach((Z)=>j(Z,K[Z])),S}if(dx($)){if(!dx(O))return!1;if(Array.isArray($)){if(!Array.isArray(O))return!1;let x=[],S=[],K=[];for(let Z of $.keys()){let X=$[Z];Vj(X)&&X[P1]?K.push(X):K.length?S.push(X):x.push(X)}if(K.length){if(K.length>1)throw Error("Pattern error: Using `...P.array(...)` several times in a single pattern is not allowed.");if(O.length<x.length+S.length)return!1;let Z=O.slice(0,x.length),X=S.length===0?[]:O.slice(-S.length),G=O.slice(x.length,S.length===0?1/0:-S.length);return x.every((L,Y)=>s(L,Z[Y],j))&&S.every((L,Y)=>s(L,X[Y],j))&&(K.length===0||s(K[0],G,j))}return $.length===O.length&&$.every((Z,X)=>s(Z,O[X],j))}return Reflect.ownKeys($).every((x)=>{let S=$[x];return((x in O)||Vj(K=S)&&K[G$]().matcherType==="optional")&&s(S,O[x],j);var K})}return Object.is(O,$)},X$=($)=>{var O,j,x;return dx($)?Vj($)?(O=(j=(x=$[G$]()).getSelectionKeys)==null?void 0:j.call(x))!=null?O:[]:Array.isArray($)?uO($,X$):uO(Object.values($),X$):[]},uO=($,O)=>$.reduce((j,x)=>j.concat(O(x)),[]);function w6(...$){if($.length===1){let[O]=$;return(j)=>s(O,j,()=>{})}if($.length===2){let[O,j]=$;return s(O,j,()=>{})}throw Error(`isMatching wasn't given the right number of arguments: expected 1 or 2, received ${$.length}.`)}function t($){return Object.assign($,{optional:()=>px($),and:(O)=>u($,O),or:(O)=>F1($,O),select:(O)=>O===void 0?dO($):dO(O,$)})}function lx($){return Object.assign(((O)=>Object.assign(O,{[Symbol.iterator](){let j=0,x=[{value:Object.assign(O,{[P1]:!0}),done:!1},{done:!0,value:void 0}];return{next:()=>{var S;return(S=x[j++])!=null?S:x.at(-1)}}}}))($),{optional:()=>lx(px($)),select:(O)=>lx(O===void 0?dO($):dO(O,$))})}function px($){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return O===void 0?(X$($).forEach((S)=>x(S,void 0)),{matched:!0,selections:j}):{matched:s($,O,x),selections:j}},getSelectionKeys:()=>X$($),matcherType:"optional"})})}var q6=($,O)=>{for(let j of $)if(!O(j))return!1;return!0},f6=($,O)=>{for(let[j,x]of $.entries())if(!O(x,j))return!1;return!0},b6=($,O)=>{let j=Reflect.ownKeys($);for(let x of j)if(!O(x,$[x]))return!1;return!0};function u(...$){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return{matched:$.every((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>uO($,X$),matcherType:"and"})})}function F1(...$){return t({[G$]:()=>({match:(O)=>{let j={},x=(S,K)=>{j[S]=K};return uO($,X$).forEach((S)=>x(S,void 0)),{matched:$.some((S)=>s(S,O,x)),selections:j}},getSelectionKeys:()=>uO($,X$),matcherType:"or"})})}function m($){return{[G$]:()=>({match:(O)=>({matched:Boolean($(O))})})}}function dO(...$){let O=typeof $[0]=="string"?$[0]:void 0,j=$.length===2?$[1]:typeof $[0]=="string"?void 0:$[0];return t({[G$]:()=>({match:(x)=>{let S={[O!=null?O:"@ts-pattern/anonymous-select-key"]:x};return{matched:j===void 0||s(j,x,(K,Z)=>{S[K]=Z}),selections:S}},getSelectionKeys:()=>[O!=null?O:"@ts-pattern/anonymous-select-key"].concat(j===void 0?[]:X$(j))})})}function E1($){return!0}function f$($){return typeof $=="number"}function i$($){return typeof $=="string"}function n$($){return typeof $=="bigint"}var w1=t(m(E1)),k6=t(m(E1)),g6=w1,s$=($)=>Object.assign(t($),{startsWith:(O)=>{return s$(u($,(j=O,m((x)=>i$(x)&&x.startsWith(j)))));var j},endsWith:(O)=>{return s$(u($,(j=O,m((x)=>i$(x)&&x.endsWith(j)))));var j},minLength:(O)=>s$(u($,((j)=>m((x)=>i$(x)&&x.length>=j))(O))),length:(O)=>s$(u($,((j)=>m((x)=>i$(x)&&x.length===j))(O))),maxLength:(O)=>s$(u($,((j)=>m((x)=>i$(x)&&x.length<=j))(O))),includes:(O)=>{return s$(u($,(j=O,m((x)=>i$(x)&&x.includes(j)))));var j},regex:(O)=>{return s$(u($,(j=O,m((x)=>i$(x)&&Boolean(x.match(j))))));var j}}),A1=s$(m(i$)),b$=($)=>Object.assign(t($),{between:(O,j)=>b$(u($,((x,S)=>m((K)=>f$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>b$(u($,((j)=>m((x)=>f$(x)&&x<j))(O))),gt:(O)=>b$(u($,((j)=>m((x)=>f$(x)&&x>j))(O))),lte:(O)=>b$(u($,((j)=>m((x)=>f$(x)&&x<=j))(O))),gte:(O)=>b$(u($,((j)=>m((x)=>f$(x)&&x>=j))(O))),int:()=>b$(u($,m((O)=>f$(O)&&Number.isInteger(O)))),finite:()=>b$(u($,m((O)=>f$(O)&&Number.isFinite(O)))),positive:()=>b$(u($,m((O)=>f$(O)&&O>0))),negative:()=>b$(u($,m((O)=>f$(O)&&O<0)))}),y6=b$(m(f$)),t$=($)=>Object.assign(t($),{between:(O,j)=>t$(u($,((x,S)=>m((K)=>n$(K)&&x<=K&&S>=K))(O,j))),lt:(O)=>t$(u($,((j)=>m((x)=>n$(x)&&x<j))(O))),gt:(O)=>t$(u($,((j)=>m((x)=>n$(x)&&x>j))(O))),lte:(O)=>t$(u($,((j)=>m((x)=>n$(x)&&x<=j))(O))),gte:(O)=>t$(u($,((j)=>m((x)=>n$(x)&&x>=j))(O))),positive:()=>t$(u($,m((O)=>n$(O)&&O>0))),negative:()=>t$(u($,m((O)=>n$(O)&&O<0)))}),v6=t$(m(n$)),h6=t(m(function($){return typeof $=="boolean"})),m6=t(m(function($){return typeof $=="symbol"})),c6=t(m(function($){return $==null})),u6=t(m(function($){return $!=null})),x$={__proto__:null,matcher:G$,optional:px,array:function(...$){return lx({[G$]:()=>({match:(O)=>{if(!Array.isArray(O))return{matched:!1};if($.length===0)return{matched:!0};let j=$[0],x={};if(O.length===0)return X$(j).forEach((K)=>{x[K]=[]}),{matched:!0,selections:x};let S=(K,Z)=>{x[K]=(x[K]||[]).concat([Z])};return{matched:O.every((K)=>s(j,K,S)),selections:x}},getSelectionKeys:()=>$.length===0?[]:X$($[0])})})},set:function(...$){return t({[G$]:()=>({match:(O)=>{if(!(O instanceof Set))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};if($.length===0)return{matched:!0};let x=(K,Z)=>{j[K]=(j[K]||[]).concat([Z])},S=$[0];return{matched:q6(O,(K)=>s(S,K,x)),selections:j}},getSelectionKeys:()=>$.length===0?[]:X$($[0])})})},map:function(...$){return t({[G$]:()=>({match:(O)=>{if(!(O instanceof Map))return{matched:!1};let j={};if(O.size===0)return{matched:!0,selections:j};let x=(X,G)=>{j[X]=(j[X]||[]).concat([G])};if($.length===0)return{matched:!0};var S;if($.length===1)throw Error(`\`P.map\` wasn't given enough arguments. Expected (key, value), received ${(S=$[0])==null?void 0:S.toString()}`);let[K,Z]=$;return{matched:f6(O,(X,G)=>{let L=s(K,G,x),Y=s(Z,X,x);return L&&Y}),selections:j}},getSelectionKeys:()=>$.length===0?[]:[...X$($[0]),...X$($[1])]})})},record:function(...$){return t({[G$]:()=>({match:(O)=>{if(O===null||typeof O!="object"||Array.isArray(O))return{matched:!1};var j;if($.length===0)throw Error(`\`P.record\` wasn't given enough arguments. Expected (value) or (key, value), received ${(j=$[0])==null?void 0:j.toString()}`);let x={},S=(X,G)=>{x[X]=(x[X]||[]).concat([G])},[K,Z]=$.length===1?[A1,$[0]]:$;return{matched:b6(O,(X,G)=>{let L=typeof X!="string"||Number.isNaN(Number(X))?null:Number(X),Y=L!==null&&s(K,L,S),Q=s(K,X,S),T=s(Z,G,S);return(Q||Y)&&T}),selections:x}},getSelectionKeys:()=>$.length===0?[]:[...X$($[0]),...X$($[1])]})})},intersection:u,union:F1,not:function($){return t({[G$]:()=>({match:(O)=>({matched:!s($,O,()=>{})}),getSelectionKeys:()=>[],matcherType:"not"})})},when:m,select:dO,any:w1,unknown:k6,_:g6,string:A1,number:y6,bigint:v6,boolean:h6,symbol:m6,nullish:c6,nonNullable:u6,instanceOf:function($){return t(m(function(O){return(j)=>j instanceof O}($)))},shape:function($){return t(m(w6($)))}};class q1 extends Error{constructor($){let O;try{O=JSON.stringify($)}catch(j){O=$}super(`Pattern matching error: no pattern matches value ${O}`),this.input=void 0,this.input=$}}var rx={matched:!1,value:void 0};function c($){return new Wj($,rx)}class Wj{constructor($,O){this.input=void 0,this.state=void 0,this.input=$,this.state=O}with(...$){if(this.state.matched)return this;let O=$[$.length-1],j=[$[0]],x;$.length===3&&typeof $[1]=="function"?x=$[1]:$.length>2&&j.push(...$.slice(1,$.length-1));let S=!1,K={},Z=(G,L)=>{S=!0,K[G]=L},X=!j.some((G)=>s(G,this.input,Z))||x&&!Boolean(x(this.input))?rx:{matched:!0,value:O(S?"@ts-pattern/anonymous-select-key"in K?K["@ts-pattern/anonymous-select-key"]:K:this.input,this.input)};return new Wj(this.input,X)}when($,O){if(this.state.matched)return this;let j=Boolean($(this.input));return new Wj(this.input,j?{matched:!0,value:O(this.input,this.input)}:rx)}otherwise($){return this.state.matched?this.state.value:$(this.input)}exhaustive($=d6){return this.state.matched?this.state.value:$(this.input)}run(){return this.exhaustive()}returnType(){return this}narrow(){return this}}function d6($){throw new q1($)}var ax,l6=new Uint8Array(16);function Bj(){if(!ax){if(typeof crypto>"u"||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ax=crypto.getRandomValues.bind(crypto)}return ax(l6)}var O$=[];for(let $=0;$<256;++$)O$.push(($+256).toString(16).slice(1));function f1($,O=0){return(O$[$[O+0]]+O$[$[O+1]]+O$[$[O+2]]+O$[$[O+3]]+"-"+O$[$[O+4]]+O$[$[O+5]]+"-"+O$[$[O+6]]+O$[$[O+7]]+"-"+O$[$[O+8]]+O$[$[O+9]]+"-"+O$[$[O+10]]+O$[$[O+11]]+O$[$[O+12]]+O$[$[O+13]]+O$[$[O+14]]+O$[$[O+15]]).toLowerCase()}var ix={};function r6($,O,j){let x;if($)x=b1($.random??$.rng?.()??Bj(),$.msecs,$.seq,O,j);else{let S=Date.now(),K=Bj();p6(ix,S,K),x=b1(K,ix.msecs,ix.seq,O,j)}return O??f1(x)}function p6($,O,j){if($.msecs??=-1/0,$.seq??=0,O>$.msecs)$.seq=j[6]<<23|j[7]<<16|j[8]<<8|j[9],$.msecs=O;else if($.seq=$.seq+1|0,$.seq===0)$.msecs++;return $}function b1($,O,j,x,S=0){if($.length<16)throw Error("Random bytes length must be >= 16");if(!x)x=new Uint8Array(16),S=0;else if(S<0||S+16>x.length)throw RangeError(`UUID byte range ${S}:${S+15} is out of buffer bounds`);return O??=Date.now(),j??=$[6]*127<<24|$[7]<<16|$[8]<<8|$[9],x[S++]=O/1099511627776&255,x[S++]=O/4294967296&255,x[S++]=O/16777216&255,x[S++]=O/65536&255,x[S++]=O/256&255,x[S++]=O&255,x[S++]=112|j>>>28&15,x[S++]=j>>>20&255,x[S++]=128|j>>>14&63,x[S++]=j>>>6&255,x[S++]=j<<2&255|$[10]&3,x[S++]=$[11],x[S++]=$[12],x[S++]=$[13],x[S++]=$[14],x[S++]=$[15],x}var h$=r6;class M${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new M$($,O)}async detail(){let{columns:$}=await this.table.detail(),O=$.find((j)=>j.column.id===this.id);if(!O)throw new w(`column ${this.id} is not on table ${this.table.id}`);return O}async name(){let $=await this.detail();return $.column.display_name??$.definition.definition.display_name}async rename($){return await this.table.database.renameColumn(this,$),this}async inferType($){return await this.table.database.inferColumnType(this,$),this}changeType($){return this.table.database.changeColumnType(this,$)}convertIntoNewColumn($){return this.table.database.convertColumnIntoNewColumn(this,$)}casts(){return this.table.database.columnCasts(this)}async delete(){await this.table.database.deleteColumn(this)}async dataType(){return(await this.detail()).definition.definition.data_type}async isMultiSelect(){return(await this.detail()).definition.definition.is_multi_select}async position(){return(await this.detail()).column.position}async definition(){return(await this.detail()).definition}async config(){return(await this.detail()).column.config??void 0}async addOptions($){return await this.table.database.addColumnOptions(this,$),this}toJSON(){return{id:this.id,tableId:this.table.id}}}class A${table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new A$($,O)}history(){return this.table.database.rowHistory(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Lj{table;id;constructor($,O){this.table=$;this.id=O}static byId($,O){return new Lj($,O)}async detail(){let{views:$}=await this.table.detail(),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`view ${this.id} is not on table ${this.table.id}`);return O}async name(){return(await this.detail()).name}async position(){return(await this.detail()).position}async layout(){return(await this.detail()).layout}async query(){return(await this.detail()).query}positions(){return this.table.database.viewPositions(this)}toJSON(){return{id:this.id,tableId:this.table.id}}}class Y${database;id;constructor($,O){this.database=$;this.id=O}static byId($,O){return new Y$($,O)}async detail(){let{tables:$}=await this.database.schema(),O=$.find((j)=>j.table.id===this.id);if(!O)throw new w(`table ${this.id} is not in database ${this.database.id}`);return O}async name(){return(await this.detail()).table.name}async rename($){return await this.database.renameTable(this,$),this}async version(){return(await this.detail()).table.version}async position(){return(await this.detail()).table.position}async columns(){let{columns:$}=await this.detail();return $.map((O)=>M$.byId(this,O.column.id))}addColumn($){return this.database.addColumn(this,$)}async reorderColumns($){return await this.database.reorderColumns(this,$),this}row($){return A$.byId(this,$)}async views(){let{views:$}=await this.detail();return $.map((O)=>Lj.byId(this,O.id))}createWebhook(){return this.database.createWebhook(this)}async delete(){await this.database.deleteTable(this)}toJSON(){return{id:this.id,databaseId:this.database.id}}}async function Nj($,O,j,x={}){let S=J(await $.storage.queryDatabases({body:{sql:j,databaseId:x.database?.id,baseVersions:Object.fromEntries((x.baseVersions??[]).map(({table:Y,version:Q})=>[Y.id,Q]))}})),K=new Map;for(let Y of[x.database,...(x.baseVersions??[]).map(({table:Q})=>Q.database)]){if(!Y)continue;let Q=K.get(Y.id);if(Q)Q.add(Y);else K.set(Y.id,new Set([Y]))}let Z=(Y)=>{let Q=K.get(Y)?.values().next().value;if(Q)return Q;let T=O($,Y);return K.set(Y,new Set([T])),T},X=(Y)=>{let Q=S.tableDatabases[Y];if(!Q)throw Error(`SQL response is missing the owner of table ${Y}`);return Y$.byId(Z(Q),Y)},G=new Set(Object.keys(S.newVersions).map((Y)=>X(Y).database.id));if(S.statement.kind==="schema")G.add(S.statement.databaseId);for(let Y of G)for(let Q of K.get(Y)??[])Q.invalidateSchema();let L=c(S.statement).with({kind:"select"},(Y)=>Y).with({kind:"schema"},({databaseId:Y,summary:Q})=>({kind:"schema",database:Z(Y),summary:Q})).with({kind:"insert"},{kind:"update"},{kind:"delete"},({kind:Y,tableId:Q,tableName:T})=>({kind:Y,table:X(Q),tableName:T})).with({kind:"alterColumnType"},({tableId:Y,tableName:Q,columnId:T,columnName:z,to:W})=>{let V=X(Y);return{kind:"alterColumnType",table:V,tableName:Q,column:M$.byId(V,T),columnName:z,to:W}}).exhaustive();return{result:S.result?a6(S.result,X,S.tableDatabases):void 0,changesApplied:S.changesApplied,insertedRows:L.kind==="insert"?S.insertedRowIds.map((Y)=>A$.byId(L.table,Y)):[],newVersions:Object.entries(S.newVersions).map(([Y,Q])=>({table:X(Y),version:Q})),readVersions:Object.entries(S.readVersions).map(([Y,Q])=>({table:X(Y),version:Q})),truncatedTables:S.truncatedTables,statement:L}}function a6($,O,j){let x=$.sourceTable&&j[$.sourceTable]?O($.sourceTable):void 0;return{columns:$.columns.map(({relatedTable:S,...K})=>({...K,relatedTable:S&&j[S]?O(S):void 0})),rows:$.rows,sourceTable:x,rowHandles:x?$.rowIds.map((S)=>A$.byId(x,S)):[]}}class Uj{table;id;createdBy;record;constructor($,O,j,x){this.table=$;this.id=O;this.createdBy=j;this.record=x}static fromRecord($,O,j){return new Uj($,j.id,O,j)}get tokenPrefix(){return this.record.tokenPrefix}get createdAt(){return this.record.createdAt}delete(){return this.table.database.deleteWebhook(this)}toJSON(){return{id:this.id,tableId:this.table.id,tokenPrefix:this.tokenPrefix}}}class tx extends SO{op;row;column;taken;constructor($,O){super($,O);this.name="MacroOpRefusedError",this.message=O.message,this.op=O.op,this.row=O.row,this.column=O.column,this.taken=O.taken}}function zj($){return c($).with({type:"relation"},({table:O})=>({type:"relation",database:O.database.id,table:O.id})).with({type:x$.not("relation")},(O)=>O).exhaustive()}var i6={USER:"People",DOCUMENT:"Documents",TASK:"Tasks",COMPANY:"Companies",CONTACT:"Contacts",CALL_RECORD:"Calls",CHANNEL:"Channels",CHAT:"Chats",PROJECT:"Projects",THREAD:"Emails",CALENDAR_EVENT:"Events",INITIATIVE:"Initiatives"};function n6($){return c($).with({type:"text"},()=>"Text").with({type:"number"},()=>"Number").with({type:"boolean"},()=>"Checkbox").with({type:"date"},()=>"Date").with({type:"link"},()=>"URL").with({type:"select",multi:!0},()=>"Multi-select").with({type:"select",multi:!1},()=>"Select").with({type:"select_number",multi:!0},()=>"Multi-number select").with({type:"select_number",multi:!1},()=>"Number select").with({type:"tag"},()=>"Tag").with({type:"entity"},({target:O})=>i6[O]).with({type:"relation"},()=>"Relation").exhaustive()}function nx($){return $.map((O)=>({id:h$(),label:O}))}function k1($,O,j){return $?.kind===O&&"change"in $&&$.change.kind===j}function sx($){return c($).with({kind:"reorder_tables"},({kind:O})=>O).with({kind:x$.union("table","column","rows","view")},({kind:O,change:j})=>`${O}.${j.kind}`).exhaustive()}function m$($,O,j){let[x]=$;if($.length!==1||!k1(x,O,j))throw new b(`expected one ${O}.${j} result, got ${$.map(sx).join(", ")||"none"}`);return x}class Q$ extends A{access=new o(this.client,"database",this);async fetch(){return J(await this.client.storage.getDatabase({path:{id:this.id}}))}assertOwns($,O){if(O.id!==this.id)throw new b(`${$} does not belong to database ${this.id}`)}static byId($,O){return new Q$($,O)}static async create($,O){let j=J(await $.storage.createDatabase({body:{name:O.name}}));return new Q$($,j.id)}static async list($){return J(await $.storage.listDatabases()).map((j)=>new Q$($,j.database.id))}query($,O){return Nj(this.client,Q$.byId,$,{...O,database:this})}invalidateSchema(){this.detail.clear()}schema(){return this.detail.get()}name=this.mappedField("database",($)=>$.name);owner=this.mappedField("database",($)=>M.byId(this.client,$.owner_id));createdAt=this.mappedField("database",($)=>$.created_at);trashedAt=this.mappedField("database",($)=>$.trashed_at??void 0);grant=this.field("grant");tables=this.mappedField("tables",($)=>$.map((O)=>Y$.byId(this,O.table.id)));async table($){let{tables:O}=await this.schema(),j=O.find((x)=>x.table.name===$);return j?Y$.byId(this,j.table.id):void 0}async createTable($){let{table:O}=m$(await this.applyOps([{kind:"table",table:h$(),change:{kind:"create",name:$.name}}]),"table","created");return Y$.byId(this,O)}async applyOps($,O={}){let j={ops:$};if(O.baseVersions!==void 0){for(let{table:S}of O.baseVersions)this.assertOwns(`table ${S.id}`,S.database);j.baseVersions=Object.fromEntries(O.baseVersions.map(({table:S,version:K})=>[S.id,K]))}let{results:x}=await this.mutate(async(S)=>{let K=await S.storage.applyDatabaseOps({path:{id:this.id},body:j});if(K.error!==void 0&&"op"in K.error)throw new tx(K.response?.status??0,K.error);return K});return x}async reorderTables($){for(let x of $)this.assertOwns(`table ${x.id}`,x.database);let O=await this.applyOps([{kind:"reorder_tables",order:$.map((x)=>x.id)}]),[j]=O;if(O.length!==1||j?.kind!=="reorder_tables")throw new b(`expected one reorder_tables result, got ${O.map(sx).join(", ")||"none"}`);return j.tables.map(({table:x})=>Y$.byId(this,x))}async deleteTable($){this.assertOwns(`table ${$.id}`,$.database),m$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"delete"}}]),"table","deleted")}async columnCasts($){return this.assertOwns(`column ${$.id}`,$.table.database),J(await this.client.storage.listDatabaseColumnCasts({path:{id:this.id,table_id:$.table.id,column_id:$.id}}))}async viewPositions($){this.assertOwns(`view ${$.id}`,$.table.database);let{positions:O}=J(await this.client.storage.getDatabaseViewPositions({path:{id:this.id,view_id:$.id}}));return O}async rowHistory($){this.assertOwns(`row ${$.id}`,$.table.database);let{changes:O}=J(await this.client.storage.getDatabaseRowHistory({path:{id:this.id,table_id:$.table.id,row_id:$.id}}));return O}async importTable($){let O=await this.mutate((j)=>j.storage.importDatabaseTable({path:{id:this.id},body:$}));return Y$.byId(this,O.id)}webhookOf($){return Uj.fromRecord(Y$.byId(this,$.tableId),M.byId(this.client,$.createdBy),$)}async webhooks(){let{webhooks:$}=J(await this.client.storage.listDatabaseWebhooks({path:{id:this.id}}));return $.map((O)=>this.webhookOf(O))}async createWebhook($){this.assertOwns("table",$.database);let O=J(await this.client.storage.createDatabaseWebhook({path:{id:this.id},body:{tableId:$.id}}));return{webhook:this.webhookOf(O.webhook),token:O.token}}async deleteWebhook($){this.assertOwns("webhook",$.table.database),J(await this.client.storage.deleteDatabaseWebhook({path:{id:this.id,webhook_id:$.id}}))}async sharePermissions(){return J(await this.client.storage.getDatabasePermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateDatabasePermissions({path:{id:this.id},body:$}))}async changeColumnType($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.table.version();return m$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"change_type",to:zj(O.to)}}],{baseVersions:[{table:$.table,version:j}]}),"column","type_changed")}async columnConversion($,O){return this.assertOwns(`column ${$.id}`,$.table.database),J(await this.client.storage.convertDatabaseColumn({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{to:zj(O)}}))}async convertColumnIntoNewColumn($,O){let j=await this.columnConversion($,O.to),x=O.name??`${await $.name()} (${n6(O.to)})`,S=h$(),K=[{kind:"column",table:$.table.id,column:S,change:{kind:"create",definition:{source:"new",name:x,type:zj(O.to),options:nx(j.options)},after:$.id}}];if(j.cells.length>0)K.push({kind:"rows",table:$.table.id,change:{kind:"update",changes:{kind:"per_row",rows:j.cells.map(({row:X,value:G})=>({row:X,cells:[{column:S,value:G}]}))}}});let[Z]=await this.applyOps(K,{baseVersions:[{table:$.table,version:j.tableVersion}]});if(!k1(Z,"column","created"))throw new b(`expected a column.created result, got ${Z?sx(Z):"none"}`);return M$.byId($.table,Z.column)}async deleteColumn($){this.assertOwns(`column ${$.id}`,$.table.database);let O=await $.table.version(),{tableVersion:j}=m$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"delete"}}],{baseVersions:[{table:$.table,version:O}]}),"column","deleted");return j}async reorderColumns($,O){this.assertOwns(`table ${$.id}`,$.database);for(let S of O)if(S.table.id!==$.id)throw new b(`column ${S.id} does not belong to table ${$.id}`);let j=await $.version(),{tableVersion:x}=m$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"reorder_columns",order:O.map((S)=>S.id)}}],{baseVersions:[{table:$,version:j}]}),"table","columns_reordered");if(x===void 0)throw new b(`table ${$.id} reordered its columns without a version`);return x}async renameTable($,O){this.assertOwns(`table ${$.id}`,$.database);let j=await $.name(),{tableVersion:x}=m$(await this.applyOps([{kind:"table",table:$.id,change:{kind:"rename",name:O,previousName:j}}]),"table","renamed");if(x===void 0)throw new b(`table ${$.id} was renamed without a version`);return x}async renameColumn($,O){this.assertOwns(`column ${$.id}`,$.table.database);let j=await $.name(),{tableVersion:x}=m$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"rename",name:O,previousName:j}}]),"column","renamed");return x}async inferColumnType($,O){return this.assertOwns(`column ${$.id}`,$.table.database),this.mutate((j)=>j.storage.inferDatabaseColumnType({path:{id:this.id,table_id:$.table.id,column_id:$.id},body:{dataType:O.dataType,baseVersion:O.baseVersion,...O.specificEntityType!==void 0?{specificEntityType:O.specificEntityType}:{}}}))}async addColumn($,O){if(this.assertOwns(`table ${$.id}`,$.database),O.after!==void 0&&O.after.table.id!==$.id)throw new b(`column ${O.after.id} does not belong to table ${$.id}`);let j="property"in O?{source:"existing",property:O.property.id}:{source:"new",name:O.name,type:zj(O.type),...O.options!==void 0?{options:nx(O.options)}:{},...O.inferType!==void 0?{inferType:O.inferType}:{}},{column:x}=m$(await this.applyOps([{kind:"column",table:$.id,column:h$(),change:{kind:"create",definition:j,...O.after!==void 0?{after:O.after.id}:{}}}]),"column","created");return M$.byId($,x)}async addColumnOptions($,O){return this.assertOwns(`column ${$.id}`,$.table.database),m$(await this.applyOps([{kind:"column",table:$.table.id,column:$.id,change:{kind:"add_options",options:nx(O)}}]),"column","options_added")}}class ex{client;constructor($){this.client=$}query($,O){return Nj(this.client,Q$.byId,$,O)}byId($){return Q$.byId(this.client,$)}create($){return Q$.create(this.client,$)}list(){return Q$.list(this.client)}}class GO extends A{document;toJSON(){return{...super.toJSON(),documentId:this.document.id}}constructor($,O,j,x){super($,j,x);this.document=O}static byId($,O,j){return new GO($,O,j)}static from($,O,j){return new GO($,O,j.uuid,j)}async fetch(){let $=J(await this.client.storage.getDocumentAnchors({path:{document_id:this.document.id}})).data.find((O)=>O.uuid===this.id);if(!$)throw new w(`Annotation ${this.id} is unavailable`);return $}kind=this.field("anchorType");page=this.field("page");async edit($){if(await this.kind()!=="placeable")throw Error("Only placeable comment annotations can be edited");await this.mutate((O)=>O.storage.editAnchor({body:{...$,uuid:this.id,anchorType:"free-comment",fileType:"pdf"}}))}async delete(){if(await this.kind()!=="highlight")throw Error("Only standalone highlights can be deleted with this endpoint");await this.mutate(($)=>$.storage.deleteAnchor({body:{uuid:this.id,anchorType:"highlight",fileType:"pdf"}}))}}class c$ extends A{documentId;constructor($,O,j,x){super($,j,x);this.documentId=O}get path(){return{parent_type:"document",parent_id:this.documentId,id:this.id}}async fetch(){return J(await this.client.storage.entityMessageGetMessage({path:this.path}))}static byId($,O,j){return new c$($,O,j)}static from($,O,j){return new c$($,O,j.id,j)}text=this.field("content");createdAt=this.field("created_at");updatedAt=this.field("updated_at");async threadId(){return(await this.detail.get()).thread_id??this.id}document(){return q.byId(this.client,this.documentId)}async author(){return M.byId(this.client,(await this.detail.get()).sender_id)}async reply($){return this.document().comment($,{threadId:await this.threadId()})}async edit($){let{content:O,mentions:j}=$$($);return await this.mutate((x)=>x.storage.entityMessageEdit({path:this.path,body:{content:O,mentions:j}})),this}async delete(){await this.mutate(($)=>$.storage.entityMessageDeleteMessage({path:this.path}))}}class lO{client;document;id;detail;constructor($,O,j){this.client=$;this.document=O;this.id=j;this.detail=new J$(async()=>J(await this.client.storage.getDocumentVersion({path:{document_id:O.id,document_version_id:j}})).data)}static byId($,O,j){return new lO($,O,j)}read(){return this.detail.get()}toJSON(){return{id:this.id,documentId:this.document.id}}}var s6=8;class q extends S${async anchors(){return J(await this.client.storage.getDocumentAnchors({path:{document_id:this.id}})).data.map(($)=>GO.from(this.client,this,$))}async createHighlight($){return GO.from(this.client,this,J(await this.client.storage.createAnchor({path:{document_id:this.id},body:{...$,fileType:"pdf",anchorType:"highlight"}})))}version($){return lO.byId(this.client,this,$)}async sharePermissions(){return J(await this.client.storage.getDocumentPermissionsV2({path:{document_id:this.id}})).documentPermissions}async permissionsToken(){return J(await this.client.storage.getDocumentPermissionsToken({path:{document_id:this.id}})).token}async prepareSave($){return J(await this.client.storage.presaveDocumentHandler({path:{document_id:this.id},body:{newBom:$}})).data}async save($){return(await this.mutate((O)=>O.storage.saveDocumentHandler({path:{document_id:this.id},body:$}))).data}async simpleSave(){return(await this.mutate(($)=>$.storage.simpleSave({path:{document_id:this.id}}))).data}messageThreadById($){return W$.byId(this.client,{type:"document",entity:this},$)}timelinePage($){return E$(this.client,{type:"document",entity:this},(O)=>c$.from(this.client,this.id,O),$)}access=new o(this.client,"document",this);async fetch(){let{data:$}=J(await this.client.storage.getDocument({path:{document_id:this.id}}));return $.documentMetadata}static byId($,O){return new q($,O)}static async create($,O){let{documentId:j}=J(await $.storage.createMarkdownHandler({body:{documentName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new q($,j)}static async createSnippet($,O){let{documentId:j}=J(await $.storage.createSnippetHandler({body:{snippetName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new q($,j)}static async createSkill($,O){let{documentId:j}=J(await $.storage.createSkillHandler({body:{skillName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null}}));return new q($,j)}static recent($,O){let j=O?.pageSize??50;return a(async(x)=>{let S=J(await $.storage.getUserDocumentsHandler({query:{limit:j,offset:x?Number(x):0,...O?.fileType!==void 0?{file_type:O.fileType}:{}}})),K=S.data?.next_offset;return{items:(S.data?.documents??[]).map((Z)=>new q($,Z.documentId)),nextCursor:K!=null?String(K):null}})}static async recentlyDeleted($){let{data:O}=J(await $.storage.recentlyDeleted({}));return O.items.filter((j)=>j.type==="document").map((j)=>new q($,j.id))}entityType="document";propertyEntityType="DOCUMENT";name=this.field("documentName");fileType=this.field("fileType");project=this.mappedField("projectId",($)=>$?n.byId(this.client,$):void 0);owner=this.mappedField("owner",($)=>M.byId(this.client,$));branchedFrom=this.mappedField("branchedFromId",($)=>$?q.byId(this.client,$):void 0);createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");deletedAt=this.field("deletedAt");async content(){let{text:$}=J(await this.client.storage.getDocumentTextContent({path:{document_id:this.id}}));if($!==null)return $;let{presigned_url:O}=J(await this.client.storage.exportDocument({path:{document_id:this.id}})),j=await fetch(O);if(!j.ok)throw new SO(j.status,{message:"failed to download document content"});return j.text()}async rename($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{documentName:$}}))}async move($){await this.mutate((O)=>O.storage.editDocument({path:{document_id:this.id},body:{projectId:$?.id??""}}))}async delete($){await this.mutate((O)=>$?.permanent?O.storage.permanentlyDeleteDocument({path:{document_id:this.id}}):O.storage.deleteDocument({path:{document_id:this.id}}))}async restore(){await this.mutate(($)=>$.storage.revertDeleteDocument({path:{document_id:this.id}}))}async copy($){let{data:O}=J(await this.client.storage.copyDocument({path:{document_id:this.id},query:$.versionId!==void 0?{version_id:$.versionId}:void 0,body:{documentName:$.name}}));return new q(this.client,O.documentMetadata.documentId)}async comments(){let $={parent_type:"document",parent_id:this.id},O=a(async(x)=>{let S=J(await this.client.storage.messageTimeline({path:$,query:{selection:JSON.stringify({limit:100,cursor:x})}}));return{items:S.items,nextCursor:S.next_cursor}}),j=[];for await(let x of O)j.push(x);return bO(j,s6,async(x)=>{let{state:S,root:K,replies:Z}=J(await this.client.storage.entityMessageGetThread({path:{...$,id:x.id}}));return{thread:S,comments:[K,...Z].map((X)=>c$.from(this.client,this.id,X))}})}async comment($,O){let j=await this.mutate((x)=>x.storage.entityMessageCreate({path:{parent_type:"document",parent_id:this.id},body:{...$$($),thread_id:O?.threadId??null}}));return c$.from(this.client,this.id,j)}async shortId(){return J(await this.client.storage.getDocumentShortId({path:{document_id:this.id}}))}async teamShare(){return J(await this.client.storage.getDocumentTeamShare({path:{document_id:this.id}}))}async setTeamShare($){await this.mutate((O)=>O.storage.setDocumentTeamShare({path:{document_id:this.id},body:{shareWithTeam:$}}))}async githubPullRequests(){let{pullRequests:$}=J(await this.client.storage.getDocumentGithubPullRequests({path:{document_id:this.id}}));return $}async branchName(){let{branchName:$}=J(await this.client.storage.getDocumentBranchName({path:{document_id:this.id}}));return $}webUrl(){return`${this.client.webAppUrl}/app/md/${this.id}`}static search=j$({filters:{document_filters:{}},type:"document",make:($,O)=>new q($,O.document_id)});toMention(){let $=this.detail.peek();return{tag:l$("m-document-mention",{documentId:this.id,documentName:$?.documentName??"",blockName:$?.fileType??"md"}),mention:{entity_type:"document",entity_id:this.id}}}}class Ij{id;name;constructor($,O){this.id=$;this.name=O}static async list($){let{skills:O}=J(await $.storage.getSystemSkillsHandler());return O.map((j)=>new Ij(j.id,j.name))}}class ox{client;async byTeamSlug($){let O=J(await this.client.storage.getDocumentByTeamSlug({path:{slug:$}}));if(typeof O!=="object"||O===null||!("data"in O)||typeof O.data!=="object"||O.data===null||!("documentMetadata"in O.data)||typeof O.data.documentMetadata!=="object"||O.data.documentMetadata===null||!("documentId"in O.data.documentMetadata)||typeof O.data.documentMetadata.documentId!=="string")throw Error("Invalid team task document response");return q.byId(this.client,O.data.documentMetadata.documentId)}async validatePermissionsToken($){let O=J(await this.client.storage.validateDocumentPermissionsToken({body:{token:$}}));return{document:q.byId(this.client,O.document_id),user:O.user_id?M.byId(this.client,O.user_id):void 0,accessLevel:O.access_level,expiresAt:O.exp,issuer:O.iss}}async createUpload($){let O={documentName:$.name,sha:$.sha,fileType:$.fileType,mimeType:$.mimeType,projectId:$.project?.id,teamId:$.team?.id,branchedFromId:$.branchedFrom?.id,emailAttachmentId:$.attachment?.id,isTask:$.isTask},j=J(await this.client.storage.createDocument({body:O})).data;return{document:q.byId(this.client,j.documentMetadata.documentId),uploadUrl:j.presignedUrl??void 0,contentType:j.contentType,content:j.documentMetadata.content}}constructor($){this.client=$}byId($){return q.byId(this.client,$)}create($){return q.create(this.client,$)}createSnippet($){return q.createSnippet(this.client,$)}createSkill($){return q.createSkill(this.client,$)}systemSkills(){return Ij.list(this.client)}search($,O){return q.search(this.client,$,O)}recent($){return q.recent(this.client,$)}recentlyDeleted(){return q.recentlyDeleted(this.client)}}class KO extends A{async fetch(){let{attachment:$}=J(await this.client.email.getAttachment({path:{id:this.id}}));return $}static byId($,O){return new KO($,O)}static from($,O){return new KO($,O.db_id,O)}filename=this.field("filename");mimeType=this.field("mime_type");size=this.field("size_bytes");dataUrl=this.field("data_url");sfsId=this.field("sfs_id");contentId=this.field("content_id");async toDocument(){let{document_id:$}=J(await this.client.email.getAttachmentDocumentId({path:{id:this.id}}));return q.byId(this.client,$)}}class H$ extends S${access=new o(this.client,"email_thread",this);async followup(){return J(await this.client.storage.getEmailFollowup({path:{thread_id:this.id}}))}async setFollowup($){return J(await this.client.storage.setEmailFollowup({path:{thread_id:this.id},body:$}))}async calendarInvitations(){return J(await this.client.email.getThreadCalendarInvitations({path:{thread_id:this.id}}))}async update($){await this.mutate((O)=>O.storage.editThreadV2({path:{thread_id:this.id},body:{projectId:$.project===void 0?void 0:$.project?.id??null,sharePermission:$.sharePermission?r$($.sharePermission):void 0}}))}entityType="email_thread";propertyEntityType="THREAD";async fetch(){let{thread:$}=J(await this.client.email.getThread({path:{thread_id:this.id},query:{limit:100}}));return $}static byId($,O){return new H$($,O)}createdAt=this.field("created_at");updatedAt=this.field("updated_at");isRead=this.field("is_read");inboxVisible=this.field("inbox_visible");accessLevel=this.field("access_level");providerId=this.field("provider_id");link=this.mappedField("link_id",($)=>U$.byId(this.client,$));project=this.mappedField("project_id",($)=>$?n.byId(this.client,$):void 0);latestInboundAt=this.field("latest_inbound_message_ts");latestOutboundAt=this.field("latest_outbound_message_ts");latestNonSpamAt=this.field("latest_non_spam_message_ts");async subject(){let{messages:$}=await this.detail.get();for(let O of $)if(O.subject)return O.subject;return}async participants(){let{messages:$}=await this.detail.get(),O=new Map;for(let j of $)for(let x of[j.from,...j.to,...j.cc,...j.bcc])if(x&&!O.has(x.email))O.set(x.email,x);return[...O.values()]}async messages($){return J(await this.client.email.getThreadMessagesHandler({path:{id:this.id},query:{...$?.since?{since:$.since}:{},...$?.limit?{limit:$.limit}:{}}})).map((j)=>R$.from(this.client,j))}async attachments(){let{messages:$}=await this.detail.get();return $.flatMap((O)=>O.attachments.map((j)=>KO.from(this.client,j)))}async reply($){let O=$.subject??await this.subject()??"",{message:j}=await this.mutate((x)=>x.email.sendMessage({body:{message:{thread_db_id:this.id,replying_to_id:$.replyingTo?.id??null,to:$.to,cc:$.cc??null,bcc:$.bcc??null,subject:O,body_text:$.bodyText}}}));return j.db_id?R$.byId(this.client,j.db_id):void 0}async archive($=!0){await this.mutate((O)=>O.email.archiveThread({path:{id:this.id},body:{value:$}}))}async updateState($){await this.mutate((O)=>O.email.updateThreadState({path:{id:this.id},body:$}))}async operations(){return J(await this.client.email.threadOperations({path:{id:this.id}}))}async markSeen(){await this.mutate(($)=>$.email.threadSeen({path:{id:this.id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveThreadLabel({path:{id:this.id},body:{label_id:$.id,value:!1}}))}async moveToProject($){await this.mutate((O)=>O.email.updateThreadProject({path:{thread_id:this.id},body:{projectId:$?.id??null}}))}static search=j$({filters:{email_filters:{}},type:"email",make:($,O)=>new H$($,O.thread_id)})}class R$ extends A{async fetch(){return J(await this.client.email.getMessage({path:{id:this.id}}))}static byId($,O){return new R$($,O)}static from($,O){return new R$($,O.db_id,O)}static async send($,O){let{message:j}=J(await $.email.sendMessage({body:{message:{to:O.to,cc:O.cc??null,bcc:O.bcc??null,subject:O.subject,body_text:O.bodyText}}}));return j.db_id?R$.byId($,j.db_id):void 0}subject=this.field("subject");from=this.field("from");to=this.field("to");cc=this.field("cc");bcc=this.field("bcc");body=this.field("body_parsed");sentAt=this.field("internal_date_ts");labels=this.field("labels");link=this.mappedField("link_id",($)=>U$.byId(this.client,$));async operationStatus(){return J(await this.client.email.messageOperationStatus({path:{id:this.id}}))}async resolveOperation($){await this.mutate((O)=>O.email.resolveMessageOperation({path:{id:this.id},body:$}))}async completeDraftAttachment($){let O=await this.link();await this.mutate((j)=>j.email.completeDraftAttachment({path:{id:this.id,attachment_id:$},headers:{"X-Email-Link-Id":O.id}}))}async transferDraft($){let O=await this.link();return this.mutate((j)=>j.email.transferDraft({path:{id:this.id},body:$,headers:{"X-Email-Link-Id":O.id}}))}async addLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!0}}))}async removeLabel($){await this.mutate((O)=>O.email.addRemoveLabel({body:{label_id:$.id,message_ids:[this.id],value:!1}}))}async thread(){return H$.byId(this.client,(await this.detail.get()).thread_db_id)}}class YO extends R${async inboxHeaders(){return{"X-Email-Link-Id":(await this.link()).id}}static byId($,O){return new YO($,O)}async update($){let O=await this.inboxHeaders();await this.mutate((j)=>j.email.createDraft({headers:O,body:{draft:{...$0($),db_id:this.id}}}))}async delete(){let $=await this.inboxHeaders();await this.mutate((O)=>O.email.deleteDraft({path:{id:this.id},headers:$}))}async schedule($,O){let j=await this.inboxHeaders();await this.mutate((x)=>x.email.upsertScheduledMessage({path:{id:this.id},headers:j,body:{send_time:$,include_signature:O?.includeSignature}}))}async unschedule(){let $=await this.inboxHeaders();await this.mutate((O)=>O.email.deleteScheduledDraft({path:{message_id:this.id},headers:$}))}async addAttachment($){let O={file_name:$.fileName,sha:$.sha,size:$.size,upload_id:$.uploadId},j=await this.inboxHeaders(),x=await this.mutate((S)=>S.email.addDraftAttachment({path:{id:this.id},headers:j,body:O}));return{attachment:rO.byId(this.client,this,x.attachment_id),uploadUrl:x.upload_url,contentType:x.content_type}}async forwardAttachment($){let O=await this.inboxHeaders(),j=await this.mutate((x)=>x.email.addForwardedAttachment({path:{id:this.id},headers:O,body:{attachment_id:$.id}}));return rO.byId(this.client,this,j.attachment_id,!0)}async removeAttachment($){if($.draft.id!==this.id)throw Error("Attachment belongs to another draft");let O=await this.inboxHeaders();if($.forwarded)await this.mutate((j)=>j.email.removeForwardedAttachment({path:{id:this.id,attachment_id:$.id},headers:O}));else await this.mutate((j)=>j.email.removeDraftAttachment({path:{id:this.id,attachment_id:$.id},headers:O}))}async verifyAttachment($){if($.draft.id!==this.id||$.forwarded)throw Error("Expected an uploaded attachment on this draft");await this.completeDraftAttachment($.id)}}class rO{draft;id;forwarded;constructor($,O,j){this.draft=$;this.id=O;this.forwarded=j}static byId($,O,j,x=!1){return new rO(O,j,x)}complete(){return this.draft.verifyAttachment(this)}remove(){return this.draft.removeAttachment(this)}toJSON(){return{id:this.id,draftId:this.draft.id,forwarded:this.forwarded}}}function $0($){let{bodyText:O,bodyHtml:j,bodyMacro:x,headers:S,includeSignature:K,thread:Z,replyingTo:X,...G}=$;return{...G,body_text:O,body_html:j===void 0?void 0:btoa(Array.from(new TextEncoder().encode(j),(L)=>String.fromCharCode(L)).join("")).replaceAll("+","-").replaceAll("/","_").replaceAll("=",""),body_macro:x,headers_json:S,include_signature:K,thread_db_id:Z?.id,replying_to_id:X?.id}}class QO extends A{inbox;constructor($,O,j,x){super($,O,j);this.inbox=x}get headers(){return this.inbox?{"X-Email-Link-Id":this.inbox.id}:void 0}static byId($,O,j){return new QO($,O,void 0,j)}static from($,O,j){return new QO($,O.id,O,j)}async fetch(){let $=J(await this.client.email.listEmailFilters({headers:this.headers})).filters.find((O)=>O.id===this.id);if(!$)throw new w(`Email filter ${this.id} is unavailable`);return $}emailAddress=this.field("email_address");emailDomain=this.field("email_domain");isImportant=this.field("is_important");async setImportant($){let O=await this.detail.get();await this.mutate((j)=>j.email.upsertEmailFilter({headers:this.headers,body:{email_address:O.email_address,email_domain:O.email_domain,is_important:$}}))}async delete(){await this.mutate(($)=>$.email.deleteEmailFilter({path:{id:this.id},headers:this.headers}))}}class e$ extends A{async fetch(){let{labels:$}=J(await this.client.email.listLabels()),O=$.find((j)=>j.id===this.id);if(!O)throw new w(`label ${this.id} not found`);return O}static byId($,O){return new e$($,O)}static async list($){let{labels:O}=J(await $.email.listLabels());return O.map((j)=>new e$($,j.id,j))}static async create($,O){let{label:j}=J(await $.email.createLabel({body:{label_name:O}}));if(!j.id)throw new b("created label has no id");return new e$($,j.id)}async delete(){J(await this.client.email.deleteLabel({path:{id:this.id}}))}name=this.field("name");linkId=this.field("linkId");type=this.field("type");createdAt=this.field("createdAt");labelListVisibility=this.field("labelListVisibility");messageListVisibility=this.field("messageListVisibility")}class O0{client;async createDraft($,O){let j=J(await this.client.email.createDraft({body:{draft:$0($)},headers:O?{"X-Email-Link-Id":O.id}:void 0}));if(!j.draft.db_id)throw Error("Draft response has no message id");return YO.byId(this.client,j.draft.db_id)}draftById($){return YO.byId(this.client,$)}async*scheduled($){let O=$?.pageSize??100;if(!Number.isInteger(O)||O<1)throw Error("pageSize must be positive");let j=Math.min(O,1000);for(let x=0;;x+=j){let S=J(await this.client.email.getScheduledMessages({query:{offset:x,limit:j},headers:$?.inbox?{"X-Email-Link-Id":$.inbox.id}:void 0}));for(let K of S.messages)yield YO.byId(this.client,K.db_id);if(S.messages.length<j)return}}async filters($){return J(await this.client.email.listEmailFilters({headers:$?{"X-Email-Link-Id":$.id}:void 0})).filters.map((O)=>QO.from(this.client,O,$))}async upsertFilter($,O){return QO.from(this.client,J(await this.client.email.upsertEmailFilter({headers:O?{"X-Email-Link-Id":O.id}:void 0,body:{email_address:$.emailAddress,email_domain:$.emailDomain,is_important:$.isImportant}})).filter,O)}async contacts(){return J(await this.client.email.listContacts()).contacts}reminders($){let{inboxes:O,...j}=$??{};return a(async(x)=>{let S=J(await this.client.storage.listEmailReminders({query:{...j,inboxIds:O?.map((K)=>K.id),cursor:x}}));return{items:S.items.map(({threadId:K,...Z})=>({...Z,thread:H$.byId(this.client,K)})),nextCursor:S.nextCursor}})}constructor($){this.client=$}byId($){return H$.byId(this.client,$)}message($){return R$.byId(this.client,$)}attachment($){return KO.byId(this.client,$)}link($){return U$.byId(this.client,$)}links(){return U$.list(this.client)}async connectionProviders(){return J(await this.client.auth.emailConnectionProviders())}async recoverDraftTransfer($){return J(await this.client.email.recoverDraftTransfer({path:{id:$}}))}send($){return R$.send(this.client,$)}search($,O){return H$.search(this.client,$,O)}inbox($){return a(async(O)=>{let j=J(await this.client.email.previewsInboxCursor({path:{view:"inbox"},query:{...$?.pageSize?{limit:$.pageSize}:{},...$?.sort?{sort_method:$.sort}:{},...O?{cursor:O}:{}}}));return{items:j.items.map((x)=>H$.byId(this.client,x.id)),nextCursor:j.next_cursor}})}label($){return e$.byId(this.client,$)}labels(){return e$.list(this.client)}createLabel($){return e$.create(this.client,$)}async deleteLabel($){J(await this.client.email.deleteLabel({path:{id:$.id}}))}async blockSender($){J(await this.client.email.blockSender({body:{email_address:$}}))}async unblockSender($){J(await this.client.email.unblockSender({body:{email_address:$}}))}async blockedSenders(){return J(await this.client.email.listBlockedSenders()).blocked_emails}}class BO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new BO($,O)}async delete(){J(await this.client.storage.deleteEntityMention({path:{mention_id:this.id}}))}toJSON(){return{id:this.id}}}class j0{client;constructor($){this.client=$}byId($){return BO.byId(this.client,$)}async create($,O){let j=J(await this.client.storage.createEntityMention({body:{source_entity_id:$.entity.id,source_entity_type:$.type,entity_id:O.entity.id,entity_type:O.type}}));return BO.byId(this.client,j.id)}}class x0{client;constructor($){this.client=$}async list($={}){let{favorites:O}=J(await this.client.storage.listFavorites({query:{entityType:$.entityTypes,entityId:$.entityIds}}));return O}async add($){return J(await this.client.storage.addFavorite({body:{entityId:$.id,entityType:$.entityType}}))}async remove($){J(await this.client.storage.removeFavoriteByEntity({path:{entity_type:$.entityType,entity_id:$.id}}))}async reorder($){J(await this.client.storage.reorderFavorites({body:{favorites:$}}))}}class o$ extends F${entityType="foreign_entity";async fetch(){return J(await this.client.storage.getForeignEntity({path:{id:this.id}}))}static byId($,O){return new o$($,O)}static fromRecord($,O){return new o$($,O.id,O)}foreignEntityId=this.field("foreignEntityId");source=this.field("foreignEntitySource");storedForId=this.field("storedForId");storedForAuthEntity=this.field("storedForAuthEntity");createdAt=this.field("createdAt");updatedAt=this.field("updatedAt");async metadata(){return(await this.detail.get()).metadata}}function g1({login:$,...O}){return{...O,login:$??void 0}}class S0{client;constructor($){this.client=$}byId($){return o$.byId(this.client,$)}async bySource($,O){return o$.fromRecord(this.client,J(await this.client.storage.getForeignEntityBySource({path:{source:$,foreign_entity_id:O}})))}async githubPullRequestFacets(){let{repositories:$,authors:O,assignees:j,labels:x}=J(await this.client.storage.getGithubPullRequestFacets());return{repositories:$,authors:O.map(g1),assignees:j.map(g1),labels:x.map(({color:S,...K})=>({...K,color:S??void 0}))}}}class u${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new u$($,O)}async detail(){let O=(await this.form.schema()).sections.flatMap((j)=>j.kind==="questions"?j.questions:[]).find((j)=>j.id===this.id);if(!O)throw new w(`question ${this.id} is not on form ${this.form.id}`);return O}async title(){return(await this.detail()).title}async column(){return M$.byId(await this.form.table(),(await this.detail()).column)}async options(){return(await this.detail()).options.map(($)=>JO.byId(this,$.id))}}class JO{question;id;constructor($,O){this.question=$;this.id=O}static byId($,O){return new JO($,O)}async detail(){let $=(await this.question.detail()).options.find((O)=>O.id===this.id);if(!$)throw new w(`option ${this.id} is not on question ${this.question.id}`);return $}async label(){return(await this.detail()).label}async color(){return(await this.detail()).color??void 0}}class LO{form;id;detail;constructor($,O,j){this.form=$;this.id=O;this.detail=new J$(()=>this.load(),j)}async load(){let $=await this.form.myResponse();if($.response.id!==this.id)throw new w(`response ${this.id} is not your current response`);return $}static byId($,O,j){return new LO($,O,j)}async status(){return(await this.detail.get()).status}async row(){return(await this.detail.get()).row}async answers(){return(await this.detail.get()).answers}async booking(){return(await this.detail.get()).booking}async refresh(){let $=await this.load();return this.detail=new J$(()=>this.load(),$),this}}class d${form;id;constructor($,O){this.form=$;this.id=O}static byId($,O){return new d$($,O)}async detail(){let $=(await this.form.schema()).sections.find((O)=>O.id===this.id);if(!$)throw new w(`section ${this.id} is not on form ${this.form.id}`);return $}async title(){return(await this.detail()).title}async questions(){let $=await this.detail();return $.kind==="questions"?$.questions.map((O)=>u$.byId(this.form,O.id)):[]}}class Tj{entityType;id;constructor($,O){this.entityType=$;this.id=O}static byId($,O){return new Tj($,O)}}class k$ extends A{async fetch(){return J(await this.client.storage.getForm({path:{id:this.id}}))}static byId($,O){return new k$($,O)}static async create($,O){let j=J(await $.storage.createForm({body:{name:O.name,source:O.table?{kind:"table",databaseId:O.table.database.id,tableId:O.table.id}:{kind:"new"}}}));return new k$($,j.form.id,j)}static async list($,O){if(!O)return J(await $.storage.listAccessibleForms()).map(({form:S})=>new k$($,S.id));return J(await $.storage.listForms({query:{databaseId:O.id}})).map((x)=>new k$($,x.id))}schema(){return this.detail.get()}name=this.mappedField("form",($)=>$.name);description=this.mappedField("form",($)=>$.description);owner=this.mappedField("form",($)=>M.byId(this.client,$.ownerId));database=this.mappedField("form",($)=>Q$.byId(this.client,$.databaseId));table=this.mappedField("form",($)=>Y$.byId(Q$.byId(this.client,$.databaseId),$.tableId));audience=this.mappedField("form",($)=>$.audience);status=this.mappedField("form",($)=>$.status);closesAt=this.mappedField("form",($)=>$.closesAt??void 0);access=this.field("access");async sections(){return(await this.detail.get()).sections.map(($)=>d$.byId(this,$.id))}async questions(){return(await this.detail.get()).sections.flatMap(($)=>$.kind==="questions"?$.questions.map((O)=>u$.byId(this,O.id)):[])}async update($){return await this.mutate((O)=>O.storage.updateForm({path:{id:this.id},body:$})),this}assertOwns($){if($.form.id!==this.id)throw new b(`question or section does not belong to form ${this.id}`)}async replaceLayout($){let O=await this.table(),j=(Z)=>{if(Z.table.id!==O.id||Z.table.database.id!==O.database.id)throw new b(`column does not belong to form ${this.id}'s table`);return Z.id},x=(Z)=>({conjunction:Z.conjunction,conditions:Z.conditions.map((X)=>c(X).with({kind:"group"},(G)=>({kind:"group",...x(G)})).with({kind:"condition"},(G)=>({kind:"condition",column:j(G.column),test:c(G.test).with({kind:"options"},(L)=>({...L,options:L.options.map((Y)=>Y.id)})).with({kind:"entities"},(L)=>({...L,entities:L.entities.map((Y)=>Y.id)})).with({kind:x$.union("presence","text","number","date","checkbox")},(L)=>L).exhaustive()})).exhaustive())}),S={sections:$.map((Z)=>{if(Z.section)this.assertOwns(Z.section);let X={id:Z.section?.id??h$(),title:Z.title,description:Z.description??""};return c(Z).with({kind:"booking"},(G)=>({...X,kind:"booking",target:G.target})).with({kind:"gate"},(G)=>({...X,kind:"gate",rules:x(G.rules),message:G.message})).with({kind:"questions"},(G)=>({...X,kind:"questions",questions:G.questions.map((L)=>{if(L.question)this.assertOwns(L.question);return{id:L.question?.id??h$(),column:j(L.column),helpText:L.helpText??"",required:L.required??!1,widget:L.widget??null}})})).exhaustive()})},K=await this.mutate((Z)=>Z.storage.putFormLayout({path:{id:this.id},body:S}));return{form:this,publicationError:K.publicationError}}wireAnswers($){return $.map(({question:O,value:j})=>{this.assertOwns(O);let x=c(j).with({type:"rows"},(S)=>({type:"rows",value:S.value.map((K)=>K.id)})).with({type:"options"},(S)=>({type:"options",value:S.value.map((K)=>{if(K.question.id!==O.id||K.question.form.id!==this.id)throw new b("option does not belong to the answered question");return{id:K.id}})})).with({type:"entities"},(S)=>({type:"entities",value:S.value.map(({entityType:K,entity:Z})=>({entityType:K,entityId:Z.id}))})).with({type:x$.union("text","number","boolean","date","link","clear")},(S)=>S).exhaustive();return{question:O.id,value:x}})}unlockedBooking($){return $?{...$,section:d$.byId(this,$.section)}:void 0}async outcome($,O){return c($).with({outcome:"stopped"},(j)=>({...j,section:d$.byId(this,j.section)})).with({outcome:"submitted"},async(j)=>{let x=A$.byId(await this.table(),j.row),S=this.unlockedBooking(j.booking);return{outcome:"submitted",response:LO.byId(this,j.response,{status:"submitted",row:x,answers:O,booking:S}),row:x,...S?{booking:S}:{}}}).exhaustive()}async submit($){let O={answers:this.wireAnswers($)};return this.outcome(J(await this.client.storage.submitFormResponse({path:{id:this.id},body:O})),$)}async editResponse($){let O={answers:this.wireAnswers($)};return this.outcome(J(await this.client.storage.editMyFormResponse({path:{id:this.id},body:O})),$)}async myResponse(){let $=J(await this.client.storage.getMyFormResponse({path:{id:this.id}})),O=await this.table(),j=await Promise.all($.answers.map(async(K)=>{let Z=u$.byId(this,K.question),X=await c(K.value).with({type:"options"},(G)=>({type:"options",value:G.value.map((L)=>{if(!("id"in L))throw new b("stored form answers must reference options by id");return JO.byId(Z,L.id)})})).with({type:"entities"},(G)=>({type:"entities",value:G.value.map((L)=>({entityType:L.entityType,entity:Tj.byId(L.entityType,L.entityId)}))})).with({type:"rows"},async(G)=>{let L=await Z.detail();if(L.kind.type!=="relation")throw new b("row answer requires a relation question");let Y=Y$.byId(Q$.byId(this.client,L.kind.database),L.kind.table);return{type:"rows",value:G.value.map((Q)=>A$.byId(Y,Q))}}).with({type:x$.union("text","number","boolean","date","link","clear")},(G)=>G).exhaustive();return{question:Z,value:X}})),x=$.response.row?A$.byId(O,$.response.row):void 0,S=this.unlockedBooking($.booking);return{...S?{booking:S}:{},response:LO.byId(this,$.response.id,{status:$.response.status,row:x,answers:j,booking:S}),status:$.response.status,stoppedAtSection:$.response.stoppedAtSection?d$.byId(this,$.response.stoppedAtSection):void 0,row:x,submittedAt:$.response.submittedAt,updatedAt:$.response.updatedAt,answers:j}}async responseSummary(){let $=J(await this.client.storage.getFormResponseSummary({path:{id:this.id}}));return{...$,stoppedBySection:$.stoppedBySection.map((O)=>({section:d$.byId(this,O.section),count:O.count}))}}async tally(){return J(await this.client.storage.getFormTally({path:{id:this.id}})).questions.map((O)=>{let j=u$.byId(this,O.question);return{question:j,responses:O.responses,buckets:O.buckets.map((x)=>({count:x.count,value:c(x.value).with({kind:"option"},(S)=>({kind:"option",option:JO.byId(j,S.option)})).with({kind:"checkbox"},(S)=>S).exhaustive()}))}})}async sharePermissions(){return J(await this.client.storage.getFormPermissions({path:{id:this.id}}))}updateSharePermissions($){return this.mutate((O)=>O.storage.updateFormPermissions({path:{id:this.id},body:$}))}webUrl(){return`${this.client.webAppUrl}/app/form/${this.id}`}respondUrl(){return`${this.client.webAppUrl}/app/form/${this.id}/respond`}}class Z0{client;constructor($){this.client=$}byId($){return k$.byId(this.client,$)}create($){return k$.create(this.client,$)}list($){return k$.list(this.client,$)}}class NO extends A{static byId($,O){return new NO($,O)}async fetch(){return J(await this.client.storage.getGithubPullRequest({path:{id:this.id}}))}title=this.field("title");url=this.field("url");status=this.field("status");async changes(){let $=J(await this.client.storage.getGithubPullRequestChanges({path:{id:this.id}}));return{changeset:$.changeset?new X0(this.client,this,$.changeset):void 0,error:$.error??void 0}}}class X0{client;pullRequest;record;constructor($,O,j){this.client=$;this.pullRequest=O;this.record=j}get id(){return this.record.id}async patch(){return J(await this.client.storage.getGithubPullRequestChangesPatch({path:{id:this.pullRequest.id},query:{changeset:this.id}})).patch}toJSON(){return{pullRequestId:this.pullRequest.id,...this.record}}}class G0{client;constructor($){this.client=$}byId($){return NO.byId(this.client,$)}forEntity($){return NO.byId(this.client,$.id)}}class UO extends A{static byId($,O){return new UO($,O)}async fetch(){return J(await this.client.storage.getHarnessPairing({path:{code:this.id}}))}name=this.field("requested_name");expiresAt=this.field("expires_at");async approve($){let O={name:$?.name,team_id:$?.team?.id,allow_permission_bypass:$?.allowPermissionBypass};return V$.from(this.client,await this.mutate((j)=>j.storage.approveHarnessPairing({path:{code:this.id},body:O})))}}class pO{client;id;constructor($,O){this.client=$;this.id=O}static byId($,O){return new pO($,O)}async claim($){let O=J(await this.client.storage.claimHarnessPairing({path:{pairing_id:this.id},body:{device_secret:$}}));return"harness"in O?{harness:V$.from(this.client,O.harness),token:O.token}:void 0}toJSON(){return{id:this.id}}}class K0{client;constructor($){this.client=$}byId($){return V$.byId(this.client,$)}async list(){return J(await this.client.storage.listHarnesses()).map(($)=>V$.from(this.client,$))}async me(){return V$.from(this.client,J(await this.client.storage.getSelfHarness()))}async deleteSelf(){J(await this.client.storage.deleteSelfHarness())}async agents(){return J(await this.client.storage.listHarnessAgents()).map(($)=>N$.byId(this.client,$.bot_id))}async sessions(){return J(await this.client.storage.listHarnessSessions()).map(($)=>i.byId(this.client,$.session_id))}pairing($){return UO.byId(this.client,$)}async createPairing($){let O=J(await this.client.storage.createHarnessPairing({body:$}));return{pairing:UO.byId(this.client,O.code),device:pO.byId(this.client,O.pairing_id),deviceSecret:O.device_secret,expiresAt:O.expires_at,pollIntervalSeconds:O.poll_interval_seconds}}}var t6="00000001-0000-0000-0000-000000000002",e6="00000001-0000-0000-0002-000000000004";function o6($){let O=$.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/pull\/([1-9][0-9]*)\/?(?:[?#].*)?$/i);if(!O)throw Error(`Expected a GitHub pull request URL like https://github.com/owner/repo/pull/1, got ${$}`);return`${O[1]}/${O[2]}/pull/${O[3]}`}class D$ extends q{static byId($,O){return new D$($,O)}static async create($,O){let{documentId:j}=J(await $.storage.createTaskHandler({body:{taskName:O.name,markdown:O.markdown??null,projectId:O.project?.id??null,teamId:O.team?.id??null,shareWithTeam:O.shareWithTeam??!0}}));return new D$($,j)}static async forPullRequest($,O){let j=o6(O),{pullRequests:x}=J(await $.storage.getGithubPullRequestTasks({body:{githubKeys:[j]}}));return(x[0]?.taskIds??[]).map((S)=>new D$($,S))}async completed(){let{subType:$}=await this.detail.get();if($!=="task")return;let j=(await this.properties()).find((x)=>x.definition.id===t6)?.value;return j?.type==="SelectOption"&&j.value.includes(e6)}webUrl(){return`${this.client.webAppUrl}/app/task/${this.id}`}static search=j$({filters:{document_filters:{sub_types:["task"],task_filters:{}}},type:"document",make:($,O)=>new D$($,O.document_id)})}class $O extends A{access=new o(this.client,"initiative",this);static byId($,O){return new $O($,O)}static from($,O){return new $O($,O.id,O)}async fetch(){return J(await this.client.storage.getInitiative({path:{initiative_id:this.id}}))}name=this.field("name");owner=this.mappedField("ownerId",($)=>M.byId(this.client,$));members=this.mappedField("memberIds",($)=>$.map((O)=>M.byId(this.client,O)));tasks=this.mappedField("taskIds",($)=>$.map((O)=>D$.byId(this.client,O)));accessLevel=this.field("userAccessLevel");sharePermissions=this.field("sharePermission");async update($){await this.mutate((O)=>O.storage.updateInitiative({path:{initiative_id:this.id},body:{name:$.name,memberIds:$.members?.map((j)=>j.id),sharePermission:$.sharePermission?r$($.sharePermission):void 0}}))}async delete(){await this.mutate(($)=>$.storage.deleteInitiative({path:{initiative_id:this.id}}))}}class Y0{client;constructor($){this.client=$}byId($){return $O.byId(this.client,$)}async list(){return J(await this.client.storage.listInitiatives()).initiatives.map(($)=>$O.byId(this.client,$.id))}async create($){return $O.from(this.client,J(await this.client.storage.createInitiative({body:{name:$.name,description:$.description,memberIds:$.members?.map((O)=>O.id),shareWithTeam:$.shareWithTeam,propertyValues:$.propertyValues}})))}}class Q0{client;constructor($){this.client=$}byId($){return I$.byId(this.client,$)}async create($){return I$.from(this.client,J(await this.client.storage.meetingCreate({body:$})))}async list(){return J(await this.client.storage.meetingList()).meetings.map(($)=>I$.from(this.client,$))}async active(){return J(await this.client.storage.meetingListActive()).meetings.map(($)=>I$.from(this.client,$))}async lookup($){return I$.from(this.client,J(await this.client.storage.meetingLookup({path:{token:$}})))}}class VO extends A{async fetch(){return J(await this.client.notification.getTypedNotificationById({path:{notification_id:this.id}}))}static byId($,O){return new VO($,O)}static from($,O){return new VO($,O.id,O)}static list($,O){return a(async(j)=>{let x=J(await $.notification.listTypedNotifications({query:{...O?.pageSize?{limit:O.pageSize}:{},...O?.states!==void 0?{states:O.states.join(",")}:{},...j?{cursor:j}:{}}}));return{items:x.items.map((S)=>VO.from($,S)),nextCursor:x.next_cursor}})}type=this.field("notification_event_type");createdAt=this.field("created_at");updatedAt=this.field("updated_at");state=this.field("state");done=this.mappedField("state",($)=>$==="done");sent=this.field("sent");viewedAt=this.field("viewed_at");deletedAt=this.field("deleted_at");owner=this.mappedField("owner_id",($)=>M.byId(this.client,$));sender=this.mappedField("sender_id",($)=>$?M.byId(this.client,$):void 0);metadata=this.field("notification_metadata");async seen(){return await this.state()!=="unseen"}async markSeen(){await this.mutate(($)=>$.notification.bulkMarkNotificationsSeen({body:{notificationIds:[this.id]}}))}async markDone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsDone({body:{notificationIds:[this.id]}}))}async markUndone(){await this.mutate(($)=>$.notification.bulkMarkNotificationsUndone({body:{notificationIds:[this.id]}}))}async delete(){await this.mutate(($)=>$.notification.deleteUserNotificationV2({path:{notification_id:this.id}}))}}class J0{client;constructor($){this.client=$}byId($){return VO.byId(this.client,$)}list($){return VO.list(this.client,$)}async markSeen($){J(await this.client.notification.bulkMarkNotificationsSeen({body:{notificationIds:$}}))}async markDone($){J(await this.client.notification.bulkMarkNotificationsDone({body:{notificationIds:$}}))}async delete($){J(await this.client.notification.bulkDeleteUserNotificationsV2({body:{notificationIds:$}}))}async preferences(){return J(await this.client.notification.getNotificationTypePreferences())}async enableType($){J(await this.client.notification.enableNotificationType({path:{notification_event_type:$}}))}async disableType($){J(await this.client.notification.disableNotificationType({path:{notification_event_type:$}}))}}class V0{client;constructor($){this.client=$}async list(){let{data:$}=J(await this.client.storage.getPinsHandler({}));return $?.recent??[]}async add($,O){J(await this.client.storage.addPinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType,pinIndex:O.index}}))}async remove($){J(await this.client.storage.removePinHandler({path:{pinned_item_id:$.id},body:{pinType:$.entityType}}))}async reorder($){J(await this.client.storage.reorderPinsHandler({body:$}))}}class W0{client;constructor($){this.client=$}byId($){return n.byId(this.client,$)}create($){return n.create(this.client,$)}search($,O){return n.search(this.client,$,O)}}class zO{client;definitionId;id;record;constructor($,O,j,x){this.client=$;this.definitionId=O;this.id=j;this.record=x}static from($,O,j){return new zO($,O,j.id,j)}get value(){return this.record.value}get color(){return this.record.color??void 0}get displayOrder(){return this.record.display_order}get createdAt(){return this.record.created_at}get updatedAt(){return this.record.updated_at}async update($){return this.record=J(await this.client.properties.updatePropertyOption({path:{definition_id:this.definitionId,option_id:this.id},body:$})),this}async delete(){J(await this.client.properties.deletePropertyOption({path:{definition_id:this.definitionId,option_id:this.id}}))}}class OO{client;id;detail;constructor($,O,j){this.client=$;this.id=O;this.detail=new J$(()=>this.fetch(),j)}async fetch(){return J(await this.client.properties.getPropertyDefinition({path:{definition_id:this.id}}))}static async create($,O){let j=J(await $.properties.createPropertyDefinition({body:{display_name:O.displayName,scope:O.scope,data_type:O.dataType}}));return new OO($,j.id,j)}static byId($,O){return new OO($,O)}static fromRecord($,O){return new OO($,O.id,O)}get displayName(){return this.detail.get().then(($)=>$.display_name)}get dataType(){return this.detail.get().then(($)=>$.data_type)}get owner(){return this.detail.get().then(($)=>$.owner)}get isSystem(){return this.detail.get().then(($)=>$.is_system)}get isMultiSelect(){return this.detail.get().then(($)=>$.is_multi_select)}get createdAt(){return this.detail.get().then(($)=>$.created_at)}get updatedAt(){return this.detail.get().then(($)=>$.updated_at)}async delete(){return J(await this.client.properties.deletePropertyDefinition({path:{definition_id:this.id}}))}async options(){return J(await this.client.properties.getPropertyOptions({path:{definition_id:this.id}})).map((O)=>zO.from(this.client,this.id,O))}async addOption($){let O=J(await this.client.properties.addPropertyOption({path:{definition_id:this.id},body:$}));return zO.from(this.client,this.id,O)}async updateOption($,O){let j=J(await this.client.properties.updatePropertyOption({path:{definition_id:this.id,option_id:$.id},body:O}));return zO.from(this.client,this.id,j)}async deleteOption($){return J(await this.client.properties.deletePropertyOption({path:{definition_id:this.id,option_id:$.id}}))}}class B0{client;constructor($){this.client=$}async list($){return J(await this.client.properties.listProperties({query:{scope:$?.scope??"all",...$?.forEntityType!==void 0?{for_entity_type:$.forEntityType}:{}}})).map((j)=>{let x="definition"in j?j.definition:j;return OO.fromRecord(this.client,x)})}create($){return OO.create(this.client,$)}definition($){return OO.byId(this.client,$)}async bulkEntityProperties($){return J(await this.client.properties.getBulkEntityProperties({body:$}))}async updateEntityPropertyOptions($,O){return J(await this.client.properties.bulkUpdateEntitiesPropertyOptions({body:{entities:$.map((x)=>x.propertyReference()),property_id:O.property.id,...O.add?{add_option_ids:O.add.map((x)=>x.id)}:{},...O.remove?{remove_option_ids:O.remove.map((x)=>x.id)}:{}}})).results}async addEntityPropertyOption($){return J(await this.client.properties.addEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async removeEntityPropertyOption($){return J(await this.client.properties.removeEntityPropertyOption({path:{...$.entity.propertyReference(),property_id:$.property.id,option_id:$.option.id}}))}async tags(){return J(await this.client.properties.listTags({}))}}function L0($){return c($).with({type:"cron"},(O)=>O).with({type:"events"},(O)=>({type:"events",filters:O.filters.map(({entities:j,...x})=>({...x,ids:j?.map((S)=>S.entity.id)}))})).exhaustive()}function $7($){return c($).with({type:"multiple"},(O)=>({type:"multiple",triggers:O.triggers.map(L0)})).with({type:"cron"},L0).with({type:"events"},L0).exhaustive()}class jO extends A{static byId($,O){return new jO($,O)}static from($,O){if(!O.id)throw Error("Routine response has no id");return new jO($,O.id,O)}async fetch(){return J(await this.client.scheduledAction.getScheduledAction({path:{id:this.id}}))}name=this.field("name");trigger=this.field("trigger");enabled=this.field("enabled");nextRunAt=this.field("next_run_at");revision=this.field("configuration_revision");owner=this.mappedField("owner",($)=>M.byId(this.client,$));async update($){await this.mutate((O)=>O.scheduledAction.updateScheduledAction({path:{id:this.id},body:U0($)}))}async setEnabled($){await this.mutate((O)=>O.scheduledAction.setScheduledActionEnabled({path:{id:this.id},body:{enabled:$}}))}async execute(){let $=J(await this.client.scheduledAction.executeScheduledActionNow({path:{id:this.id}}));if($.resource)return c($.resource).with({type:"agent"},(O)=>i.byId(this.client,O.id)).with({type:"chat"},(O)=>Z$.byId(this.client,O.id)).exhaustive();return $.chat_id?Z$.byId(this.client,$.chat_id):void 0}async history(){return J(await this.client.scheduledAction.listScheduledActionHistory({path:{id:this.id}})).map(($)=>new N0(this,$))}async delete(){await this.mutate(($)=>$.scheduledAction.deleteScheduledAction({path:{id:this.id}}))}}class N0{routine;record;constructor($,O){this.routine=$;this.record=O}get id(){return this.record.id??void 0}toJSON(){return{routine:this.routine.id,...this.record}}}function U0($){let O={prompt:$.prompt,user_prompt:$.userPrompt,model:$.model,agent:$.agent?{bot_id:$.agent.id}:void 0};return{kind:"Agent",name:$.name,enabled:$.enabled,trigger:$7($.trigger),task:{...O}}}class z0{client;constructor($){this.client=$}byId($){return jO.byId(this.client,$)}async create($){return jO.from(this.client,J(await this.client.scheduledAction.createScheduledAction({body:{...U0($),enabled:$.enabled??!0}})))}async list($){return J(await this.client.scheduledAction.listScheduledActions({query:{include_events:$?.includeEvents}})).map((O)=>jO.from(this.client,O))}}class I0{client;constructor($){this.client=$}byId($){return D$.byId(this.client,$)}create($){return D$.create(this.client,$)}forPullRequest($){return D$.forPullRequest(this.client,$)}search($,O){return D$.search(this.client,$,O)}}class T0{client;constructor($){this.client=$}byId($){return T$.byId(this.client,$)}current(){return T$.current(this.client)}list(){return T$.list(this.client)}}class H0{client;constructor($){this.client=$}async get($){return J(await this.client.unfurl.getUnfurl({query:{url:$}}))}async bulk($){return J(await this.client.unfurl.getUnfurlBulk({body:{url_list:$}}))}}class R0{client;constructor($){this.client=$}byId($){return M.byId(this.client,$)}me(){return M.me(this.client)}}class xO extends A{signingSecret;constructor($,O,j,x){super($,O,j);this.signingSecret=x}async fetch(){return J(await this.client.storage.getWebhook({path:{webhook_id:this.id}}))}static async create($,O){let j=J(await $.storage.createWebhook({body:{endpoint_url:O.url,namespace:O.namespace,name:O.name,filters:O.filters,scope:O.scope??"user",...O.headers!==void 0?{headers:O.headers}:{}}}));return new xO($,j.id,j,j.signing_secret)}static byId($,O){return new xO($,O)}static fromRecord($,O){return new xO($,O.id,O)}name=this.field("name");namespace=this.field("namespace");endpointUrl=this.field("endpoint_url");status=this.field("status");isValid=this.field("is_valid");filters=this.field("filters");createdAt=this.field("created_at");workspaceId=this.field("workspace_id");createdBy=this.mappedField("created_by_user_id",($)=>M.byId(this.client,$));async scope(){let $=await this.detail.get();return $.workspace_id===$.created_by_user_id?"user":"team"}async update($){await this.mutate((O)=>O.storage.patchWebhook({path:{webhook_id:this.id},body:$}))}async rename($){await this.update({name:$})}async setUrl($){await this.update({endpoint_url:$})}async setFilters($){await this.update({filters:$})}async pause(){await this.update({status:"paused"})}async resume(){await this.update({status:"active"})}async delete(){await this.mutate(($)=>$.storage.deleteWebhook({path:{webhook_id:this.id}}))}async validate(){return this.mutate(($)=>$.storage.validateWebhook({path:{webhook_id:this.id}}))}}class D0{client;constructor($){this.client=$}create($){return xO.create(this.client,$)}byId($){return xO.byId(this.client,$)}async list(){let{webhooks:$}=J(await this.client.storage.listWebhooks());return $.map((O)=>xO.fromRecord(this.client,O))}}function C0($){if("properties"in $.data)return $.data.properties;if($.tag==="calendarEvent")return $.data.extra.properties;return[]}function y1($,O,j){let x=[];for(let S of C0(O)){if(S.definition.data_type!=="TAG"||S.value?.type!=="SelectOption")continue;for(let K of S.value.value){let Z=j.get(K);if(Z&&!x.some((X)=>X.label===Z.label&&X.scope===Z.scope))x.push(Z)}}switch(O.tag){case"document":return{type:"document",id:O.data.id,entity:q.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name,fileType:O.data.fileType,subType:O.data.subType?.type};case"chat":return{type:"ai_chat",id:O.data.id,entity:Z$.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"project":return{type:"project",id:O.data.id,entity:n.byId($,O.data.id),snapshot:O,tags:x,name:O.data.name};case"emailThread":return{type:"email",id:O.data.id,entity:H$.byId($,O.data.id),snapshot:O,tags:x,subject:O.data.name,snippet:O.data.snippet,senderName:O.data.senderName,senderEmail:O.data.senderEmail,inboxVisible:O.data.inboxVisible,isRead:O.data.isRead,isDraft:O.data.isDraft};case"channel":return{type:"channel",id:O.data.channel.id,entity:f.byId($,O.data.channel.id),snapshot:O,tags:x,name:O.data.channel.name};case"channelThread":return{type:"channel_thread",id:O.data.id,entity:new g$($,O.data.channel_id,O.data.id),snapshot:O,tags:x,channelId:O.data.channel_id};case"call":return{type:"call",id:O.data.callId,entity:K$.byId($,O.data.callId),snapshot:O,tags:x,createdBy:O.data.createdBy};case"calendarEvent":return{type:"calendar_event",id:O.data.id,entity:z$.byId($,O.data.id),snapshot:O,tags:x,title:O.data.title,status:O.data.status,location:O.data.location,conferenceUrl:O.data.conferenceUrl,conferenceProvider:O.data.conferenceProvider,time:O.data.time};case"foreignEntity":return{type:"foreign_entity",id:O.data.id,entity:o$.byId($,O.data.id),snapshot:O,tags:x,foreignEntityId:O.data.foreignEntityId,foreignEntitySource:O.data.foreignEntitySource,metadata:O.data.metadata};default:throw Error(`Unexpected workspace entity type: ${O.tag}`)}}var v1="00000000-0000-0000-0000-000000000000",_0={document:["df","id"],project:["pf","pid"],ai_chat:["cf","cid"],email:["ef","ThreadId"],channel:["chanf","ChannelId"],channel_thread:["cthf","ThreadId"],call:["callf","CallId"],calendar_event:["calf","id"],foreign_entity:["fef","id"]},Hj=($)=>$.replace(/[A-Z]/g,(O)=>O.toLowerCase()),h1=($,O)=>$==null?O:{"&":[$,O]};function M0($,O){if(!$||typeof $!=="object"||Array.isArray($))throw Error(`Invalid workspace ${O}: expected a filter expression.`);let j=Object.entries($),x=j[0];if(j.length!==1||x===void 0)throw Error(`Invalid workspace ${O}: use exactly one of l, &, |, !.`);let[S,K]=x;if(S==="l")return;if(S==="!"){M0(K,`${O}.!`);return}if(S!=="&"&&S!=="|")throw Error(`Invalid workspace ${O}: use l, &, | or !.`);if(!Array.isArray(K)||K.length!==2)throw Error(`Invalid workspace ${O}.${S}: expected exactly two expressions. Use {l: {...}} for a single condition; nest binary operators for three or more.`);K.forEach((Z,X)=>{M0(Z,`${O}.${S}[${X}]`)})}class Rj{client;tagSets;constructor($){this.client=$}sets(){return this.tagSets??=this.client.properties.listTags({}).then(J),this.tagSets}async tagMap(){let $=new Map;for(let O of await this.sets())for(let j of O.options)if(j.value.type==="string")$.set(j.id,{label:j.value.value,scope:O.scope==="user"?"personal":"team"});return $}async body($){for(let[S,K,Z]of[["sortBy",$.sortBy,["recently_viewed","recently_updated","recently_created"]],["emailPreset",$.emailPreset,["signal"]],["tagsMatch",$.tagsMatch,["any","all"]]])if(K!==void 0&&!Z.includes(K))throw Error(`Invalid workspace ${S}: ${K}`);if($.includeTypes!==void 0&&(!Array.isArray($.includeTypes)||$.includeTypes.some((S)=>!Object.hasOwn(_0,S))))throw Error(`Invalid workspace includeTypes. Supported values: ${Object.keys(_0).join(", ")}. Tasks use document with df: {l: {dst: 'task'}}.`);for(let S of["df","pf","cf","ef","chanf","cthf","callf","fef","calf","propf"])if($[S]!=null)M0($[S],S);if($.tags?.some((S)=>S.scope!==void 0&&S.scope!=="personal"&&S.scope!=="team"))throw Error("Invalid workspace tag scope");if($.limit!==void 0&&!Number.isFinite($.limit))throw Error("Workspace limit must be finite");let O={df:$.df,pf:$.pf,cf:$.cf,ef:$.ef,chanf:$.chanf,cthf:$.cthf,callf:$.callf,fef:$.fef,calf:$.calf,propf:$.propf,ccf:{l:{id:v1}},favorites_only:$.favoritesOnly,expand:!0,limit:Math.max(1,Math.min(500,Math.trunc($.limit??50))),sort_method:$.sortBy==="recently_viewed"?"viewed_at":$.sortBy==="recently_created"?"created_at":"updated_at",sort_direction:"desc",emailView:$.emailView??"inbox"};if($.emailPreset==="signal")O.ef={"&":[{l:{Importance:!0}},{l:{Shared:"exclude"}}]};let j=$.inbox?.trim();if(j){let{links:S}=J(await this.client.email.listLinks()),K=S.filter((X)=>Hj(X.email_address)===Hj(j)),Z=K[0];if(!Z)throw Error(`No connected inbox matches "${j}". Connected inboxes: ${S.map((X)=>X.email_address).join(", ")}.`);if(K.length>1)throw Error(`Multiple connected inboxes match "${j}"; cannot pick one.`);O.ef=h1(O.ef,{l:{Owner:Z.id}})}let x=$.includeTypes??($.emailPreset==="signal"?["email"]:void 0);if(x?.length){for(let[S,[K,Z]]of Object.entries(_0))if(!x.includes(S))O[K]={l:{[Z]:v1}}}if($.tags?.length){let S=(await this.sets()).flatMap((G)=>{let L=G.definition;if(!L)return[];return G.options.flatMap((Y)=>Y.value.type==="string"?[{id:Y.id,definitionId:L.id,label:Y.value.value,scope:G.scope==="user"?"personal":"team"}]:[])}),K=new Map;for(let G of $.tags){let L=S.filter((Y)=>Hj(Y.label)===Hj(G.label.trim())&&(!G.scope||Y.scope===G.scope));if(!L.length)throw Error(`Unknown tag "${G.label}". Available tags: ${S.map((Y)=>`${Y.label} (${Y.scope})`).join(", ")}.`);if($.tagsMatch==="all"&&L.length>1)throw Error(`Tag "${G.label}" is ambiguous; specify personal or team scope.`);for(let Y of L)K.set(Y.id,Y)}let X=[...K.values()].map((G)=>({l:{pd:G.definitionId,v:{so:G.id}}})).reduce((G,L)=>G===void 0?L:{[$.tagsMatch==="all"?"&":"|"]:[G,L]},void 0);O.propf=h1(O.propf,X)}return O}}class A0{client;constructor($){this.client=$}async page($={}){let O=new Rj(this.client);return this.fetch(O,await O.body($),$.cursor)}async*list($={}){let O=new Rj(this.client),j=await O.body($);yield*a((x)=>this.fetch(O,j,x))}async fetch($,O,j){let x=J(await this.client.storage.postItemsSoupAst({body:O,query:j?{cursor:j}:void 0})),K=x.items.some((Z)=>C0(Z).some((X)=>X.definition.data_type==="TAG"))?await $.tagMap():new Map;return{items:x.items.map((Z)=>y1(this.client,Z,K)),nextCursor:x.next_cursor,hasMore:x.next_cursor!=null}}}function m1({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let Q,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,I=Y.signal??new AbortController().signal;while(!0){if(I.aborted)break;B++;let P=Y.headers instanceof Headers?Y.headers:new Headers(Y.headers);if(Q!==void 0)P.set("Last-Event-ID",Q);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);let N=await(Y.fetch??globalThis.fetch)(C);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",k);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;U+=l,U=U.replace(/\r\n?/g,`
`);let g=U.split(`
`);U=g.pop()??"";for(let r of g){let p=r.split(`
`),F=[],y;for(let R of p)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))y=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))Q=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let h=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(h))V=h}let _,v=!1;if(F.length){let R=F.join(`
-`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:Q,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var O7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},j7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},x7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Dj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(j7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=O7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return IO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},IO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Cj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,Q])=>{G=[...G,Y,$?Q:encodeURIComponent(Q)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=x7(x),X=Object.entries(S).map(([G,L])=>IO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var S7=/\{[^{}]+\}/g,Z7=({path:$,url:O})=>{let j=O,x=O.match(S7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,Dj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,Cj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${IO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},c1=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=Z7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function P0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var u1=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var d1={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var l1=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=Dj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=Cj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=IO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},r1=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},X7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function p1($){for(let O of $.security??[]){if(X7($,O.name))continue;let j=await u1(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var F0=($)=>c1({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:l1($.querySerializer),url:$.url}),E0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Mj($.headers,O.headers),j},G7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Mj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?G7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class _j{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var a1=()=>({error:new _j,request:new _j,response:new _j}),K7=l1({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Y7={"Content-Type":"application/json"},aO=($={})=>({...d1,headers:Y7,parseAs:"auto",querySerializer:K7,...$});var w0=($={})=>{let O=E0(aO(),$),j=()=>({...O}),x=(Y)=>{return O=E0(O,Y),j()},S=a1(),K=async(Y)=>{let Q={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:Mj(O.headers,Y.headers),serializedBody:void 0};if(Q.security)await p1(Q);if(Q.requestValidator)await Q.requestValidator(Q);if(Q.body!==void 0&&Q.bodySerializer)Q.serializedBody=Q.bodySerializer(Q.body);if(Q.body===void 0||Q.serializedBody==="")Q.headers.delete("Content-Type");let T=Q,z=F0(T);return{opts:T,url:z}},Z=async(Y)=>{let Q=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:P0(V)};z=new Request(B,I);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?r1(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),E;try{E=JSON.parse(C)}catch{}throw E??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},Q)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(Q)=>Z({...Q,method:Y}),G=(Y)=>async(Q)=>{let{opts:T,url:z}=await K(Q);return m1({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:P0(T),url:z})};return{buildUrl:(Y)=>F0({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var i1=w0(aO());class n1{client;constructor($){this.client=$?.client??i1}}class s1{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Aj extends n1{static __registry=new s1;constructor($){super($);Aj.__registry.set(this,$?.key)}discoverAgentCapabilitiesHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-capabilities/discover",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentCodingPreferences($){return($?.client??this.client).get({url:"/agent-coding-preferences",...$})}putAgentCodingPreferences($){return($.client??this.client).put({url:"/agent-coding-preferences",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentConversations($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}",...$})}startFreshAgentConversation($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/start-fresh",...$,headers:{"Content-Type":"application/json",...$.headers}})}retryAgentConversationTurn($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/turns/{source}/retry",...$,headers:{"Content-Type":"application/json",...$.headers}})}loadAgentModelsHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-models/load",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentRepositories($){return($?.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-repositories",...$})}listAgentRepositoryBranches($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-repositories/branches",...$})}getAgentSandboxSize($){return($?.client??this.client).get({url:"/agent-sandbox-size",...$})}putAgentSandboxSize($){return($.client??this.client).put({url:"/agent-sandbox-size",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAgentSession($){return($.client??this.client).post({url:"/agent-sessions",...$,headers:{"Content-Type":"application/json",...$.headers}})}agentSessionsForPullRequest($){return($.client??this.client).post({url:"/agent-sessions/by-pull-request",...$,headers:{"Content-Type":"application/json",...$.headers}})}agentSessionsForPullRequests($){return($.client??this.client).post({url:"/agent-sessions/by-pull-requests",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewAgentSessions($){return($.client??this.client).post({url:"/agent-sessions/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}warmAgentSessionHandler($){return($.client??this.client).post({url:"/agent-sessions/warm",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAgentSession($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}",...$})}getAgentSession($){return($.client??this.client).get({url:"/agent-sessions/{session_id}",...$})}setAgentSessionArchived($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionChanges($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/changes",...$})}getAgentSessionChangesPatch($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/changes/patch",...$})}refreshAgentSessionChanges($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/changes/refresh",...$})}getCodeExecution($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/code-executions/{execution_id}",...$})}listExecutionReviews($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/code-executions/{execution_id}/reviews",...$})}controlAgentSession($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/control",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionLog($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/log",...$})}renameAgentSession($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionPermissions($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/permissions",...$})}updateAgentSessionPermissions($){return($.client??this.client).patch({url:"/agent-sessions/{session_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}unlinkAgentSessionPullRequest($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}/pull-requests",...$})}listAgentSessionPullRequests($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/pull-requests",...$})}linkAgentSessionPullRequest($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/pull-requests",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionQueue($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/queue",...$})}removeQueuedAction($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}/queue/{action_id}",...$})}editQueuedAction($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/queue/{action_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}steerQueuedAction($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/queue/{action_id}/steer",...$})}createSessionReview($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/reviews",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSessionReview($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/reviews/{review_id}",...$})}decideSessionReview($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/reviews/{review_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}putAgentSessionSandboxSize($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/sandbox-size",...$,headers:{"Content-Type":"application/json",...$.headers}})}answerAgentSessionToolApproval($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/tool-approvals/{approval_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}disconnect($){return($.client??this.client).delete({security:[{scheme:"bearer",type:"http"}],url:"/claude-auth",...$,headers:{"Content-Type":"application/json",...$.headers}})}status($){return($?.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/claude-auth",...$})}complete($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/claude-auth/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}start($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/claude-auth/start",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function t1({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let Q,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,I=Y.signal??new AbortController().signal;while(!0){if(I.aborted)break;B++;let P=Y.headers instanceof Headers?Y.headers:new Headers(Y.headers);if(Q!==void 0)P.set("Last-Event-ID",Q);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);let N=await(Y.fetch??globalThis.fetch)(C);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",k);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;U+=l,U=U.replace(/\r\n?/g,`
+`);try{_=JSON.parse(R),v=!0}catch{_=R}}if(v){if(S)await S(_);if(x)_=await x(_)}if(j?.({data:_,event:y,id:Q,retry:V}),F.length)yield _}}}finally{I.removeEventListener("abort",k),H.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let C=Math.min(V*2**(B-1),X??30000);await T(C)}}}()}}var O7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},j7=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},x7=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},Dj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((G)=>encodeURIComponent(G))).join(j7(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=O7(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return IO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},IO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},Cj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let G=[];Object.entries(S).forEach(([Y,Q])=>{G=[...G,Y,$?Q:encodeURIComponent(Q)]});let L=G.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=x7(x),X=Object.entries(S).map(([G,L])=>IO({allowReserved:$,name:x==="deepObject"?`${j}[${G}]`:G,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var S7=/\{[^{}]+\}/g,Z7=({path:$,url:O})=>{let j=O,x=O.match(S7);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let G=$[Z];if(G===void 0||G===null)continue;if(Array.isArray(G)){j=j.replace(S,Dj({explode:K,name:Z,style:X,value:G}));continue}if(typeof G==="object"){j=j.replace(S,Cj({explode:K,name:Z,style:X,value:G,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${IO({name:Z,value:G})}`);continue}let L=encodeURIComponent(X==="label"?`.${G}`:G);j=j.replace(S,L)}return j},c1=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=Z7({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function P0($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var u1=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var d1={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var l1=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let G=Dj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(G)S.push(G)}else if(typeof Z==="object"){let G=Cj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(G)S.push(G)}else{let G=IO({allowReserved:X.allowReserved,name:K,value:Z});if(G)S.push(G)}}return S.join("&")}},r1=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},X7=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function p1($){for(let O of $.security??[]){if(X7($,O.name))continue;let j=await u1(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var F0=($)=>c1({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:l1($.querySerializer),url:$.url}),E0=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=Mj($.headers,O.headers),j},G7=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},Mj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?G7(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class _j{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var a1=()=>({error:new _j,request:new _j,response:new _j}),K7=l1({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),Y7={"Content-Type":"application/json"},aO=($={})=>({...d1,headers:Y7,parseAs:"auto",querySerializer:K7,...$});var w0=($={})=>{let O=E0(aO(),$),j=()=>({...O}),x=(Y)=>{return O=E0(O,Y),j()},S=a1(),K=async(Y)=>{let Q={...O,...Y,fetch:Y.fetch??O.fetch??globalThis.fetch,headers:Mj(O.headers,Y.headers),serializedBody:void 0};if(Q.security)await p1(Q);if(Q.requestValidator)await Q.requestValidator(Q);if(Q.body!==void 0&&Q.bodySerializer)Q.serializedBody=Q.bodySerializer(Q.body);if(Q.body===void 0||Q.serializedBody==="")Q.headers.delete("Content-Type");let T=Q,z=F0(T);return{opts:T,url:z}},Z=async(Y)=>{let Q=Y.throwOnError??O.throwOnError,T=Y.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Y),I={redirect:"follow",...V,body:P0(V)};z=new Request(B,I);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?r1(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let H;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":H=await W[N]();break;case"json":{let U=await W.text();H=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(H);if(V.responseTransformer)H=await V.responseTransformer(H)}return V.responseStyle==="data"?H:{data:H,...D}}let C=await W.text(),E;try{E=JSON.parse(C)}catch{}throw E??C}catch(V){let B=V;for(let I of S.error.fns)if(I)B=await I(B,W,z,Y);if(B=B||{},Q)throw B;return T==="data"?void 0:{error:B,request:z,response:W}}},X=(Y)=>(Q)=>Z({...Q,method:Y}),G=(Y)=>async(Q)=>{let{opts:T,url:z}=await K(Q);return m1({...T,body:T.body,method:Y,onRequest:async(W,V)=>{let B=new Request(W,V);for(let I of S.request.fns)if(I)B=await I(B,T);return B},serializedBody:P0(T),url:z})};return{buildUrl:(Y)=>F0({...O,...Y}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:G("CONNECT"),delete:G("DELETE"),get:G("GET"),head:G("HEAD"),options:G("OPTIONS"),patch:G("PATCH"),post:G("POST"),put:G("PUT"),trace:G("TRACE")},trace:X("TRACE")}};var i1=w0(aO());class n1{client;constructor($){this.client=$?.client??i1}}class s1{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class Aj extends n1{static __registry=new s1;constructor($){super($);Aj.__registry.set(this,$?.key)}discoverAgentCapabilitiesHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-capabilities/discover",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentCodingPreferences($){return($?.client??this.client).get({url:"/agent-coding-preferences",...$})}putAgentCodingPreferences($){return($.client??this.client).put({url:"/agent-coding-preferences",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentConversations($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}",...$})}startFreshAgentConversation($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/start-fresh",...$,headers:{"Content-Type":"application/json",...$.headers}})}retryAgentConversationTurn($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-conversations/{channel_id}/{bot_id}/turns/{source}/retry",...$,headers:{"Content-Type":"application/json",...$.headers}})}loadAgentModelsHandler($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/agent-models/load",...$,headers:{"Content-Type":"application/json",...$.headers}})}listAgentRepositories($){return($?.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-repositories",...$})}listAgentRepositoryBranches($){return($.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/agent-repositories/branches",...$})}getAgentSandboxSize($){return($?.client??this.client).get({url:"/agent-sandbox-size",...$})}putAgentSandboxSize($){return($.client??this.client).put({url:"/agent-sandbox-size",...$,headers:{"Content-Type":"application/json",...$.headers}})}createAgentSession($){return($.client??this.client).post({url:"/agent-sessions",...$,headers:{"Content-Type":"application/json",...$.headers}})}agentSessionsForPullRequest($){return($.client??this.client).post({url:"/agent-sessions/by-pull-request",...$,headers:{"Content-Type":"application/json",...$.headers}})}agentSessionsForPullRequests($){return($.client??this.client).post({url:"/agent-sessions/by-pull-requests",...$,headers:{"Content-Type":"application/json",...$.headers}})}previewAgentSessions($){return($.client??this.client).post({url:"/agent-sessions/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}warmAgentSessionHandler($){return($.client??this.client).post({url:"/agent-sessions/warm",...$,headers:{"Content-Type":"application/json",...$.headers}})}deleteAgentSession($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}",...$})}getAgentSession($){return($.client??this.client).get({url:"/agent-sessions/{session_id}",...$})}setAgentSessionArchived($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/archived",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionChanges($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/changes",...$})}getAgentSessionChangesPatch($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/changes/patch",...$})}refreshAgentSessionChanges($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/changes/refresh",...$})}getCodeExecution($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/code-executions/{execution_id}",...$})}listExecutionReviews($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/code-executions/{execution_id}/reviews",...$})}controlAgentSession($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/control",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionLog($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/log",...$})}getAgentSessionFoldedLog($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/log/folded",...$})}renameAgentSession($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/name",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionPermissions($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/permissions",...$})}updateAgentSessionPermissions($){return($.client??this.client).patch({url:"/agent-sessions/{session_id}/permissions",...$,headers:{"Content-Type":"application/json",...$.headers}})}unlinkAgentSessionPullRequest($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}/pull-requests",...$})}listAgentSessionPullRequests($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/pull-requests",...$})}linkAgentSessionPullRequest($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/pull-requests",...$,headers:{"Content-Type":"application/json",...$.headers}})}getAgentSessionQueue($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/queue",...$})}removeQueuedAction($){return($.client??this.client).delete({url:"/agent-sessions/{session_id}/queue/{action_id}",...$})}editQueuedAction($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/queue/{action_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}steerQueuedAction($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/queue/{action_id}/steer",...$})}createSessionReview($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/reviews",...$,headers:{"Content-Type":"application/json",...$.headers}})}getSessionReview($){return($.client??this.client).get({url:"/agent-sessions/{session_id}/reviews/{review_id}",...$})}decideSessionReview($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/reviews/{review_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}putAgentSessionSandboxSize($){return($.client??this.client).put({url:"/agent-sessions/{session_id}/sandbox-size",...$,headers:{"Content-Type":"application/json",...$.headers}})}answerAgentSessionToolApproval($){return($.client??this.client).post({url:"/agent-sessions/{session_id}/tool-approvals/{approval_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}disconnect($){return($.client??this.client).delete({security:[{scheme:"bearer",type:"http"}],url:"/claude-auth",...$,headers:{"Content-Type":"application/json",...$.headers}})}status($){return($?.client??this.client).get({security:[{scheme:"bearer",type:"http"}],url:"/claude-auth",...$})}complete($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/claude-auth/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}start($){return($.client??this.client).post({security:[{scheme:"bearer",type:"http"}],url:"/claude-auth/start",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function t1({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:G,url:L,...Y}){let Q,T=G??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,I=Y.signal??new AbortController().signal;while(!0){if(I.aborted)break;B++;let P=Y.headers instanceof Headers?Y.headers:new Headers(Y.headers);if(Q!==void 0)P.set("Last-Event-ID",Q);try{let D={redirect:"follow",...Y,body:Y.serializedBody,headers:P,signal:I},C=new Request(L,D);if($)C=await $(L,D);let N=await(Y.fetch??globalThis.fetch)(C);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let H=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",k=()=>{try{H.cancel()}catch{}};I.addEventListener("abort",k);try{while(!0){let{done:d,value:l}=await H.read();if(d)break;U+=l,U=U.replace(/\r\n?/g,`
`);let g=U.split(`
`);U=g.pop()??"";for(let r of g){let p=r.split(`
diff --git a/crates/folds/agent_fold/AGENTS.md b/crates/folds/agent_fold/AGENTS.md
index de184ebc4a..c2570b1dac 100644
--- a/crates/folds/agent_fold/AGENTS.md
+++ b/crates/folds/agent_fold/AGENTS.md
@@ -56,7 +56,9 @@ to the browser via `inbound/wasm`.
- `cargo test -p agent_fold`.
- After changing `inbound/wire.rs` or exported `domain/model.rs` types:
`cargo run -p agent_fold --bin export_types` and commit the regenerated
- TypeScript.
+ TypeScript: the web client's copy and the SDK's
+ `packages/sdk/generated/agent-fold/`, which types
+ `AgentSession.foldedLog()`.
## Gotchas
diff --git a/crates/folds/agent_fold/src/bin/export_types.rs b/crates/folds/agent_fold/src/bin/export_types.rs
index 4f4552ee3f..3fb6789ab8 100644
--- a/crates/folds/agent_fold/src/bin/export_types.rs
+++ b/crates/folds/agent_fold/src/bin/export_types.rs
@@ -18,15 +18,25 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
.register::<FoldedMessage>()
.register::<FoldedStreamEvent>()
.register::<SessionMetadata>();
- let output = Path::new(env!("CARGO_MANIFEST_DIR"))
- .join("../../../apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts");
-
let generated = Typescript::default().export(&types, specta_serde::Format)?;
let generated = generated
.lines()
.map(str::trim_end)
.collect::<Vec<_>>()
.join("\n");
- fs::write(output, format!("{generated}\n"))?;
+
+ // The web client folds in the browser; the SDK reads the same messages
+ // folded by `GET /agent-sessions/{id}/log/folded`.
+ let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../..");
+ for output in [
+ "apps/web/src/lib/service-clients/service-agent-fold/generated/types.ts",
+ "packages/sdk/generated/agent-fold/index.ts",
+ ] {
+ let output = root.join(output);
+ if let Some(parent) = output.parent() {
+ fs::create_dir_all(parent)?;
+ }
+ fs::write(output, format!("{generated}\n"))?;
+ }
Ok(())
}
diff --git a/crates/folds/agent_fold/src/inbound/mod.rs b/crates/folds/agent_fold/src/inbound/mod.rs
index dab9868146..e3fea16112 100644
--- a/crates/folds/agent_fold/src/inbound/mod.rs
+++ b/crates/folds/agent_fold/src/inbound/mod.rs
@@ -1,10 +1,10 @@
//! Adapters that drive the fold from outside.
//!
-//! There are two: [`wire`], the browser-specific envelopes around the domain
-//! vocabulary, and [`wasm`], the wasm-bindgen glue that carries them there. Services do not need an
-//! adapter - they call [`crate::domain::ports::FoldedMessageRepo`] directly -
-//! and the HTTP surface that used to fold on their behalf is gone, because
-//! the client folds for itself now.
+//! There are two: [`wire`], the envelopes around the domain vocabulary that
+//! readers receive, and [`wasm`], the wasm-bindgen glue that carries them to
+//! the browser. Services call [`crate::domain::ports::FoldedMessageRepo`]
+//! directly. The web client folds for itself; `agent_session` serves the same
+//! [`wire`] messages over HTTP for readers that do not, such as the SDK.
/// Browser-specific wire envelopes, kept apart from the wasm-bindgen glue so
/// a native binary can derive TypeScript from them. See the module docs.
diff --git a/crates/folds/agent_fold/src/inbound/wire.rs b/crates/folds/agent_fold/src/inbound/wire.rs
index 32eeb22c37..171fb6cadb 100644
--- a/crates/folds/agent_fold/src/inbound/wire.rs
+++ b/crates/folds/agent_fold/src/inbound/wire.rs
@@ -1,4 +1,4 @@
-//! The browser-facing envelopes around the serializable domain vocabulary.
+//! The reader-facing envelopes around the serializable domain vocabulary.
//!
//! The renderable message, tool, permission, and metadata types live in
//! [`crate::domain::model`] and define their wire representation directly.
@@ -20,7 +20,7 @@ use specta::Type;
#[cfg(test)]
mod test;
-/// One renderable message, scoped to its agent session for the browser.
+/// One renderable message, scoped to its agent session for its reader.
#[derive(Serialize, Type)]
#[serde(rename_all = "camelCase")]
pub struct FoldedMessage {
diff --git a/packages/code-mode-sdk/scripts/catalog.ts b/packages/code-mode-sdk/scripts/catalog.ts
index 0780793d55..441b22b8f4 100644
--- a/packages/code-mode-sdk/scripts/catalog.ts
+++ b/packages/code-mode-sdk/scripts/catalog.ts
@@ -1,7 +1,7 @@
/** Short capability labels; API signatures and contracts are generated by TypeDoc. */
export const descriptions: Record<string, string> = {
'agent-sessions':
- 'Create and inspect agent sessions, saved code executions, and editable email or calendar review stacks.',
+ "Create and inspect agent sessions, read any viewable session's history as folded messages (`session.foldedLog()`), saved code executions, and editable email or calendar review stacks.",
agents: 'Configure agents, pair hosts and inspect their sessions.',
'api-keys': 'Create, list and revoke user API keys.',
'entity-mentions': 'Create and delete typed resource mention relationships.',
diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/README.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/README.md
index 721d35b63b..aa3e5a3020 100644
--- a/packages/sdk-docs/reference/generated/agent-harness/types.gen/README.md
+++ b/packages/sdk-docs/reference/generated/agent-harness/types.gen/README.md
@@ -22,6 +22,7 @@
- [AgentRespondElicitationAction](type-aliases/AgentRespondElicitationAction.md)
- [AgentSessionChangesPatchResponse](type-aliases/AgentSessionChangesPatchResponse.md)
- [AgentSessionChangesResponse](type-aliases/AgentSessionChangesResponse.md)
+- [AgentSessionFoldedLogResponse](type-aliases/AgentSessionFoldedLogResponse.md)
- [AgentSessionLogEntryDto](type-aliases/AgentSessionLogEntryDto.md)
- [AgentSessionLogResponse](type-aliases/AgentSessionLogResponse.md)
- [AgentSessionPreviewData](type-aliases/AgentSessionPreviewData.md)
@@ -143,6 +144,11 @@
- [GetAgentSessionData](type-aliases/GetAgentSessionData.md)
- [GetAgentSessionError](type-aliases/GetAgentSessionError.md)
- [GetAgentSessionErrors](type-aliases/GetAgentSessionErrors.md)
+- [GetAgentSessionFoldedLogData](type-aliases/GetAgentSessionFoldedLogData.md)
+- [GetAgentSessionFoldedLogError](type-aliases/GetAgentSessionFoldedLogError.md)
+- [GetAgentSessionFoldedLogErrors](type-aliases/GetAgentSessionFoldedLogErrors.md)
+- [GetAgentSessionFoldedLogResponse](type-aliases/GetAgentSessionFoldedLogResponse.md)
+- [GetAgentSessionFoldedLogResponses](type-aliases/GetAgentSessionFoldedLogResponses.md)
- [GetAgentSessionLogData](type-aliases/GetAgentSessionLogData.md)
- [GetAgentSessionLogError](type-aliases/GetAgentSessionLogError.md)
- [GetAgentSessionLogErrors](type-aliases/GetAgentSessionLogErrors.md)
diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/AgentSessionFoldedLogResponse.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/AgentSessionFoldedLogResponse.md
new file mode 100644
index 0000000000..f8b2b31aa0
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/AgentSessionFoldedLogResponse.md
@@ -0,0 +1,12 @@
+# Type Alias: AgentSessionFoldedLogResponse
+
+> **AgentSessionFoldedLogResponse** = \{ `bot`: [`SessionBot`](SessionBot.md); `messages`: \{\[`key`: `string`\]: `unknown`; \}[]; \}
+
+Response body for one session's folded log.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-bot"></a> `bot` | [`SessionBot`](SessionBot.md) | The agent whose messages these are; it sent every agent message. |
+| <a id="property-messages"></a> `messages` | \{\[`key`: `string`\]: `unknown`; \}[] | The conversation, oldest first: prompts, replies, tool calls and their results, plans, permission requests and how each turn ended. Each element is a `FoldedMessage` from the fold's TypeScript contract, which the SDK exports; the schema is opaque here because those types are described with specta rather than utoipa. |
diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/GetAgentSessionFoldedLogData.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/GetAgentSessionFoldedLogData.md
new file mode 100644
index 0000000000..16a3bb0225
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/GetAgentSessionFoldedLogData.md
@@ -0,0 +1,13 @@
+# Type Alias: GetAgentSessionFoldedLogData
+
+> **GetAgentSessionFoldedLogData** = \{ `body?`: `never`; `path`: \{ `session_id`: `string`; \}; `query?`: `never`; `url`: `"/agent-sessions/{session_id}/log/folded"`; \}
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-body"></a> `body?` | `never` | - |
+| <a id="property-path"></a> `path` | \{ `session_id`: `string`; \} | - |
+| `path.session_id` | `string` | ID of the agent session |
+| <a id="property-query"></a> `query?` | `never` | - |
+| <a id="property-url"></a> `url` | `"/agent-sessions/{session_id}/log/folded"` | - |
diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/GetAgentSessionFoldedLogError.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/GetAgentSessionFoldedLogError.md
new file mode 100644
index 0000000000..f49eb50e6c
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/GetAgentSessionFoldedLogError.md
@@ -0,0 +1,3 @@
+# Type Alias: GetAgentSessionFoldedLogError
+
+> **GetAgentSessionFoldedLogError** = [`GetAgentSessionFoldedLogErrors`](GetAgentSessionFoldedLogErrors.md)\[keyof [`GetAgentSessionFoldedLogErrors`](GetAgentSessionFoldedLogErrors.md)\]
diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/GetAgentSessionFoldedLogErrors.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/GetAgentSessionFoldedLogErrors.md
new file mode 100644
index 0000000000..6258c859d9
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/GetAgentSessionFoldedLogErrors.md
@@ -0,0 +1,11 @@
+# Type Alias: GetAgentSessionFoldedLogErrors
+
+> **GetAgentSessionFoldedLogErrors** = \{ `401`: `string`; `403`: `string`; `500`: `string`; \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-401"></a> `401` | `string` |
+| <a id="property-403"></a> `403` | `string` |
+| <a id="property-500"></a> `500` | `string` |
diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/GetAgentSessionFoldedLogResponse.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/GetAgentSessionFoldedLogResponse.md
new file mode 100644
index 0000000000..57b880e9d6
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/GetAgentSessionFoldedLogResponse.md
@@ -0,0 +1,3 @@
+# Type Alias: GetAgentSessionFoldedLogResponse
+
+> **GetAgentSessionFoldedLogResponse** = [`GetAgentSessionFoldedLogResponses`](GetAgentSessionFoldedLogResponses.md)\[keyof [`GetAgentSessionFoldedLogResponses`](GetAgentSessionFoldedLogResponses.md)\]
diff --git a/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/GetAgentSessionFoldedLogResponses.md b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/GetAgentSessionFoldedLogResponses.md
new file mode 100644
index 0000000000..3f683f884b
--- /dev/null
+++ b/packages/sdk-docs/reference/generated/agent-harness/types.gen/type-aliases/GetAgentSessionFoldedLogResponses.md
@@ -0,0 +1,9 @@
+# Type Alias: GetAgentSessionFoldedLogResponses
+
+> **GetAgentSessionFoldedLogResponses** = \{ `200`: [`AgentSessionFoldedLogResponse`](AgentSessionFoldedLogResponse.md); \}
+
+## Properties
+
+| Property | Type |
+| ------ | ------ |
+| <a id="property-200"></a> `200` | [`AgentSessionFoldedLogResponse`](AgentSessionFoldedLogResponse.md) |
diff --git a/packages/sdk-docs/reference/src/entities/agent-sessions/agent-session/README.md b/packages/sdk-docs/reference/src/entities/agent-sessions/agent-session/README.md
index 758ad927ab..6f453bd98e 100644
--- a/packages/sdk-docs/reference/src/entities/agent-sessions/agent-session/README.md
+++ b/packages/sdk-docs/reference/src/entities/agent-sessions/agent-session/README.md
@@ -7,5 +7,6 @@
## Type Aliases
- [CreateManagedSessionOptions](type-aliases/CreateManagedSessionOptions.md)
+- [FoldedAgentSessionLog](type-aliases/FoldedAgentSessionLog.md)
- [SelectableRepository](type-aliases/SelectableRepository.md)
- [SessionPullRequest](type-aliases/SessionPullRequest.md)
diff --git a/packages/sdk-docs/reference/src/entities/agent-sessions/agent-session/classes/AgentSession.md b/packages/sdk-docs/reference/src/entities/agent-sessions/agent-session/classes/AgentSession.md
index 748a38aee1..2fcdbaa8b1 100644
--- a/packages/sdk-docs/reference/src/entities/agent-sessions/agent-session/classes/AgentSession.md
+++ b/packages/sdk-docs/reference/src/entities/agent-sessions/agent-session/classes/AgentSession.md
@@ -102,6 +102,23 @@ Delete this session and any live resources it owns.
***
+### foldedLog()
+
+> **foldedLog**(): `Promise`\<[`FoldedAgentSessionLog`](../type-aliases/FoldedAgentSessionLog.md)\>
+
+Read this session's whole history as the conversation the app renders:
+each user prompt and agent reply, oldest first, with tool calls and their
+results, plans, permission requests and how each turn ended. Works on any
+session the caller can view, live or finished, so it is the way to read
+what another agent session did. Prefer it to [log](#log), which returns
+raw protocol frames.
+
+#### Returns
+
+`Promise`\<[`FoldedAgentSessionLog`](../type-aliases/FoldedAgentSessionLog.md)\>
+
+***
+
### linkPullRequest()
> **linkPullRequest**(`url`): `Promise`\<`void`\>
diff --git a/packages/sdk-docs/reference/src/entities/agent-sessions/agent-session/type-aliases/FoldedAgentSessionLog.md b/packages/sdk-docs/reference/src/entities/agent-sessions/agent-session/type-aliases/FoldedAgentSessionLog.md
new file mode 100644
index 0000000000..ca58a46d45
--- /dev/null
+++ b/packages/sdk-docs/reference/src/entities/agent-sessions/agent-session/type-aliases/FoldedAgentSessionLog.md
@@ -0,0 +1,12 @@
+# Type Alias: FoldedAgentSessionLog
+
+> **FoldedAgentSessionLog** = \{ `bot`: [`SessionBot`](../../../../../generated/agent-harness/types.gen/type-aliases/SessionBot.md); `messages`: `FoldedMessage`[]; \}
+
+A session's history folded into readable messages, oldest first.
+
+## Properties
+
+| Property | Type | Description |
+| ------ | ------ | ------ |
+| <a id="property-bot"></a> `bot` | [`SessionBot`](../../../../../generated/agent-harness/types.gen/type-aliases/SessionBot.md) | The agent that sent every agent message. |
+| <a id="property-messages"></a> `messages` | `FoldedMessage`[] | Prompts and replies with their tool calls, results, plans, permission requests and how each turn ended. |
diff --git a/packages/sdk-docs/reference/src/macro/README.md b/packages/sdk-docs/reference/src/macro/README.md
index 04809c6f1a..0166f6a7dd 100644
--- a/packages/sdk-docs/reference/src/macro/README.md
+++ b/packages/sdk-docs/reference/src/macro/README.md
@@ -214,6 +214,12 @@ Re-exports [EntityReference](../entities/reference/type-aliases/EntityReference.
***
+### FoldedAgentSessionLog
+
+Re-exports [FoldedAgentSessionLog](../entities/agent-sessions/agent-session/type-aliases/FoldedAgentSessionLog.md)
+
+***
+
### Form
Re-exports [Form](../entities/forms/form/classes/Form.md)
diff --git a/packages/sdk/AGENTS.md b/packages/sdk/AGENTS.md
index 397b1c48d8..f12807e50f 100644
--- a/packages/sdk/AGENTS.md
+++ b/packages/sdk/AGENTS.md
@@ -36,6 +36,8 @@ excluded from source linting.
- Regenerate Rust OpenAPI and web service clients before `bun run sync-specs &&
bun run generate`; do not copy deployed schemas over a local API change.
+- `generated/agent-fold/` is not from OpenAPI: `cargo run -p agent_fold --bin
+ export_types` writes it, and `foldedLog()` casts the opaque wire schema to it.
- Workspace advanced filters use the server's serialized AST names, not Rust
enum variant names. Validate new filter examples against the real local API.
- Async iterators are lazy; `limit` is page size. Preserve filters on every page
diff --git a/packages/sdk/generated/agent-fold/index.ts b/packages/sdk/generated/agent-fold/index.ts
new file mode 100644
index 0000000000..b3ce791fc8
--- /dev/null
+++ b/packages/sdk/generated/agent-fold/index.ts
@@ -0,0 +1,1383 @@
+// This file has been generated by Specta. Do not edit this file manually.
+/** One step of work, worded for a person reading a conversation. */
+export type ActivityRow = {
+ /** The tool call's id, stable across updates; `plan` for a plan update. */
+ id: string,
+ /** What happened, as a verb phrase: `Ran`, `Reading`, `Search documents`. */
+ label: string,
+ /**
+ * What it happened to - a command, a file, a query - when that is safe
+ * to show to everyone who can read the conversation.
+ */
+ detail: string | null,
+ /** Where it got to. */
+ status: ActivityStatus,
+};
+
+/** Where one step of work got to. */
+export type ActivityStatus =
+/** Started and not finished, including a call waiting on permission. */
+"running" |
+/** Finished successfully. */
+"completed" |
+/** Finished unsuccessfully. */
+"failed" |
+/** Still running when its turn ended: nobody knows whether it finished. */
+"interrupted";
+
+/**
+ * The JSON-RPC id of a request the agent made, as the agent wrote it.
+ *
+ * Kept in the agent's own shape - a number stays a number - because an
+ * answer has to echo it exactly; `"7"` does not answer `7`.
+ */
+export type AgentRequestId =
+/**
+ * A numeric id. Exported as a plain TypeScript number: agents count
+ * requests from zero, nowhere near where an `i64` stops round-tripping.
+ */
+number |
+/** A string id. */
+string;
+
+/**
+ * Terminal output with ANSI escape sequences left in place.
+ *
+ * Stripping here would be lossy and irreversible, and the escapes carry real
+ * information - the recordings are full of colorized `ls` and `grep` output.
+ * Rendering decides whether to interpret, strip, or ignore them.
+ */
+export type AnsiText = string;
+
+/**
+ * A chosen option, with the title it was offered under when the schema gave
+ * one. `title` is `None` for a value no option declared.
+ */
+export type AnsweredChoice = {
+ /** The value submitted. */
+ value: string,
+ /** The label it was offered under. */
+ title: string | null,
+};
+
+/**
+ * One property's answer, resolved against the schema that asked for it.
+ *
+ * The correlation happens here so that no client repeats it: an option's
+ * title is looked up where the options live, and the harness "Other" idiom -
+ * a free-text answer arriving under a *different* key than the property it
+ * replaces, sometimes alongside the choice it replaces (see the
+ * `elicitation_claude_single_select` fixture, which carries both) - collapses
+ * to a single [`AnsweredValue::Custom`].
+ */
+export type AnsweredField = {
+ /**
+ * The property this answers, or the key it arrived under when no
+ * property claimed it.
+ */
+ name: string,
+ /** What to show as the label: the property's title, else its name. */
+ label: string,
+ /** The answer. */
+ value: AnsweredValue,
+};
+
+/** An answer's value, in the vocabulary the property declared. */
+export type AnsweredValue =
+/** Free text. */
+{ kind: "text";
+/** The text as submitted. */
+text: string } |
+/**
+ * A number, whole or not, exactly as it was submitted.
+ *
+ * Text rather than `f64`: a JSON integer can outrun `f64`'s exact range,
+ * and `f64` has a `number | null` TypeScript face because a non-finite
+ * float serializes as null. Nothing computes with an answer - it is
+ * rendered - so the digits are what matter.
+ */
+{ kind: "number";
+/** The number as written. */
+text: string } |
+/** A yes/no. */
+{ kind: "boolean";
+/** Whether it was checked. */
+checked: boolean } |
+/** One of the offered options. */
+{ kind: "choice";
+/** The option chosen, with the title it was offered under. */
+choice: AnsweredChoice } |
+/** Several of the offered options. */
+{ kind: "choices";
+/** The options chosen, in the order they were submitted. */
+choices: AnsweredChoice[] } |
+/**
+ * The free-text escape: the user typed their own answer instead of
+ * picking, and it arrived under the property's `customField`.
+ */
+{ kind: "custom";
+/** What they typed. */
+text: string } |
+/**
+ * A value this fold could not read as any of the above - a nested
+ * object, or an array of something other than strings.
+ */
+{ kind: "unrecognized";
+/** The value, verbatim. */
+raw: unknown };
+
+/** Who produced a [`FoldedMessage`]. */
+export type Author =
+/**
+ * A person, via `session/prompt`.
+ *
+ * The id comes from the log row rather than the ACP payload, and is
+ * absent when the prompt was not attributed to a user.
+ */
+{ kind: "user";
+/** The attributed user's id. */
+userId: string | null } |
+/** The agent. */
+{ kind: "agent" };
+
+/**
+ * One slash command the harness advertises.
+ *
+ * Mirrors ACP's `AvailableCommand`, flattened: the only input shape ACP
+ * defines today is "unstructured text after the name," so the hint is
+ * carried directly rather than through a nested enum.
+ */
+export type AvailableCommand = {
+ /**
+ * Bare name as advertised (`"qc"`, `"honeycomb:query-patterns"`) - no
+ * leading slash, which is client syntax rather than part of the name.
+ */
+ name: string,
+ /** Human-readable description, verbatim from the harness. */
+ description: string,
+ /** Placeholder text for the command's input, when it takes any. */
+ inputHint: string | null,
+};
+
+/** A session control operation shown in the conversation timeline. */
+export type Control =
+/** The runtime was asked to switch models. */
+{ kind: "set_model";
+/** The model slug requested by the caller. */
+model: string } |
+/** The runtime was asked to change an advertised session setting. */
+{ kind: "set_config_option";
+/** Opaque config id supplied by the runtime. */
+config_id: string;
+/** Opaque select value requested by the caller. */
+value: string } |
+/** The runtime was asked to compact its context. */
+{ kind: "compact" } |
+/** The runtime was asked to stop its current work. */
+{ kind: "stop" };
+
+/**
+ * How the runtime disposed of a [`Control`], like [`PermissionOutcome`] for
+ * permission requests. Pending is a legitimate final state: a control the
+ * session died before answering stays pending.
+ */
+export type ControlOutcome =
+/** No response yet. */
+{ kind: "pending" } |
+/** Acknowledged - immediately so for a stop, which nothing can answer. */
+{ kind: "accepted" } |
+/** Answered with a JSON-RPC error. */
+{ kind: "rejected";
+/** The error's message, verbatim. */
+message: string };
+
+/** One choice in a select. */
+export type ElicitationOption = {
+ /** The value sent back when chosen. */
+ value: string,
+ /**
+ * Label to show; absent for an untitled `enum`, where the value is the
+ * label.
+ */
+ title: string | null,
+ /** Help text, when the agent gave one. */
+ description: string | null,
+};
+
+/**
+ * How an elicitation has resolved so far.
+ *
+ * [`Self::Pending`] is a legitimate final state on a dead session, like an
+ * unanswered permission.
+ */
+export type ElicitationOutcome =
+/** No response has gone out yet. */
+{ kind: "pending" } |
+/** The user submitted the form, or consented to open the URL. */
+{ kind: "accepted";
+/**
+ * What they answered: one entry per property the schema declared and
+ * the content answered, in declaration order, then any key no
+ * property claimed. Empty for a URL consent, which carries no
+ * content.
+ */
+answers: AnsweredField[] } |
+/** The user explicitly said no. */
+{ kind: "declined" } |
+/** The user dismissed it, or a stop cancelled it. */
+{ kind: "cancelled" } |
+/** URL only: the agent reported the external interaction finished. */
+{ kind: "completed" } |
+/**
+ * The response was a JSON-RPC error - including this client's own
+ * refusal of a request it could not hold.
+ */
+{ kind: "errored";
+/** The error's message, verbatim. */
+message: string } |
+/** A result arrived that this fold could not read as an ACP action. */
+{ kind: "unrecognized" };
+
+/** One form field. */
+export type ElicitationProperty = {
+ /** The key the answer is sent back under. */
+ name: string,
+ /** Label to show, when the agent gave one. */
+ title: string | null,
+ /** Help text, when the agent gave one. */
+ description: string | null,
+ /** The field's type and constraints. */
+ schema: ElicitationPropertySchema,
+};
+
+/**
+ * A field's type and constraints, mirroring ACP's restricted property
+ * schemas.
+ */
+export type ElicitationPropertySchema =
+/** Free text, or a single choice when `options` is non-empty. */
+{ type: "string";
+/** Minimum length, when constrained. */
+minLength: number | null;
+/** Maximum length, when constrained. */
+maxLength: number | null;
+/**
+ * A regular expression the value must match. Agent-supplied, so a
+ * renderer must bound its evaluation.
+ */
+pattern: string | null;
+/**
+ * ACP's format hint as its wire string (`email`, `uri`, `date`,
+ * `date-time`, or something this fold does not know).
+ */
+format: string | null;
+/** Pre-filled value. */
+default: string | null;
+/** The choices, when this is a single select. Empty for free text. */
+options: ElicitationOption[];
+/**
+ * The key a free-text answer is sent under when one is accepted
+ * alongside `options` - the user picks a choice *or* types their
+ * own. A harness idiom (Claude Code's and Codex's "Other" field),
+ * never ACP's own; `None` for a plain select.
+ */
+customField: string | null } |
+/** A floating-point number. */
+{ type: "number";
+/** Lower bound, when constrained. */
+minimum: number | null;
+/** Upper bound, when constrained. */
+maximum: number | null;
+/** Pre-filled value. */
+default: number | null } |
+/** A whole number. */
+{ type: "integer";
+/** Lower bound, when constrained. */
+minimum: number | null;
+/** Upper bound, when constrained. */
+maximum: number | null;
+/** Pre-filled value. */
+default: number | null } |
+/** A yes/no. */
+{ type: "boolean";
+/** Pre-filled value. */
+default: boolean | null } |
+/** Several choices from a list. */
+{ type: "multi_select";
+/** Fewest selections allowed, when constrained. */
+minItems: number | null;
+/** Most selections allowed, when constrained. */
+maxItems: number | null;
+/** The choices. */
+options: ElicitationOption[];
+/** Pre-selected values. */
+default: string[];
+/**
+ * The key a free-text answer is sent under when one is accepted
+ * instead of the choices. Harness idiom, `None` for a plain
+ * multi-select. See the `String` variant.
+ */
+customField: string | null } |
+/**
+ * A property type this fold does not know. A renderer shows that it
+ * cannot display the field; decline and cancel still work.
+ */
+{ type: "unrecognized";
+/** The wire `type`. */
+typeName: string;
+/** The property schema, verbatim. */
+raw: unknown };
+
+/** What the agent asked for. */
+export type ElicitationRequest =
+/** Structured data through a form the client renders. */
+{ kind: "form";
+/** The restricted schema describing the form. */
+schema: ElicitationSchema } |
+/** An out-of-band interaction the user consents to open. */
+{ kind: "url";
+/**
+ * The agent's handle for this interaction; `elicitation/complete`
+ * names it.
+ */
+elicitationId: string;
+/** Where the user is sent. */
+url: string } |
+/**
+ * A Macro user tool (`SendEmail`, `CreateCalendarEvent`) paused for the
+ * user's review: the agent drafted the call and asks before it runs.
+ *
+ * Recognized from the call the form is scoped to - a tool this fold
+ * already knows as a user tool - or from `_meta.macro.userTool`, which
+ * Macro's own agent stamps. The draft is the call's arguments whole,
+ * so a client with the tool's own composer renders that and answers
+ * with the whole edited draft; `schema` is the flat form the agent also
+ * sent, for a client without one.
+ */
+{ kind: "user_tool";
+/** The tool, by Macro's name. */
+tool: string;
+/** The call's arguments - the tool's own JSON. */
+draft: unknown;
+/** The restricted form describing the draft's flat fields. */
+schema: ElicitationSchema } |
+/**
+ * A mode this fold does not know. Kept raw so nothing is lost; a
+ * renderer must not treat it as form or url.
+ */
+{ kind: "unrecognized";
+/** The wire mode. */
+mode: string;
+/** The request params, verbatim. */
+raw: unknown };
+
+/**
+ * The JSON-RPC id of an agent's `elicitation/create` request, carried whole
+ * so the answer echoes exactly what the agent sent.
+ *
+ * Agents pick these, not us: Claude Code counts from `0`, others use
+ * strings. `null` is not a legal id for a request that expects a response,
+ * so it is not representable here.
+ */
+export type ElicitationRequestId =
+/**
+ * A numeric JSON-RPC id. Specta refuses `i64` (it does not fit a JS
+ * number); agents count their requests from zero, so `i32` is the
+ * honest TypeScript face.
+ */
+number |
+/** A string JSON-RPC id. */
+string;
+
+/** ACP's restricted form schema: a flat object of primitive properties. */
+export type ElicitationSchema = {
+ /** Schema-level title, when the agent gave one. */
+ title: string | null,
+ /** Schema-level description, when the agent gave one. */
+ description: string | null,
+ /** The fields, in the order the agent declared them. */
+ properties: ElicitationProperty[],
+ /** Property names the agent requires an answer for. */
+ required: string[],
+};
+
+/** An external page where the person can act on a [`FailureNotice`]. */
+export type FailureLink = {
+ /** The link's text, e.g. `Manage Cursor usage`. */
+ label: string,
+ /** The page, absolute. */
+ url: string,
+};
+
+/**
+ * A turn failure the person who prompted can act on, in their terms.
+ *
+ * A runtime attaches this to the `session/prompt` error as its `data`; the
+ * fold reads it back onto the failed turn's stop reason. It exists so a
+ * billing wall or a disconnected integration renders as an instruction with
+ * somewhere to go, not as the runtime's error text - and so the runtime's
+ * error text, which for a report includes source locations, never has to
+ * double as the thing a person reads.
+ */
+export type FailureNotice = {
+ /** Which class of failure, for readers that treat one specially. */
+ kind: FailureNoticeKind,
+ /** One short line naming what happened. */
+ title: string,
+ /** What it means and what to do, in plain language. */
+ body: string,
+ /** Where acting on it happens, when that is somewhere else. */
+ link?: FailureLink | null,
+};
+
+/** The classes of actionable failure a runtime can report. */
+export type FailureNoticeKind =
+/**
+ * The person's own account with the provider has no budget left for
+ * this work; the fix is on the provider's billing page.
+ */
+"provider_usage_limit" |
+/** The selected model cannot read image attachments in this conversation. */
+"unsupported_image_input";
+
+/** A file modification a tool reported. */
+export type FileDiff = {
+ /** The file that changed. */
+ path: string,
+ /** Prior contents, absent when the file is new. */
+ oldText: string | null,
+ /** New contents. */
+ newText: string,
+};
+
+/** One renderable message, scoped to its agent session for its reader. */
+export type FoldedMessage = {
+ /** Session that scopes this message id. */
+ agentSessionId: string,
+ /** The turn within the session, assigned in log order from zero. */
+ turn: number,
+ /** Who produced the message. */
+ author: Author,
+ /**
+ * The id the control endpoint returned for the action that derived this
+ * message, for correlation. Absent on agent messages and on frames the
+ * control plane did not mint.
+ */
+ requestId: string | null,
+ /** Ordered renderable content. Never empty. */
+ parts: MessagePart[],
+ /** How the turn ended, absent while it remains in flight. */
+ stop: StopReason | null,
+ /**
+ * Derived from an action this client issued that the log has not yet
+ * confirmed. A reader shows it as sending; it flips off in place when
+ * the confirmed frame arrives.
+ */
+ pending: boolean,
+ /**
+ * How an agent's reply reads as a conversation, the same boundaries the
+ * server posts channel messages by. Empty on a user's message.
+ */
+ segments: Segment[],
+ /**
+ * What an agent's unfinished reply is doing now; absent once its turn
+ * has ended and on a user's message.
+ */
+ phase: TurnPhase | null,
+ /**
+ * When a user's prompt was posted, RFC 3339. Absent on agent and control
+ * messages, until the log confirms a prompt, and on history a runtime
+ * replayed on load.
+ */
+ postedAt: string | null,
+};
+
+/**
+ * One change a pushed frame implied.
+ *
+ * Payloads are carried whole rather than as deltas: a reader replaces the
+ * message under the same session, turn, and author, or replaces its metadata
+ * outright.
+ */
+export type FoldedStreamEvent =
+/** A message derived for the first time. */
+{ kind: "new";
+/** The message as it now stands. */
+message: FoldedMessage } |
+/** A previously reported message, changed. */
+{ kind: "update";
+/** The message as it now stands. */
+message: FoldedMessage } |
+/** Replace all messages for this session, including removal of old rows. */
+{ kind: "replace";
+/** The complete committed conversation. */
+messages: FoldedMessage[] } |
+/** The session's metadata changed; here it is in full. */
+{ kind: "metadata";
+/** The metadata as it now stands. */
+metadata: SessionMetadata };
+
+/**
+ * Which ACP agent produced a session's log.
+ *
+ * ACP names none of a harness's conventions - which `_meta` keys it writes,
+ * what it calls its tools, how it reports a subagent - so the fold has to
+ * know who it is reading in order to read those. The agent announces itself
+ * in the `initialize` response's `agentInfo.name`; a log that starts
+ * mid-session (a resume) is recognized from the `_meta` namespaces its
+ * first tool frames carry instead. Carried on the metadata so a reader can
+ * show it and never has to infer it.
+ *
+ * [`Self::Unknown`] is a real state, not a failure: every reader falls back
+ * to the harness-neutral conventions, and a harness this fold has not met
+ * still folds to the generic vocabulary.
+ */
+export type Harness =
+/** `@agentclientprotocol/claude-agent-acp`. */
+"claude_code" |
+/** `OpenCode`, whose ACP server is built in. */
+"open_code" |
+/** OpenAI Codex, through `codex-acp`. */
+"codex" |
+/** Cursor cloud agents, through this repository's `cursor_cloud_agents`. */
+"cursor" |
+/** Macro's own in-process agent, `agent_inmem`. */
+"macro" |
+/** Nous Research's Hermes agent. */
+"hermes" |
+/** OpenClaw. */
+"open_claw" |
+/** Not announced, or an agent this fold does not know. */
+"unknown";
+
+/** A unit of renderable content. */
+export type MessagePart =
+/** Prose from the user or the agent. */
+{ kind: "text";
+/** The prose. */
+text: string } |
+/**
+ * A file the user attached to their prompt, by where it can be fetched.
+ *
+ * Read off the prompt's `resource_link` blocks - the only shape this
+ * side sends files in, since bytes never ride the log. Rendering decides
+ * from `mime_type` whether that is a thumbnail or a chip.
+ */
+{ kind: "attachment";
+/** Where the file can be fetched - a static file service URL. */
+uri: string;
+/** Display name, typically the original file name. */
+name: string;
+/** The file's media type, when the sender knew it. */
+mimeType: string | null;
+/**
+ * Size in bytes, when the sender knew it. A double on the wire:
+ * specta refuses 64-bit integers, and no file this renders is
+ * anywhere near the precision limit.
+ */
+size: number | null } |
+/** The agent's reasoning, which a reader may want to hide by default. */
+{ kind: "thought";
+/** The reasoning. */
+text: string } |
+/** A tool the agent invoked. */
+{ kind: "tool_use";
+/** The ACP `toolCallId`. */
+id: ToolUseId;
+/** What the harness called the tool. */
+name: ToolName;
+/** Where the call got to. */
+status: ToolStatus;
+/** What the tool did, as far as the log reveals. */
+detail: ToolDetail } |
+/** The agent asking to proceed. */
+{ kind: "permission";
+/** The agent request id an approval must echo. */
+requestId: AgentRequestId;
+/** The tool call permission was requested for. */
+toolCall: ToolUseId;
+/** The choices offered, in the order ACP listed them. */
+options: PermissionOption[];
+/** How the request has resolved so far. */
+outcome: PermissionOutcome } |
+/**
+ * An MCP tool call the egress proxy is holding, or held, until the
+ * session's owner approved it: made in a turn somebody else prompted.
+ */
+{ kind: "tool_approval";
+/** The approval an answer names. */
+approvalId: string;
+/** `macro`, or the connected app's slug. */
+serverSlug: string;
+/** What a person calls the server the tool is on. */
+serverName: string;
+/** The tool called. */
+toolName: string;
+/** What it was called with. */
+arguments: unknown;
+/** Who prompted the turn; absent for a bot on nobody's behalf. */
+requestedBy: string | null;
+/** Where it stands. */
+status: ToolApprovalStatus;
+/** Who resolved it, when a person did. */
+resolvedBy: string | null;
+/**
+ * Approved for good: the person who asked may make the calls it
+ * covers without the owner being asked again.
+ */
+remembered: boolean } |
+/** A user-issued control operation on the session. */
+{ kind: "control";
+/** The requested operation. */
+control: Control;
+/** How the runtime disposed of it so far. */
+outcome: ControlOutcome } |
+/** The agent's working todo list for the turn. */
+{ kind: "plan";
+/** The tasks, in the order the agent listed them. */
+entries: PlanEntry[] } |
+/**
+ * The agent asking the user a question.
+ *
+ * When the question was asked on behalf of a tool call this fold had
+ * already opened (Claude Code's `AskUserQuestion`), this part *replaces*
+ * that tool's part in place: the question is the call, and rendering
+ * both would show one thing twice.
+ */
+{ kind: "elicitation";
+/**
+ * The agent's `elicitation/create` request id - what an answer must
+ * echo.
+ */
+requestId: ElicitationRequestId;
+/** The tool call the question belongs to, when the agent said. */
+toolCall: ToolUseId | null;
+/** What the agent is asking, in prose. */
+message: string;
+/** The form or URL. */
+request: ElicitationRequest;
+/** How it has resolved so far. */
+outcome: ElicitationOutcome;
+/**
+ * The harness's own reading of the answer, when it reported one
+ * after the response went back (Claude Code echoes the chosen
+ * option through its tool result). Absent otherwise.
+ *
+ * Shaped like [`ElicitationOutcome::Accepted`]'s answers so a reader
+ * renders one vocabulary either way, though a harness keys these by
+ * question prose rather than by property, so each `name` is that
+ * prose rather than a schema property.
+ */
+reported: AnsweredField[] | null;
+/**
+ * For a user tool's review ([`ElicitationRequest::UserTool`]): how
+ * the tool itself ended once the user answered - run with the
+ * reviewed draft, rejected, or failed - read from the absorbed
+ * call's later updates. Absent until the tool reports, and for
+ * every other kind of question.
+ */
+toolOutcome: UserToolOutcome | null };
+
+/** One model the runtime offers. */
+export type ModelOption = {
+ /** The value to send back to select this model. */
+ id: string,
+ /** Human-readable label. */
+ name: string,
+ /** Descriptive copy - pricing, context size, and the like. */
+ description: string | null,
+ /** Image input support, absent when the runtime does not advertise it. */
+ supportsImages?: boolean | null,
+ /**
+ * The heading the runtime listed this model under, when it grouped its
+ * options (ACP's `SessionConfigSelectGroup.name`). `None` for a runtime
+ * that offered a flat list; the flattened order still follows the
+ * runtime's, group by group.
+ */
+ group: string | null,
+};
+
+/**
+ * The one elicitation the user can answer right now, surfaced on
+ * [`SessionMetadata`](super::SessionMetadata) so a reader need not scan the
+ * transcript for it.
+ */
+export type PendingElicitation = {
+ /** The agent's request id; what an answer must name. */
+ requestId: ElicitationRequestId,
+ /** The turn whose agent message holds the matching part. */
+ turn: number,
+ /** The tool call it was asked on behalf of, when any. */
+ toolCall: ToolUseId | null,
+ /** What the agent is asking, in prose. */
+ message: string,
+ /** The form or URL. */
+ request: ElicitationRequest,
+};
+
+/** An answerable request. Each variant retains its own response semantics. */
+export type PendingInteraction =
+/** A choice among the permission options offered by the agent. */
+{
+ kind: "permission",
+} & PendingPermission |
+/** A form, URL consent, or user tool review. */
+{
+ kind: "elicitation",
+} & PendingElicitation |
+/**
+ * An MCP tool call held until the session's owner approves it. Only
+ * the owner may approve or decline; anyone with edit access may cancel.
+ */
+{
+ kind: "tool_approval",
+} & PendingToolApproval;
+
+/** A permission request the current connection can still answer. */
+export type PendingPermission = {
+ /** The agent's request id, preserving numeric and string identities. */
+ requestId: AgentRequestId,
+ /** The turn that asked. */
+ turn: number,
+ /** The tool whose execution needs permission. */
+ toolCall: ToolUseId,
+ /** The options the agent offered. */
+ options: PermissionOption[],
+};
+
+/** A held MCP tool call the owner can still answer. */
+export type PendingToolApproval = {
+ /** The approval an answer names. */
+ approvalId: string,
+ /** The turn the call was made in. */
+ turn: number,
+ /** `macro`, or the connected app's slug. */
+ serverSlug: string,
+ /** What a person calls the server the tool is on. */
+ serverName: string,
+ /** The tool called. */
+ toolName: string,
+ /** Who prompted the turn; absent for a bot on nobody's behalf. */
+ requestedBy: string | null,
+};
+
+/** One choice offered for a permission request. */
+export type PermissionOption = {
+ /** The id to report back when this option is chosen. */
+ id: string,
+ /** Label to show. */
+ name: string,
+ /** What kind of choice this is. */
+ kind: PermissionOptionKind,
+};
+
+/**
+ * What kind of choice a [`PermissionOption`] offers, mirroring ACP's
+ * `PermissionOptionKind`.
+ *
+ * ACP's enum is `#[non_exhaustive]`, but unlike [`StopReason`] there is no
+ * wire string worth preserving for a variant this fold does not model: the
+ * fold only ever sees one of these once the whole permission request has
+ * already deserialized successfully, and a wire value ACP added after this
+ * was written would have failed that deserialize already - so an unmatched
+ * kind here cannot happen in practice, not "happens and is rendered
+ * unlabeled."
+ */
+export type PermissionOptionKind =
+/** Allow this operation only this time. */
+"allow_once" |
+/** Allow this operation and remember the choice. */
+"allow_always" |
+/** Reject this operation only this time. */
+"reject_once" |
+/** Reject this operation and remember the choice. */
+"reject_always";
+
+/**
+ * How a permission request has resolved so far.
+ *
+ * Not just "chosen or not": nothing chosen has more than one cause, and a
+ * reader deciding whether to still show the options needs to tell them
+ * apart. [`Self::Pending`] may still resolve; [`Self::Errored`] and
+ * [`Self::Unrecognized`] have already resolved, just not into anything this
+ * fold can show as a choice.
+ */
+export type PermissionOutcome =
+/** No response has arrived yet - the request is still outstanding. */
+{ kind: "pending" } |
+/** An option was chosen. */
+{ kind: "selected";
+/** The chosen option's id. */
+optionId: string } |
+/** The request was cancelled without a choice. */
+{ kind: "cancelled" } |
+/**
+ * The response was a JSON-RPC error rather than a result: the harness
+ * failed to answer the request rather than resolving it.
+ */
+{ kind: "errored" } |
+/**
+ * A result arrived, but this fold could not make sense of it - a
+ * payload that did not match ACP's response shape, or an outcome ACP
+ * added after this was written.
+ */
+{ kind: "unrecognized" };
+
+/** One task on an agent plan. */
+export type PlanEntry = {
+ /** What this task aims to accomplish. */
+ content: string,
+ /** The task's relative importance. */
+ priority: PlanEntryPriority,
+ /** Where the task got to. */
+ status: PlanEntryStatus,
+};
+
+/**
+ * A [`PlanEntry`]'s relative importance, mirroring ACP's
+ * `PlanEntryPriority`.
+ */
+export type PlanEntryPriority =
+/** Critical to the overall goal. */
+"high" |
+/** Important but not critical. */
+"medium" |
+/** Nice to have but not essential. */
+"low";
+
+/** Where a [`PlanEntry`] got to, mirroring ACP's `PlanEntryStatus`. */
+export type PlanEntryStatus =
+/** Not started yet. */
+"pending" |
+/** Currently being worked on. */
+"in_progress" |
+/** Successfully completed. */
+"completed";
+
+/** A run of a reply's parts that reads as one unit. */
+export type Segment = {
+ /** Position among the reply's segments, from zero. */
+ index: number,
+ /** What the segment is. */
+ kind: SegmentKind,
+ /** Index of the segment's first part. */
+ start: number,
+ /** Index one past the segment's last part. */
+ end: number,
+ /**
+ * Whether the segment can still change: false only for the last segment
+ * of a reply that is still being written.
+ */
+ sealed: boolean,
+ /** The steps, for an activity segment; empty otherwise. */
+ rows: ActivityRow[],
+};
+
+/** What a segment of a reply is. */
+export type SegmentKind =
+/** A passage the agent wrote. */
+"prose" |
+/** A run of tool calls and plan updates. */
+"activity" |
+/** A permission or a question the agent put to the user. */
+"interaction";
+
+/** The supported ACP session-config shapes. */
+export type SessionConfigKind =
+/** A single-value selector. */
+{ type: "select";
+/** The value currently selected by the agent. */
+currentValue: string;
+/** Choices in the order advertised by the agent. */
+options: SessionConfigSelectOption[] } |
+/** An on/off setting. */
+{ type: "boolean";
+/** The value currently selected by the agent. */
+currentValue: boolean };
+
+/** One session setting advertised by an ACP agent. */
+export type SessionConfigOption = {
+ /** Opaque id to return in `session/set_config_option`. */
+ id: string,
+ /** Human-readable label supplied by the agent. */
+ name: string,
+ /** Optional explanatory copy supplied by the agent. */
+ description: string | null,
+ /** ACP semantic category, such as `model` or `thought_level`. */
+ category: string | null,
+} & SessionConfigKind;
+
+/** One value in an ACP select option. */
+export type SessionConfigSelectOption = {
+ /** Opaque value to return in `session/set_config_option`. */
+ value: string,
+ /** Human-readable label supplied by the agent. */
+ name: string,
+ /** Optional explanatory copy supplied by the agent. */
+ description: string | null,
+ /** Optional group heading supplied by the agent. */
+ group: string | null,
+};
+
+/**
+ * Session-level state derived from the log, latest-wins and carried whole.
+ * Fields start absent and fill in as the log reveals them.
+ *
+ * `PartialEq` only: a pending form's numeric bounds are `f64`.
+ */
+export type SessionMetadata = {
+ /** The agent that produced the log. See [`Harness`]. */
+ harness: Harness,
+ /**
+ * Current model per the runtime's own `configOptions` responses, so a
+ * rejected model change never moves it.
+ */
+ model: string | null,
+ /** The models the runtime offers, in the order it listed them. */
+ supportedModels: ModelOption[],
+ /**
+ * Every setting the ACP agent currently advertises. The list is replaced
+ * whole whenever ACP returns a new `configOptions` snapshot.
+ */
+ configOptions: SessionConfigOption[],
+ /** Session title, when the harness reports one. */
+ title: string | null,
+ /**
+ * The slash commands the harness most recently advertised, in the order
+ * it listed them. Empty until the first `available_commands_update`,
+ * which arrives right after session setup, before any turn.
+ */
+ availableCommands: AvailableCommand[],
+ /**
+ * The last system event's wire name (`"acp_ready"`, `"disconnected"`),
+ * `None` until the runtime reports one.
+ */
+ status: string | null,
+ /**
+ * Requests the user can answer on the current turn and connection.
+ * Multiple permissions may coexist with the one allowed elicitation.
+ * History remains in the transcript after these live requests clear.
+ */
+ pendingInteractions: PendingInteraction[],
+ /**
+ * Where the newest turn stands, as one value. Readers used to derive it
+ * from the transcript's tail, the status, and their own record of what
+ * they had posted; this is that derivation done once, in the fold.
+ */
+ turn: TurnState,
+};
+
+/**
+ * Why a turn stopped.
+ *
+ * All but one variant is parsed straight off ACP's `stopReason` wire string
+ * by [`FromStr`]: the `snake_case` variant names are the wire names, and
+ * anything unmodelled falls through to [`Self::Other`], so parsing never
+ * fails. [`Self::Failed`] is the exception - no wire string produces it,
+ * because it is what a turn that got no `stopReason` at all stopped for.
+ */
+export type StopReason =
+/** The agent finished its turn. */
+{ kind: "end_turn" } |
+/** The model hit its token limit. */
+{ kind: "max_tokens" } |
+/** The agent hit its turn-request limit. */
+{ kind: "max_turn_requests" } |
+/** The agent declined. */
+{ kind: "refusal" } |
+/** The turn was cancelled. */
+{ kind: "cancelled" } |
+/** A stop reason this fold does not model, as its wire string. */
+{ kind: "other";
+/** The unrecognized wire value. */
+reason: string } |
+/**
+ * The runtime answered the prompt with a JSON-RPC error, so the turn
+ * produced no reply and never will.
+ *
+ * Constructed by the fold, never parsed: an error response carries no
+ * `stopReason` to read. Modelled as a stop reason rather than as
+ * something alongside one because that is what it is - a turn that
+ * ended - and because every reader already asks `stop` whether a turn
+ * is still running. A turn left with no stop reason reads as forever in
+ * flight, which is how a failed prompt used to wedge a session.
+ */
+{ kind: "failed";
+/** The runtime's error message, verbatim. */
+message: string;
+/**
+ * The failure in the person's terms, when the runtime classified it
+ * as one they can act on. Absent for an opaque failure, which a
+ * reader shows as `message` alone.
+ */
+notice?: FailureNotice | null };
+
+/**
+ * What a subagent reported back, as far as its harness told us.
+ *
+ * Every field is optional because every harness tells us a different
+ * subset: Claude Code reports timings, token counts and a per-tool
+ * breakdown; OpenCode names the child session and its model; Cursor and
+ * Hermes give back little more than the text. A reader shows what is
+ * there.
+ */
+export type SubagentResult = {
+ /** The subagent's answer, as text. */
+ text: string | null,
+ /** Why the subagent failed, when it did. */
+ error: string | null,
+ /**
+ * The harness's id for the subagent or its session, for anyone who
+ * wants to find it again.
+ */
+ agentId: string | null,
+ /** The model the subagent ran on. */
+ model: string | null,
+ /**
+ * Wall-clock time the subagent took. `u32` because the browser
+ * contract forbids 64-bit integers; 49 days of milliseconds is plenty.
+ */
+ durationMs: number | null,
+ /** Tokens the subagent consumed. `u32` for the same reason. */
+ tokens: number | null,
+ /** How many tools the subagent called. */
+ toolUses: number | null,
+ /** What kinds of tools the subagent called. */
+ stats: ToolStats | null,
+};
+
+/** Where a held call stands. */
+export type ToolApprovalStatus =
+/** Held until the owner answers. */
+"pending" |
+/** The owner approved it; the call went through. */
+"approved" |
+/** The owner refused it; the call did not run. */
+"denied" |
+/** Someone with edit access, the agent, or the session gave up on it. */
+"cancelled" |
+/** Nobody answered in time. */
+"expired";
+
+/**
+ * What a tool call actually did.
+ *
+ * Discriminated by what a reader needs in order to render it, not by ACP's
+ * [`ToolKind`](agent_client_protocol::ToolKind). A terminal wants command and
+ * output; an edit wants a diff; a handful of others want the paths they
+ * touched or whatever text they reported; everything else wants its raw
+ * input shown as JSON. Every named [`ToolKind`](agent_client_protocol::ToolKind)
+ * has a variant here, so the fold never falls back to [`Self::Other`] for a
+ * kind ACP defines - only for `switch_mode` (nothing a reader would want
+ * rendered) and a kind this fold does not yet know about.
+ *
+ * Three variants are chosen by *name* rather than kind: Macro's own tools
+ * ([`Self::Macro`], [`Self::UserTool`]) arrive as ACP `other`, and what a
+ * reader wants for them is the tool's own JSON, not a generic card; a
+ * delegation ([`Self::Subagent`]) is a tool call by whatever name its
+ * harness gives it. The harness layer decides which names are which.
+ */
+export type ToolDetail =
+/** A shell command. ACP's `execute`. */
+{ kind: "terminal";
+/** The command line, when the harness reported one. */
+command: string | null;
+/** Captured output, ANSI escapes intact. See [`AnsiText`]. */
+output: AnsiText | null;
+/** Process exit code, when the harness reported one. */
+exitCode: number | null } |
+/** One or more file modifications. ACP's `edit`. */
+{ kind: "edit";
+/** The diffs ACP reported for this call. */
+diffs: FileDiff[] } |
+/** A file read. ACP's `read`. */
+{ kind: "read";
+/** Paths this call touched. */
+paths: string[] } |
+/** One or more files removed. ACP's `delete`. */
+{ kind: "delete";
+/** Paths this call touched. */
+paths: string[] } |
+/**
+ * One or more files moved or renamed. ACP's `move`.
+ *
+ * Only the paths a reader can be sure of. ACP has no standard field for
+ * "from" versus "to" - a call's `locations` is just the set of paths it
+ * touched - so this does not guess at a direction.
+ */
+{ kind: "move";
+/** Paths this call touched. */
+paths: string[] } |
+/** A search. ACP's `search`. */
+{ kind: "search";
+/** Paths this call touched. */
+paths: string[];
+/** Text the call reported - e.g. matched lines - when any. */
+output: string | null } |
+/** Retrieving external data. ACP's `fetch`. */
+{ kind: "fetch";
+/** Text the call reported, when any. */
+output: string | null } |
+/**
+ * Explicit reasoning surfaced as its own tool call, as distinct from
+ * [`MessagePart::Thought`], which is reasoning streamed inline. ACP's
+ * `think`.
+ */
+{ kind: "think";
+/** Text the call reported, when any. */
+output: string | null } |
+/**
+ * Anything else: ACP's `switch_mode`, a tool from an MCP server the fold
+ * knows nothing about, and any kind - including `other` itself,
+ * [`ToolKind`](agent_client_protocol::ToolKind)'s default for a call
+ * that names no kind at all - this fold has no special rendering for.
+ * What a reader wants is the exchange itself: the request the agent
+ * made and the response it got, as JSON.
+ */
+{ kind: "other";
+/** ACP's tool kind, as its wire string. */
+acpKind: string;
+/** Text the call reported in its content blocks, when any. */
+output: string | null;
+/**
+ * The tool's own arguments, when reported - out of any wrapper the
+ * harness put around them.
+ */
+input: unknown;
+/**
+ * The tool's own result, when the harness reported one in
+ * `rawOutput` - out of the harness's wrapper and MCP's envelope, so
+ * an MCP tool's `structuredContent` (or its text, parsed when it is
+ * JSON) arrives as the JSON the tool returned.
+ */
+result: unknown;
+/** The error text, when the harness's wrapper reported failure. */
+error: string | null } |
+/**
+ * A Macro tool the fold knows by name - reached over Macro's MCP
+ * server, or called in-process by Macro's own agent. Input and output
+ * are the tool's own JSON, any MCP envelope already removed, so a
+ * reader that knows the tool renders it without parsing the wire.
+ */
+{ kind: "macro";
+/** The tool's arguments, as it defines them. */
+input: unknown;
+/**
+ * The tool's result, as it defines it; absent until the call
+ * completes.
+ */
+output: unknown;
+/** The error text, when the call failed. */
+error: string | null } |
+/**
+ * A Macro user tool: the agent drafted it, the user finishes it after
+ * the turn. See [`UserToolOutcome`].
+ */
+{ kind: "user_tool";
+/**
+ * The draft, as the tool defines its arguments; patched as the
+ * user edits.
+ */
+input: unknown;
+/** Where the user got to with it. */
+outcome: UserToolOutcome } |
+/**
+ * Work the agent delegated to another agent.
+ *
+ * ACP has no notion of this; every harness spells it as a tool call by
+ * its own conventions (Claude Code's `Agent`, OpenCode's and Cursor's
+ * `task`, Codex's `spawnAgent`, Hermes's `delegate_task`), and the
+ * harness reader recognizes it. What the subagent itself did nests in
+ * `children` when the harness attributes its calls to the parent -
+ * only Claude Code does today - and is otherwise summarized in
+ * `result`.
+ */
+{ kind: "subagent";
+/**
+ * What to call the delegation: the harness's description when it
+ * gave one, else the first line of the brief, else the tool's own
+ * name. Always present, so a reader never has to pick a fallback
+ * itself; `description` and `prompt` stay exactly what the harness
+ * said.
+ */
+title: string;
+/**
+ * Which kind of agent was delegated to (`general-purpose`,
+ * `explore`), when the harness names one.
+ */
+agentType: string | null;
+/** A short description of the task, when given. */
+description: string | null;
+/** The brief the subagent was given. */
+prompt: string | null;
+/**
+ * Whether the subagent was started in the background: its call
+ * completes at once and its answer, if any, arrives some other way.
+ */
+background: boolean;
+/**
+ * The subagent's own parts, in arrival order, for a harness that
+ * attributes them to the parent call.
+ */
+children: MessagePart[];
+/**
+ * What the subagent reported back, once it has.
+ *
+ * Boxed: this is by far the widest thing a part can hold, and every
+ * part pays for the widest variant.
+ */
+result: SubagentResult | null };
+
+/**
+ * What a harness called a tool.
+ *
+ * ACP has no tool-name field - a call carries a human-readable `title` and a
+ * coarse `kind`, nothing more. The name a reader wants (`Bash`, `ReadContent`)
+ * is a harness convention: Claude Code writes it to `_meta`, others put it
+ * in the title, and tools reached over MCP arrive namespaced as
+ * `mcp__<server>__<tool>`. This type is the one place that namespacing is
+ * understood, so no reader downstream ever splits a string.
+ *
+ * Parsing is infallible: a string that is not an MCP name is a native one,
+ * however odd it looks. Nothing is dropped for being unrecognized.
+ */
+export type ToolName =
+/**
+ * A tool the harness owns: `Bash`, `Read`, `Write`, or a Macro tool
+ * called in-process by Macro's own agent.
+ */
+{ kind: "native";
+/** The name as the harness reported it. */
+name: string } |
+/**
+ * A tool reached over MCP, from the server the harness registered it
+ * under.
+ */
+{ kind: "mcp";
+/** The MCP server's name, as the harness registered it. */
+server: string;
+/** The tool's name on that server. */
+tool: string };
+
+/**
+ * A subagent's tool use, by kind. Claude Code's `toolStats`, in the fold's
+ * vocabulary.
+ */
+export type ToolStats = {
+ /** Files read. */
+ reads: number,
+ /** Searches run. */
+ searches: number,
+ /** Shell commands run. */
+ commands: number,
+ /** Files edited. */
+ edits: number,
+ /** Lines added across those edits. */
+ linesAdded: number,
+ /** Lines removed across those edits. */
+ linesRemoved: number,
+ /** Anything else. */
+ other: number,
+};
+
+/**
+ * How far a tool call progressed.
+ *
+ * [`ToolStatus::Pending`] and [`ToolStatus::Running`] are legitimate final
+ * states, not errors: a live session's newest calls have not finished, and a
+ * session that dies mid-call leaves one behind permanently.
+ */
+export type ToolStatus =
+/** Not started - either still streaming input or awaiting permission. */
+"pending" |
+/** Currently running. */
+"running" |
+/** Finished successfully. */
+"completed" |
+/** Finished unsuccessfully. */
+"failed";
+
+/** A tool call within a turn, identified by its ACP `toolCallId`. */
+export type ToolUseId = string;
+
+/** What the agent is doing right now, as a typing indicator says it. */
+export type TurnPhase =
+/** Nothing to show yet, or between steps. */
+"thinking" |
+/** Writing prose. */
+"writing" |
+/** Running a tool. */
+"working" |
+/** Waiting on the user to answer a permission or a question. */
+"waiting";
+
+/** Where the newest turn stands. */
+export type TurnState =
+/** No turn is open. */
+"idle" |
+/**
+ * A prompt this client issued is on the wire, unconfirmed, and the agent
+ * has produced nothing. Only a speculative fold reports this.
+ */
+"starting" |
+/** A turn is open and the agent is working. */
+"running" |
+/** A stop was issued against the open turn and no stop reason has arrived. */
+"stopping" |
+/**
+ * The open turn is waiting on a permission, elicitation, or tool
+ * approval response.
+ */
+"blocked" |
+/** The runtime reported `disconnected`; whatever was open is not moving. */
+"disconnected";
+
+/**
+ * How far a user tool has got - the fold's reading of the backend's
+ * `UserToolResponse`, restated each time the call is patched.
+ *
+ * A user tool's call completes, from ACP's point of view, the moment the
+ * agent invokes it: the backend answers `"PendingUserExecution"` and does
+ * nothing. What happens next - the user editing, sending, or rejecting the
+ * draft - reaches the log as later patches to the same call, so
+ * [`Self::Pending`] is where every user tool starts and where one the user
+ * never touched stays.
+ */
+export type UserToolOutcome =
+/** Awaiting the user. The draft is whatever the input currently holds. */
+{ kind: "pending" } |
+/**
+ * The user edited the draft without finishing it; the input holds
+ * their edits.
+ */
+{ kind: "edited" } |
+/** `SendEmail`: the email went out. */
+{ kind: "sent";
+/** The sent message's id. */
+messageId: string;
+/** The thread the message landed in. */
+threadId: string } |
+/** `SendEmail`: the user saved the draft instead of sending it. */
+{ kind: "draft";
+/** The saved draft's id. */
+draftId: string;
+/** The thread the draft belongs to, when it is a reply. */
+threadId: string | null } |
+/**
+ * The user executed the tool; this is what the tool returned. The shape
+ * is the tool's own - a calendar event for `CreateCalendarEvent`.
+ */
+{ kind: "completed";
+/** The tool's result, verbatim. */
+result: unknown } |
+/** The user declined. */
+{ kind: "rejected" } |
+/** The call itself failed before the user could act. */
+{ kind: "failed";
+/** The error, as reported. */
+message: string } |
+/**
+ * A result arrived that this fold could not read as a user tool
+ * response - a shape the backend added after this was written.
+ */
+{ kind: "unrecognized" };
diff --git a/packages/sdk/generated/agent-harness/index.ts b/packages/sdk/generated/agent-harness/index.ts
index 66194b57e4..a6d5f446de 100644
--- a/packages/sdk/generated/agent-harness/index.ts
+++ b/packages/sdk/generated/agent-harness/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AccessLevel, AgentAction, AgentActionId, AgentConfigKindDto, AgentConfigOptionDto, AgentConfigSelectOptionDto, AgentConversationDto, AgentConversationsDto, AgentConversationSessionDto, AgentConversationTurnDto, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSessionsForPullRequestData, AgentSessionsForPullRequestError, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponse, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsError, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponse, AgentSessionsForPullRequestsResponses, AgentSetConfigOptionAction, AgentSetModelAction, AiAdmissionErrorBody, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalError, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponse, AnswerAgentSessionToolApprovalResponses, AnswerToolApprovalRequest, AnswerToolApprovalResponse, BotId, CapabilityHarnessDto, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSharePermission, ClientOptions, CodingPreferencesBody, CompleteData, CompleteErrors, CompleteRequest, CompleteResponse, CompleteResponses, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, ConversationTurnState, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateReview, CreateSessionReviewData, CreateSessionReviewErrors, CreateSessionReviewResponse, CreateSessionReviewResponses, CreateSessionThread, DecideSessionReviewData, DecideSessionReviewErrors, DecideSessionReviewResponse, DecideSessionReviewResponses, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponse, DisconnectResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponse, DiscoverAgentCapabilitiesHandlerResponses, DiscoverAgentCapabilitiesRequest, DiscoverAgentCapabilitiesResponse, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmptyRequest, ExecutionActivity, ExecutionId, ExecutionRecord, ExecutionStatus, ExternalSessionResponse, FileChangeKindDto, GetAgentCodingPreferencesData, GetAgentCodingPreferencesError, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponse, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsError, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponse, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GetCodeExecutionData, GetCodeExecutionErrors, GetCodeExecutionResponse, GetCodeExecutionResponses, GetSessionReviewData, GetSessionReviewErrors, GetSessionReviewResponse, GetSessionReviewResponses, GitRefDto, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestError, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponse, LinkAgentSessionPullRequestResponses, LinkShare, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponse, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsError, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponse, ListAgentSessionPullRequestsResponses, ListExecutionReviewsData, ListExecutionReviewsErrors, ListExecutionReviewsResponse, ListExecutionReviewsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, ModelHarnessDto, PermissionAnswer, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PullRequestLinkedSession, PullRequestLinkSource, PullRequestSessions, PullRequestSessionsResponse, PullRequestsSessionsResponse, PullRequestUrl, PullRequestUrls, PutAgentCodingPreferencesData, PutAgentCodingPreferencesError, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponse, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, RecordedCallStatus, RecordedToolCall, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnRequest, RetryAgentConversationTurnResponse, RetryAgentConversationTurnResponses, ReviewDecision, ReviewId, ReviewItem, ReviewItemStatus, ReviewKind, ReviewRecord, SandboxSize, SandboxSizeBody, SessionBot, SessionPullRequestLink, SessionPullRequestsResponse, SessionStatusDto, SetAgentSessionArchivedData, SetAgentSessionArchivedError, SetAgentSessionArchivedErrors, SetAgentSessionArchivedRequest, SetAgentSessionArchivedResponse, SetAgentSessionArchivedResponses, SharePermissionV2, StartData, StartErrors, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationRequest, StartFreshAgentConversationResponse, StartFreshAgentConversationResponses, StartResponse, StartResponse2, StartResponses, StatusData, StatusErrors, StatusResponse, StatusResponse2, StatusResponses, SteerQueuedActionData, SteerQueuedActionError, SteerQueuedActionErrors, SteerQueuedActionResponse, SteerQueuedActionResponses, ToolApprovalAnswerDto, ToolApprovalStatusDto, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestError, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponse, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponse, WarmAgentSessionHandlerResponses, WarmAgentSessionRequest, WarmAgentSessionResponse, WithAgentSessionId } from './types.gen';
+export type { AccessLevel, AgentAction, AgentActionId, AgentConfigKindDto, AgentConfigOptionDto, AgentConfigSelectOptionDto, AgentConversationDto, AgentConversationsDto, AgentConversationSessionDto, AgentConversationTurnDto, AgentModelDto, AgentModelsStatusDto, AgentPermissionAction, AgentPromptAction, AgentRepositoriesResponse, AgentRepositoryBranchesResponse, AgentRepositoryDto, AgentRespondElicitationAction, AgentSessionChangesPatchResponse, AgentSessionChangesResponse, AgentSessionFoldedLogResponse, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, AgentSessionsForPullRequestData, AgentSessionsForPullRequestError, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponse, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsError, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponse, AgentSessionsForPullRequestsResponses, AgentSetConfigOptionAction, AgentSetModelAction, AiAdmissionErrorBody, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalError, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponse, AnswerAgentSessionToolApprovalResponses, AnswerToolApprovalRequest, AnswerToolApprovalResponse, BotId, CapabilityHarnessDto, CaptureAttemptDto, CaptureOutcomeDto, ChangedFileDto, ChangesetDto, ChangesetSourceDto, ChannelSharePermission, ClientOptions, CodingPreferencesBody, CompleteData, CompleteErrors, CompleteRequest, CompleteResponse, CompleteResponses, ControlAgentSessionData, ControlAgentSessionError, ControlAgentSessionErrors, ControlAgentSessionResponse, ControlAgentSessionResponses, ControlRequest, ControlResponse, ControlStatusDto, ConversationTurnState, CreateAgentSessionData, CreateAgentSessionError, CreateAgentSessionErrors, CreateAgentSessionRequest, CreateAgentSessionResponse, CreateAgentSessionResponse2, CreateAgentSessionResponses, CreateReview, CreateSessionReviewData, CreateSessionReviewErrors, CreateSessionReviewResponse, CreateSessionReviewResponses, CreateSessionThread, DecideSessionReviewData, DecideSessionReviewErrors, DecideSessionReviewResponse, DecideSessionReviewResponses, DeleteAgentSessionData, DeleteAgentSessionError, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponse, DisconnectResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponse, DiscoverAgentCapabilitiesHandlerResponses, DiscoverAgentCapabilitiesRequest, DiscoverAgentCapabilitiesResponse, DocumentId, EditQueuedActionData, EditQueuedActionError, EditQueuedActionErrors, EditQueuedActionRequest, EditQueuedActionResponse, EditQueuedActionResponses, ElicitationAnswer, ElicitationContentValue, ElicitationRequestId, EmptyRequest, ExecutionActivity, ExecutionId, ExecutionRecord, ExecutionStatus, ExternalSessionResponse, FileChangeKindDto, GetAgentCodingPreferencesData, GetAgentCodingPreferencesError, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponse, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeError, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponse, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesError, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchError, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponse, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponse, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionError, GetAgentSessionErrors, GetAgentSessionFoldedLogData, GetAgentSessionFoldedLogError, GetAgentSessionFoldedLogErrors, GetAgentSessionFoldedLogResponse, GetAgentSessionFoldedLogResponses, GetAgentSessionLogData, GetAgentSessionLogError, GetAgentSessionLogErrors, GetAgentSessionLogResponse, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsError, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponse, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueError, GetAgentSessionQueueErrors, GetAgentSessionQueueResponse, GetAgentSessionQueueResponses, GetAgentSessionResponse, GetAgentSessionResponses, GetCodeExecutionData, GetCodeExecutionErrors, GetCodeExecutionResponse, GetCodeExecutionResponses, GetSessionReviewData, GetSessionReviewErrors, GetSessionReviewResponse, GetSessionReviewResponses, GitRefDto, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestError, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponse, LinkAgentSessionPullRequestResponses, LinkShare, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponse, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponse, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponse, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsError, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponse, ListAgentSessionPullRequestsResponses, ListExecutionReviewsData, ListExecutionReviewsErrors, ListExecutionReviewsResponse, ListExecutionReviewsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponse, LoadAgentModelsHandlerResponses, LoadAgentModelsRequest, LoadAgentModelsResponse, LogDirectionDto, LogFrameDto, MessageParent, ModelHarnessDto, PermissionAnswer, PreviewAgentSessionsData, PreviewAgentSessionsError, PreviewAgentSessionsErrors, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, PreviewAgentSessionsResponse2, PreviewAgentSessionsResponses, PromptAttachment, PullRequestLinkedSession, PullRequestLinkSource, PullRequestSessions, PullRequestSessionsResponse, PullRequestsSessionsResponse, PullRequestUrl, PullRequestUrls, PutAgentCodingPreferencesData, PutAgentCodingPreferencesError, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponse, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeError, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponse, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeError, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponse, PutAgentSessionSandboxSizeResponses, QueuedActionDto, RecordedCallStatus, RecordedToolCall, RefreshAgentSessionChangesData, RefreshAgentSessionChangesError, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponse, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionError, RemoveQueuedActionErrors, RemoveQueuedActionResponse, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionError, RenameAgentSessionErrors, RenameAgentSessionRequest, RenameAgentSessionResponse, RenameAgentSessionResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnRequest, RetryAgentConversationTurnResponse, RetryAgentConversationTurnResponses, ReviewDecision, ReviewId, ReviewItem, ReviewItemStatus, ReviewKind, ReviewRecord, SandboxSize, SandboxSizeBody, SessionBot, SessionPullRequestLink, SessionPullRequestsResponse, SessionStatusDto, SetAgentSessionArchivedData, SetAgentSessionArchivedError, SetAgentSessionArchivedErrors, SetAgentSessionArchivedRequest, SetAgentSessionArchivedResponse, SetAgentSessionArchivedResponses, SharePermissionV2, StartData, StartErrors, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationRequest, StartFreshAgentConversationResponse, StartFreshAgentConversationResponses, StartResponse, StartResponse2, StartResponses, StatusData, StatusErrors, StatusResponse, StatusResponse2, StatusResponses, SteerQueuedActionData, SteerQueuedActionError, SteerQueuedActionErrors, SteerQueuedActionResponse, SteerQueuedActionResponses, ToolApprovalAnswerDto, ToolApprovalStatusDto, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestError, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponse, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsError, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponse, UpdateAgentSessionPermissionsResponses, UpdateChannelSharePermission, UpdateOperation, UpdateSharePermissionRequestV2, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponse, WarmAgentSessionHandlerResponses, WarmAgentSessionRequest, WarmAgentSessionResponse, WithAgentSessionId } from './types.gen';
diff --git a/packages/sdk/generated/agent-harness/sdk.gen.ts b/packages/sdk/generated/agent-harness/sdk.gen.ts
index 1a2ff9c0f8..88373b14e2 100644
--- a/packages/sdk/generated/agent-harness/sdk.gen.ts
+++ b/packages/sdk/generated/agent-harness/sdk.gen.ts
@@ -2,7 +2,7 @@
import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';
import { client } from './client.gen';
-import type { AgentSessionsForPullRequestData, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponses, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponses, CompleteData, CompleteErrors, CompleteResponses, ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, CreateSessionReviewData, CreateSessionReviewErrors, CreateSessionReviewResponses, DecideSessionReviewData, DecideSessionReviewErrors, DecideSessionReviewResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, GetAgentCodingPreferencesData, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, GetCodeExecutionData, GetCodeExecutionErrors, GetCodeExecutionResponses, GetSessionReviewData, GetSessionReviewErrors, GetSessionReviewResponses, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponses, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponses, ListExecutionReviewsData, ListExecutionReviewsErrors, ListExecutionReviewsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentCodingPreferencesData, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RefreshAgentSessionChangesData, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnResponses, SetAgentSessionArchivedData, SetAgentSessionArchivedErrors, SetAgentSessionArchivedResponses, StartData, StartErrors, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationResponses, StartResponses, StatusData, StatusErrors, StatusResponses, SteerQueuedActionData, SteerQueuedActionErrors, SteerQueuedActionResponses, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponses, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponses } from './types.gen';
+import type { AgentSessionsForPullRequestData, AgentSessionsForPullRequestErrors, AgentSessionsForPullRequestResponses, AgentSessionsForPullRequestsData, AgentSessionsForPullRequestsErrors, AgentSessionsForPullRequestsResponses, AnswerAgentSessionToolApprovalData, AnswerAgentSessionToolApprovalErrors, AnswerAgentSessionToolApprovalResponses, CompleteData, CompleteErrors, CompleteResponses, ControlAgentSessionData, ControlAgentSessionErrors, ControlAgentSessionResponses, CreateAgentSessionData, CreateAgentSessionErrors, CreateAgentSessionResponses, CreateSessionReviewData, CreateSessionReviewErrors, CreateSessionReviewResponses, DecideSessionReviewData, DecideSessionReviewErrors, DecideSessionReviewResponses, DeleteAgentSessionData, DeleteAgentSessionErrors, DeleteAgentSessionResponses, DisconnectData, DisconnectErrors, DisconnectResponses, DiscoverAgentCapabilitiesHandlerData, DiscoverAgentCapabilitiesHandlerErrors, DiscoverAgentCapabilitiesHandlerResponses, EditQueuedActionData, EditQueuedActionErrors, EditQueuedActionResponses, GetAgentCodingPreferencesData, GetAgentCodingPreferencesErrors, GetAgentCodingPreferencesResponses, GetAgentSandboxSizeData, GetAgentSandboxSizeErrors, GetAgentSandboxSizeResponses, GetAgentSessionChangesData, GetAgentSessionChangesErrors, GetAgentSessionChangesPatchData, GetAgentSessionChangesPatchErrors, GetAgentSessionChangesPatchResponses, GetAgentSessionChangesResponses, GetAgentSessionData, GetAgentSessionErrors, GetAgentSessionFoldedLogData, GetAgentSessionFoldedLogErrors, GetAgentSessionFoldedLogResponses, GetAgentSessionLogData, GetAgentSessionLogErrors, GetAgentSessionLogResponses, GetAgentSessionPermissionsData, GetAgentSessionPermissionsErrors, GetAgentSessionPermissionsResponses, GetAgentSessionQueueData, GetAgentSessionQueueErrors, GetAgentSessionQueueResponses, GetAgentSessionResponses, GetCodeExecutionData, GetCodeExecutionErrors, GetCodeExecutionResponses, GetSessionReviewData, GetSessionReviewErrors, GetSessionReviewResponses, LinkAgentSessionPullRequestData, LinkAgentSessionPullRequestErrors, LinkAgentSessionPullRequestResponses, ListAgentConversationsData, ListAgentConversationsErrors, ListAgentConversationsResponses, ListAgentRepositoriesData, ListAgentRepositoriesErrors, ListAgentRepositoriesResponses, ListAgentRepositoryBranchesData, ListAgentRepositoryBranchesErrors, ListAgentRepositoryBranchesResponses, ListAgentSessionPullRequestsData, ListAgentSessionPullRequestsErrors, ListAgentSessionPullRequestsResponses, ListExecutionReviewsData, ListExecutionReviewsErrors, ListExecutionReviewsResponses, LoadAgentModelsHandlerData, LoadAgentModelsHandlerErrors, LoadAgentModelsHandlerResponses, PreviewAgentSessionsData, PreviewAgentSessionsErrors, PreviewAgentSessionsResponses, PutAgentCodingPreferencesData, PutAgentCodingPreferencesErrors, PutAgentCodingPreferencesResponses, PutAgentSandboxSizeData, PutAgentSandboxSizeErrors, PutAgentSandboxSizeResponses, PutAgentSessionSandboxSizeData, PutAgentSessionSandboxSizeErrors, PutAgentSessionSandboxSizeResponses, RefreshAgentSessionChangesData, RefreshAgentSessionChangesErrors, RefreshAgentSessionChangesResponses, RemoveQueuedActionData, RemoveQueuedActionErrors, RemoveQueuedActionResponses, RenameAgentSessionData, RenameAgentSessionErrors, RenameAgentSessionResponses, RetryAgentConversationTurnData, RetryAgentConversationTurnErrors, RetryAgentConversationTurnResponses, SetAgentSessionArchivedData, SetAgentSessionArchivedErrors, SetAgentSessionArchivedResponses, StartData, StartErrors, StartFreshAgentConversationData, StartFreshAgentConversationErrors, StartFreshAgentConversationResponses, StartResponses, StatusData, StatusErrors, StatusResponses, SteerQueuedActionData, SteerQueuedActionErrors, SteerQueuedActionResponses, UnlinkAgentSessionPullRequestData, UnlinkAgentSessionPullRequestErrors, UnlinkAgentSessionPullRequestResponses, UpdateAgentSessionPermissionsData, UpdateAgentSessionPermissionsErrors, UpdateAgentSessionPermissionsResponses, WarmAgentSessionHandlerData, WarmAgentSessionHandlerResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -380,6 +380,17 @@ export class Sdk extends HeyApiClient {
return (options.client ?? this.client).get<GetAgentSessionLogResponses, GetAgentSessionLogErrors, ThrowOnError>({ url: '/agent-sessions/{session_id}/log', ...options });
}
+ /**
+ * One agent session's history folded into renderable messages: the same
+ * fold the web client runs over [`get_agent_session_log_handler`]'s frames.
+ *
+ * For readers that do not run the fold themselves, such as SDK programs and
+ * agents reading another session's history.
+ */
+ public getAgentSessionFoldedLog<ThrowOnError extends boolean = false>(options: Options<GetAgentSessionFoldedLogData, ThrowOnError>): RequestResult<GetAgentSessionFoldedLogResponses, GetAgentSessionFoldedLogErrors, ThrowOnError> {
+ return (options.client ?? this.client).get<GetAgentSessionFoldedLogResponses, GetAgentSessionFoldedLogErrors, ThrowOnError>({ url: '/agent-sessions/{session_id}/log/folded', ...options });
+ }
+
/**
* Rename an agent session.
*/
diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.ts
index b7d0f5b154..bd9e577869 100644
--- a/packages/sdk/generated/agent-harness/types.gen.ts
+++ b/packages/sdk/generated/agent-harness/types.gen.ts
@@ -352,6 +352,26 @@ export type AgentSessionChangesResponse = {
changeset?: null | ChangesetDto;
};
+/**
+ * Response body for one session's folded log.
+ */
+export type AgentSessionFoldedLogResponse = {
+ /**
+ * The agent whose messages these are; it sent every agent message.
+ */
+ bot: SessionBot;
+ /**
+ * The conversation, oldest first: prompts, replies, tool calls and their
+ * results, plans, permission requests and how each turn ended. Each
+ * element is a `FoldedMessage` from the fold's TypeScript contract,
+ * which the SDK exports; the schema is opaque here because those types
+ * are described with specta rather than utoipa.
+ */
+ messages: Array<{
+ [key: string]: unknown;
+ }>;
+};
+
/**
* One entry of a session's protocol log.
*
@@ -2652,6 +2672,32 @@ export type GetAgentSessionLogResponses = {
export type GetAgentSessionLogResponse = GetAgentSessionLogResponses[keyof GetAgentSessionLogResponses];
+export type GetAgentSessionFoldedLogData = {
+ body?: never;
+ path: {
+ /**
+ * ID of the agent session
+ */
+ session_id: string;
+ };
+ query?: never;
+ url: '/agent-sessions/{session_id}/log/folded';
+};
+
+export type GetAgentSessionFoldedLogErrors = {
+ 401: string;
+ 403: string;
+ 500: string;
+};
+
+export type GetAgentSessionFoldedLogError = GetAgentSessionFoldedLogErrors[keyof GetAgentSessionFoldedLogErrors];
+
+export type GetAgentSessionFoldedLogResponses = {
+ 200: AgentSessionFoldedLogResponse;
+};
+
+export type GetAgentSessionFoldedLogResponse = GetAgentSessionFoldedLogResponses[keyof GetAgentSessionFoldedLogResponses];
+
export type RenameAgentSessionData = {
body: RenameAgentSessionRequest;
path: {
diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.json
index 6fa8876338..acf218e6cd 100644
--- a/packages/sdk/specs/agent-harness.json
+++ b/packages/sdk/specs/agent-harness.json
@@ -1490,6 +1490,68 @@
}
}
},
+ "/agent-sessions/{session_id}/log/folded": {
+ "get": {
+ "tags": ["agent-sessions"],
+ "summary": "One agent session's history folded into renderable messages: the same\nfold the web client runs over [`get_agent_session_log_handler`]'s frames.",
+ "description": "For readers that do not run the fold themselves, such as SDK programs and\nagents reading another session's history.",
+ "operationId": "get_agent_session_folded_log",
+ "parameters": [
+ {
+ "name": "session_id",
+ "in": "path",
+ "description": "ID of the agent session",
+ "required": true,
+ "schema": {
+ "type": "string",
+ "format": "uuid"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/AgentSessionFoldedLogResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "403": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/agent-sessions/{session_id}/name": {
"put": {
"tags": ["agent-sessions"],
@@ -3204,6 +3266,24 @@
}
}
},
+ "AgentSessionFoldedLogResponse": {
+ "type": "object",
+ "description": "Response body for one session's folded log.",
+ "required": ["bot", "messages"],
+ "properties": {
+ "bot": {
+ "$ref": "#/components/schemas/SessionBot",
+ "description": "The agent whose messages these are; it sent every agent message."
+ },
+ "messages": {
+ "type": "array",
+ "items": {
+ "type": "object"
+ },
+ "description": "The conversation, oldest first: prompts, replies, tool calls and their\nresults, plans, permission requests and how each turn ended. Each\nelement is a `FoldedMessage` from the fold's TypeScript contract,\nwhich the SDK exports; the schema is opaque here because those types\nare described with specta rather than utoipa."
+ }
+ }
+ },
"AgentSessionLogEntryDto": {
"allOf": [
{
diff --git a/packages/sdk/src/entities/agent-sessions/agent-session.ts b/packages/sdk/src/entities/agent-sessions/agent-session.ts
index a0d745a511..113de5f624 100644
--- a/packages/sdk/src/entities/agent-sessions/agent-session.ts
+++ b/packages/sdk/src/entities/agent-sessions/agent-session.ts
@@ -1,3 +1,4 @@
+import type { FoldedMessage } from '../../../generated/agent-fold';
import type {
AgentAction,
AgentSessionChangesResponse,
@@ -8,6 +9,7 @@ import type {
PromptAttachment,
PullRequestLinkSource,
SandboxSize,
+ SessionBot,
} from '../../../generated/agent-harness/types.gen';
import { unwrap } from '../../utils';
import type { MacroClient } from '../../utils/client';
@@ -23,6 +25,17 @@ import { QueuedAction } from './queued-action';
import { type CreateReviewOptions, SessionReview } from './review';
import { ToolApproval } from './tool-approval';
+/** A session's history folded into readable messages, oldest first. */
+export type FoldedAgentSessionLog = {
+ /** The agent that sent every agent message. */
+ bot: SessionBot;
+ /**
+ * Prompts and replies with their tool calls, results, plans, permission
+ * requests and how each turn ended.
+ */
+ messages: FoldedMessage[];
+};
+
/** A GitHub pull request linked to a session. */
export type SessionPullRequest = {
/** The pull request's `owner/repo/pull/number` key. */
@@ -419,6 +432,25 @@ export class AgentSession extends MacroEntity<AgentSessionResponse> {
);
}
+ /**
+ * Read this session's whole history as the conversation the app renders:
+ * each user prompt and agent reply, oldest first, with tool calls and their
+ * results, plans, permission requests and how each turn ended. Works on any
+ * session the caller can view, live or finished, so it is the way to read
+ * what another agent session did. Prefer it to {@link log}, which returns
+ * raw protocol frames.
+ */
+ async foldedLog(): Promise<FoldedAgentSessionLog> {
+ const { bot, messages } = unwrap(
+ await this.client.agentHarness.getAgentSessionFoldedLog({
+ path: { session_id: this.id },
+ }),
+ );
+ // The schema is opaque: the server serializes the fold's `FoldedMessage`,
+ // whose TypeScript contract is generated from the same Rust type.
+ return { bot, messages: messages as FoldedMessage[] };
+ }
+
/** Read the complete raw protocol log for this session. */
async log(): Promise<AgentSessionLogResponse> {
return unwrap(
diff --git a/packages/sdk/src/macro.ts b/packages/sdk/src/macro.ts
index 4f9534e0db..0ac3be6802 100644
--- a/packages/sdk/src/macro.ts
+++ b/packages/sdk/src/macro.ts
@@ -229,6 +229,7 @@ export class Macro<T extends MacroOpts = MacroOpts> {
}
}
+export type { FoldedAgentSessionLog } from './entities/agent-sessions/agent-session';
export type { CodeResult } from './entities/agent-sessions/code-execution';
export {
AgentConversation,
diff --git a/packages/sdk/tests/agent-sessions.test.ts b/packages/sdk/tests/agent-sessions.test.ts
index ded1a3db61..31c2338481 100644
--- a/packages/sdk/tests/agent-sessions.test.ts
+++ b/packages/sdk/tests/agent-sessions.test.ts
@@ -1,4 +1,5 @@
import { afterEach, describe, expect, test } from 'bun:test';
+import type { FoldedMessage } from '../generated/agent-fold';
import type {
AgentSessionChangesResponse,
AgentSessionResponse,
@@ -413,6 +414,42 @@ describe('AgentSession', () => {
});
});
+ test('reads the folded log', async () => {
+ const bot = { id: session.botId, name: 'Agent', handle: 'agent' };
+ const messages: FoldedMessage[] = [
+ {
+ agentSessionId: sessionId,
+ turn: 0,
+ author: { kind: 'agent' },
+ requestId: null,
+ parts: [{ kind: 'text', text: 'Done.' }],
+ stop: null,
+ pending: false,
+ segments: [],
+ phase: null,
+ postedAt: null,
+ },
+ ];
+ let request: Request | undefined;
+ globalThis.fetch = (async (input) => {
+ request = input instanceof Request ? input : new Request(input);
+ return Response.json({ bot, messages }, { status: 200 });
+ }) as typeof fetch;
+ const macro = new Macro({
+ token: 'user-token',
+ hosts: { 'agent-harness': 'https://agent.example.test' },
+ });
+
+ await expect(
+ macro.agentSessions.byId(sessionId).foldedLog(),
+ ).resolves.toEqual({ bot, messages });
+
+ expect(request?.method).toBe('GET');
+ expect(request?.url).toBe(
+ `https://agent.example.test/agent-sessions/${sessionId}/log/folded`,
+ );
+ });
+
test('lists the queue and edits, steers, or removes an entry through its handle', async () => {
const actionId = '0198a4cc-e138-7670-a308-a6b766602704';
const requests: Request[] = [];
diff --git a/services/agent_harness_service/src/api/swagger.rs b/services/agent_harness_service/src/api/swagger.rs
index 1917a3c101..8d44dd53ae 100644
--- a/services/agent_harness_service/src/api/swagger.rs
+++ b/services/agent_harness_service/src/api/swagger.rs
@@ -27,13 +27,13 @@ use agent_session::inbound::axum_router::pull_requests::{
SessionPullRequestsResponse,
};
use agent_session::inbound::axum_router::{
- self, AgentSessionLogEntryDto, AgentSessionLogResponse, AgentSessionPreviewData,
- AgentSessionPreviewDto, AgentSessionQueueResponse, AgentSessionResponse, CodingPreferencesBody,
- ControlRequest, ControlResponse, ControlStatusDto, CreateAgentSessionRequest,
- CreateAgentSessionResponse, CreateSessionThread, EditQueuedActionRequest, LogDirectionDto,
- LogFrameDto, PreviewAgentSessionsRequest, PreviewAgentSessionsResponse, QueuedActionDto,
- RenameAgentSessionRequest, SandboxSizeBody, SessionStatusDto, SetAgentSessionArchivedRequest,
- WithAgentSessionId,
+ self, AgentSessionFoldedLogResponse, AgentSessionLogEntryDto, AgentSessionLogResponse,
+ AgentSessionPreviewData, AgentSessionPreviewDto, AgentSessionQueueResponse,
+ AgentSessionResponse, CodingPreferencesBody, ControlRequest, ControlResponse, ControlStatusDto,
+ CreateAgentSessionRequest, CreateAgentSessionResponse, CreateSessionThread,
+ EditQueuedActionRequest, LogDirectionDto, LogFrameDto, PreviewAgentSessionsRequest,
+ PreviewAgentSessionsResponse, QueuedActionDto, RenameAgentSessionRequest, SandboxSizeBody,
+ SessionStatusDto, SetAgentSessionArchivedRequest, WithAgentSessionId,
};
use claude_cloud_agents::inbound::auth as claude_auth;
use utoipa::{
@@ -82,6 +82,7 @@ impl Modify for SecurityAddon {
axum_router::pull_requests::sessions_for_pull_request,
axum_router::pull_requests::sessions_for_pull_requests,
axum_router::get_agent_session_log_handler,
+ axum_router::get_agent_session_folded_log_handler,
axum_router::control_agent_session_handler,
axum_router::get_agent_session_queue_handler,
axum_router::edit_queued_action_handler,
@@ -141,6 +142,7 @@ impl Modify for SecurityAddon {
PullRequestLinkSource,
SessionStatusDto,
AgentSessionLogResponse,
+ AgentSessionFoldedLogResponse,
AgentSessionLogEntryDto,
SessionBot,
LogFrameDto,