@mitralab.io/sdk-core 0.3.11 → 0.3.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -543,6 +543,17 @@ interface AgentMessageListOptions extends PageOptions {
543
543
  include?: "plan";
544
544
  /** Id of a message: only the rows recorded before it, so the next page back holds still. */
545
545
  before?: string;
546
+ /**
547
+ * `root` asks only for the rows of the chat itself, with every kind, and the page counts only
548
+ * them: a subagent's rows no longer push the chat out of the newest page. A Copilot without it
549
+ * ignores it and answers every thread.
550
+ */
551
+ thread?: "root";
552
+ /**
553
+ * The `toolId` of the tool call that spawned a subagent: only that subagent's rows. A Copilot
554
+ * without it ignores it and answers every thread.
555
+ */
556
+ parentToolId?: string;
546
557
  }
547
558
  type AppColor = {
548
559
  type: "SOLID";
@@ -1126,7 +1137,7 @@ interface IntegrationExecution {
1126
1137
  source: string | null;
1127
1138
  createdAt: string;
1128
1139
  }
1129
- type CopilotProvider = "ANTHROPIC" | "OPENAI" | (string & {});
1140
+ type CopilotProvider = "ANTHROPIC" | "OPENAI" | "GOOGLE" | (string & {});
1130
1141
  /** Execution runtime a chat is born on. Absent means the Copilot server default. */
1131
1142
  type AgentTaskRuntime = "T3" | "RUNNER";
1132
1143
  /** Credential scope a call or a chat resolves against. Absent means the Copilot server default. */
@@ -2481,6 +2492,13 @@ interface NewAgentTaskSessionOptions {
2481
2492
  interface ExistingAgentTaskSessionOptions {
2482
2493
  taskId: string;
2483
2494
  transport?: AgentSessionTransport;
2495
+ /**
2496
+ * With the session open for this task in `error`, closes it and opens a new one, as a "try
2497
+ * again" does. A session in any other status is returned as is. Without it a failed session
2498
+ * keeps being returned until it is closed, so a screen that asks for the session on every
2499
+ * render does not reopen it in a loop.
2500
+ */
2501
+ reopen?: boolean;
2484
2502
  }
2485
2503
  type AgentTaskSessionOptions = NewAgentTaskSessionOptions | ExistingAgentTaskSessionOptions;
2486
2504
  interface AgentSendOptions {
@@ -2493,6 +2511,12 @@ interface AgentSendOptions {
2493
2511
  * `resumeQueue`. With no turn running the message starts one.
2494
2512
  */
2495
2513
  mode?: "queue" | "steer";
2514
+ /**
2515
+ * The id to send the message with, in place of a new one: for a layer that held the message
2516
+ * before it reached the session and already showed the person this id. It must not have gone
2517
+ * out before, since the Copilot does not dedupe by it.
2518
+ */
2519
+ clientMessageId?: string;
2496
2520
  }
2497
2521
  interface AgentSendAndWaitOptions extends AgentSendOptions {
2498
2522
  signal?: AbortSignal;
@@ -2512,7 +2536,7 @@ interface AgentBackgroundTask {
2512
2536
  /** The subagent's own thread, when it has one. */
2513
2537
  childThreadId?: string;
2514
2538
  }
2515
- interface AgentQueueItem extends AgentSendOptions {
2539
+ interface AgentQueueItem extends Omit<AgentSendOptions, "clientMessageId"> {
2516
2540
  /** The `clientMessageId` the message went out with: what `send` returned for it. */
2517
2541
  id: string;
2518
2542
  text: string;
@@ -2690,6 +2714,12 @@ type AgentTimelineItem = ({
2690
2714
  /** On the tool call that spawned a subagent: its last state, as the box's `subagentUpdate`. */
2691
2715
  subagent?: Partial<AgentSubagentFrame>;
2692
2716
  } & AgentTimelineItemIdentity);
2717
+ interface AgentSubagentHistory {
2718
+ items: readonly AgentTimelineItem[];
2719
+ hasOlder: boolean;
2720
+ /** The oldest row read, to pass as `before` for the page before this one; absent on none. */
2721
+ before?: string;
2722
+ }
2693
2723
  interface AgentTurnResult {
2694
2724
  task: AgentTask;
2695
2725
  content: string;
@@ -2751,6 +2781,17 @@ interface AgentTaskSessionEventMap {
2751
2781
  * that does not wait for the answer can close it or return.
2752
2782
  */
2753
2783
  accepted: Record<string, never>;
2784
+ /**
2785
+ * A message this session sent did not reach the server within `deliveryDelayMs` of the send
2786
+ * (the network is down, or the server does not answer): `delayed`, then `sent` when it gets
2787
+ * there or `failed` when it cannot go, which also comes as `error`. Only a delayed message has
2788
+ * this event. A delayed message is not dropped and goes out once, so it must not be sent again:
2789
+ * the Copilot does not dedupe by `clientMessageId`, and a second send is a second message.
2790
+ */
2791
+ delivery: {
2792
+ clientMessageId: string;
2793
+ state: "delayed" | "sent" | "failed";
2794
+ };
2754
2795
  cancelled: Record<string, never>;
2755
2796
  /** T3's queue of the chat changed: a message entered it, moved, or left it. */
2756
2797
  queueChange: {
@@ -2864,12 +2905,26 @@ interface AgentTaskSession {
2864
2905
  */
2865
2906
  readonly hasOlder: boolean;
2866
2907
  /**
2867
- * Reads the page before the oldest row `history` holds, with the size `loadHistory` used, and
2868
- * puts it before `history`, in the box's order. Resolves with the items it added (none when
2869
- * there is nothing older) and emits `historyLoaded`. A read still running when `history` is
2870
- * replaced resolves with nothing.
2908
+ * Reads the page before the oldest row `history` holds, with `limit` or else the size
2909
+ * `loadHistory` used, and puts it before `history`, in the box's order. A page that starts in
2910
+ * the middle of a turn is read on back to the person's message that opened it, so `history`
2911
+ * never starts inside a turn. Resolves with the items it added (none when there is nothing
2912
+ * older) and emits `historyLoaded`. A read still running when `history` is replaced resolves
2913
+ * with nothing.
2871
2914
  */
2872
- loadOlder(): Promise<readonly AgentTimelineItem[]>;
2915
+ loadOlder(options?: {
2916
+ limit?: number;
2917
+ }): Promise<readonly AgentTimelineItem[]>;
2918
+ /**
2919
+ * Reads the pieces of the subagent the tool call `toolId` spawned, which `history` leaves out:
2920
+ * the newest `limit` rows (the Copilot's page size without it), or the ones before `before`.
2921
+ * Resolves with them in the box's order, whether there are older ones, and the `before` that
2922
+ * reads the page before this one.
2923
+ */
2924
+ loadSubagent(toolId: string, options?: {
2925
+ limit?: number;
2926
+ before?: string;
2927
+ }): Promise<AgentSubagentHistory>;
2873
2928
  /** Changes the text of a queued message (T3's `queued-run.edit`); only the box channel takes it. */
2874
2929
  editQueueItem(id: string, text: string): void;
2875
2930
  /** Takes a message out of the queue (T3's `queued-run.cancel`); only the box channel takes it. */
@@ -2905,6 +2960,11 @@ interface AgentTaskSessionManagerOptions {
2905
2960
  eventSource: AgentTaskEventSource;
2906
2961
  /** Where the box channel may live and how to dial it outside a browser. */
2907
2962
  directChannel?: AgentDirectChannelOptions;
2963
+ /**
2964
+ * How long a message may take to reach the server before the session emits `delivery` with
2965
+ * `delayed`. 20 s by default: past a cold box, whose channel takes 5 to 10 s to open.
2966
+ */
2967
+ deliveryDelayMs?: number;
2908
2968
  }
2909
2969
  declare function toAgentTimelineItem(message: AgentMessage): AgentTimelineItem;
2910
2970
  declare function createAgentTaskSessionManager(options: AgentTaskSessionManagerOptions): AgentTaskSessionManager;
@@ -3093,4 +3153,4 @@ declare function expectPage<T extends object>(value: unknown, context: string, e
3093
3153
  declare function expectLegacyPage<T extends object>(value: unknown, context: string, errors?: SdkCoreErrorFactory, validateItem?: (value: unknown, context: string, errors: SdkCoreErrorFactory) => T): LegacyPage<T>;
3094
3154
  declare function expectEmpty(value: unknown, context: string, errors?: SdkCoreErrorFactory): void;
3095
3155
 
3096
- export { API_KEY_EXCHANGE_PATH, type AgentBackgroundTask, type AgentBulkDeleteResult, type AgentConnection, type AgentConnectionCreateInput, type AgentConnectionCustomProvider, type AgentConnectionCustomProviderInput, type AgentConnectionsModule, type AgentCredentialOptions, type AgentCredentialScope, type AgentCredentialsModule, type AgentDefinition, type AgentDirectChannelOptions, type AgentFetch, type AgentFetchResponse, type AgentHistoryCursor, type AgentInput, type AgentMessage, type AgentMessageListOptions, type AgentModel, type AgentNotification, type AgentPieceIdentity, type AgentPlan, type AgentPlanStep, type AgentProviderUsage, type AgentQueueItem, type AgentReadyProvider, type AgentSendAndWaitOptions, type AgentSendOptions, type AgentSessionTransport, type AgentSubagent, type AgentSubagentFrame, type AgentSubagentStatus, type AgentTask, type AgentTaskChannel, type AgentTaskCreateInput, type AgentTaskEvent, type AgentTaskEventConnection, type AgentTaskEventObserver, type AgentTaskEventSource, type AgentTaskInput, type AgentTaskLastTurn, type AgentTaskListOptions, type AgentTaskRuntime, type AgentTaskSession, type AgentTaskSessionEventMap, type AgentTaskSessionManager, type AgentTaskSessionManagerOptions, type AgentTaskSessionOptions, type AgentTaskSessionStatus, type AgentTaskTurn, AgentTaskTurnError, type AgentTaskTurnStateEntry, type AgentTasksModule, type AgentTasksWithSessions, type AgentTimelineItem, type AgentTimelineItemIdentity, type AgentToolEvent, type AgentTurnCompaction, type AgentTurnEndedEvent, type AgentTurnEvent, type AgentTurnEventCompaction, type AgentTurnEventUsage, type AgentTurnResult, type AgentTurnStartedEvent, type AgentTurnUsage, type AgentTurnUsageRequest, type AgentUpdateItem, type AgentWebSocket, type AgentWebSocketConstructor, type AgentsModule, type AiProviders, type AiProvidersModule, type ApiKeyExchangeCaller, type AppColor, type AppContext, type AppCreateInput, type AppDefinition, type AppDeploy, type AppDomain, type AppFiles, type AppGetOptions, type AppListOptions, type AppMember, type AppPublishOptions, type AppSummary, type AppUpdateInput, type AppVersion, type AppVersionStatus, type AppsModule, type AuthModule, type AuthenticationResult, type BatchExecution, type BatchStatementResult, type BulkUnsubscribeResult, type ColumnInput, type ConnectionConfig, type ConnectionConfigResponse, type ConnectionTestResult, type ContextModule, type ContextModuleDependencies, type CopilotProvider, type CredentialStatus, type CredentialUsage, type CredentialUsageWindow, type CustomQueriesModule, type CustomQueryDefinition, type CustomQueryInput, type CustomQuerySummary, type CustomQueryUpdateInput, type DataSourceBulkItemResult, type DataSourceBulkResult, type DataSourceCreateInput, type DataSourceDbType, type DataSourceDefinition, type DataSourceInstanceType, type DataSourceUpdateInput, type DataSourcesModule, type DdlStatement, type DeviceAuthorization, type DmlStatement, type EmptyFunctionInput, type EntitiesModule, type EntitiesProxy, type EntityListOptions, type EntityListResponse, type EntityTable, type ExistingAgentTaskSessionOptions, type FileCreator, type FileDownloadOptions, type FileKind, type FileMetadata, type FileReadUrl, type FileReadUrlItem, type FileReadUrlOptions, type FileReadUrls, type FileStatus, FileTransferError, type FileTransferErrorDetails, type FileTransferStep, type FileUpload, type FileUploadInput, type FileUploadOptions, type FileVisibility, type FilesFetch, type FilesFetchResponse, type FilesModule, type FilesModuleOptions, type FunctionBulkCreateInput, type FunctionBulkDeleteInput, type FunctionBulkDeleteResult, type FunctionBulkPatchInput, type FunctionBulkPatchItem, type FunctionBulkUpdateItem, type FunctionCreateInput, type FunctionDefinition, type FunctionExecution, type FunctionListOptions, type FunctionPatchInput, type FunctionRuntime, type FunctionSecrets, type FunctionSummary, type FunctionUpdateInput, type FunctionVersion, type FunctionVersionListOptions, type FunctionVisibility, type FunctionsAdminModule, type FunctionsModule, type FunctionsModuleOptions, type HttpMethod, type ImportColumnMapping, type ImportDefinition, type ImportExecution, type ImportExecutionListOptions, type ImportInput, type ImportProcessing, type ImportSchedule, type ImportSource, type ImportSourceResponse, type ImportTarget, type ImportsModule, type IncludedAiQuota, type IncludedAiQuotaWindow, type IntegrationAdminModule, type IntegrationConnectionStatus, type IntegrationCredentialRule, type IntegrationExecution, type IntegrationFieldSchema, type IntegrationFieldSchemaInput, type IntegrationLoginConfig, type IntegrationModule, type IntegrationProxyMode, type IntegrationRequestConfig, type IntegrationResource, type IntegrationResourceInput, type IntegrationResourceParam, type IntegrationResourceSummary, type IntegrationResourceUpdateInput, type IntegrationResourcesModule, type IntegrationTemplate, type IntegrationTemplateSummary, type IntegrationTemplateType, type IntegrationTemplatesModule, type IntegrationTokenExtraction, type InviteAppUserInput, type InvocationType, type JsonValue, type LegacyPage, type ListTablesOptions, type ListTemplateConfigsOptions, type ManagedAiProfile, type MembersModule, type MessageAccepted, type MessengerModule, type NewAgentTaskSessionOptions, type OAuthExchangeInput, type OAuthStartResult, type OpencodeAiProvider, type Page, type PageOptions, type PlanPrice, type ProviderCredentialStatus, type ProxyInput, type ProxyResult, type PublicFunctionAsyncResult, type PublicFunctionResult, type PublicFunctionsModule, type QueriesModule, type QueryParamPrimitive, type QueryParamValue, type QueryResult, type SchemaModule, type SchemaScope, type SchemaTables, type SdkCore, SdkCoreConfigurationError, type SdkCoreErrorFactory, type SdkCoreOptions, SdkCoreResponseError, type SdkCoreTransports, type SendEmailInput, type SqlModule, type TableColumn, type TableDefinition, type TableForeignKey, type TemplateConfig, type TemplateConfigBulkItemResult, type TemplateConfigBulkResult, type TemplateConfigCreateInput, type TemplateConfigPage, type TemplateConfigSummary, type TemplateConfigUpdateInput, type Tenant, type TestCredentialsInput, type Transport, type TransportRequestOptions, type User, type UserPlan, type WorkflowDefinition, type WorkflowExecution, type WorkflowInput, type WorkflowSummary, type WorkflowsModule, appAccessTokenPath, createAgentConnectionsModule, createAgentCredentialsModule, createAgentTaskSessionManager, createAgentTasksModule, createAgentsModule, createAiProvidersModule, createAppsModule, createAuthModule, createContextModule, createCustomQueriesModule, createDataSourcesModule, createEntitiesModule, createFilesModule, createFunctionsAdminModule, createFunctionsModule, createImportsModule, createIntegrationAdminModule, createIntegrationModule, createIntegrationResourcesModule, createIntegrationTemplatesModule, createMembersModule, createMessengerModule, createPublicFunctionsModule, createQueriesModule, createSchemaModule, createSdkCore, createSqlModule, createWorkflowsModule, defaultSdkCoreErrorFactory, encodePathSegment, expectEmpty, expectLegacyPage, expectNullableObject, expectObject, expectObjectArray, expectPage, expectStringArray, isAgentTurnEvent, isWorkspaceSession, readTokenAppId, readTokenExpiry, resolveApiKeyToken, toAgentTimelineItem, tokenAuthorizesApp, withAgentTaskSessions };
3156
+ export { API_KEY_EXCHANGE_PATH, type AgentBackgroundTask, type AgentBulkDeleteResult, type AgentConnection, type AgentConnectionCreateInput, type AgentConnectionCustomProvider, type AgentConnectionCustomProviderInput, type AgentConnectionsModule, type AgentCredentialOptions, type AgentCredentialScope, type AgentCredentialsModule, type AgentDefinition, type AgentDirectChannelOptions, type AgentFetch, type AgentFetchResponse, type AgentHistoryCursor, type AgentInput, type AgentMessage, type AgentMessageListOptions, type AgentModel, type AgentNotification, type AgentPieceIdentity, type AgentPlan, type AgentPlanStep, type AgentProviderUsage, type AgentQueueItem, type AgentReadyProvider, type AgentSendAndWaitOptions, type AgentSendOptions, type AgentSessionTransport, type AgentSubagent, type AgentSubagentFrame, type AgentSubagentHistory, type AgentSubagentStatus, type AgentTask, type AgentTaskChannel, type AgentTaskCreateInput, type AgentTaskEvent, type AgentTaskEventConnection, type AgentTaskEventObserver, type AgentTaskEventSource, type AgentTaskInput, type AgentTaskLastTurn, type AgentTaskListOptions, type AgentTaskRuntime, type AgentTaskSession, type AgentTaskSessionEventMap, type AgentTaskSessionManager, type AgentTaskSessionManagerOptions, type AgentTaskSessionOptions, type AgentTaskSessionStatus, type AgentTaskTurn, AgentTaskTurnError, type AgentTaskTurnStateEntry, type AgentTasksModule, type AgentTasksWithSessions, type AgentTimelineItem, type AgentTimelineItemIdentity, type AgentToolEvent, type AgentTurnCompaction, type AgentTurnEndedEvent, type AgentTurnEvent, type AgentTurnEventCompaction, type AgentTurnEventUsage, type AgentTurnResult, type AgentTurnStartedEvent, type AgentTurnUsage, type AgentTurnUsageRequest, type AgentUpdateItem, type AgentWebSocket, type AgentWebSocketConstructor, type AgentsModule, type AiProviders, type AiProvidersModule, type ApiKeyExchangeCaller, type AppColor, type AppContext, type AppCreateInput, type AppDefinition, type AppDeploy, type AppDomain, type AppFiles, type AppGetOptions, type AppListOptions, type AppMember, type AppPublishOptions, type AppSummary, type AppUpdateInput, type AppVersion, type AppVersionStatus, type AppsModule, type AuthModule, type AuthenticationResult, type BatchExecution, type BatchStatementResult, type BulkUnsubscribeResult, type ColumnInput, type ConnectionConfig, type ConnectionConfigResponse, type ConnectionTestResult, type ContextModule, type ContextModuleDependencies, type CopilotProvider, type CredentialStatus, type CredentialUsage, type CredentialUsageWindow, type CustomQueriesModule, type CustomQueryDefinition, type CustomQueryInput, type CustomQuerySummary, type CustomQueryUpdateInput, type DataSourceBulkItemResult, type DataSourceBulkResult, type DataSourceCreateInput, type DataSourceDbType, type DataSourceDefinition, type DataSourceInstanceType, type DataSourceUpdateInput, type DataSourcesModule, type DdlStatement, type DeviceAuthorization, type DmlStatement, type EmptyFunctionInput, type EntitiesModule, type EntitiesProxy, type EntityListOptions, type EntityListResponse, type EntityTable, type ExistingAgentTaskSessionOptions, type FileCreator, type FileDownloadOptions, type FileKind, type FileMetadata, type FileReadUrl, type FileReadUrlItem, type FileReadUrlOptions, type FileReadUrls, type FileStatus, FileTransferError, type FileTransferErrorDetails, type FileTransferStep, type FileUpload, type FileUploadInput, type FileUploadOptions, type FileVisibility, type FilesFetch, type FilesFetchResponse, type FilesModule, type FilesModuleOptions, type FunctionBulkCreateInput, type FunctionBulkDeleteInput, type FunctionBulkDeleteResult, type FunctionBulkPatchInput, type FunctionBulkPatchItem, type FunctionBulkUpdateItem, type FunctionCreateInput, type FunctionDefinition, type FunctionExecution, type FunctionListOptions, type FunctionPatchInput, type FunctionRuntime, type FunctionSecrets, type FunctionSummary, type FunctionUpdateInput, type FunctionVersion, type FunctionVersionListOptions, type FunctionVisibility, type FunctionsAdminModule, type FunctionsModule, type FunctionsModuleOptions, type HttpMethod, type ImportColumnMapping, type ImportDefinition, type ImportExecution, type ImportExecutionListOptions, type ImportInput, type ImportProcessing, type ImportSchedule, type ImportSource, type ImportSourceResponse, type ImportTarget, type ImportsModule, type IncludedAiQuota, type IncludedAiQuotaWindow, type IntegrationAdminModule, type IntegrationConnectionStatus, type IntegrationCredentialRule, type IntegrationExecution, type IntegrationFieldSchema, type IntegrationFieldSchemaInput, type IntegrationLoginConfig, type IntegrationModule, type IntegrationProxyMode, type IntegrationRequestConfig, type IntegrationResource, type IntegrationResourceInput, type IntegrationResourceParam, type IntegrationResourceSummary, type IntegrationResourceUpdateInput, type IntegrationResourcesModule, type IntegrationTemplate, type IntegrationTemplateSummary, type IntegrationTemplateType, type IntegrationTemplatesModule, type IntegrationTokenExtraction, type InviteAppUserInput, type InvocationType, type JsonValue, type LegacyPage, type ListTablesOptions, type ListTemplateConfigsOptions, type ManagedAiProfile, type MembersModule, type MessageAccepted, type MessengerModule, type NewAgentTaskSessionOptions, type OAuthExchangeInput, type OAuthStartResult, type OpencodeAiProvider, type Page, type PageOptions, type PlanPrice, type ProviderCredentialStatus, type ProxyInput, type ProxyResult, type PublicFunctionAsyncResult, type PublicFunctionResult, type PublicFunctionsModule, type QueriesModule, type QueryParamPrimitive, type QueryParamValue, type QueryResult, type SchemaModule, type SchemaScope, type SchemaTables, type SdkCore, SdkCoreConfigurationError, type SdkCoreErrorFactory, type SdkCoreOptions, SdkCoreResponseError, type SdkCoreTransports, type SendEmailInput, type SqlModule, type TableColumn, type TableDefinition, type TableForeignKey, type TemplateConfig, type TemplateConfigBulkItemResult, type TemplateConfigBulkResult, type TemplateConfigCreateInput, type TemplateConfigPage, type TemplateConfigSummary, type TemplateConfigUpdateInput, type Tenant, type TestCredentialsInput, type Transport, type TransportRequestOptions, type User, type UserPlan, type WorkflowDefinition, type WorkflowExecution, type WorkflowInput, type WorkflowSummary, type WorkflowsModule, appAccessTokenPath, createAgentConnectionsModule, createAgentCredentialsModule, createAgentTaskSessionManager, createAgentTasksModule, createAgentsModule, createAiProvidersModule, createAppsModule, createAuthModule, createContextModule, createCustomQueriesModule, createDataSourcesModule, createEntitiesModule, createFilesModule, createFunctionsAdminModule, createFunctionsModule, createImportsModule, createIntegrationAdminModule, createIntegrationModule, createIntegrationResourcesModule, createIntegrationTemplatesModule, createMembersModule, createMessengerModule, createPublicFunctionsModule, createQueriesModule, createSchemaModule, createSdkCore, createSqlModule, createWorkflowsModule, defaultSdkCoreErrorFactory, encodePathSegment, expectEmpty, expectLegacyPage, expectNullableObject, expectObject, expectObjectArray, expectPage, expectStringArray, isAgentTurnEvent, isWorkspaceSession, readTokenAppId, readTokenExpiry, resolveApiKeyToken, toAgentTimelineItem, tokenAuthorizesApp, withAgentTaskSessions };
package/dist/index.js CHANGED
@@ -1825,7 +1825,9 @@ function createAgentTasksModule(transport, errors = defaultSdkCoreErrorFactory)
1825
1825
  sort: options.sort,
1826
1826
  kinds: options.kinds,
1827
1827
  include: options.include,
1828
- before: options.before
1828
+ before: options.before,
1829
+ thread: options.thread,
1830
+ parentToolId: options.parentToolId
1829
1831
  }
1830
1832
  }),
1831
1833
  context,
@@ -4539,7 +4541,15 @@ var AgentDirectChannel = class {
4539
4541
 
4540
4542
  // src/agentSession.ts
4541
4543
  var CANCEL_SAFETY_MS = 1e4;
4544
+ var DELIVERY_DELAY_MS = 2e4;
4545
+ var MAX_TURN_START_READS = 10;
4542
4546
  var RECONCILE_DELAY_MS = 1e3;
4547
+ var ROOT_HISTORY = {
4548
+ sort: "createdAt,desc",
4549
+ kinds: "all",
4550
+ include: "plan",
4551
+ thread: "root"
4552
+ };
4543
4553
  var ENDED_POLLS_BEFORE_NEWEST = 3;
4544
4554
  var TURN_TAIL_TYPES = /* @__PURE__ */ new Set([
4545
4555
  "textDelta",
@@ -4711,6 +4721,10 @@ function rowOrHeld(held, row, liveComparable) {
4711
4721
  function hasOlderRows(page) {
4712
4722
  return page.page.totalPages > page.page.number + 1;
4713
4723
  }
4724
+ function pageWithOlder(content, older) {
4725
+ const size = content.length;
4726
+ return { content, page: { size, totalElements: size, totalPages: older ? 2 : 1, number: 0 } };
4727
+ }
4714
4728
  function isChatRow(message) {
4715
4729
  return (message.type === "TEXT" || message.type === "ERROR" || message.type === "TOOL_USE") && message.parentToolId === void 0;
4716
4730
  }
@@ -4803,6 +4817,12 @@ function toAgentTimelineItem(message) {
4803
4817
  ...parentToolIdOf(message.parentToolId)
4804
4818
  };
4805
4819
  }
4820
+ function parentToolIdOfItem(item) {
4821
+ return item.kind === "tool" ? item.tool.parentToolId : item.parentToolId;
4822
+ }
4823
+ function rootItemsOf(messages) {
4824
+ return messages.map(toAgentTimelineItem).filter((item) => parentToolIdOfItem(item) === void 0);
4825
+ }
4806
4826
  function liveAtOf(event) {
4807
4827
  return new Date(typeof event.timestamp === "number" ? event.timestamp : Date.now()).toISOString();
4808
4828
  }
@@ -4816,13 +4836,17 @@ function createAgentTaskSessionManager(options) {
4816
4836
  session(requested) {
4817
4837
  if ("taskId" in requested) {
4818
4838
  const current = sessions.get(requested.taskId);
4819
- if (current && current.status !== "closed") return current;
4839
+ if (current && current.status !== "closed") {
4840
+ if (!requested.reopen || current.status !== "error") return current;
4841
+ current.close();
4842
+ }
4820
4843
  }
4821
4844
  const sessionOptions = "create" in requested && requested.agentId && !requested.runtime && channel.canDial(requested.transport) ? { ...requested, runtime: "T3" } : requested;
4822
4845
  const session = new CoreAgentTaskSession(sessionOptions, {
4823
4846
  tasks: options.tasks,
4824
4847
  eventSource: options.eventSource,
4825
4848
  channel,
4849
+ deliveryDelayMs: options.deliveryDelayMs ?? DELIVERY_DELAY_MS,
4826
4850
  onTaskId: (taskId, value) => sessions.set(taskId, value),
4827
4851
  onClose: (taskId, value) => {
4828
4852
  if (sessions.get(taskId) === value) sessions.delete(taskId);
@@ -4915,6 +4939,9 @@ var CoreAgentTaskSession = class {
4915
4939
  openingCursor;
4916
4940
  historyLimit;
4917
4941
  _hasOlder = false;
4942
+ // The oldest row read so far, kept or not: a page of a Copilot that ignores `thread=root` can
4943
+ // be all subagent rows, and reading before the oldest kept row would read it again (#162).
4944
+ olderCursor;
4918
4945
  // Moves whenever `history` is replaced, so a `loadOlder` still reading drops what it read.
4919
4946
  historyGeneration = 0;
4920
4947
  // Whether the box the channel follows counts in the log of the history's rows. A box whose hello
@@ -4924,6 +4951,8 @@ var CoreAgentTaskSession = class {
4924
4951
  // flag above starts over at each reread, and a page from the old log may come again.
4925
4952
  channelLog;
4926
4953
  olderRead = null;
4954
+ // Messages sent and not at the server yet, by `clientMessageId`, each with its `delivery` clock.
4955
+ deliveries = /* @__PURE__ */ new Map();
4927
4956
  get taskId() {
4928
4957
  return this._taskId;
4929
4958
  }
@@ -4952,7 +4981,7 @@ var CoreAgentTaskSession = class {
4952
4981
  this.requireOpen();
4953
4982
  if (!prompt.trim()) return void 0;
4954
4983
  if (this.isBusy()) return this.steer(prompt, options);
4955
- const clientMessageId = newClientMessageId();
4984
+ const clientMessageId = options.clientMessageId || newClientMessageId();
4956
4985
  this.startDispatch(prompt, options, clientMessageId);
4957
4986
  return clientMessageId;
4958
4987
  }
@@ -4964,13 +4993,19 @@ var CoreAgentTaskSession = class {
4964
4993
  const sendOptions = {
4965
4994
  ...options.agentType ? { agentType: options.agentType } : {},
4966
4995
  ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {},
4967
- ...options.mode ? { mode: options.mode } : {}
4996
+ ...options.mode ? { mode: options.mode } : {},
4997
+ ...options.clientMessageId ? { clientMessageId: options.clientMessageId } : {}
4968
4998
  };
4969
4999
  if (this.isBusy()) {
4970
5000
  this.steer(prompt, sendOptions, waiter);
4971
5001
  return waiter.promise;
4972
5002
  }
4973
- this.startDispatch(prompt, sendOptions, newClientMessageId(), waiter);
5003
+ this.startDispatch(
5004
+ prompt,
5005
+ sendOptions,
5006
+ sendOptions.clientMessageId || newClientMessageId(),
5007
+ waiter
5008
+ );
4974
5009
  return waiter.promise;
4975
5010
  }
4976
5011
  async cancel() {
@@ -5015,14 +5050,14 @@ var CoreAgentTaskSession = class {
5015
5050
  }
5016
5051
  async loadHistory(options = {}) {
5017
5052
  if (!this._taskId) return [];
5053
+ const generation = this.historyGeneration;
5018
5054
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
5019
5055
  ...options.limit !== void 0 ? { size: options.limit } : {},
5020
- sort: "createdAt,desc",
5021
- kinds: "all",
5022
- include: "plan"
5056
+ ...ROOT_HISTORY
5023
5057
  });
5024
5058
  this.historyLimit = options.limit;
5025
- await this.rereadHistory(page);
5059
+ const whole = this.reachesHistory(page) ? page : await this.backToTurnStart(page, options.limit, generation);
5060
+ if (whole) await this.rereadHistory(whole);
5026
5061
  const history = this.history;
5027
5062
  this.emit("historyLoaded", { history });
5028
5063
  return history;
@@ -5030,34 +5065,25 @@ var CoreAgentTaskSession = class {
5030
5065
  get hasOlder() {
5031
5066
  return this._hasOlder;
5032
5067
  }
5033
- loadOlder() {
5068
+ loadOlder(options = {}) {
5034
5069
  if (this.olderRead?.generation !== this.historyGeneration) {
5035
5070
  const generation = this.historyGeneration;
5036
- const promise = this.readOlder(generation).finally(() => {
5071
+ const size = options.limit ?? this.historyLimit;
5072
+ const promise = this.readOlder(generation, size).finally(() => {
5037
5073
  if (this.olderRead?.promise === promise) this.olderRead = null;
5038
5074
  });
5039
5075
  this.olderRead = { generation, promise };
5040
5076
  }
5041
5077
  return this.olderRead.promise;
5042
5078
  }
5043
- async readOlder(generation) {
5044
- const oldest = oldestRowOf(this._history);
5045
- if (!this._taskId || !this._hasOlder || !oldest) return [];
5046
- let page;
5047
- try {
5048
- page = await this.dependencies.tasks.listMessages(this._taskId, {
5049
- before: oldest.id,
5050
- ...this.historyLimit !== void 0 ? { size: this.historyLimit } : {},
5051
- sort: "createdAt,desc",
5052
- kinds: "all",
5053
- include: "plan"
5054
- });
5055
- } catch (error) {
5056
- if (generation !== this.historyGeneration || this.isClosed()) return [];
5057
- throw error;
5058
- }
5059
- if (generation !== this.historyGeneration || this.isClosed()) return [];
5060
- const rows = [...page.content].reverse().map(toAgentTimelineItem);
5079
+ async readOlder(generation, size) {
5080
+ const before = this.olderCursor ?? oldestRowOf(this._history)?.id;
5081
+ if (!this._taskId || !this._hasOlder || !before) return [];
5082
+ const page = await this.readBefore(before, size, generation);
5083
+ const whole = page && await this.backToTurnStart(page, size, generation);
5084
+ if (!whole) return [];
5085
+ this.olderCursor = whole.content[whole.content.length - 1]?.id ?? before;
5086
+ const rows = rootItemsOf([...whole.content].reverse());
5061
5087
  const rowsLog = [...rows].reverse().find((item) => item.boxLog !== void 0)?.boxLog;
5062
5088
  const liveComparable = this.rowsInChannelLog && (this.channelLog === void 0 || rowsLog === void 0 || rowsLog === this.channelLog);
5063
5089
  const taken = /* @__PURE__ */ new Set();
@@ -5069,11 +5095,73 @@ var CoreAgentTaskSession = class {
5069
5095
  taken.add(held);
5070
5096
  return rowOrHeld(held, row, liveComparable);
5071
5097
  });
5072
- this._hasOlder = hasOlderRows(page);
5098
+ this._hasOlder = hasOlderRows(whole);
5073
5099
  this._history = [...older, ...this._history.filter((item) => !taken.has(item))];
5074
5100
  this.emit("historyLoaded", { history: this.history });
5075
5101
  return older;
5076
5102
  }
5103
+ async loadSubagent(toolId, options = {}) {
5104
+ if (!this._taskId) return { items: [], hasOlder: false };
5105
+ const page = await this.dependencies.tasks.listMessages(this._taskId, {
5106
+ ...options.limit !== void 0 ? { size: options.limit } : {},
5107
+ ...options.before !== void 0 ? { before: options.before } : {},
5108
+ sort: "createdAt,desc",
5109
+ kinds: "all",
5110
+ include: "plan",
5111
+ parentToolId: toolId
5112
+ });
5113
+ const items = [...page.content].reverse().map(toAgentTimelineItem).filter((item) => parentToolIdOfItem(item) === toolId);
5114
+ const oldest = page.content[page.content.length - 1];
5115
+ return {
5116
+ items,
5117
+ hasOlder: hasOlderRows(page),
5118
+ ...oldest === void 0 ? {} : { before: oldest.id }
5119
+ };
5120
+ }
5121
+ // The rows recorded before `before`, or null once `history` was replaced or the session closed:
5122
+ // a read of a history since replaced resolves with nothing, as its success would.
5123
+ async readBefore(before, size, generation) {
5124
+ try {
5125
+ const page = await this.dependencies.tasks.listMessages(this._taskId, {
5126
+ before,
5127
+ ...size !== void 0 ? { size } : {},
5128
+ ...ROOT_HISTORY
5129
+ });
5130
+ return generation !== this.historyGeneration || this.isClosed() ? null : page;
5131
+ } catch (error) {
5132
+ if (generation !== this.historyGeneration || this.isClosed()) return null;
5133
+ throw error;
5134
+ }
5135
+ }
5136
+ // The Copilot pages by piece, so a page can start inside a turn, and without the person's
5137
+ // message that opened it a screen cannot tell the answer from the text between tools (Crew,
5138
+ // 0.3.9). The rows before it are read with the same size until that message, and what the last
5139
+ // read brought from before it is left for the next page. A steer is a person's message too: a
5140
+ // turn steered past a page boundary starts at the steer. Rows carry no turn id to do better.
5141
+ async backToTurnStart(page, size, generation) {
5142
+ let content = page.content;
5143
+ let last = page;
5144
+ let reads = 0;
5145
+ while (hasOlderRows(last) && reads < MAX_TURN_START_READS) {
5146
+ const oldest = content[content.length - 1];
5147
+ if (!oldest || oldest.sender === "USER") break;
5148
+ reads++;
5149
+ const older = await this.readBefore(oldest.id, size, generation);
5150
+ if (!older) return null;
5151
+ const known = new Set(content.map((message) => message.id));
5152
+ if (older.content.some((message) => known.has(message.id))) break;
5153
+ last = older;
5154
+ const start = older.content.findIndex((message) => message.sender === "USER");
5155
+ if (start >= 0) {
5156
+ const left = start + 1 < older.content.length;
5157
+ content = [...content, ...older.content.slice(0, start + 1)];
5158
+ return pageWithOlder(content, left || hasOlderRows(older));
5159
+ }
5160
+ if (older.content.length === 0) break;
5161
+ content = [...content, ...older.content];
5162
+ }
5163
+ return content === page.content ? page : pageWithOlder(content, hasOlderRows(last));
5164
+ }
5077
5165
  // A page that starts at a piece held live, with live pieces before it that no row of the page
5078
5166
  // takes, skipped rows the Copilot wrote between two rereads (more than a page of them): kept as
5079
5167
  // they are, those pieces never get their rows, and `loadOlder` only reads before the oldest row.
@@ -5092,9 +5180,7 @@ var CoreAgentTaskSession = class {
5092
5180
  older = await this.dependencies.tasks.listMessages(this._taskId, {
5093
5181
  before: oldest.id,
5094
5182
  ...this.historyLimit !== void 0 ? { size: this.historyLimit } : {},
5095
- sort: "createdAt,desc",
5096
- kinds: "all",
5097
- include: "plan"
5183
+ ...ROOT_HISTORY
5098
5184
  });
5099
5185
  } catch (error) {
5100
5186
  if (generation !== this.historyGeneration || this.isClosed()) return;
@@ -5106,10 +5192,14 @@ var CoreAgentTaskSession = class {
5106
5192
  }
5107
5193
  this.replaceHistory(current);
5108
5194
  }
5195
+ reachesHistory(page) {
5196
+ const oldest = rootItemsOf(page.content).pop();
5197
+ return oldest !== void 0 && this._history.some((item) => samePiece(item, oldest));
5198
+ }
5109
5199
  // Newest first, as the Copilot answers. Once rows before the page were read, a row the history
5110
5200
  // does not hold at all (one the session never heard) is still inside the gap.
5111
5201
  skipsRows(page, extended) {
5112
- const rows = page.content.map(toAgentTimelineItem);
5202
+ const rows = rootItemsOf(page.content);
5113
5203
  const first = rows[rows.length - 1];
5114
5204
  if (!first) return false;
5115
5205
  const anchor = this._history.findIndex((item) => samePiece(item, first));
@@ -5127,7 +5217,7 @@ var CoreAgentTaskSession = class {
5127
5217
  // `loadOlder` (#145). A page that does not reach the history it already has replaces it.
5128
5218
  replaceHistory(page) {
5129
5219
  const oldest = oldestRowOf(this._history)?.id;
5130
- const rows = [...page.content].reverse().map(toAgentTimelineItem);
5220
+ const rows = rootItemsOf([...page.content].reverse());
5131
5221
  const rowsLog = [...rows].reverse().find((item) => item.boxLog !== void 0)?.boxLog;
5132
5222
  const liveComparable = this.rowsInChannelLog && (this.channelLog === void 0 || rowsLog === void 0 || rowsLog === this.channelLog);
5133
5223
  this.rowsInChannelLog = true;
@@ -5135,7 +5225,10 @@ var CoreAgentTaskSession = class {
5135
5225
  const anchor = first ? this._history.findIndex((item) => samePiece(item, first)) : -1;
5136
5226
  const kept = anchor < 0 ? [] : this._history.slice(0, anchor).filter((item) => !rows.some((row) => samePiece(item, row)));
5137
5227
  const replaced = anchor < 0 ? this._history : this._history.slice(anchor);
5138
- if (anchor < 0) this._hasOlder = hasOlderRows(page);
5228
+ if (anchor < 0) {
5229
+ this._hasOlder = hasOlderRows(page);
5230
+ this.olderCursor = page.content[page.content.length - 1]?.id;
5231
+ }
5139
5232
  const used = /* @__PURE__ */ new Set();
5140
5233
  const merged = rows.map((row) => {
5141
5234
  const held = this._history.find((item) => !used.has(item) && samePiece(item, row));
@@ -5225,6 +5318,8 @@ var CoreAgentTaskSession = class {
5225
5318
  this.connection?.close();
5226
5319
  this.connection = null;
5227
5320
  this.recoveryGeneration += 1;
5321
+ for (const delivery of this.deliveries.values()) clearTimeout(delivery.timer);
5322
+ this.deliveries.clear();
5228
5323
  const closedError = new Error("Agent task session is closed.");
5229
5324
  this.activeWaiter?.reject(closedError);
5230
5325
  this.activeWaiter = void 0;
@@ -5252,6 +5347,7 @@ var CoreAgentTaskSession = class {
5252
5347
  }
5253
5348
  startDispatch(prompt, options, clientMessageId, waiter) {
5254
5349
  this.sentTexts.set(clientMessageId, prompt);
5350
+ this.watchDelivery(clientMessageId);
5255
5351
  this.dispatching = true;
5256
5352
  let handedOver;
5257
5353
  this.handOff = new Promise((resolve) => {
@@ -5265,6 +5361,9 @@ var CoreAgentTaskSession = class {
5265
5361
  this.setStatus("idle");
5266
5362
  }
5267
5363
  return false;
5364
+ }).then((sent) => {
5365
+ this.deliveryEnded(clientMessageId, sent ? "sent" : "failed");
5366
+ return sent;
5268
5367
  }).finally(() => {
5269
5368
  handedOver();
5270
5369
  if (this.dispatch === dispatch) {
@@ -5363,7 +5462,7 @@ var CoreAgentTaskSession = class {
5363
5462
  // session for a message that asks for another model, which would end that turn.
5364
5463
  steer(prompt, options, waiter) {
5365
5464
  const steered = {
5366
- clientMessageId: newClientMessageId(),
5465
+ clientMessageId: options.clientMessageId || newClientMessageId(),
5367
5466
  ...waiter ? { waiter } : {},
5368
5467
  taken: false
5369
5468
  };
@@ -5373,6 +5472,7 @@ var CoreAgentTaskSession = class {
5373
5472
  this.strayedSteers.push(steered);
5374
5473
  }
5375
5474
  this.sentTexts.set(steered.clientMessageId, prompt);
5475
+ this.watchDelivery(steered.clientMessageId);
5376
5476
  const input = messageInput(prompt, options);
5377
5477
  this.pendingSteers += 1;
5378
5478
  const handed = this.handOff.then(async () => {
@@ -5388,6 +5488,7 @@ var CoreAgentTaskSession = class {
5388
5488
  void handed.then(({ admitted }) => admitted).then((admitted) => {
5389
5489
  if (!admitted) {
5390
5490
  this.forgetSteer(steered);
5491
+ this.deliveryEnded(steered.clientMessageId, "failed");
5391
5492
  waiter?.reject(
5392
5493
  steered.refusal ?? new AgentTaskTurnError("The Agent box did not take the message.")
5393
5494
  );
@@ -5397,6 +5498,7 @@ var CoreAgentTaskSession = class {
5397
5498
  this.acceptOnce(steered.clientMessageId);
5398
5499
  }).catch((error) => {
5399
5500
  this.forgetSteer(steered);
5501
+ this.deliveryEnded(steered.clientMessageId, "failed");
5400
5502
  waiter?.reject(error);
5401
5503
  this.emitSendError(error);
5402
5504
  }).finally(() => {
@@ -5533,7 +5635,7 @@ var CoreAgentTaskSession = class {
5533
5635
  this.options.transport,
5534
5636
  historyCursor
5535
5637
  ).then((connection) => {
5536
- if (this.isClosed() || this._status === "error") {
5638
+ if (this.isClosed() || this._status === "error" && !this.dispatching) {
5537
5639
  connection.close();
5538
5640
  return;
5539
5641
  }
@@ -5577,9 +5679,7 @@ var CoreAgentTaskSession = class {
5577
5679
  if (!this._taskId) return;
5578
5680
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
5579
5681
  size: 100,
5580
- sort: "createdAt,desc",
5581
- kinds: "all",
5582
- include: "plan"
5682
+ ...ROOT_HISTORY
5583
5683
  });
5584
5684
  this.turnBaselineIds = new Set(page.content.map((message) => message.id));
5585
5685
  }
@@ -5587,9 +5687,7 @@ var CoreAgentTaskSession = class {
5587
5687
  if (!this._taskId) return false;
5588
5688
  const page = await this.dependencies.tasks.listMessages(this._taskId, {
5589
5689
  size: 100,
5590
- sort: "createdAt,desc",
5591
- kinds: "all",
5592
- include: "plan"
5690
+ ...ROOT_HISTORY
5593
5691
  });
5594
5692
  await this.rereadHistory(page);
5595
5693
  this.emit("historyLoaded", { history: this.history });
@@ -5909,6 +6007,7 @@ var CoreAgentTaskSession = class {
5909
6007
  if (ours) this.acceptOnce(id);
5910
6008
  }
5911
6009
  acceptOnce(id) {
6010
+ this.deliveryEnded(id, "sent");
5912
6011
  if (this.acceptedIds.includes(id)) return;
5913
6012
  this.acceptedIds.push(id);
5914
6013
  if (this.acceptedIds.length > 32) this.acceptedIds.shift();
@@ -6081,7 +6180,7 @@ var CoreAgentTaskSession = class {
6081
6180
  if (oldest?.sequence === void 0 || oldest.boxLog !== newest?.boxLog) return false;
6082
6181
  return sequence < oldest.sequence;
6083
6182
  }
6084
- liveText(event, payload, kind, parentToolId) {
6183
+ liveText(event, payload, kind) {
6085
6184
  const itemId = typeof payload?.itemId === "string" ? payload.itemId : void 0;
6086
6185
  if (itemId === void 0) return;
6087
6186
  const piece = itemDeltaOf(payload).itemDelta ?? (typeof payload?.text === "string" ? payload.text : "");
@@ -6095,8 +6194,7 @@ var CoreAgentTaskSession = class {
6095
6194
  text: piece,
6096
6195
  at: liveAtOf(event),
6097
6196
  itemId,
6098
- ...sequence === void 0 ? {} : { sequence },
6099
- ...parentToolIdOf(parentToolId)
6197
+ ...sequence === void 0 ? {} : { sequence }
6100
6198
  }),
6101
6199
  (item) => {
6102
6200
  const held = item.lastSequence ?? item.sequence;
@@ -6129,7 +6227,7 @@ var CoreAgentTaskSession = class {
6129
6227
  // An approval or a question T3 asks mid-turn enters where it came, with the frame's payload as
6130
6228
  // it came, as the Copilot records it (`APPROVAL` and `USER_INPUT_REQUEST` rows). It still
6131
6229
  // reaches the app as a `raw` event, as before.
6132
- liveRequest(event, payload, parentToolId) {
6230
+ liveRequest(event, payload) {
6133
6231
  if (!payload) return;
6134
6232
  const kind = event.type === "approval" ? "approval" : event.type === "notification" ? "notification" : "userInputRequest";
6135
6233
  const itemId = typeof payload.itemId === "string" ? payload.itemId : void 0;
@@ -6143,8 +6241,7 @@ var CoreAgentTaskSession = class {
6143
6241
  payload,
6144
6242
  at: liveAtOf(event),
6145
6243
  ...sequence === void 0 ? {} : { sequence },
6146
- ...itemId === void 0 ? {} : { itemId },
6147
- ...parentToolIdOf(parentToolId)
6244
+ ...itemId === void 0 ? {} : { itemId }
6148
6245
  };
6149
6246
  return kind === "notification" ? { ...item, kind, ...notificationFieldsOf(payload) } : { ...item, kind };
6150
6247
  },
@@ -6191,7 +6288,9 @@ var CoreAgentTaskSession = class {
6191
6288
  }
6192
6289
  // A child thread's frames are the subagent's conversation: they open no turn and settle no
6193
6290
  // message. Its text and tools still reach `delta`, `content` and `tool` as they did in 0.2.13,
6194
- // which knew no subagents, so an app that only bumps the version sees what it saw before.
6291
+ // which knew no subagents, so an app that only bumps the version sees what it saw before. None
6292
+ // enters `history`, which holds the chat's own thread as `thread=root` reads it back: the
6293
+ // subagent's pieces come from `loadSubagent`, and its approvals still reach `raw`.
6195
6294
  handleSubagentFrame(event, payload) {
6196
6295
  const parentToolId = payload.parentToolId;
6197
6296
  switch (event.type) {
@@ -6202,7 +6301,6 @@ var CoreAgentTaskSession = class {
6202
6301
  const kind = event.type === "thinking" ? "thinking" : "text";
6203
6302
  const identity = { ...itemDeltaOf(payload), ...pieceIdentityOf(event, payload) };
6204
6303
  if (kind === "text") this._content += delta;
6205
- this.liveText(event, payload, kind, parentToolId);
6206
6304
  this.emit("delta", { delta, kind, parentToolId, ...identity });
6207
6305
  this.emit("subagentDelta", { parentToolId, delta, kind, ...identity });
6208
6306
  break;
@@ -6213,15 +6311,10 @@ var CoreAgentTaskSession = class {
6213
6311
  ...toolEventOf(event, payload, event.type === "toolCall" ? "call" : "result"),
6214
6312
  parentToolId
6215
6313
  };
6216
- this.liveTool(tool, event);
6217
6314
  this.emit("tool", tool);
6218
6315
  this.emit("subagentTool", tool);
6219
6316
  break;
6220
6317
  }
6221
- case "approval":
6222
- case "user_input_request":
6223
- this.liveRequest(event, payload, parentToolId);
6224
- break;
6225
6318
  case "contextCompacted":
6226
6319
  this.emitCompaction(event, payload, parentToolId);
6227
6320
  break;
@@ -6372,6 +6465,29 @@ var CoreAgentTaskSession = class {
6372
6465
  }
6373
6466
  return waiter;
6374
6467
  }
6468
+ // A message waits in silence for whatever it needs before it leaves (the task, the channel, a
6469
+ // read of the history, the box's answer) when the network is down without failing the request
6470
+ // (Crew, 0.3.9). Failing it after a deadline could not stop the request already out, which may
6471
+ // still deliver it, and a send again would be a second message: the screen is told instead.
6472
+ watchDelivery(id) {
6473
+ const delivery = {
6474
+ timer: void 0,
6475
+ delayed: false
6476
+ };
6477
+ delivery.timer = setTimeout(() => {
6478
+ delivery.timer = void 0;
6479
+ delivery.delayed = true;
6480
+ this.emit("delivery", { clientMessageId: id, state: "delayed" });
6481
+ }, this.dependencies.deliveryDelayMs);
6482
+ this.deliveries.set(id, delivery);
6483
+ }
6484
+ deliveryEnded(id, state) {
6485
+ const delivery = this.deliveries.get(id);
6486
+ if (!delivery) return;
6487
+ this.deliveries.delete(id);
6488
+ clearTimeout(delivery.timer);
6489
+ if (delivery.delayed) this.emit("delivery", { clientMessageId: id, state });
6490
+ }
6375
6491
  emitError(prefix, error) {
6376
6492
  const code = errorCode(error);
6377
6493
  this.emit("error", {