zcode-app-cli 3.10.2-18 → 3.11.2-19

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.
@@ -7986,7 +7986,7 @@ var require_ipaddr = __commonJS({
7986
7986
  });
7987
7987
 
7988
7988
  // src/mcp/server.ts
7989
- import { basename as basename7, isAbsolute as isAbsolute11, resolve as resolve10 } from "node:path";
7989
+ import { basename as basename8, isAbsolute as isAbsolute11, resolve as resolve10 } from "node:path";
7990
7990
  import { isMainThread, parentPort, Worker, workerData } from "node:worker_threads";
7991
7991
 
7992
7992
  // ../../../../node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs
@@ -37231,6 +37231,16 @@ function isImageProcessorPortError(error98) {
37231
37231
  return error98 instanceof ImageProcessorPortError;
37232
37232
  }
37233
37233
 
37234
+ // ../contracts/dist/interfaces/pdf-document.port.js
37235
+ var PdfDocumentPortError = class extends Error {
37236
+ code;
37237
+ constructor(code, message, options) {
37238
+ super(message, options);
37239
+ this.code = code;
37240
+ this.name = "PdfDocumentPortError";
37241
+ }
37242
+ };
37243
+
37234
37244
  // ../contracts/dist/interfaces/permission.port.js
37235
37245
  var PermissionCapabilityGroup = {
37236
37246
  OfficialCua: "official_cua"
@@ -62095,6 +62105,27 @@ var browserViewportInputSchema = browserViewportSizeSchema.extend({
62095
62105
  width: external_exports3.number().int().min(BROWSER_VIEWPORT_LIMITS2.minWidth).max(BROWSER_VIEWPORT_LIMITS2.maxWidth),
62096
62106
  height: external_exports3.number().int().min(BROWSER_VIEWPORT_LIMITS2.minHeight).max(BROWSER_VIEWPORT_LIMITS2.maxHeight)
62097
62107
  });
62108
+ var BROWSER_VIEWPORT_ZOOM_OPTIONS = [
62109
+ "fit",
62110
+ "50",
62111
+ "75",
62112
+ "100",
62113
+ "125",
62114
+ "150",
62115
+ "200"
62116
+ ];
62117
+ var browserViewportZoomSchema = external_exports3.enum(BROWSER_VIEWPORT_ZOOM_OPTIONS);
62118
+ var DEFAULT_BROWSER_VIEWPORT_ZOOM = "fit";
62119
+ var embeddedBrowserViewportPreferenceSchema = external_exports3.object({
62120
+ mode: external_exports3.enum(["normal", "responsive"]),
62121
+ viewport: browserViewportInputSchema,
62122
+ zoom: browserViewportZoomSchema
62123
+ }).strict();
62124
+ var DEFAULT_EMBEDDED_BROWSER_VIEWPORT_PREFERENCE = {
62125
+ mode: "normal",
62126
+ viewport: { width: 393, height: 852 },
62127
+ zoom: DEFAULT_BROWSER_VIEWPORT_ZOOM
62128
+ };
62098
62129
  var browserCommandMethodSchema = external_exports3.enum([
62099
62130
  "navigate",
62100
62131
  "back",
@@ -63699,6 +63730,7 @@ var hookExecutionProjectionSchema = external_exports3.object({
63699
63730
  didExecute: external_exports3.boolean(),
63700
63731
  state: external_exports3.enum(["running", "completed", "failed"]),
63701
63732
  outcome: external_exports3.enum(["success", "blocked", "failed", "cancelled", "timed_out"]).optional(),
63733
+ blockReason: external_exports3.string().trim().min(1).optional(),
63702
63734
  startedAt: timestampSchema,
63703
63735
  endedAt: timestampSchema.optional(),
63704
63736
  durationMs: external_exports3.number().nonnegative().optional(),
@@ -64738,6 +64770,23 @@ function sanitizeDesktopWindowSize(value) {
64738
64770
  const { desktopWindowSize: _desktopWindowSize, ...next } = raw;
64739
64771
  return next;
64740
64772
  }
64773
+ function sanitizeEmbeddedBrowserViewportPreference(value) {
64774
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
64775
+ return value;
64776
+ }
64777
+ const raw = value;
64778
+ if (!("embeddedBrowserViewportPreference" in raw)) {
64779
+ return value;
64780
+ }
64781
+ const parsed = embeddedBrowserViewportPreferenceSchema.safeParse(
64782
+ raw.embeddedBrowserViewportPreference
64783
+ );
64784
+ if (parsed.success) {
64785
+ return value;
64786
+ }
64787
+ const { embeddedBrowserViewportPreference: _embeddedBrowserViewportPreference, ...next } = raw;
64788
+ return next;
64789
+ }
64741
64790
  function migrateOptimizeAgentExperienceDefault(value) {
64742
64791
  if (!value || typeof value !== "object" || Array.isArray(value)) {
64743
64792
  return value;
@@ -64943,6 +64992,9 @@ var appSettingsObjectSchema = external_exports3.object({
64943
64992
  httpProxyNoProxy: nonEmptyStringSchema2.optional(),
64944
64993
  httpProxyCaCertPath: nonEmptyStringSchema2.optional(),
64945
64994
  embeddedBrowserAllowInsecureCertificates: external_exports3.boolean().default(false),
64995
+ embeddedBrowserViewportPreference: embeddedBrowserViewportPreferenceSchema.default(
64996
+ DEFAULT_EMBEDDED_BROWSER_VIEWPORT_PREFERENCE
64997
+ ),
64946
64998
  // 2026-08-21:输入框电脑操作入口改为默认不展示,设置项保留、默认关闭。
64947
64999
  // default 只对缺省字段生效,显式存过 false 的用户仍保持展示。
64948
65000
  computerUseComposerEntryHidden: external_exports3.boolean().default(true),
@@ -64992,13 +65044,15 @@ var appSettingsObjectSchema = external_exports3.object({
64992
65044
  zcodeEndpointOrigin: zcodeEndpointOriginSchema.optional()
64993
65045
  });
64994
65046
  var appSettingsSchema = external_exports3.preprocess(
64995
- (value) => sanitizeDesktopWindowSize(
64996
- migrateMessageStreamShowReasoningDefault(
64997
- migrateCloseToTrayOnWindowsDefault(
64998
- migrateOptimizeAgentExperienceDefault(
64999
- migrateLegacyLocalePreference(
65000
- sanitizeZCodeEndpointOrigin(
65001
- migrateLegacyWorkspaceSession(migrateLegacyBuiltinAgentCliProviders(value))
65047
+ (value) => sanitizeEmbeddedBrowserViewportPreference(
65048
+ sanitizeDesktopWindowSize(
65049
+ migrateMessageStreamShowReasoningDefault(
65050
+ migrateCloseToTrayOnWindowsDefault(
65051
+ migrateOptimizeAgentExperienceDefault(
65052
+ migrateLegacyLocalePreference(
65053
+ sanitizeZCodeEndpointOrigin(
65054
+ migrateLegacyWorkspaceSession(migrateLegacyBuiltinAgentCliProviders(value))
65055
+ )
65002
65056
  )
65003
65057
  )
65004
65058
  )
@@ -65018,6 +65072,7 @@ var appSettingsPatchSchema = external_exports3.object({
65018
65072
  httpProxyNoProxy: nonEmptyStringSchema2.optional(),
65019
65073
  httpProxyCaCertPath: nonEmptyStringSchema2.optional(),
65020
65074
  embeddedBrowserAllowInsecureCertificates: external_exports3.boolean().optional(),
65075
+ embeddedBrowserViewportPreference: embeddedBrowserViewportPreferenceSchema.optional(),
65021
65076
  computerUseComposerEntryHidden: external_exports3.boolean().optional(),
65022
65077
  taskAutoArchiveEnabled: external_exports3.boolean().optional(),
65023
65078
  taskAutoArchiveOlderThanDays: external_exports3.number().int().positive().max(365).optional(),
@@ -65563,6 +65618,8 @@ var MCP_SERVER_FAILURE_KINDS = [
65563
65618
  "unexpected_disconnect",
65564
65619
  "oauth_authorization_failed",
65565
65620
  "official_origin_untrusted",
65621
+ "not_authenticated",
65622
+ "coding_plan_required",
65566
65623
  "server_not_found",
65567
65624
  "server_unavailable",
65568
65625
  "rate_limited",
@@ -66821,6 +66878,7 @@ var zcodeOfficialMcpAuthHeadersResponseSchema = external_exports3.discriminatedU
66821
66878
  }).strict()
66822
66879
  ]);
66823
66880
  var zcodePluginOptionValueSchema = external_exports3.union([external_exports3.string(), external_exports3.number(), external_exports3.boolean()]);
66881
+ var zcodePluginScopeSchema = external_exports3.enum(["user", "workspace"]);
66824
66882
  var zcodePluginHookDetailSchema = external_exports3.object({
66825
66883
  event: nonEmptyString2,
66826
66884
  matcher: external_exports3.string().optional(),
@@ -66877,7 +66935,12 @@ var zcodePluginInfoSchema = external_exports3.object({
66877
66935
  hookDetails: external_exports3.array(zcodePluginHookDetailSchema).optional(),
66878
66936
  rootPath: external_exports3.string(),
66879
66937
  userConfig: external_exports3.record(external_exports3.string(), zcodePluginUserConfigOptionSchema).optional(),
66880
- configuredOptions: external_exports3.record(external_exports3.string(), zcodePluginOptionValueSchema).optional()
66938
+ configuredOptions: external_exports3.record(external_exports3.string(), zcodePluginOptionValueSchema).optional(),
66939
+ // 缺省表示 package 可用;missing 用于保留已声明但目标 Host 尚未物化的配置行。
66940
+ packageStatus: external_exports3.literal("missing").optional(),
66941
+ rootSource: zcodePluginScopeSchema.optional(),
66942
+ enabledSource: zcodePluginScopeSchema.optional(),
66943
+ optionSources: external_exports3.record(external_exports3.string(), zcodePluginScopeSchema).optional()
66881
66944
  }).strict();
66882
66945
  var zcodePluginDiagnosticSchema = external_exports3.object({
66883
66946
  code: external_exports3.string(),
@@ -66886,7 +66949,8 @@ var zcodePluginDiagnosticSchema = external_exports3.object({
66886
66949
  pluginId: external_exports3.string().optional()
66887
66950
  }).strict();
66888
66951
  var zcodePluginsListParamsSchema = external_exports3.object({
66889
- workspace: zcodeWorkspaceRefSchema
66952
+ workspace: zcodeWorkspaceRefSchema,
66953
+ configScope: zcodePluginScopeSchema.optional()
66890
66954
  }).strict();
66891
66955
  var zcodePluginsListResultSchema = external_exports3.object({
66892
66956
  plugins: external_exports3.array(zcodePluginInfoSchema),
@@ -66967,13 +67031,13 @@ var zcodePluginsSetEnabledParamsSchema = external_exports3.object({
66967
67031
  workspace: zcodeWorkspaceRefSchema,
66968
67032
  pluginId: nonEmptyString2,
66969
67033
  enabled: external_exports3.boolean(),
66970
- operationId: nonEmptyString2.optional()
67034
+ operationId: nonEmptyString2.optional(),
67035
+ scope: zcodePluginScopeSchema.optional()
66971
67036
  }).strict();
66972
67037
  var zcodePluginsSetEnabledResultSchema = external_exports3.object({
66973
67038
  plugin: zcodePluginInfoSchema,
66974
67039
  enabled: external_exports3.boolean()
66975
67040
  }).strict();
66976
- var zcodePluginScopeSchema = external_exports3.enum(["user", "workspace"]);
66977
67041
  var zcodePluginStoreListingSchema = external_exports3.object({
66978
67042
  displayName: external_exports3.string().optional(),
66979
67043
  displayNameI18n: external_exports3.record(external_exports3.string(), external_exports3.string()).optional(),
@@ -67059,7 +67123,8 @@ var zcodeInstalledPluginSummarySchema = external_exports3.object({
67059
67123
  listing: zcodePluginStoreListingSchema.optional()
67060
67124
  }).strict();
67061
67125
  var zcodePluginsOverviewParamsSchema = external_exports3.object({
67062
- workspace: zcodeWorkspaceRefSchema
67126
+ workspace: zcodeWorkspaceRefSchema,
67127
+ configScope: zcodePluginScopeSchema.optional()
67063
67128
  }).strict();
67064
67129
  var zcodePluginsOverviewResultSchema = external_exports3.object({
67065
67130
  marketplaces: external_exports3.array(zcodePluginMarketplaceSummarySchema),
@@ -67140,12 +67205,19 @@ var zcodePluginsConfigureParamsSchema = external_exports3.object({
67140
67205
  workspace: zcodeWorkspaceRefSchema,
67141
67206
  pluginId: nonEmptyString2,
67142
67207
  options: jsonObjectSchema2,
67208
+ clearOptionKeys: external_exports3.array(nonEmptyString2).optional(),
67209
+ scope: zcodePluginScopeSchema.optional(),
67143
67210
  dryRun: external_exports3.boolean().optional()
67144
67211
  }).strict();
67145
67212
  var zcodePluginsConfigureResultSchema = external_exports3.object({
67146
67213
  pluginId: nonEmptyString2,
67147
67214
  diagnostics: external_exports3.array(zcodePluginDiagnosticSchema)
67148
67215
  }).strict();
67216
+ var zcodePluginsResetConfigParamsSchema = external_exports3.object({
67217
+ workspace: zcodeWorkspaceRefSchema,
67218
+ pluginId: nonEmptyString2,
67219
+ scope: zcodePluginScopeSchema.optional()
67220
+ }).strict();
67149
67221
  var zcodePluginsValidateParamsSchema = external_exports3.object({
67150
67222
  workspace: zcodeWorkspaceRefSchema,
67151
67223
  pluginName: nonEmptyString2.optional(),
@@ -67360,6 +67432,7 @@ var zcodeProtocolMethods = {
67360
67432
  pluginsUpdate: "plugins/update",
67361
67433
  pluginsRestoreBuiltin: "plugins/restoreBuiltin",
67362
67434
  pluginsConfigure: "plugins/configure",
67435
+ pluginsResetConfig: "plugins/resetConfig",
67363
67436
  pluginsValidate: "plugins/validate",
67364
67437
  pluginsDescribe: "plugins/describe",
67365
67438
  automationCreate: "automation/create",
@@ -67683,6 +67756,14 @@ var zcodePromptAttachmentSchema = external_exports3.discriminatedUnion("kind", [
67683
67756
  dataBase64: external_exports3.string().optional(),
67684
67757
  localPath: external_exports3.string().optional()
67685
67758
  }).strict(),
67759
+ external_exports3.object({
67760
+ kind: external_exports3.literal("pdf"),
67761
+ filename: external_exports3.string(),
67762
+ mimeType: external_exports3.string(),
67763
+ sizeBytes: external_exports3.number().int().nonnegative().optional(),
67764
+ dataBase64: external_exports3.string().optional(),
67765
+ localPath: external_exports3.string().optional()
67766
+ }).strict(),
67686
67767
  external_exports3.object({
67687
67768
  kind: external_exports3.literal("file"),
67688
67769
  filename: external_exports3.string(),
@@ -68580,6 +68661,8 @@ var hostLogResponseSchema = external_exports3.object({
68580
68661
  var zcodeTaskMigrationSourceSchema = external_exports3.enum(["claudeCode"]);
68581
68662
  var hostAgentProcessSpawnedResponseSchema = external_exports3.object({
68582
68663
  type: external_exports3.literal("agent-process-spawned"),
68664
+ /** 进程泳道(mcp-status / repo-wiki 等),旧 Host 不带该字段。 */
68665
+ lane: nonEmptyStringSchema3.optional(),
68583
68666
  pid: external_exports3.number().int().positive(),
68584
68667
  provider: zcodeProviderSchema,
68585
68668
  workspacePath: nonEmptyStringSchema3,
@@ -68591,6 +68674,8 @@ var hostAgentProcessSpawnedResponseSchema = external_exports3.object({
68591
68674
  });
68592
68675
  var hostAgentProcessReadyResponseSchema = external_exports3.object({
68593
68676
  type: external_exports3.literal("agent-process-ready"),
68677
+ /** 进程泳道(mcp-status / repo-wiki 等),旧 Host 不带该字段。 */
68678
+ lane: nonEmptyStringSchema3.optional(),
68594
68679
  pid: external_exports3.number().int().positive(),
68595
68680
  provider: zcodeProviderSchema,
68596
68681
  workspacePath: nonEmptyStringSchema3,
@@ -68601,6 +68686,8 @@ var hostAgentProcessReadyResponseSchema = external_exports3.object({
68601
68686
  });
68602
68687
  var hostAgentProcessExitedResponseSchema = external_exports3.object({
68603
68688
  type: external_exports3.literal("agent-process-exited"),
68689
+ /** 进程泳道(mcp-status / repo-wiki 等),旧 Host 不带该字段。 */
68690
+ lane: nonEmptyStringSchema3.optional(),
68604
68691
  pid: external_exports3.number().int().positive(),
68605
68692
  provider: zcodeProviderSchema,
68606
68693
  workspacePath: nonEmptyStringSchema3,
@@ -68619,6 +68706,8 @@ var hostAgentProcessExitedResponseSchema = external_exports3.object({
68619
68706
  });
68620
68707
  var hostAgentProcessErrorResponseSchema = external_exports3.object({
68621
68708
  type: external_exports3.literal("agent-process-error"),
68709
+ /** 进程泳道(mcp-status / repo-wiki 等),旧 Host 不带该字段。 */
68710
+ lane: nonEmptyStringSchema3.optional(),
68622
68711
  pid: external_exports3.number().int().positive().nullable(),
68623
68712
  provider: zcodeProviderSchema,
68624
68713
  workspacePath: nonEmptyStringSchema3,
@@ -68865,6 +68954,14 @@ var zcodePromptVideoAttachmentSchema = external_exports3.object({
68865
68954
  dataBase64: external_exports3.string().optional(),
68866
68955
  localPath: external_exports3.string().optional()
68867
68956
  });
68957
+ var zcodePromptPdfAttachmentSchema = external_exports3.object({
68958
+ kind: external_exports3.literal("pdf"),
68959
+ filename: external_exports3.string(),
68960
+ mimeType: external_exports3.string(),
68961
+ sizeBytes: external_exports3.number().int().nonnegative().optional(),
68962
+ dataBase64: external_exports3.string().optional(),
68963
+ localPath: external_exports3.string().optional()
68964
+ });
68868
68965
  var zcodePromptFileAttachmentSchema = external_exports3.object({
68869
68966
  kind: external_exports3.literal("file"),
68870
68967
  filename: external_exports3.string(),
@@ -68877,6 +68974,7 @@ var zcodePromptFileAttachmentSchema = external_exports3.object({
68877
68974
  var zcodePromptAttachmentSchema2 = external_exports3.discriminatedUnion("kind", [
68878
68975
  zcodePromptImageAttachmentSchema,
68879
68976
  zcodePromptVideoAttachmentSchema,
68977
+ zcodePromptPdfAttachmentSchema,
68880
68978
  zcodePromptFileAttachmentSchema
68881
68979
  ]);
68882
68980
  var zcodePersistedToolCallSchema = external_exports3.object({
@@ -69298,7 +69396,7 @@ var REMOTE_RUNTIME_TOOL_RUNTIME = {
69298
69396
  ugrep: {
69299
69397
  ...RUNTIME_TOOL_RUNTIME.ugrep,
69300
69398
  versions: {
69301
- linux: "v7.5.0-2"
69399
+ linux: "v7.8.4-1"
69302
69400
  }
69303
69401
  }
69304
69402
  };
@@ -69377,6 +69475,14 @@ var REPO_SNAPSHOT_DELTA_SCHEMA = repoSnapshotSchema(
69377
69475
  "delta",
69378
69476
  REPO_SNAPSHOT_ARTIFACT_SCHEMA_VERSION
69379
69477
  );
69478
+ var REPO_SNAPSHOT_EXTRA_MANIFEST_SCHEMA = repoSnapshotSchema(
69479
+ "extra_manifest",
69480
+ "v1"
69481
+ );
69482
+ var REPO_SNAPSHOT_EXTRA_DELTA_SCHEMA = repoSnapshotSchema(
69483
+ "extra_delta",
69484
+ "v1"
69485
+ );
69380
69486
  var REPO_SNAPSHOT_ENCRYPTED_ARTIFACT_SCHEMA = repoSnapshotSchema(
69381
69487
  "encrypted_artifact",
69382
69488
  REPO_SNAPSHOT_ARTIFACT_SCHEMA_VERSION
@@ -69441,7 +69547,7 @@ function isProviderVisibleModelInputMediaBlock(block) {
69441
69547
  return block.type === "image" || block.type === "video" || isProviderVisiblePdfModelInputBlock(block);
69442
69548
  }
69443
69549
  function isProviderVisiblePdfModelInputBlock(block) {
69444
- return block.type === "file" && block.mediaType === "application/pdf" && block.dataUrl !== void 0 && // 修复原因:PDF 提取文本为空字符串时,adapter 会回退发送 file-data。
69550
+ return block.type === "file" && block.mediaType.split(";", 1)[0]?.trim().toLowerCase() === "application/pdf" && block.dataUrl !== void 0 && // 修复原因:PDF 提取文本为空字符串时,adapter 会回退发送 file-data。
69445
69551
  // 只有非空文本能替代 provider-visible PDF 文件数据。
69446
69552
  (block.text === void 0 || block.text.length === 0);
69447
69553
  }
@@ -70632,6 +70738,66 @@ function getPublicEgressIpBlockReason(value) {
70632
70738
  return void 0;
70633
70739
  }
70634
70740
 
70741
+ // ../contracts/dist/tools/read-pdf.js
70742
+ var READ_PDF_NATIVE_MAX_INPUT_BYTES = 20 * 1024 * 1024;
70743
+ var READ_PDF_EXTRACT_MAX_INPUT_BYTES = 100 * 1024 * 1024;
70744
+ var READ_PDF_NATIVE_MAX_PAGES = 10;
70745
+ var READ_PDF_MAX_PAGES_PER_REQUEST = 20;
70746
+ var READ_PDF_RENDER_TIMEOUT_MS = 12e4;
70747
+ var READ_PDF_PAGES_DESCRIPTION = 'Page range for PDF files (e.g., "1-5", "3", "10-20"). Only applicable to PDF files. Maximum 20 pages per request.';
70748
+ var ReadErrorCode = {
70749
+ PDF_INVALID_PAGES: 7,
70750
+ PDF_PAGE_RANGE_TOO_LARGE: 8,
70751
+ PDF_PAGES_IMAGES_UNSUPPORTED: 10,
70752
+ PDF_CONFIGURATION_ERROR: 11,
70753
+ PDF_INVALID: 12,
70754
+ PDF_TOO_LARGE: 13,
70755
+ PDF_TOO_MANY_PAGES: 14,
70756
+ PDF_TIMEOUT: 15,
70757
+ PDF_PASSWORD_PROTECTED: 16,
70758
+ PDF_PAGE_OUT_OF_RANGE: 17,
70759
+ PDF_PERMISSION_DENIED: 18,
70760
+ PDF_IO_ERROR: 19,
70761
+ PDF_PROCESS_FAILED: 20
70762
+ };
70763
+ function parseReadPdfPageRange(value) {
70764
+ const normalized = value.trim();
70765
+ if (/^\d+-$/u.test(normalized)) {
70766
+ const firstPage2 = Number(normalized.slice(0, -1));
70767
+ return Number.isSafeInteger(firstPage2) && firstPage2 >= 1 ? { firstPage: firstPage2, lastPage: Number.POSITIVE_INFINITY } : void 0;
70768
+ }
70769
+ const match = /^(\d+)(?:-(\d+))?$/u.exec(normalized);
70770
+ if (!match)
70771
+ return void 0;
70772
+ const firstPage = Number(match[1]);
70773
+ const lastPage = Number(match[2] ?? match[1]);
70774
+ if (!Number.isSafeInteger(firstPage) || !Number.isSafeInteger(lastPage) || firstPage < 1 || lastPage < firstPage) {
70775
+ return void 0;
70776
+ }
70777
+ return { firstPage, lastPage };
70778
+ }
70779
+ function readPdfPageCount(range) {
70780
+ return range.lastPage === Number.POSITIVE_INFINITY ? READ_PDF_MAX_PAGES_PER_REQUEST + 1 : range.lastPage - range.firstPage + 1;
70781
+ }
70782
+ function getReadPdfPagesValidationFailure(filePath, pages) {
70783
+ if (pages === void 0 || !filePath.toLowerCase().endsWith(".pdf"))
70784
+ return void 0;
70785
+ const range = parseReadPdfPageRange(pages);
70786
+ if (!range) {
70787
+ return {
70788
+ errorCode: ReadErrorCode.PDF_INVALID_PAGES,
70789
+ message: `Invalid pages parameter: "${pages}". Use formats like "1-5", "3", or "10-20". Pages are 1-indexed.`
70790
+ };
70791
+ }
70792
+ if (readPdfPageCount(range) > READ_PDF_MAX_PAGES_PER_REQUEST) {
70793
+ return {
70794
+ errorCode: ReadErrorCode.PDF_PAGE_RANGE_TOO_LARGE,
70795
+ message: `Page range "${pages}" exceeds maximum of ${READ_PDF_MAX_PAGES_PER_REQUEST} pages per request. Please use a smaller range.`
70796
+ };
70797
+ }
70798
+ return void 0;
70799
+ }
70800
+
70635
70801
  // ../contracts/dist/tools/read.js
70636
70802
  var READ_MAX_FILE_SIZE_BYTES = 256 * 1024;
70637
70803
  var READ_MAX_OUTPUT_TOKENS = 25e3;
@@ -70691,18 +70857,29 @@ var ReadProviderInputBaseSchema = external_exports2.object({
70691
70857
  */
70692
70858
  limit: external_exports2.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional().describe("The number of lines to read. Only provide if the file is too large to read at once.")
70693
70859
  });
70694
- var ReadInputSchema = ReadProviderInputBaseSchema.extend({
70695
- /**
70696
- * Legacy runtime-only page range input. Not exposed to model providers until PDF reading is provider-ready.
70697
- */
70698
- pages: external_exports2.string().optional().describe("Legacy runtime-only page range input. Not exposed to model providers until PDF reading is provider-ready.")
70699
- }).superRefine(validateReadInputSemantics);
70860
+ var ReadProviderPdfInputSchema = ReadProviderInputBaseSchema.extend({
70861
+ pages: external_exports2.string().optional().describe(READ_PDF_PAGES_DESCRIPTION)
70862
+ });
70863
+ var ReadInputSchema = ReadProviderPdfInputSchema.superRefine(validateReadInputSemantics);
70700
70864
  var ReadInputJsonSchema = toToolJsonSchema(ReadProviderInputBaseSchema);
70865
+ var ReadPdfInputJsonSchema = toToolJsonSchema(ReadProviderPdfInputSchema);
70701
70866
  function validateReadInputSemantics(input, context) {
70702
70867
  if (typeof input.file_path !== "string")
70703
70868
  return;
70704
70869
  const filePath = input.file_path;
70705
70870
  const lowerPath = filePath.toLowerCase();
70871
+ const pagesFailure = typeof input.pages === "string" ? getReadPdfPagesValidationFailure(filePath, input.pages) : void 0;
70872
+ if (pagesFailure) {
70873
+ context.addIssue({
70874
+ code: external_exports2.ZodIssueCode.custom,
70875
+ path: ["pages"],
70876
+ message: pagesFailure.message
70877
+ });
70878
+ return;
70879
+ }
70880
+ validateReadPathSemantics(filePath, lowerPath, context);
70881
+ }
70882
+ function validateReadPathSemantics(filePath, lowerPath, context) {
70706
70883
  if (BLOCKING_DEVICE_PATHS.has(lowerPath)) {
70707
70884
  context.addIssue({
70708
70885
  code: external_exports2.ZodIssueCode.custom,
@@ -70722,11 +70899,11 @@ function validateReadInputSemantics(input, context) {
70722
70899
  }
70723
70900
  function readFileExtension(path2) {
70724
70901
  const lastSlash = Math.max(path2.lastIndexOf("/"), path2.lastIndexOf("\\"));
70725
- const basename8 = path2.slice(lastSlash + 1);
70726
- const dotIndex = basename8.lastIndexOf(".");
70902
+ const basename9 = path2.slice(lastSlash + 1);
70903
+ const dotIndex = basename9.lastIndexOf(".");
70727
70904
  if (dotIndex <= 0)
70728
70905
  return void 0;
70729
- return basename8.slice(dotIndex);
70906
+ return basename9.slice(dotIndex);
70730
70907
  }
70731
70908
  var ReadTextOutputSchema = external_exports2.object({
70732
70909
  type: external_exports2.literal("text"),
@@ -70795,10 +70972,10 @@ var ReadPdfOutputSchema = external_exports2.object({
70795
70972
  }).strict();
70796
70973
  var ReadPartsOutputSchema = external_exports2.object({
70797
70974
  type: external_exports2.literal("parts"),
70798
- outputDir: external_exports2.string(),
70975
+ filePath: external_exports2.string(),
70799
70976
  numParts: external_exports2.number().int().nonnegative(),
70800
- totalPages: external_exports2.number().int().nonnegative(),
70801
- originalSize: external_exports2.number().int().nonnegative()
70977
+ originalSize: external_exports2.number().int().nonnegative(),
70978
+ pages: external_exports2.array(ReadImageOutputSchema.extend({ pageNumber: external_exports2.number().int().positive() }))
70802
70979
  }).strict();
70803
70980
  var ReadUnchangedOutputSchema = external_exports2.object({
70804
70981
  type: external_exports2.literal("file_unchanged"),
@@ -72551,13 +72728,7 @@ var MessageHistoryImpl = class {
72551
72728
  };
72552
72729
  }
72553
72730
  addUser(content, metadata) {
72554
- this.entries.push({
72555
- message: {
72556
- role: "user",
72557
- content
72558
- },
72559
- metadata: cloneRuntimeMessageMetadata(metadata)
72560
- });
72731
+ this.entries.push(createRuntimeUserEntry(content, metadata));
72561
72732
  this.cacheStats.totalMessages = this.entries.length;
72562
72733
  }
72563
72734
  addAttachment(source, content) {
@@ -72568,42 +72739,19 @@ var MessageHistoryImpl = class {
72568
72739
  this.entries.push(...entries.map(cloneRuntimeMessageEntry));
72569
72740
  this.cacheStats.totalMessages = this.entries.length;
72570
72741
  }
72571
- addAssistant(content, toolCalls, reasoning, modelRef2) {
72572
- const reasoningBlocks = reasoning?.map((block) => cloneReasoningBlock(block)) ?? [];
72573
- this.entries.push({
72574
- message: {
72575
- role: "assistant",
72576
- content: reasoningBlocks.length > 0 ? [
72577
- ...reasoningBlocks,
72578
- ...content.length > 0 ? [{ type: "text", text: content }] : []
72579
- ] : content,
72580
- toolCalls: toolCalls?.map((tc) => ({
72581
- id: tc.id,
72582
- name: tc.name,
72583
- input: tc.input
72584
- })),
72585
- ...modelRef2 ? { modelRef: { ...modelRef2 } } : {}
72586
- }
72587
- });
72742
+ addAssistant(content, toolCalls, reasoning, modelRef2, tokens) {
72743
+ this.entries.push(createRuntimeAssistantEntry(content, toolCalls, reasoning, modelRef2, tokens));
72588
72744
  this.cacheStats.totalMessages = this.entries.length;
72589
72745
  }
72590
72746
  addToolResult(toolCallId, toolName, content, success3, isError = !success3) {
72591
- this.entries.push({
72592
- message: {
72593
- role: "tool",
72594
- content,
72595
- toolCallId,
72596
- toolName,
72597
- isError
72598
- }
72599
- });
72747
+ this.entries.push(createRuntimeToolResultEntry(toolCallId, toolName, content, isError));
72600
72748
  this.cacheStats.totalMessages = this.entries.length;
72601
72749
  }
72602
72750
  borrowReadOnlyRuntimeEntries() {
72603
72751
  return this.entries;
72604
72752
  }
72605
72753
  toRuntimeEntries() {
72606
- return cloneRuntimeMessageEntries(this.entries);
72754
+ return this.entries.map(cloneRuntimeMessageEntry);
72607
72755
  }
72608
72756
  replaceMessages(messages) {
72609
72757
  this.entries = messages.map(cloneEntryInput);
@@ -72694,6 +72842,45 @@ function systemReminderAttachmentEntry(source, content) {
72694
72842
  metadata: systemReminderRuntimeMetadata(source)
72695
72843
  };
72696
72844
  }
72845
+ function createRuntimeUserEntry(content, metadata) {
72846
+ return {
72847
+ message: {
72848
+ role: "user",
72849
+ content
72850
+ },
72851
+ metadata: cloneRuntimeMessageMetadata(metadata)
72852
+ };
72853
+ }
72854
+ function createRuntimeAssistantEntry(content, toolCalls, reasoning, modelRef2, tokens) {
72855
+ const reasoningBlocks = reasoning?.map((block) => cloneReasoningBlock(block)) ?? [];
72856
+ return {
72857
+ message: {
72858
+ role: "assistant",
72859
+ content: reasoningBlocks.length > 0 ? [
72860
+ ...reasoningBlocks,
72861
+ ...content.length > 0 ? [{ type: "text", text: content }] : []
72862
+ ] : content,
72863
+ toolCalls: toolCalls?.map((toolCall) => ({
72864
+ id: toolCall.id,
72865
+ name: toolCall.name,
72866
+ input: toolCall.input
72867
+ })),
72868
+ ...modelRef2 ? { modelRef: { ...modelRef2 } } : {}
72869
+ },
72870
+ ...tokens ? { tokens: cloneTokenUsageInfo(tokens) } : {}
72871
+ };
72872
+ }
72873
+ function createRuntimeToolResultEntry(toolCallId, toolName, content, isError) {
72874
+ return {
72875
+ message: {
72876
+ role: "tool",
72877
+ content,
72878
+ toolCallId,
72879
+ toolName,
72880
+ isError
72881
+ }
72882
+ };
72883
+ }
72697
72884
  function isKnownSystemReminderSource(value) {
72698
72885
  return typeof value === "string" && SYSTEM_REMINDER_SOURCES.includes(value);
72699
72886
  }
@@ -72703,9 +72890,6 @@ function cloneEntryInput(input) {
72703
72890
  }
72704
72891
  return { message: cloneModelInputMessage(input) };
72705
72892
  }
72706
- function cloneRuntimeMessageEntries(entries) {
72707
- return entries.map(cloneRuntimeMessageEntry);
72708
- }
72709
72893
  function cloneRuntimeMessageEntry(entry) {
72710
72894
  if (entry.kind === "attachment") {
72711
72895
  return {
@@ -72717,7 +72901,28 @@ function cloneRuntimeMessageEntry(entry) {
72717
72901
  }
72718
72902
  return {
72719
72903
  message: cloneModelInputMessage(entry.message),
72720
- metadata: cloneRuntimeMessageMetadata(entry.metadata)
72904
+ metadata: cloneRuntimeMessageMetadata(entry.metadata),
72905
+ ...entry.tokens ? { tokens: cloneTokenUsageInfo(entry.tokens) } : {},
72906
+ ...entry.queryScope ? { queryScope: entry.queryScope } : {}
72907
+ };
72908
+ }
72909
+ function invalidateRuntimeTokenUsage(tokens) {
72910
+ return {
72911
+ ...tokens,
72912
+ total: 0,
72913
+ input: 0,
72914
+ output: 0,
72915
+ reasoning: 0,
72916
+ cache: {
72917
+ read: 0,
72918
+ write: 0
72919
+ }
72920
+ };
72921
+ }
72922
+ function cloneTokenUsageInfo(tokens) {
72923
+ return {
72924
+ ...tokens,
72925
+ cache: { ...tokens.cache }
72721
72926
  };
72722
72927
  }
72723
72928
  function cloneRuntimeMessageMetadata(metadata) {
@@ -73075,7 +73280,18 @@ function compactPreservedSegmentMessages(messages, boundaryIndex) {
73075
73280
  if (headIndex < 0 || tailIndex < headIndex || tailIndex >= boundaryIndex) {
73076
73281
  return [];
73077
73282
  }
73078
- return messages.slice(headIndex, tailIndex + 1).filter(isCompactPreservableSessionMessage);
73283
+ return messages.slice(headIndex, tailIndex + 1).filter(isCompactPreservableSessionMessage).map(cloneCompactPreservedSessionMessage);
73284
+ }
73285
+ function cloneCompactPreservedSessionMessage(message) {
73286
+ if (message.info.role !== "assistant")
73287
+ return message;
73288
+ return {
73289
+ ...message,
73290
+ info: {
73291
+ ...message.info,
73292
+ tokens: invalidateRuntimeTokenUsage(message.info.tokens)
73293
+ }
73294
+ };
73079
73295
  }
73080
73296
  function compactBoundaryFromMessage(message) {
73081
73297
  for (const part of message.parts) {
@@ -73121,10 +73337,10 @@ async function filePartToContentBlock(part, artifactStore) {
73121
73337
  source
73122
73338
  };
73123
73339
  }
73124
- if (part.mime === "application/pdf" && dataUrl) {
73340
+ if (isPdfMime(part.mime) && dataUrl) {
73125
73341
  return {
73126
73342
  type: "file",
73127
- mediaType: part.mime,
73343
+ mediaType: "application/pdf",
73128
73344
  name: part.filename,
73129
73345
  dataUrl,
73130
73346
  source
@@ -73187,7 +73403,7 @@ async function filePartDataUrl(part, artifactStore) {
73187
73403
  }
73188
73404
  }
73189
73405
  function attachmentRefFromFilePart(part) {
73190
- const artifactUri = (part.source?.type === "file" || part.source?.type === "symbol") && (isImageMime(part.mime) || part.mime.startsWith("video/")) ? durableArtifactUriFromFilePart(part) : void 0;
73406
+ const artifactUri = (part.source?.type === "file" || part.source?.type === "symbol") && (isImageMime(part.mime) || part.mime.startsWith("video/") || isPdfMime(part.mime)) ? durableArtifactUriFromFilePart(part) : void 0;
73191
73407
  return {
73192
73408
  id: part.id,
73193
73409
  // Bug 根因:冷恢复正文已经来自 durable artifact,却仍把持久化的原始 path 当作
@@ -73209,6 +73425,9 @@ function durableArtifactUriFromFilePart(part) {
73209
73425
  function isImageMime(mime) {
73210
73426
  return mime === "image/*" || mime.startsWith("image/");
73211
73427
  }
73428
+ function isPdfMime(mime) {
73429
+ return mime.split(";", 1)[0]?.trim().toLowerCase() === "application/pdf";
73430
+ }
73212
73431
  function isUsableDataUrl(value) {
73213
73432
  const commaIndex = value.indexOf(",");
73214
73433
  return value.startsWith("data:") && commaIndex >= 0 && value.slice(commaIndex + 1).length > 0;
@@ -73223,6 +73442,50 @@ function isRecord2(value) {
73223
73442
  return typeof value === "object" && value !== null && !Array.isArray(value);
73224
73443
  }
73225
73444
 
73445
+ // ../core/dist/agent/message-history-usage.js
73446
+ function persistedTokenUsageBaseline(tokens) {
73447
+ if (!tokens)
73448
+ return void 0;
73449
+ const inputTokens = persistedInputWindowTokens(tokens);
73450
+ if (inputTokens === void 0 || inputTokens <= 0)
73451
+ return void 0;
73452
+ const outputTokens = positiveInteger2(tokens.output) ?? 0;
73453
+ const cacheReadTokens = nonNegativeInteger2(tokens.cache.read) ?? 0;
73454
+ const cacheWriteTokens = nonNegativeInteger2(tokens.cache.write) ?? 0;
73455
+ const totalTokens = positiveInteger2(tokens.total);
73456
+ const contextUsageTokens = outputTokens > 0 ? inputTokens + outputTokens : totalTokens !== void 0 && totalTokens >= inputTokens ? totalTokens : void 0;
73457
+ return {
73458
+ cacheReadTokens,
73459
+ cacheWriteTokens,
73460
+ contextUsageTokens,
73461
+ inputTokens,
73462
+ outputTokens
73463
+ };
73464
+ }
73465
+ function persistedInputWindowTokens(tokens) {
73466
+ const inputTokens = positiveInteger2(tokens.input);
73467
+ if (inputTokens !== void 0)
73468
+ return inputTokens;
73469
+ const totalTokens = positiveInteger2(tokens.total);
73470
+ if (totalTokens !== void 0) {
73471
+ return Math.max(0, totalTokens - (nonNegativeInteger2(tokens.output) ?? 0));
73472
+ }
73473
+ const cacheTokens = (nonNegativeInteger2(tokens.cache.read) ?? 0) + (nonNegativeInteger2(tokens.cache.write) ?? 0);
73474
+ return cacheTokens > 0 ? cacheTokens : void 0;
73475
+ }
73476
+ function positiveInteger2(value) {
73477
+ if (value === void 0 || !Number.isFinite(value))
73478
+ return void 0;
73479
+ const integer3 = Math.floor(value);
73480
+ return integer3 > 0 ? integer3 : void 0;
73481
+ }
73482
+ function nonNegativeInteger2(value) {
73483
+ if (value === void 0 || !Number.isFinite(value))
73484
+ return void 0;
73485
+ const integer3 = Math.floor(value);
73486
+ return integer3 >= 0 ? integer3 : void 0;
73487
+ }
73488
+
73226
73489
  // ../core/dist/agent/session-history-hydrator.js
73227
73490
  var INTERRUPTED_TOOL_RESULT = "[Tool execution was interrupted before resume]";
73228
73491
  async function hydrateMessageHistoryFromSession(input) {
@@ -73253,8 +73516,9 @@ async function hydrateMessageHistoryFromSession(input) {
73253
73516
  const text = assistantTextFromParts(parts);
73254
73517
  const reasoning = assistantReasoningFromParts(parts);
73255
73518
  const toolParts = parts.filter(isToolPart);
73256
- if (text.trim().length === 0 && reasoning.length === 0 && toolParts.length === 0)
73519
+ if (text.trim().length === 0 && reasoning.length === 0 && toolParts.length === 0 && !persistedTokenUsageBaseline(message.info.tokens)) {
73257
73520
  continue;
73521
+ }
73258
73522
  input.history.addAssistant(text, toolParts.map((part) => ({
73259
73523
  id: part.callID,
73260
73524
  input: part.state.input,
@@ -73263,7 +73527,7 @@ async function hydrateMessageHistoryFromSession(input) {
73263
73527
  modelId: message.info.modelID,
73264
73528
  providerId: message.info.providerID,
73265
73529
  ...message.info.variant ? { variant: message.info.variant } : {}
73266
- });
73530
+ }, message.info.tokens);
73267
73531
  appliedMessageCount++;
73268
73532
  for (const part of toolParts) {
73269
73533
  const providerToolName = providerToolNameFromPart(part);
@@ -78320,11 +78584,11 @@ function createErrorResult(toolCall, error98, durationMs) {
78320
78584
  completedAt: /* @__PURE__ */ new Date()
78321
78585
  };
78322
78586
  }
78323
- function createToolHandlerFailureError(toolCall, failure) {
78324
- return createCoreError(CoreErrorType.ToolExecutionFailed, failure.message, {
78587
+ function createToolHandlerFailureError(toolCall, failure2) {
78588
+ return createCoreError(CoreErrorType.ToolExecutionFailed, failure2.message, {
78325
78589
  context: {
78326
- code: failure.errorCode,
78327
- toolHandlerFailure: failure,
78590
+ code: failure2.errorCode,
78591
+ toolHandlerFailure: failure2,
78328
78592
  toolCallId: toolCall.id,
78329
78593
  toolName: toolCall.name
78330
78594
  },
@@ -78368,7 +78632,7 @@ async function emitToolCallStarted(deps, toolCall, traceContext, turnId, startTi
78368
78632
  }
78369
78633
  });
78370
78634
  }
78371
- async function emitToolCallResult(deps, toolCall, traceContext, turnId, serialization, durationMs, display, perf) {
78635
+ async function emitToolCallResult(deps, toolCall, traceContext, turnId, serialization, durationMs, display, perf, skillMetadata) {
78372
78636
  await deps.emitEvent({
78373
78637
  id: crypto.randomUUID(),
78374
78638
  sessionId: deps.sessionId,
@@ -78379,6 +78643,7 @@ async function emitToolCallResult(deps, toolCall, traceContext, turnId, serializ
78379
78643
  sequenceNumber: 0,
78380
78644
  payload: {
78381
78645
  toolCallId: toolCall.id,
78646
+ ...skillMetadata ? { skillMetadata } : {},
78382
78647
  result: {
78383
78648
  success: true,
78384
78649
  content: serialization.content,
@@ -78394,7 +78659,7 @@ async function emitToolCallResult(deps, toolCall, traceContext, turnId, serializ
78394
78659
  }
78395
78660
  });
78396
78661
  }
78397
- async function emitToolCallError(deps, toolCallId, traceContext, turnId, error98) {
78662
+ async function emitToolCallError(deps, toolCallId, traceContext, turnId, error98, skillMetadata) {
78398
78663
  await deps.emitEvent({
78399
78664
  id: crypto.randomUUID(),
78400
78665
  sessionId: deps.sessionId,
@@ -78403,7 +78668,11 @@ async function emitToolCallError(deps, toolCallId, traceContext, turnId, error98
78403
78668
  timestamp: /* @__PURE__ */ new Date(),
78404
78669
  traceId: traceContext.traceId,
78405
78670
  sequenceNumber: 0,
78406
- payload: { toolCallId, error: error98 }
78671
+ payload: {
78672
+ toolCallId,
78673
+ error: error98,
78674
+ ...skillMetadata ? { skillMetadata } : {}
78675
+ }
78407
78676
  });
78408
78677
  }
78409
78678
  async function emitPermissionRequested(deps, toolCall, input, requestId, riskLevel, reason, suggestedPermissionUpdates, traceContext) {
@@ -79428,13 +79697,13 @@ async function executeWithTimeout(handler, input, context, timeoutMs, abortContr
79428
79697
  });
79429
79698
  });
79430
79699
  }
79431
- function resolveTimeoutMs(entry, input, defaultTimeoutMs) {
79700
+ function resolveTimeoutMs(entry, input, defaultTimeoutMs, context) {
79432
79701
  const policy = entry.timeout;
79433
79702
  if (policy?.kind === "none") {
79434
79703
  return void 0;
79435
79704
  }
79436
79705
  const defaultMs = policy?.defaultMs ?? entry.metadata.timeoutMs ?? defaultTimeoutMs;
79437
- const entryResolvedMs = entry.resolveTimeoutBudgetMs?.(input);
79706
+ const entryResolvedMs = entry.resolveTimeoutBudgetMs?.(input, context);
79438
79707
  const requestedMs = entryResolvedMs ?? (policy?.allowCallOverride && isRecord4(input) && typeof input.timeout_ms === "number" ? input.timeout_ms : policy?.allowCallOverride && isRecord4(input) && typeof input.timeout === "number" ? input.timeout : defaultMs);
79439
79708
  const cappedMs = policy?.maxMs === void 0 ? requestedMs : Math.min(requestedMs, policy.maxMs);
79440
79709
  const cleanupGraceMs = Math.max(0, Math.trunc(policy?.cleanupGraceMs ?? 0));
@@ -86025,6 +86294,33 @@ function sanitizeModelConnectionInfo(connection) {
86025
86294
  return safeConnection;
86026
86295
  }
86027
86296
 
86297
+ // ../core/dist/tool/model-contract.js
86298
+ function resolveToolEntryModelContract(entry, context) {
86299
+ const projection = entry.resolveModelContract?.(context);
86300
+ if (!projection)
86301
+ return entry;
86302
+ return {
86303
+ ...entry,
86304
+ ...projection.inputSchema ? { inputSchema: projection.inputSchema } : {},
86305
+ metadata: {
86306
+ ...entry.metadata,
86307
+ ...projection.description !== void 0 ? { description: projection.description } : {}
86308
+ }
86309
+ };
86310
+ }
86311
+ function projectToolModelContract(contract, entry, context) {
86312
+ if (!entry)
86313
+ return contract;
86314
+ const projection = entry.resolveModelContract?.(context);
86315
+ if (!projection)
86316
+ return contract;
86317
+ return {
86318
+ ...contract,
86319
+ ...projection.description !== void 0 ? { description: projection.description } : {},
86320
+ ...projection.inputSchema ? { inputSchema: projection.inputSchema } : {}
86321
+ };
86322
+ }
86323
+
86028
86324
  // ../core/dist/tool/executor/call-runner.js
86029
86325
  async function executeToolCall(deps, backgroundTasks, toolCall, options) {
86030
86326
  const totalStartedAt = Date.now();
@@ -86036,7 +86332,12 @@ async function executeToolCall(deps, backgroundTasks, toolCall, options) {
86036
86332
  async function executeToolCallImpl(deps, backgroundTasks, toolCall, totalStartedAt, options, telemetry) {
86037
86333
  const parentTraceContext = options?.traceContext ?? getCurrentTraceContext() ?? deps.traceContext ?? createRootTraceContext({ sessionId: deps.sessionId, turnId: deps.turnId });
86038
86334
  const emptyToolName = isEmptyToolName(toolCall.name);
86039
- const entry = emptyToolName ? void 0 : deps.registry.get(toolCall.name);
86335
+ const registeredEntry = emptyToolName ? void 0 : deps.registry.get(toolCall.name);
86336
+ const model = options?.model ?? deps.model;
86337
+ const entry = registeredEntry ? resolveToolEntryModelContract(registeredEntry, {
86338
+ model,
86339
+ turnExecutionModel: options?.turnExecutionModel
86340
+ }) : void 0;
86040
86341
  const canonicalToolCall = entry && toolCall.name !== entry.metadata.name ? { ...toolCall, name: entry.metadata.name } : toolCall;
86041
86342
  const traceContext = createChildTraceContext(parentTraceContext, {
86042
86343
  sessionId: deps.sessionId,
@@ -86146,13 +86447,16 @@ async function executeToolCallImpl(deps, backgroundTasks, toolCall, totalStarted
86146
86447
  toolCallId: canonicalToolCall.id,
86147
86448
  toolName: canonicalToolCall.name
86148
86449
  });
86149
- const timeoutMs = resolveTimeoutMs(entry, executionInput, deps.defaultTimeoutMs);
86450
+ const timeoutMs = resolveTimeoutMs(entry, executionInput, deps.defaultTimeoutMs, {
86451
+ model,
86452
+ turnExecutionModel: options?.turnExecutionModel
86453
+ });
86150
86454
  const executionAbortController = new AbortController();
86151
86455
  const unlinkParentAbort = linkAbortSignal(options?.signal, executionAbortController);
86152
86456
  let readFileStateMetadata;
86457
+ let skillTelemetryMetadata;
86153
86458
  let failureStage = "handler";
86154
86459
  try {
86155
- const model = options?.model ?? deps.model;
86156
86460
  const modelRef2 = model ? { providerId: model.providerId, modelId: model.modelId } : deps.getModelRef?.() ?? deps.modelRef;
86157
86461
  const bashShellSelection = deps.getBashShellSelection?.() ?? deps.bashShellSelection;
86158
86462
  const embeddedSearchDecision = modelRef2 ? resolveEmbeddedSearchBranchCapability({
@@ -86178,6 +86482,7 @@ async function executeToolCallImpl(deps, backgroundTasks, toolCall, totalStarted
86178
86482
  fileSystemPort: deps.fileSystemPort,
86179
86483
  httpClientPort: deps.httpClientPort,
86180
86484
  imageProcessorPort: deps.imageProcessorPort,
86485
+ pdfDocumentPort: deps.pdfDocumentPort,
86181
86486
  model,
86182
86487
  modelConnectionPort: deps.modelConnectionPort,
86183
86488
  modelRef: modelRef2,
@@ -86200,6 +86505,9 @@ async function executeToolCallImpl(deps, backgroundTasks, toolCall, totalStarted
86200
86505
  recordReadFileStateMetadata: (metadata) => {
86201
86506
  readFileStateMetadata = metadata;
86202
86507
  },
86508
+ recordSkillTelemetryMetadata: (metadata) => {
86509
+ skillTelemetryMetadata = metadata;
86510
+ },
86203
86511
  bashShellSelection,
86204
86512
  setWorkingDirectory: deps.setWorkingDirectory,
86205
86513
  workingDirectory: deps.getWorkingDirectory(),
@@ -86250,7 +86558,7 @@ async function executeToolCallImpl(deps, backgroundTasks, toolCall, totalStarted
86250
86558
  startedAt: new Date(startTime),
86251
86559
  completedAt: /* @__PURE__ */ new Date()
86252
86560
  };
86253
- await emitToolCallResult(deps, canonicalToolCall, traceContext, turnId, serialization, durationMs, display, perf);
86561
+ await emitToolCallResult(deps, canonicalToolCall, traceContext, turnId, serialization, durationMs, display, perf, skillTelemetryMetadata);
86254
86562
  await backgroundTasks.trackBackgroundTask(canonicalToolCall, output, traceContext, turnId);
86255
86563
  deps.logger?.info("Tool call completed", {
86256
86564
  ...traceContextToLogContext(traceContext),
@@ -86288,7 +86596,7 @@ async function executeToolCallImpl(deps, backgroundTasks, toolCall, totalStarted
86288
86596
  error: error98,
86289
86597
  toolName: canonicalToolCall.name
86290
86598
  });
86291
- await emitToolCallError(deps, canonicalToolCall.id, traceContext, turnId, result.error);
86599
+ await emitToolCallError(deps, canonicalToolCall.id, traceContext, turnId, result.error, skillTelemetryMetadata);
86292
86600
  deps.logger?.error("Tool call failed", error98 instanceof Error ? error98 : new Error(String(error98)), {
86293
86601
  ...traceContextToLogContext(traceContext),
86294
86602
  durationMs,
@@ -86372,6 +86680,7 @@ var ToolExecutorImpl = class {
86372
86680
  fileSystemPort: options.fileSystemPort,
86373
86681
  httpClientPort: options.httpClientPort,
86374
86682
  imageProcessorPort: options.imageProcessorPort,
86683
+ pdfDocumentPort: options.pdfDocumentPort,
86375
86684
  model: options.model,
86376
86685
  modelConnectionPort: options.modelConnectionPort,
86377
86686
  embeddedSearchBackend: options.embeddedSearchBackend,
@@ -86420,7 +86729,7 @@ function createToolExecutor2(options) {
86420
86729
  }
86421
86730
 
86422
86731
  // ../core/dist/tool/handlers/read.js
86423
- import { basename as basename3, dirname, extname } from "node:path";
86732
+ import { basename as basename4, dirname, extname } from "node:path";
86424
86733
 
86425
86734
  // ../core/dist/tool/read-file-state.js
86426
86735
  import { platform as currentPlatform2 } from "node:process";
@@ -86724,10 +87033,12 @@ function createToolTrace(context) {
86724
87033
 
86725
87034
  // ../core/dist/runtime/helpers/attachment-data-url.js
86726
87035
  function parseDataUrlHeader(dataUrl) {
86727
- const match = /^data:([^;,]+)(?:;base64)?,/i.exec(dataUrl);
86728
- if (!match)
87036
+ const commaIndex = dataUrl.indexOf(",");
87037
+ if (dataUrl.slice(0, "data:".length).toLowerCase() !== "data:" || commaIndex < 0) {
86729
87038
  return void 0;
86730
- return { mediaType: match[1].toLowerCase() };
87039
+ }
87040
+ const mediaType = dataUrl.slice("data:".length, commaIndex).split(";", 1)[0]?.trim();
87041
+ return mediaType ? { mediaType: mediaType.toLowerCase() } : void 0;
86731
87042
  }
86732
87043
  function base64PayloadByteLength(payload) {
86733
87044
  const paddingBytes = payload.endsWith("==") ? 2 : payload.endsWith("=") ? 1 : 0;
@@ -86843,6 +87154,257 @@ function createToolTrace2(context) {
86843
87154
  };
86844
87155
  }
86845
87156
 
87157
+ // ../core/dist/tool/handlers/read-pdf.js
87158
+ import { basename as basename3 } from "node:path";
87159
+ var READ_PROVIDER_PDF_DESCRIPTION_LINE = '- Reads PDFs via the `pages` parameter (e.g. "1-5", max 20 pages/request; required for PDFs over 10 pages).';
87160
+ var READ_ERROR_CODE_BY_PDF_DOCUMENT_ERROR = {
87161
+ cancelled: void 0,
87162
+ corrupted: ReadErrorCode.PDF_INVALID,
87163
+ io_error: ReadErrorCode.PDF_IO_ERROR,
87164
+ page_out_of_range: ReadErrorCode.PDF_PAGE_OUT_OF_RANGE,
87165
+ password_protected: ReadErrorCode.PDF_PASSWORD_PROTECTED,
87166
+ permission_denied: ReadErrorCode.PDF_PERMISSION_DENIED,
87167
+ process_failed: ReadErrorCode.PDF_PROCESS_FAILED,
87168
+ timeout: ReadErrorCode.PDF_TIMEOUT,
87169
+ unavailable: ReadErrorCode.PDF_CONFIGURATION_ERROR
87170
+ };
87171
+ var READ_PDF_TOOL_TIMEOUT_MS = READ_PDF_RENDER_TIMEOUT_MS + 3e4;
87172
+ function isPdfPath(filePath) {
87173
+ return filePath.toLowerCase().endsWith(".pdf");
87174
+ }
87175
+ function supportsPdfForExecution(context) {
87176
+ if (context.turnExecutionModel) {
87177
+ return context.turnExecutionModel.modelInputMediaCapabilities?.supportsPdf === true;
87178
+ }
87179
+ return context.model?.properties.supportsPdf === true;
87180
+ }
87181
+ function supportsImagesForExecution(context) {
87182
+ if (context.turnExecutionModel) {
87183
+ return context.turnExecutionModel.modelInputMediaCapabilities?.supportsImages;
87184
+ }
87185
+ return context.model?.properties.supportsImages;
87186
+ }
87187
+ function resolveReadInputSchema(context) {
87188
+ return supportsPdfForExecution(context) ? ReadPdfInputJsonSchema : ReadInputJsonSchema;
87189
+ }
87190
+ function resolveReadProviderDescription(baseDescription, context) {
87191
+ if (!supportsPdfForExecution(context))
87192
+ return baseDescription;
87193
+ const lines = baseDescription.split("\n");
87194
+ const imageLineIndex = lines.findIndex((line) => line.startsWith("- Reads images"));
87195
+ if (imageLineIndex < 0)
87196
+ return `${baseDescription}
87197
+ ${READ_PROVIDER_PDF_DESCRIPTION_LINE}`;
87198
+ lines.splice(imageLineIndex + 1, 0, READ_PROVIDER_PDF_DESCRIPTION_LINE);
87199
+ return lines.join("\n");
87200
+ }
87201
+ function resolveReadTimeoutBudgetMs(input, context) {
87202
+ if (!context || !supportsPdfForExecution(context) || !isRecord11(input))
87203
+ return void 0;
87204
+ return typeof input.file_path === "string" && isPdfPath(input.file_path) && typeof input.pages === "string" ? READ_PDF_TOOL_TIMEOUT_MS : void 0;
87205
+ }
87206
+ async function readPdfFile(input, context) {
87207
+ if (input.pages !== void 0 && supportsImagesForExecution(context) === false) {
87208
+ return failure(ReadErrorCode.PDF_PAGES_IMAGES_UNSUPPORTED, "The current model supports PDF input but does not support image input; remove the pages parameter.");
87209
+ }
87210
+ const fileSystemPort = context.fileSystemPort;
87211
+ if (!fileSystemPort) {
87212
+ return failure(ReadErrorCode.PDF_CONFIGURATION_ERROR, "FileSystemPort is not configured for Read tool.");
87213
+ }
87214
+ const trace = createToolTrace3(context);
87215
+ const stat2 = await fileSystemPort.stat({ path: input.filePath, trace }, { signal: context.abortSignal });
87216
+ if (stat2.kind !== "file") {
87217
+ return failure(ReadErrorCode.PDF_INVALID, `Path is not a regular file: ${input.filePath}`);
87218
+ }
87219
+ if (stat2.sizeBytes === 0) {
87220
+ return failure(ReadErrorCode.PDF_INVALID, `PDF file is empty: ${input.filePath}`);
87221
+ }
87222
+ return input.pages === void 0 ? await readNativePdf(input.filePath, stat2.sizeBytes, trace, context) : await readPdfPages(input.filePath, input.pages, stat2.sizeBytes, trace, context);
87223
+ }
87224
+ async function readNativePdf(filePath, sizeBytes, trace, context) {
87225
+ if (sizeBytes > READ_PDF_NATIVE_MAX_INPUT_BYTES) {
87226
+ return failure(ReadErrorCode.PDF_TOO_LARGE, `PDF file exceeds maximum allowed size of ${formatFileSize(READ_PDF_NATIVE_MAX_INPUT_BYTES)}.`);
87227
+ }
87228
+ if (context.pdfDocumentPort) {
87229
+ try {
87230
+ const pageCount = await context.pdfDocumentPort.getPageCount({ filePath, trace }, { signal: context.abortSignal });
87231
+ if (pageCount !== void 0 && pageCount > READ_PDF_NATIVE_MAX_PAGES) {
87232
+ return failure(ReadErrorCode.PDF_TOO_MANY_PAGES, `This PDF has ${pageCount} pages, which is too many to read at once. Use the pages parameter to read specific page ranges (e.g., pages: "1-5"). Maximum ${READ_PDF_MAX_PAGES_PER_REQUEST} pages per request.`);
87233
+ }
87234
+ } catch (error98) {
87235
+ rethrowPdfCancellation(error98, context.abortSignal);
87236
+ throw error98;
87237
+ }
87238
+ }
87239
+ const read = await context.fileSystemPort.readBinaryFile({ path: filePath, maxBytes: READ_PDF_NATIVE_MAX_INPUT_BYTES, trace }, { signal: context.abortSignal });
87240
+ if (!hasPdfMagic(read.content)) {
87241
+ return failure(ReadErrorCode.PDF_INVALID, `File is not a valid PDF (missing %PDF- header): ${filePath}`);
87242
+ }
87243
+ return {
87244
+ type: "pdf",
87245
+ filePath,
87246
+ base64: Buffer.from(read.content).toString("base64"),
87247
+ originalSize: read.sizeBytes
87248
+ };
87249
+ }
87250
+ async function readPdfPages(filePath, pagesInput, sizeBytes, trace, context) {
87251
+ if (sizeBytes > READ_PDF_EXTRACT_MAX_INPUT_BYTES) {
87252
+ return failure(ReadErrorCode.PDF_TOO_LARGE, `PDF file exceeds maximum allowed size for text extraction (${formatFileSize(READ_PDF_EXTRACT_MAX_INPUT_BYTES)}).`);
87253
+ }
87254
+ const range = parseReadPdfPageRange(pagesInput);
87255
+ if (!range) {
87256
+ return failure(ReadErrorCode.PDF_INVALID, `Invalid pages parameter: "${pagesInput}". Use formats like "1-5", "3", or "10-20". Pages are 1-indexed.`);
87257
+ }
87258
+ if (range.lastPage === Number.POSITIVE_INFINITY || range.lastPage - range.firstPage + 1 > READ_PDF_MAX_PAGES_PER_REQUEST) {
87259
+ return failure(ReadErrorCode.PDF_INVALID, `Page range "${pagesInput}" exceeds maximum of ${READ_PDF_MAX_PAGES_PER_REQUEST} pages per request. Please use a smaller range.`);
87260
+ }
87261
+ if (!context.pdfDocumentPort) {
87262
+ return failure(ReadErrorCode.PDF_CONFIGURATION_ERROR, "PDF page extraction is not configured in this runtime.");
87263
+ }
87264
+ if (!context.imageProcessorPort) {
87265
+ return failure(ReadErrorCode.PDF_CONFIGURATION_ERROR, "ImageProcessorPort is not configured for PDF page extraction.");
87266
+ }
87267
+ try {
87268
+ const renderedPages = await context.pdfDocumentPort.renderPages({
87269
+ filePath,
87270
+ firstPage: range.firstPage,
87271
+ lastPage: range.lastPage,
87272
+ trace
87273
+ }, { signal: context.abortSignal });
87274
+ const preparedPages = await Promise.all(renderedPages.map(async (page) => {
87275
+ const prepared = await context.imageProcessorPort.prepareForModel({
87276
+ data: page.data,
87277
+ maxBase64Bytes: READ_IMAGE_MAX_BASE64_BYTES,
87278
+ maxDimension: READ_IMAGE_MAX_DIMENSION,
87279
+ maxRawBytes: READ_IMAGE_TARGET_BYTES,
87280
+ maxTokens: READ_MAX_OUTPUT_TOKENS,
87281
+ mediaType: page.mediaType,
87282
+ tokenToBase64CharRatio: READ_IMAGE_TOKEN_TO_BASE64_CHAR_RATIO,
87283
+ trace
87284
+ }, { signal: context.abortSignal });
87285
+ return {
87286
+ type: "image",
87287
+ pageNumber: page.pageNumber,
87288
+ base64: Buffer.from(prepared.data).toString("base64"),
87289
+ mimeType: isReadImageMime(prepared.mediaType) ? prepared.mediaType : page.mediaType,
87290
+ originalSize: page.data.byteLength,
87291
+ transformedSize: prepared.transformedSizeBytes,
87292
+ resized: prepared.resized,
87293
+ compressed: prepared.compressed,
87294
+ compressionStrategy: prepared.strategy,
87295
+ dimensions: {
87296
+ originalWidth: prepared.originalWidth,
87297
+ originalHeight: prepared.originalHeight,
87298
+ displayWidth: prepared.width,
87299
+ displayHeight: prepared.height
87300
+ }
87301
+ };
87302
+ }));
87303
+ preparedPages.sort((left, right) => left.pageNumber - right.pageNumber);
87304
+ return {
87305
+ type: "parts",
87306
+ filePath,
87307
+ numParts: preparedPages.length,
87308
+ originalSize: sizeBytes,
87309
+ pages: preparedPages
87310
+ };
87311
+ } catch (error98) {
87312
+ rethrowPdfCancellation(error98, context.abortSignal);
87313
+ if (error98 instanceof PdfDocumentPortError) {
87314
+ const errorCode = READ_ERROR_CODE_BY_PDF_DOCUMENT_ERROR[error98.code];
87315
+ if (errorCode === void 0)
87316
+ throw error98;
87317
+ return failure(errorCode, error98.message);
87318
+ }
87319
+ throw error98;
87320
+ }
87321
+ }
87322
+ function rethrowPdfCancellation(error98, signal) {
87323
+ if (error98 instanceof PdfDocumentPortError && error98.code === "cancelled") {
87324
+ throw createCoreError(CoreErrorType.ToolCancelled, error98.message, {
87325
+ cause: error98,
87326
+ recoverable: true
87327
+ });
87328
+ }
87329
+ if (signal.aborted) {
87330
+ throw error98;
87331
+ }
87332
+ }
87333
+ function formatReadPdfOutput(output) {
87334
+ return [
87335
+ {
87336
+ type: "text",
87337
+ text: `PDF file read: ${output.filePath} (${formatFileSize(output.originalSize)})`
87338
+ },
87339
+ {
87340
+ type: "file",
87341
+ mediaType: "application/pdf",
87342
+ name: basename3(output.filePath),
87343
+ dataUrl: `data:application/pdf;base64,${output.base64}`,
87344
+ source: {
87345
+ id: "read-pdf",
87346
+ kind: "inline",
87347
+ mimeType: "application/pdf",
87348
+ placeholder: basename3(output.filePath),
87349
+ sizeBytes: output.originalSize
87350
+ }
87351
+ }
87352
+ ];
87353
+ }
87354
+ function formatReadPdfPagesOutput(output) {
87355
+ return [
87356
+ {
87357
+ type: "text",
87358
+ text: `PDF pages extracted: ${output.numParts} page(s) from ${output.filePath} (${formatFileSize(output.originalSize)})`
87359
+ },
87360
+ ...output.pages.map((page) => ({
87361
+ type: "image",
87362
+ mediaType: page.mimeType,
87363
+ dataUrl: `data:${page.mimeType};base64,${page.base64}`,
87364
+ source: {
87365
+ id: `read-pdf-page-${page.pageNumber}`,
87366
+ kind: "inline",
87367
+ mimeType: page.mimeType,
87368
+ placeholder: `PDF page ${page.pageNumber}`,
87369
+ sizeBytes: page.transformedSize ?? page.originalSize
87370
+ }
87371
+ }))
87372
+ ];
87373
+ }
87374
+ function formatFileSize(bytes) {
87375
+ if (bytes < 1024)
87376
+ return `${bytes} bytes`;
87377
+ if (bytes < 1024 * 1024)
87378
+ return `${oneDecimal(bytes / 1024)}KB`;
87379
+ if (bytes < 1024 * 1024 * 1024)
87380
+ return `${oneDecimal(bytes / (1024 * 1024))}MB`;
87381
+ return `${oneDecimal(bytes / (1024 * 1024 * 1024))}GB`;
87382
+ }
87383
+ function oneDecimal(value) {
87384
+ return value.toFixed(1).replace(/\.0$/u, "");
87385
+ }
87386
+ function hasPdfMagic(data) {
87387
+ return data.byteLength >= 5 && Buffer.from(data.subarray(0, 5)).toString("ascii") === "%PDF-";
87388
+ }
87389
+ function isReadImageMime(value) {
87390
+ return value === "image/jpeg" || value === "image/png" || value === "image/gif" || value === "image/webp";
87391
+ }
87392
+ function failure(errorCode, message) {
87393
+ return { result: false, errorCode, message };
87394
+ }
87395
+ function createToolTrace3(context) {
87396
+ return {
87397
+ traceId: context.traceId,
87398
+ spanId: context.spanId,
87399
+ parentSpanId: context.parentSpanId,
87400
+ sessionId: context.sessionId,
87401
+ turnId: context.turnId
87402
+ };
87403
+ }
87404
+ function isRecord11(value) {
87405
+ return typeof value === "object" && value !== null && !Array.isArray(value);
87406
+ }
87407
+
86846
87408
  // ../core/dist/tool/handlers/read.js
86847
87409
  var FILE_UNCHANGED_STUB = "Wasted call \u2014 file unchanged since your last Read. Refer to that earlier tool_result instead.";
86848
87410
  var READ_PROVIDER_DESCRIPTION = [
@@ -86875,9 +87437,11 @@ function formatReadOutput(output) {
86875
87437
  return formatReadImageOutput(output);
86876
87438
  case "video":
86877
87439
  return formatReadVideoOutput(output);
86878
- case "notebook":
86879
87440
  case "pdf":
87441
+ return formatReadPdfOutput(output);
86880
87442
  case "parts":
87443
+ return formatReadPdfPagesOutput(output);
87444
+ case "notebook":
86881
87445
  return stringifyReadOutputFallback(output);
86882
87446
  }
86883
87447
  }
@@ -86917,7 +87481,7 @@ function stringifyReadOutputFallback(output) {
86917
87481
  return JSON.stringify(output) ?? "";
86918
87482
  }
86919
87483
  var readHandler = async (input, context) => {
86920
- const { file_path, offset, limit } = parseReadInput(input);
87484
+ const { file_path, offset, limit, pages } = parseReadInput(input);
86921
87485
  const fileSystemPort = context.fileSystemPort;
86922
87486
  if (!fileSystemPort) {
86923
87487
  throw createCoreError(CoreErrorType.ConfigurationError, "FileSystemPort is not configured for Read tool", {
@@ -86943,6 +87507,9 @@ var readHandler = async (input, context) => {
86943
87507
  if (videoMime) {
86944
87508
  return await readVideoFile(filePath, videoMime, context);
86945
87509
  }
87510
+ if (isPdfPath(filePath) && supportsPdfForExecution(context)) {
87511
+ return await readPdfFile({ filePath, pages }, context);
87512
+ }
86946
87513
  const trace = createReadTrace(context);
86947
87514
  const stat2 = await fileSystemPort.stat({ path: filePath, trace }, { signal: context.abortSignal });
86948
87515
  const readFileState = getReadFileState(context);
@@ -87026,6 +87593,17 @@ function parseReadInput(input) {
87026
87593
  recoverable: true
87027
87594
  });
87028
87595
  }
87596
+ function validateReadInput(input) {
87597
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
87598
+ return { result: true };
87599
+ }
87600
+ const candidate = input;
87601
+ if (typeof candidate.file_path !== "string" || typeof candidate.pages !== "string") {
87602
+ return { result: true };
87603
+ }
87604
+ const failure2 = getReadPdfPagesValidationFailure(candidate.file_path, candidate.pages);
87605
+ return failure2 ? { result: false, ...failure2 } : { result: true };
87606
+ }
87029
87607
  function getReadInputToolUseErrorMessage(error98) {
87030
87608
  const issues = error98.issues;
87031
87609
  if (!Array.isArray(issues))
@@ -87124,11 +87702,11 @@ async function findSimilarFilename(filePath, context) {
87124
87702
  return void 0;
87125
87703
  try {
87126
87704
  const parent = dirname(filePath);
87127
- const targetName = basename3(filePath);
87128
- const targetStem = basename3(filePath, extname(filePath));
87705
+ const targetName = basename4(filePath);
87706
+ const targetStem = basename4(filePath, extname(filePath));
87129
87707
  const listed = await fileSystemPort.listDirectory({ path: parent, trace: createReadTrace(context) }, { signal: context.abortSignal });
87130
87708
  const entries = listed.entries.filter((entry) => entry.kind === "file" || entry.kind === "symlink").map((entry) => entry.name).filter((name) => name !== targetName).sort();
87131
- const sameStem = entries.find((name) => basename3(name, extname(name)) === targetStem);
87709
+ const sameStem = entries.find((name) => basename4(name, extname(name)) === targetStem);
87132
87710
  if (sameStem)
87133
87711
  return sameStem;
87134
87712
  return entries.find((name) => levenshteinDistance(name, targetName) <= 3);
@@ -87166,6 +87744,12 @@ var readToolEntry = {
87166
87744
  needsApproval: false
87167
87745
  },
87168
87746
  handler: readHandler,
87747
+ validateInput: validateReadInput,
87748
+ resolveModelContract: (context) => ({
87749
+ description: resolveReadProviderDescription(READ_PROVIDER_DESCRIPTION, context),
87750
+ inputSchema: resolveReadInputSchema(context)
87751
+ }),
87752
+ resolveTimeoutBudgetMs: resolveReadTimeoutBudgetMs,
87169
87753
  formatModelContent: formatReadModelContent,
87170
87754
  inputSchema: ReadInputJsonSchema,
87171
87755
  outputSchema: ReadOutputJsonSchema,
@@ -87192,12 +87776,12 @@ var readToolEntry = {
87192
87776
  },
87193
87777
  timeout: {
87194
87778
  defaultMs: 3e4,
87195
- maxMs: 3e4,
87779
+ maxMs: READ_PDF_TOOL_TIMEOUT_MS,
87196
87780
  allowCallOverride: false
87197
87781
  },
87198
87782
  cancellation: {
87199
87783
  supported: true,
87200
- cleanup: "none",
87784
+ cleanup: "required",
87201
87785
  userVisibleMessage: "Read was cancelled before file content was returned"
87202
87786
  },
87203
87787
  trace: {
@@ -87255,7 +87839,7 @@ var WRITE_USER_MODIFIED_NOTE = " The user modified your proposed content before
87255
87839
  var WRITE_NOT_READ_MESSAGE = "File has not been read yet. Read it first before writing to it.";
87256
87840
  var WRITE_STALE_MESSAGE = "File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.";
87257
87841
  function formatWriteModelContent(output) {
87258
- if (!isRecord11(output)) {
87842
+ if (!isRecord12(output)) {
87259
87843
  return "The file has been written successfully.";
87260
87844
  }
87261
87845
  const filePath = typeof output.filePath === "string" ? output.filePath : "the file";
@@ -87516,12 +88100,12 @@ function recordReadFileStateMetadata2(context, entry) {
87516
88100
  if (metadata)
87517
88101
  context.recordReadFileStateMetadata(metadata);
87518
88102
  }
87519
- function isRecord11(value) {
88103
+ function isRecord12(value) {
87520
88104
  return typeof value === "object" && value !== null && !Array.isArray(value);
87521
88105
  }
87522
88106
 
87523
88107
  // ../core/dist/tool/handlers/edit.js
87524
- import { basename as basename4, dirname as dirname2, extname as extname2 } from "node:path";
88108
+ import { basename as basename5, dirname as dirname2, extname as extname2 } from "node:path";
87525
88109
 
87526
88110
  // ../core/dist/tool/edit-matchers.js
87527
88111
  var BROAD_MATCHERS = /* @__PURE__ */ new Set([
@@ -87854,9 +88438,9 @@ var EDIT_NOT_READ_MESSAGE = "File has not been read yet. Read it first before wr
87854
88438
  var EDIT_STALE_MESSAGE = "File has been modified since read, either by the user or by a linter. Read it again before attempting to write it.";
87855
88439
  var EDIT_FRESHNESS_SUFFIX = " (file state is current in your context \u2014 no need to Read it back)";
87856
88440
  function formatEditModelContent(output) {
87857
- const filePath = isRecord12(output) && typeof output.filePath === "string" ? output.filePath : "the file";
87858
- const userModified = isRecord12(output) && output.userModified === true;
87859
- const replaceAll = isRecord12(output) && output.replaceAll === true;
88441
+ const filePath = isRecord13(output) && typeof output.filePath === "string" ? output.filePath : "the file";
88442
+ const userModified = isRecord13(output) && output.userModified === true;
88443
+ const replaceAll = isRecord13(output) && output.replaceAll === true;
87860
88444
  const modifiedNote = userModified ? ". The user modified your proposed changes before accepting them. " : "";
87861
88445
  const freshnessSuffix = userModified ? "" : EDIT_FRESHNESS_SUFFIX;
87862
88446
  if (replaceAll) {
@@ -88045,7 +88629,7 @@ var editToolEntry = {
88045
88629
  function editFailure(errorCode, message) {
88046
88630
  return { result: false, errorCode, message };
88047
88631
  }
88048
- function isRecord12(value) {
88632
+ function isRecord13(value) {
88049
88633
  return typeof value === "object" && value !== null && !Array.isArray(value);
88050
88634
  }
88051
88635
  function countOccurrences(content, needle) {
@@ -88094,11 +88678,11 @@ async function findSimilarFilename2(filePath, context) {
88094
88678
  return void 0;
88095
88679
  try {
88096
88680
  const parent = dirname2(filePath);
88097
- const targetName = basename4(filePath);
88098
- const targetStem = basename4(filePath, extname2(filePath));
88681
+ const targetName = basename5(filePath);
88682
+ const targetStem = basename5(filePath, extname2(filePath));
88099
88683
  const listed = await fileSystemPort.listDirectory({ path: parent, trace: createEditTrace(context) }, { signal: context.abortSignal });
88100
88684
  const entries = listed.entries.filter((entry) => entry.kind === "file" || entry.kind === "symlink").map((entry) => entry.name).filter((name) => name !== targetName).sort();
88101
- const sameStem = entries.find((name) => basename4(name, extname2(name)) === targetStem);
88685
+ const sameStem = entries.find((name) => basename5(name, extname2(name)) === targetStem);
88102
88686
  if (sameStem)
88103
88687
  return sameStem;
88104
88688
  return entries.find((name) => levenshteinDistance2(name, targetName) <= 3);
@@ -91796,7 +92380,7 @@ function formatStderrForModel(result) {
91796
92380
  return message;
91797
92381
  }
91798
92382
  function isBashOutputProviderError(output) {
91799
- if (!isRecord13(output))
92383
+ if (!isRecord14(output))
91800
92384
  return false;
91801
92385
  return isBashProviderErrorStatus(output);
91802
92386
  }
@@ -91867,7 +92451,7 @@ function maybeImageContent(result) {
91867
92451
  }
91868
92452
  ];
91869
92453
  }
91870
- function isRecord13(value) {
92454
+ function isRecord14(value) {
91871
92455
  return typeof value === "object" && value !== null && !Array.isArray(value);
91872
92456
  }
91873
92457
 
@@ -91920,7 +92504,7 @@ async function prepareBashImageOutput(stdout, context) {
91920
92504
  data: parsed.data,
91921
92505
  maxDimension: READ_IMAGE_MAX_DIMENSION,
91922
92506
  mediaType: parsed.mediaType,
91923
- trace: createToolTrace3(context)
92507
+ trace: createToolTrace4(context)
91924
92508
  }, { signal: context.abortSignal });
91925
92509
  return {
91926
92510
  stdout: `data:${resized.mediaType};base64,${Buffer.from(resized.data).toString("base64")}`
@@ -91959,7 +92543,7 @@ function shouldFallbackToOriginalImage(error98) {
91959
92543
  return true;
91960
92544
  return error98.code === "processing_failed";
91961
92545
  }
91962
- function createToolTrace3(context) {
92546
+ function createToolTrace4(context) {
91963
92547
  return {
91964
92548
  traceId: context.traceId,
91965
92549
  spanId: context.spanId,
@@ -92865,7 +93449,8 @@ function resolveBashTimeoutMs(inputTimeoutMs, policy) {
92865
93449
 
92866
93450
  // ../core/dist/tool/handlers/bash.js
92867
93451
  var MAX_INLINE_OUTPUT_BYTES = 3e4;
92868
- var MAX_PERSISTED_OUTPUT_BYTES = 64 * 1024 * 1024;
93452
+ var MAX_ARTIFACT_OUTPUT_BYTES = 64 * 1024 * 1024;
93453
+ var MAX_RUNTIME_PERSISTED_OUTPUT_BYTES = 5 * 1024 * 1024 * 1024;
92869
93454
  var BASH_PROVIDER_DESCRIPTION = createBashProviderDescription({
92870
93455
  defaultTimeoutMs: DEFAULT_BASH_TIMEOUT_POLICY.defaultTimeoutMs,
92871
93456
  maxTimeoutMs: DEFAULT_BASH_TIMEOUT_POLICY.maxTimeoutMs
@@ -93113,7 +93698,8 @@ function createExecutionRequest(input, context, timeoutPolicy) {
93113
93698
  outputLimit: {
93114
93699
  maxInlineBytes: MAX_INLINE_OUTPUT_BYTES,
93115
93700
  maxBufferBytes: MAX_INLINE_OUTPUT_BYTES,
93116
- maxPersistedBytes: MAX_PERSISTED_OUTPUT_BYTES,
93701
+ maxPersistedBytes: MAX_RUNTIME_PERSISTED_OUTPUT_BYTES,
93702
+ maxArtifactBytes: MAX_ARTIFACT_OUTPUT_BYTES,
93117
93703
  persistOutput: input.run_in_background ? "always" : "on_truncate",
93118
93704
  killProcessOnPersistedLimit: input.run_in_background === true
93119
93705
  },
@@ -106660,7 +107246,7 @@ function extractResults(toolResults) {
106660
107246
  function collectResults(value) {
106661
107247
  if (Array.isArray(value))
106662
107248
  return value.flatMap((item) => collectResults(item));
106663
- if (!isRecord14(value))
107249
+ if (!isRecord15(value))
106664
107250
  return [];
106665
107251
  const url3 = stringValue(value.url);
106666
107252
  const type = stringValue(value.type);
@@ -106703,7 +107289,7 @@ function extractSourcesFromSummary(summary) {
106703
107289
  function collectSources(value) {
106704
107290
  if (Array.isArray(value))
106705
107291
  return value.flatMap((item) => collectSources(item));
106706
- if (!isRecord14(value))
107292
+ if (!isRecord15(value))
106707
107293
  return [];
106708
107294
  const url3 = stringValue(value.url);
106709
107295
  if (url3)
@@ -106744,7 +107330,7 @@ function nullableString(value) {
106744
107330
  function stringValue(value) {
106745
107331
  return typeof value === "string" && value.length > 0 ? value : void 0;
106746
107332
  }
106747
- function isRecord14(value) {
107333
+ function isRecord15(value) {
106748
107334
  return typeof value === "object" && value !== null && !Array.isArray(value);
106749
107335
  }
106750
107336
 
@@ -107476,6 +108062,11 @@ var skillHandler = async (input, context) => {
107476
108062
  turnId: context.turnId
107477
108063
  }
107478
108064
  }, { signal: context.abortSignal });
108065
+ context.recordSkillTelemetryMetadata?.({
108066
+ ...loaded.metadata.qualifiedName ? { qualifiedName: loaded.metadata.qualifiedName } : {},
108067
+ ...loaded.metadata.pluginId ? { pluginId: loaded.metadata.pluginId } : {},
108068
+ source: loaded.metadata.source
108069
+ });
107479
108070
  return [
107480
108071
  `<skill_content name="${loaded.metadata.name}">`,
107481
108072
  `# Skill: ${loaded.metadata.name}`,
@@ -107805,11 +108396,11 @@ var cronDeleteHandler = async (input, context) => {
107805
108396
  assertNotAutomationTurn(context, "CronDelete");
107806
108397
  const parsed = CronDeleteInputSchema.parse(input);
107807
108398
  assertAutomationPort(context, "CronDelete");
107808
- await context.automationPort.delete(parsed);
108399
+ const deleted = await context.automationPort.delete(parsed);
107809
108400
  return {
107810
- deleted: true,
108401
+ deleted,
107811
108402
  id: parsed.id,
107812
- message: `Deleted automation ${parsed.id}.`
108403
+ message: deleted ? `Deleted automation ${parsed.id}.` : `Automation ${parsed.id} was not found in the current workspace.`
107813
108404
  };
107814
108405
  };
107815
108406
  function cronPermission(permission, reason, needsApproval) {
@@ -110690,7 +111281,8 @@ var InMemoryHookRunner = class {
110690
111281
  await this.emitHookEvent(SessionEventType.HookRunBlocked, input, hookInvocationId, hookRunId, hookIndex, clientVisibleHookCount, hook, descriptor2, startedAt, {
110691
111282
  durationMs: 0,
110692
111283
  errorCode: admission.reasonCode,
110693
- outcome: HookOutcome.Blocked
111284
+ outcome: HookOutcome.Blocked,
111285
+ ...admission.reasonCode ? { blockReason: sanitizeHookDisplayText(admission.reasonCode) } : {}
110694
111286
  });
110695
111287
  continue;
110696
111288
  }
@@ -110725,14 +111317,21 @@ var InMemoryHookRunner = class {
110725
111317
  continue;
110726
111318
  }
110727
111319
  try {
110728
- const output = await this.runCallbackWithTimeout(hook, input, runtimeIndex, options.signal);
111320
+ const callbackResult = await this.runCallbackWithTimeout(hook, input, runtimeIndex, options.signal);
111321
+ const { output, diagnostics } = unwrapHookCallbackResult(callbackResult);
110729
111322
  const durationMs = Date.now() - startedAt;
110730
111323
  const processed = processHookOutput(input.hookEventName, output);
110731
111324
  mergeHookRunResult(result, processed);
110732
- const blocked = processed.permissionBehavior === "deny" || processed.preventContinuation || processed.blockRequested;
111325
+ const blocked = processed.permissionBehavior === "deny" || processed.permissionRequestResult?.behavior === "deny" || processed.preventContinuation || processed.blockRequested;
111326
+ const blockReason = blocked ? sanitizeHookDisplayText(processed.stopReason ?? processed.hookPermissionDecisionReason ?? (processed.permissionRequestResult?.behavior === "deny" ? processed.permissionRequestResult.message : void 0) ?? "Hook blocked execution") : void 0;
111327
+ const safeDiagnostics = blocked ? sanitizeHookDiagnostics(diagnostics) : void 0;
110733
111328
  await this.emitHookEvent(blocked ? SessionEventType.HookRunBlocked : SessionEventType.HookRunCompleted, input, hookInvocationId, hookRunId, hookIndex, clientVisibleHookCount, hook, descriptor2, startedAt, {
110734
111329
  durationMs,
110735
- outcome: blocked ? HookOutcome.Blocked : HookOutcome.Success
111330
+ outcome: blocked ? HookOutcome.Blocked : HookOutcome.Success,
111331
+ ...blockReason ? { blockReason } : {},
111332
+ ...safeDiagnostics?.errorMessage ? { errorMessage: safeDiagnostics.errorMessage } : {},
111333
+ ...safeDiagnostics?.stderrPreview ? { stderrPreview: safeDiagnostics.stderrPreview } : {},
111334
+ ...safeDiagnostics?.stdoutPreview ? { stdoutPreview: safeDiagnostics.stdoutPreview } : {}
110736
111335
  });
110737
111336
  } catch (error98) {
110738
111337
  const durationMs = Date.now() - startedAt;
@@ -110855,6 +111454,33 @@ var InMemoryHookRunner = class {
110855
111454
  });
110856
111455
  }
110857
111456
  };
111457
+ function unwrapHookCallbackResult(result) {
111458
+ if (isHookCallbackResult(result)) {
111459
+ return { output: result.output, diagnostics: result.diagnostics };
111460
+ }
111461
+ return { output: result, diagnostics: void 0 };
111462
+ }
111463
+ function isHookCallbackResult(value) {
111464
+ return Boolean(value && typeof value === "object" && "kind" in value && value.kind === "hookCallbackResult");
111465
+ }
111466
+ function sanitizeHookDiagnostics(diagnostics) {
111467
+ if (!diagnostics)
111468
+ return void 0;
111469
+ const sanitize = (value) => {
111470
+ const trimmed = value?.trim();
111471
+ return trimmed ? sanitizeHookDisplayText(trimmed).slice(0, 4e3) : void 0;
111472
+ };
111473
+ const errorMessage = sanitize(diagnostics.errorMessage);
111474
+ const stderrPreview = sanitize(diagnostics.stderrPreview);
111475
+ const stdoutPreview = sanitize(diagnostics.stdoutPreview);
111476
+ if (!errorMessage && !stderrPreview && !stdoutPreview)
111477
+ return void 0;
111478
+ return {
111479
+ ...errorMessage ? { errorMessage } : {},
111480
+ ...stderrPreview ? { stderrPreview } : {},
111481
+ ...stdoutPreview ? { stdoutPreview } : {}
111482
+ };
111483
+ }
110858
111484
  function createInMemoryHookRunner(options) {
110859
111485
  return new InMemoryHookRunner(options);
110860
111486
  }
@@ -110936,10 +111562,10 @@ function createConfiguredHookCallback(options, event, hook, matcherIndex, hookIn
110936
111562
  }
110937
111563
  function processHookExecutionResult(input, result, event) {
110938
111564
  if (result.status === "completed" && (result.exitCode ?? 0) === 0) {
110939
- return parseHookStdout(result.stdout.text, event);
111565
+ return attachHookDiagnostics(parseHookStdout(result.stdout.text, event), result);
110940
111566
  }
110941
111567
  if (result.exitCode === 2) {
110942
- return createExitCodeBlockOutput(input, result);
111568
+ return attachHookDiagnostics(createExitCodeBlockOutput(input, result), result);
110943
111569
  }
110944
111570
  const message = result.error?.message ?? trimForPreview(result.stderr.text) ?? `Hook process exited with status ${result.status}`;
110945
111571
  throw createCoreError(CoreErrorType.ToolExecutionFailed, "Hook process failed", {
@@ -110954,6 +111580,20 @@ function processHookExecutionResult(input, result, event) {
110954
111580
  recoverable: true
110955
111581
  });
110956
111582
  }
111583
+ function attachHookDiagnostics(output, result) {
111584
+ const stderrPreview = trimForPreview(result.stderr.text);
111585
+ const stdoutPreview = result.exitCode === 2 ? trimForPreview(result.stdout.text) : void 0;
111586
+ if (!stderrPreview && !stdoutPreview)
111587
+ return output;
111588
+ return {
111589
+ kind: "hookCallbackResult",
111590
+ ...output ? { output } : {},
111591
+ diagnostics: {
111592
+ ...stderrPreview ? { errorMessage: stderrPreview, stderrPreview } : {},
111593
+ ...stdoutPreview ? { stdoutPreview } : {}
111594
+ }
111595
+ };
111596
+ }
110957
111597
  function parseHookStdout(stdout, event) {
110958
111598
  const trimmed = stdout.trim();
110959
111599
  if (!trimmed || !trimmed.startsWith("{"))
@@ -111918,8 +112558,8 @@ var v4AttachmentPreviewSourceResultSchema = external_exports3.union([
111918
112558
  var v4AttachmentReadResultSchema = external_exports3.object({
111919
112559
  dataBase64: external_exports3.string(),
111920
112560
  mediaType: external_exports3.string().refine(
111921
- (value) => value.startsWith("image/") || value.startsWith("video/"),
111922
- "attachment preview only supports image/video media types"
112561
+ (value) => value.startsWith("image/") || value.startsWith("video/") || value.split(";", 1)[0]?.trim().toLowerCase() === "application/pdf",
112562
+ "attachment preview only supports image/video/pdf media types"
111923
112563
  ),
111924
112564
  totalBytes: external_exports3.number().int().nonnegative().max(PROTOCOL_V4_LIMITS.attachmentPreviewMaxBytes),
111925
112565
  nextOffset: external_exports3.number().int().positive().nullable()
@@ -112322,6 +112962,9 @@ var toolLifecycleFactSchema = external_exports3.object({
112322
112962
  agentId: external_exports3.string().min(1).optional(),
112323
112963
  agentType: external_exports3.string().optional(),
112324
112964
  childSessionId: external_exports3.string().min(1).optional(),
112965
+ skillQualifiedName: external_exports3.string().min(1).optional(),
112966
+ skillPluginId: external_exports3.string().min(1).optional(),
112967
+ skillSource: external_exports3.enum(["agents", "zcode", "bundled", "plugin", "remote"]).optional(),
112325
112968
  performance: toolPerformanceFactSchema.optional(),
112326
112969
  automationId: external_exports3.string().min(1).optional()
112327
112970
  }).strict();
@@ -113744,7 +114387,7 @@ function createExploreSubagentPort(options) {
113744
114387
  activityWatchdog.stop();
113745
114388
  taskAbort.dispose();
113746
114389
  borrowedForegroundAgentIds.delete(lifecycle.agentId);
113747
- await writeCompletedAgentArtifacts(lifecycle, request, completed.output, completed.events);
114390
+ await writeCompletedAgentArtifacts(lifecycle, request, completed.output);
113748
114391
  registry3.update(lifecycle.agentId, (task) => ({
113749
114392
  ...withoutRuntimeMessageState(task),
113750
114393
  status: "completed",
@@ -114065,7 +114708,6 @@ function createSubagentLifecycle(options, request, profile) {
114065
114708
  const metadataFile = join8(agentOutputDir, "metadata.json");
114066
114709
  const outputFile = join8(agentOutputDir, "output.txt");
114067
114710
  const taskOutputFile = join8(agentOutputDir, "task.output");
114068
- const transcriptFile = join8(agentOutputDir, "transcript.jsonl");
114069
114711
  const runTraceContext = createChildTraceContext(request.trace, {
114070
114712
  sessionId: request.sessionId,
114071
114713
  turnId: request.turnId,
@@ -114091,7 +114733,6 @@ function createSubagentLifecycle(options, request, profile) {
114091
114733
  metadataFile,
114092
114734
  outputFile,
114093
114735
  taskOutputFile,
114094
- transcriptFile,
114095
114736
  profile,
114096
114737
  startedAt,
114097
114738
  runTraceContext,
@@ -114108,7 +114749,6 @@ function createSubagentLifecycleFromTask(options, request, profile, task) {
114108
114749
  const metadataFile = join8(agentOutputDir, "metadata.json");
114109
114750
  const outputFile = join8(agentOutputDir, "output.txt");
114110
114751
  const taskOutputFile = join8(agentOutputDir, "task.output");
114111
- const transcriptFile = join8(agentOutputDir, "transcript.jsonl");
114112
114752
  const runTraceContext = createChildTraceContext(request.trace, {
114113
114753
  sessionId: request.sessionId,
114114
114754
  turnId: request.turnId,
@@ -114136,7 +114776,6 @@ function createSubagentLifecycleFromTask(options, request, profile, task) {
114136
114776
  metadataFile,
114137
114777
  outputFile,
114138
114778
  taskOutputFile,
114139
- transcriptFile,
114140
114779
  profile,
114141
114780
  startedAt,
114142
114781
  runTraceContext,
@@ -114562,7 +115201,7 @@ async function finalizeBackgroundCompletion(options, request, lifecycle, registr
114562
115201
  const current = registry3.get(lifecycle.agentId);
114563
115202
  if (current && isTerminalRuntimeTask(current))
114564
115203
  return;
114565
- await writeCompletedAgentArtifacts(lifecycle, request, completed.output, completed.events);
115204
+ await writeCompletedAgentArtifacts(lifecycle, request, completed.output);
114566
115205
  const notification = formatLocalAgentTaskNotification2({
114567
115206
  agentId: completed.output.agentId,
114568
115207
  agentType: completed.output.agentType,
@@ -114855,10 +115494,9 @@ async function emitSubagentEvent(options, type, request, traceContext, payload)
114855
115494
  });
114856
115495
  await options.emitParentEvent(event, traceContext);
114857
115496
  }
114858
- async function writeCompletedAgentArtifacts(lifecycle, request, output, events = []) {
115497
+ async function writeCompletedAgentArtifacts(lifecycle, request, output) {
114859
115498
  const text = output.content.map((block) => block.text).join("\n\n");
114860
115499
  await writeAgentOutputFiles(lifecycle, text);
114861
- await writeAgentTranscriptFile(lifecycle, events);
114862
115500
  await writeAgentMetadataFile(lifecycle, request, "completed", {
114863
115501
  completedAt: (/* @__PURE__ */ new Date()).toISOString(),
114864
115502
  totalDurationMs: output.totalDurationMs,
@@ -114902,11 +115540,6 @@ async function writeAgentOutputFiles(lifecycle, content) {
114902
115540
  await writeTextFile(lifecycle.outputFile, content);
114903
115541
  await writeTextFile(lifecycle.taskOutputFile, content);
114904
115542
  }
114905
- async function writeAgentTranscriptFile(lifecycle, events) {
114906
- const jsonl = events.map((event) => JSON.stringify(event)).join("\n");
114907
- await writeTextFile(lifecycle.transcriptFile, jsonl.length > 0 ? `${jsonl}
114908
- ` : "");
114909
- }
114910
115543
  async function writeAgentMetadataFile(lifecycle, request, status, extra = {}) {
114911
115544
  await writeTextFile(lifecycle.metadataFile, `${JSON.stringify({
114912
115545
  agentId: lifecycle.agentId,
@@ -114923,7 +115556,6 @@ async function writeAgentMetadataFile(lifecycle, request, status, extra = {}) {
114923
115556
  prompt: request.prompt,
114924
115557
  status,
114925
115558
  taskOutputFile: lifecycle.taskOutputFile,
114926
- transcriptFile: lifecycle.transcriptFile,
114927
115559
  updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
114928
115560
  workspaceRoot: request.workspaceRoot,
114929
115561
  ...extra
@@ -114936,7 +115568,7 @@ function aggregateModelUsage(events) {
114936
115568
  if (event.type !== SessionEventType.ModelComplete)
114937
115569
  continue;
114938
115570
  const payload = event.payload;
114939
- if (!isRecord15(payload) || !isRecord15(payload.usage)) {
115571
+ if (!isRecord16(payload) || !isRecord16(payload.usage)) {
114940
115572
  continue;
114941
115573
  }
114942
115574
  const modelUsage = payload.usage;
@@ -114951,7 +115583,7 @@ function resolveSubagentToolUseCount(events) {
114951
115583
  let turnCompleteToolCallCount = 0;
114952
115584
  let sawTurnCompleteToolCallCount = false;
114953
115585
  for (const event of events) {
114954
- if (event.type !== SessionEventType.TurnComplete || !isRecord15(event.payload)) {
115586
+ if (event.type !== SessionEventType.TurnComplete || !isRecord16(event.payload)) {
114955
115587
  continue;
114956
115588
  }
114957
115589
  const toolCallCount = event.payload.toolCallCount;
@@ -114994,7 +115626,7 @@ function resolveTotalTokens(usage) {
114994
115626
  }
114995
115627
  return getModelUsageTotalTokens(usage);
114996
115628
  }
114997
- function isRecord15(value) {
115629
+ function isRecord16(value) {
114998
115630
  return typeof value === "object" && value !== null && !Array.isArray(value);
114999
115631
  }
115000
115632
  function resolveAllowedTools(profile, options, executionModelRef2) {
@@ -115268,7 +115900,7 @@ var defaultPermissionConfig = {
115268
115900
  };
115269
115901
 
115270
115902
  // ../core/dist/runtime/deps.js
115271
- import { basename as basename5, join as join9, resolve as resolve7 } from "node:path";
115903
+ import { basename as basename6, join as join9, resolve as resolve7 } from "node:path";
115272
115904
 
115273
115905
  // ../core/dist/agent/read-file-state-hydrator.js
115274
115906
  async function hydrateReadFileStateFromSession(input) {
@@ -116280,12 +116912,22 @@ function buildProviderRequestMessages(input) {
116280
116912
  const renderedMessages = projectedEntries.map(renderProjectedEntryToModelMessage);
116281
116913
  const mergeResult = ENABLE_MCS_ADJACENT_USER_MERGE ? mergeAdjacentUserMessages(renderedMessages) : skipAdjacentUserMessageMerge(renderedMessages);
116282
116914
  const messages = mergeResult.messages;
116915
+ const sourceEntries = [];
116916
+ for (const [projectedIndex, mergedIndex] of mergeResult.indexMap.entries()) {
116917
+ if (sourceEntries[mergedIndex] !== void 0)
116918
+ continue;
116919
+ const entry = projectedEntries[projectedIndex];
116920
+ if (entry && !isRuntimeAttachmentEntry(entry)) {
116921
+ sourceEntries[mergedIndex] = entry;
116922
+ }
116923
+ }
116283
116924
  const finalLatestRealUserMessageIndex = latestRealUserMessageIndex >= 0 ? mergeResult.indexMap[latestRealUserMessageIndex] ?? -1 : -1;
116284
116925
  const cacheControlIndex = input.applyCacheControl === true ? finalizeLatestNonSystemMessageCacheControl(messages, {
116285
116926
  skipCacheWrite: input.skipCacheWrite === true
116286
116927
  }) : void 0;
116287
116928
  return {
116288
116929
  messages,
116930
+ sourceEntries,
116289
116931
  diagnostics: {
116290
116932
  bubbledAttachmentEntryCount: reorderResult.bubbledAttachmentEntryCount,
116291
116933
  ...finalLatestRealUserMessageIndex >= 0 ? { latestRealUserMessageIndex: finalLatestRealUserMessageIndex } : {},
@@ -116578,6 +117220,8 @@ function findLatestRealUserEntryIndex(entries) {
116578
117220
  const entry = entries[index];
116579
117221
  if (isRuntimeAttachmentEntry(entry))
116580
117222
  continue;
117223
+ if (entry.queryScope === "output_token_continuation")
117224
+ continue;
116581
117225
  if (entry.message.role !== "user" || isToolResultUserMessage(entry.message))
116582
117226
  continue;
116583
117227
  if (!entry.metadata)
@@ -117046,7 +117690,7 @@ function buildPostCompactRuntimeEntries(activeEntries, summaryEntry, options = {
117046
117690
  return [
117047
117691
  ...activeEntries.slice(0, prefixCount).map(cloneRuntimeEntry2),
117048
117692
  cloneRuntimeEntry2(summaryEntry),
117049
- ...(options.preservedEntries ?? []).map(cloneRuntimeEntry2),
117693
+ ...(options.preservedEntries ?? []).map(cloneCompactPreservedRuntimeEntry),
117050
117694
  ...(options.postCompactReminderEntries ?? []).map(cloneRuntimeEntry2)
117051
117695
  ];
117052
117696
  }
@@ -117097,6 +117741,16 @@ function maybeLocalMicrocompactRuntimeEntries(input) {
117097
117741
  function cloneRuntimeEntry2(entry) {
117098
117742
  return cloneRuntimeMessageEntry(entry);
117099
117743
  }
117744
+ function cloneCompactPreservedRuntimeEntry(entry) {
117745
+ const cloned = cloneRuntimeEntry2(entry);
117746
+ if (cloned.kind === "attachment" || cloned.message.role !== "assistant" || !cloned.tokens) {
117747
+ return cloned;
117748
+ }
117749
+ return {
117750
+ ...cloned,
117751
+ tokens: invalidateRuntimeTokenUsage(cloned.tokens)
117752
+ };
117753
+ }
117100
117754
 
117101
117755
  // ../core/dist/runtime/helpers/official-cua-media.js
117102
117756
  var OFFICIAL_CUA_RASTER_UNAVAILABLE_TEXT = "This CUA raster is not visible in this request. Do not send a coordinate target; capture a new raster first.";
@@ -117245,7 +117899,7 @@ function modelContentForToolResult(result) {
117245
117899
  function isErrorForToolResult(result) {
117246
117900
  if (!result.success)
117247
117901
  return true;
117248
- if (!isRecord17(result.output))
117902
+ if (!isRecord18(result.output))
117249
117903
  return false;
117250
117904
  const explicitIsError = result.output.isError ?? result.output.is_error;
117251
117905
  if (typeof explicitIsError === "boolean")
@@ -117265,7 +117919,7 @@ function stringifyForEstimation(value) {
117265
117919
  return String(value);
117266
117920
  }
117267
117921
  }
117268
- function isRecord17(value) {
117922
+ function isRecord18(value) {
117269
117923
  return typeof value === "object" && value !== null && !Array.isArray(value);
117270
117924
  }
117271
117925
  function parseMcpToolName(name) {
@@ -117328,14 +117982,14 @@ function findProviderBusinessFailureInMetadata(providerMetadata) {
117328
117982
  return void 0;
117329
117983
  }
117330
117984
  function createCoreErrorFromProviderBusinessLike(error98) {
117331
- const failure = readProviderBusinessFailureFromUnknown(error98);
117332
- if (!failure) {
117985
+ const failure2 = readProviderBusinessFailureFromUnknown(error98);
117986
+ if (!failure2) {
117333
117987
  return void 0;
117334
117988
  }
117335
- return createCoreError(CoreErrorType.ModelError, failure.message, {
117989
+ return createCoreError(CoreErrorType.ModelError, failure2.message, {
117336
117990
  context: {
117337
- ...failure.providerCode ? { providerCode: failure.providerCode } : {},
117338
- ...failure.responseBodySummary ? { responseBodySummary: failure.responseBodySummary } : {}
117991
+ ...failure2.providerCode ? { providerCode: failure2.providerCode } : {},
117992
+ ...failure2.responseBodySummary ? { responseBodySummary: failure2.responseBodySummary } : {}
117339
117993
  },
117340
117994
  recoverable: true,
117341
117995
  retryable: false
@@ -117503,16 +118157,16 @@ function finalizeSuspiciousEmptyModelResult(input) {
117503
118157
  throw createSuspiciousEmptyModelResultError(input.finishReason, input.rawFinishReason, input.model);
117504
118158
  }
117505
118159
  function tryCreateProviderBusinessModelErrorFromMetadata(providerMetadata, model) {
117506
- const failure = findProviderBusinessFailureInMetadata(providerMetadata);
117507
- if (!failure) {
118160
+ const failure2 = findProviderBusinessFailureInMetadata(providerMetadata);
118161
+ if (!failure2) {
117508
118162
  return void 0;
117509
118163
  }
117510
- return createCoreError(CoreErrorType.ModelError, failure.message, {
118164
+ return createCoreError(CoreErrorType.ModelError, failure2.message, {
117511
118165
  context: {
117512
118166
  ...model ? { modelId: model.modelId, providerId: model.providerId } : {},
117513
- ...failure.providerCode ? { providerCode: failure.providerCode } : {},
118167
+ ...failure2.providerCode ? { providerCode: failure2.providerCode } : {},
117514
118168
  source: "provider",
117515
- ...failure.responseBodySummary ? { responseBodySummary: failure.responseBodySummary } : {}
118169
+ ...failure2.responseBodySummary ? { responseBodySummary: failure2.responseBodySummary } : {}
117516
118170
  },
117517
118171
  recoverable: true,
117518
118172
  retryable: false
@@ -117926,7 +118580,7 @@ var MAX_IMAGE_ATTACHMENT_DIMENSION = 2e3;
117926
118580
 
117927
118581
  // ../core/dist/runtime/helpers/attachment-placeholder.js
117928
118582
  function resolvedPlaceholderAttachment(attachment, placeholder, errorCode, options = {}) {
117929
- const mime = options.mime ?? (attachment.type === "image" ? "image/*" : "text/plain");
118583
+ const mime = options.mime ?? (attachment.type === "image" ? "image/*" : attachment.type === "pdf" ? "application/pdf" : "text/plain");
117930
118584
  const safeOriginalRef = safeAttachmentOriginalRef(attachment);
117931
118585
  return {
117932
118586
  contentBlock: { type: "text", text: `[Attached ${mime}: ${placeholder}]` },
@@ -117940,9 +118594,10 @@ function resolvedPlaceholderAttachment(attachment, placeholder, errorCode, optio
117940
118594
  },
117941
118595
  mime,
117942
118596
  source: options.source,
117943
- // Bug 根因:无效 video data URL 虽已降级为占位文本,过去仍会通过 file part 的 url 落入 session。
117944
- // 只收紧 video;image/file 的既有占位恢复行为保持不变。
117945
- url: attachment.type === "video" ? safeOriginalRef ?? "" : attachment.path ?? attachment.content ?? ""
118597
+ // Bug 根因:无效 media data URL 虽已降级为占位文本,过去仍会通过 file part 的 url
118598
+ // 把 base64 正文落入 session。PDF 不得把 data URL 写入 part.data;可恢复的 artifact
118599
+ // URI 仍保留,便于后续诊断和按既定授权路径重试。
118600
+ url: attachment.type === "video" || attachment.type === "pdf" ? attachment.content?.startsWith("zcode-artifact://") ? attachment.content : attachment.path ?? (attachment.type === "pdf" ? "inline:pdf" : safeOriginalRef ?? "") : attachment.path ?? attachment.content ?? ""
117946
118601
  };
117947
118602
  }
117948
118603
 
@@ -117996,13 +118651,39 @@ function inferImageMimeFromPath2(path2) {
117996
118651
  return "image/png";
117997
118652
  }
117998
118653
 
118654
+ // ../core/dist/runtime/helpers/attachment-pdf.js
118655
+ var PDF_INPUT_MAX_BYTES = 20 * 1024 * 1024;
118656
+ function parseInlinePdfDataUrl(dataUrl) {
118657
+ const commaIndex = dataUrl.indexOf(",");
118658
+ if (dataUrl.slice(0, "data:".length).toLowerCase() !== "data:" || commaIndex < 0) {
118659
+ return void 0;
118660
+ }
118661
+ const headerParts = dataUrl.slice("data:".length, commaIndex).split(";");
118662
+ const mediaType = headerParts.shift()?.trim().toLowerCase();
118663
+ const payload = dataUrl.slice(commaIndex + 1);
118664
+ if (mediaType !== "application/pdf" || headerParts.at(-1)?.trim().toLowerCase() !== "base64" || !isStrictBase64Payload(payload)) {
118665
+ return void 0;
118666
+ }
118667
+ const bytes = Buffer.from(payload, "base64");
118668
+ if (!isPdfBytes(bytes))
118669
+ return void 0;
118670
+ return {
118671
+ mediaType: "application/pdf",
118672
+ sizeBytes: base64PayloadByteLength(payload),
118673
+ bytes
118674
+ };
118675
+ }
118676
+ function isPdfBytes(bytes) {
118677
+ return bytes.byteLength >= 5 && bytes[0] === 37 && bytes[1] === 80 && bytes[2] === 68 && bytes[3] === 70 && bytes[4] === 45;
118678
+ }
118679
+
117999
118680
  // ../core/dist/runtime/helpers/attachment-path-reference.js
118000
118681
  function resolvedInlineTextAttachment(attachment, index) {
118001
118682
  const content = attachment.content ?? "";
118002
118683
  const placeholder = attachment.path ?? `attachment-${index + 1}`;
118003
118684
  return {
118004
118685
  contentBlock: { type: "text", text: content },
118005
- filename: attachment.path ? basename5(attachment.path) : void 0,
118686
+ filename: attachment.path ? basename6(attachment.path) : void 0,
118006
118687
  metadata: {
118007
118688
  originalUrl: safeAttachmentOriginalRef(attachment),
118008
118689
  preview: {
@@ -118066,6 +118747,8 @@ function formatPathReferenceReason(reason) {
118066
118747
  }
118067
118748
  if (reason === "image_too_large")
118068
118749
  return "the image is larger than the inline media budget";
118750
+ if (reason === "pdf_too_large")
118751
+ return "the PDF is larger than the inline PDF input limit";
118069
118752
  if (reason === "text_too_large")
118070
118753
  return "the text file is larger than the inline text budget";
118071
118754
  if (reason === "video_too_large")
@@ -118118,6 +118801,55 @@ async function resolveInlineMediaAttachment(attachment, index, parsedMediaType,
118118
118801
  url: resource2.url
118119
118802
  };
118120
118803
  }
118804
+ if (attachment.type === "pdf" && attachment.content) {
118805
+ const pdfData = parseInlinePdfDataUrl(attachment.content);
118806
+ if (!pdfData) {
118807
+ return resolvedPlaceholderAttachment(attachment, placeholder, "attachment_pdf_invalid", {
118808
+ filename: attachment.filename,
118809
+ mime: "application/pdf",
118810
+ sizeBytes: attachment.sizeBytes
118811
+ });
118812
+ }
118813
+ if (pdfData.sizeBytes === 0 || pdfData.sizeBytes > PDF_INPUT_MAX_BYTES) {
118814
+ return resolvedPlaceholderAttachment(attachment, placeholder, "attachment_pdf_invalid", {
118815
+ filename: attachment.filename,
118816
+ mime: "application/pdf",
118817
+ sizeBytes: pdfData.sizeBytes
118818
+ });
118819
+ }
118820
+ const resource2 = await persistAttachmentDataUrl(attachment.content, index, pdfData.mediaType, {
118821
+ abortSignal: options.abortSignal,
118822
+ artifactStore: options.artifactStore,
118823
+ existingArtifactUri: options.existingArtifactUri,
118824
+ sessionId: options.sessionId,
118825
+ traceContext: options.traceContext,
118826
+ turnId: options.turnId
118827
+ });
118828
+ return {
118829
+ contentBlock: {
118830
+ type: "file",
118831
+ mediaType: pdfData.mediaType,
118832
+ name: attachment.filename,
118833
+ dataUrl: attachment.content,
118834
+ source: {
118835
+ id: `turn-attachment-${index + 1}`,
118836
+ kind: "inline",
118837
+ mimeType: pdfData.mediaType,
118838
+ placeholder,
118839
+ ...resource2.metadata.artifactUri ? { uri: resource2.metadata.artifactUri } : {}
118840
+ }
118841
+ },
118842
+ filename: attachment.filename,
118843
+ metadata: {
118844
+ recoverability: resource2.metadata.recoverability,
118845
+ sizeBytes: pdfData.sizeBytes,
118846
+ storageKind: resource2.metadata.storageKind,
118847
+ ...resource2.metadata.artifactUri ? { artifactUri: resource2.metadata.artifactUri } : {}
118848
+ },
118849
+ mime: pdfData.mediaType,
118850
+ url: resource2.url
118851
+ };
118852
+ }
118121
118853
  if (attachment.type !== "video" || !attachment.content)
118122
118854
  return void 0;
118123
118855
  const videoData = parseInlineVideoDataUrl(attachment.content);
@@ -118177,8 +118909,8 @@ async function resolveInlineMediaAttachment(attachment, index, parsedMediaType,
118177
118909
  async function resolveLocalMediaAttachment(attachment, index, options) {
118178
118910
  const attachmentPath = attachment.path;
118179
118911
  const absolutePath = resolve7(options.workingDirectory, attachmentPath);
118180
- const filename = basename5(absolutePath);
118181
- const mime = attachment.type === "image" ? inferImageMimeFromPath2(absolutePath) : inferVideoMimeFromPath(absolutePath) ?? attachment.mimeType ?? "video/mp4";
118912
+ const filename = basename6(absolutePath);
118913
+ const mime = attachment.type === "image" ? inferImageMimeFromPath2(absolutePath) : attachment.type === "pdf" ? "application/pdf" : inferVideoMimeFromPath(absolutePath) ?? attachment.mimeType ?? "video/mp4";
118182
118914
  const source = {
118183
118915
  type: "file",
118184
118916
  path: absolutePath,
@@ -118208,7 +118940,83 @@ async function resolveLocalMediaAttachment(attachment, index, options) {
118208
118940
  source,
118209
118941
  stat: stat2
118210
118942
  };
118211
- return attachment.type === "image" ? resolveLocalImageAttachment(context) : resolveLocalVideoAttachment(context);
118943
+ if (attachment.type === "image")
118944
+ return resolveLocalImageAttachment(context);
118945
+ if (attachment.type === "pdf")
118946
+ return resolveLocalPdfAttachment(context);
118947
+ return resolveLocalVideoAttachment(context);
118948
+ }
118949
+ async function resolveLocalPdfAttachment(context) {
118950
+ const { absolutePath, attachment, filename, mime, options, source, stat: stat2 } = context;
118951
+ if (stat2.sizeBytes > PDF_INPUT_MAX_BYTES) {
118952
+ return resolvedPathReferenceAttachment(attachment, attachment.path, {
118953
+ filename,
118954
+ mime,
118955
+ sizeBytes: stat2.sizeBytes,
118956
+ source,
118957
+ reason: "pdf_too_large"
118958
+ });
118959
+ }
118960
+ let read;
118961
+ try {
118962
+ read = await options.fileSystemPort.readBinaryFile({ path: absolutePath, maxBytes: PDF_INPUT_MAX_BYTES, trace: options.traceContext }, { signal: options.abortSignal });
118963
+ } catch (error98) {
118964
+ if (isFileSystemPortError(error98) && error98.code === "too_large") {
118965
+ return resolvedPathReferenceAttachment(attachment, attachment.path, {
118966
+ filename,
118967
+ mime,
118968
+ source,
118969
+ reason: "pdf_too_large"
118970
+ });
118971
+ }
118972
+ return localMediaReadFailure(attachment, filename, mime, source);
118973
+ }
118974
+ if (read.bytesRead === 0 || !isPdfBytes(read.content)) {
118975
+ return resolvedPlaceholderAttachment(attachment, attachment.path, "attachment_pdf_invalid", {
118976
+ filename,
118977
+ mime,
118978
+ sizeBytes: read.sizeBytes,
118979
+ source
118980
+ });
118981
+ }
118982
+ const dataUrl = `data:${mime};base64,${Buffer.from(read.content).toString("base64")}`;
118983
+ const resource = await persistAttachmentDataUrl(dataUrl, context.index, mime, {
118984
+ abortSignal: options.abortSignal,
118985
+ artifactStore: options.artifactStore,
118986
+ sessionId: options.sessionId,
118987
+ traceContext: options.traceContext,
118988
+ turnId: options.turnId
118989
+ });
118990
+ return {
118991
+ contentBlock: {
118992
+ type: "file",
118993
+ mediaType: mime,
118994
+ name: filename,
118995
+ dataUrl,
118996
+ source: {
118997
+ id: `turn-attachment-${context.index + 1}`,
118998
+ kind: "local_file",
118999
+ mimeType: mime,
119000
+ path: absolutePath,
119001
+ placeholder: attachment.path,
119002
+ sizeBytes: read.sizeBytes,
119003
+ sha256: read.revision?.hash,
119004
+ ...resource.metadata.artifactUri ? { uri: resource.metadata.artifactUri } : {}
119005
+ }
119006
+ },
119007
+ filename,
119008
+ metadata: {
119009
+ originalUrl: attachment.path,
119010
+ recoverability: resource.metadata.recoverability,
119011
+ sha256: read.revision?.hash,
119012
+ sizeBytes: read.sizeBytes,
119013
+ storageKind: resource.metadata.storageKind,
119014
+ ...resource.metadata.artifactUri ? { artifactUri: resource.metadata.artifactUri } : {}
119015
+ },
119016
+ mime,
119017
+ source,
119018
+ url: resource.url
119019
+ };
118212
119020
  }
118213
119021
  async function resolveLocalImageAttachment(context) {
118214
119022
  const { absolutePath, attachment, filename, index, mime, options, source, stat: stat2 } = context;
@@ -118363,7 +119171,7 @@ function summarizeTurnAttachmentsForEvent(attachments) {
118363
119171
  return void 0;
118364
119172
  return attachments.map((attachment, index) => {
118365
119173
  const path2 = attachment.path;
118366
- const fileName = attachment.filename ?? (path2 ? basename5(path2) : void 0) ?? `attachment-${index + 1}`;
119174
+ const fileName = attachment.filename ?? (path2 ? basename6(path2) : void 0) ?? `attachment-${index + 1}`;
118367
119175
  const dataUrlMime = attachment.content !== void 0 ? parseDataUrlHeader(attachment.content)?.mediaType : void 0;
118368
119176
  const mime = attachment.mimeType ?? dataUrlMime ?? (attachment.type === "url" ? "text/uri-list" : path2 ? attachment.type === "image" ? inferImageMimeFromPath2(path2) : inferAttachmentMimeFromPath(path2) : "application/octet-stream");
118369
119177
  const bytes = attachment.sizeBytes ?? (attachment.content !== void 0 ? Buffer.byteLength(attachment.content, "utf8") : 0);
@@ -118393,6 +119201,13 @@ async function resolveTurnAttachment(attachment, index, options) {
118393
119201
  };
118394
119202
  }
118395
119203
  if (attachment.content) {
119204
+ if (attachment.type === "pdf" && !isDataOrArtifactUrl(attachment.content)) {
119205
+ return resolvedPlaceholderAttachment(attachment, attachment.path ?? `attachment-${index + 1}`, "attachment_pdf_invalid", {
119206
+ filename: attachment.filename,
119207
+ mime: "application/pdf",
119208
+ sizeBytes: attachment.sizeBytes
119209
+ });
119210
+ }
118396
119211
  if (attachment.type !== "image" && !isDataOrArtifactUrl(attachment.content)) {
118397
119212
  return resolvedInlineTextAttachment(attachment, index);
118398
119213
  }
@@ -118408,7 +119223,7 @@ async function resolveTurnAttachment(attachment, index, options) {
118408
119223
  }
118409
119224
  const fileSystemPort = options.fileSystemPort;
118410
119225
  if (attachment.path && fileSystemPort) {
118411
- if (attachment.type === "image" || attachment.type === "video") {
119226
+ if (attachment.type === "image" || attachment.type === "video" || attachment.type === "pdf") {
118412
119227
  return await resolveLocalMediaAttachment(attachment, index, {
118413
119228
  ...options,
118414
119229
  fileSystemPort
@@ -118447,7 +119262,7 @@ async function resolvedInlineAttachment(attachment, index, options) {
118447
119262
  }
118448
119263
  async function resolveLocalFileAttachment(attachment, options) {
118449
119264
  const absolutePath = resolve7(options.workingDirectory, attachment.path);
118450
- const filename = basename5(absolutePath);
119265
+ const filename = basename6(absolutePath);
118451
119266
  const mime = "text/plain";
118452
119267
  const source = {
118453
119268
  type: "file",
@@ -118697,7 +119512,7 @@ function cloneContentBlock(block) {
118697
119512
  }
118698
119513
 
118699
119514
  // ../core/dist/runtime/helpers/media-budget.js
118700
- var DEFAULT_MODEL_REQUEST_MEDIA_BUDGET_BYTES = 4 * 1024 * 1024;
119515
+ var DEFAULT_MODEL_REQUEST_MEDIA_BUDGET_BYTES = 75 * 1024 * 1024;
118701
119516
  function projectMessagesForModelMediaPolicy(messages, capabilities, options = {}) {
118702
119517
  const capabilityProjection = projectMessagesForMediaCapabilities(messages, capabilities);
118703
119518
  const mediaBudgetProjection = projectMessagesForMediaBudget(capabilityProjection.messages, {
@@ -118919,7 +119734,7 @@ async function projectMessagesWithMediaAttachmentPaths(messages, artifactStore)
118919
119734
  return message;
118920
119735
  changed = true;
118921
119736
  const content = message.content.map((block) => {
118922
- if (block.type !== "image" && block.type !== "video" || !pathByBlock.has(block)) {
119737
+ if (!isPathProjectableUserMedia(block) || !pathByBlock.has(block)) {
118923
119738
  return cloneContentBlock3(block);
118924
119739
  }
118925
119740
  return {
@@ -118941,15 +119756,16 @@ async function projectMessagesWithMediaAttachmentPaths(messages, artifactStore)
118941
119756
  return changed ? projected : messages;
118942
119757
  }
118943
119758
  function isPathProjectableUserMedia(block) {
118944
- return (block.type === "image" || block.type === "video") && (block.source?.kind === "inline" && block.source.uri?.startsWith("zcode-artifact://") === true || block.source?.kind === "local_file" && Boolean(block.source.path));
119759
+ return (block.type === "image" || block.type === "video" || isPdfBlock(block)) && (block.source?.kind === "inline" && block.source.uri?.startsWith("zcode-artifact://") === true || block.source?.kind === "local_file" && Boolean(block.source.path));
118945
119760
  }
118946
119761
  async function resolveMediaAttachmentPath(block, artifactStore) {
118947
119762
  const source = block.source;
119763
+ const mediaType = isPdfBlock(block) ? "pdf" : block.type;
118948
119764
  if (source.kind === "local_file" && source.path)
118949
119765
  return source.path;
118950
119766
  const uri = source.uri;
118951
119767
  if (!uri?.startsWith("zcode-artifact://") || !artifactStore?.ensureMediaAttachmentPath) {
118952
- throw mediaAttachmentMaterializationError(block.type, source.placeholder ?? uri ?? source.id);
119768
+ throw mediaAttachmentMaterializationError(mediaType, source.placeholder ?? uri ?? source.id);
118953
119769
  }
118954
119770
  try {
118955
119771
  const result = await artifactStore.ensureMediaAttachmentPath({
@@ -118962,7 +119778,7 @@ async function resolveMediaAttachmentPath(block, artifactStore) {
118962
119778
  throw new Error("empty derived path");
118963
119779
  return result.path;
118964
119780
  } catch (error98) {
118965
- throw mediaAttachmentMaterializationError(block.type, source.placeholder ?? uri, error98);
119781
+ throw mediaAttachmentMaterializationError(mediaType, source.placeholder ?? uri, error98);
118966
119782
  }
118967
119783
  }
118968
119784
  function mediaAttachmentMaterializationError(type, label, cause) {
@@ -118971,9 +119787,12 @@ function mediaAttachmentMaterializationError(type, label, cause) {
118971
119787
  });
118972
119788
  }
118973
119789
  function mediaSourceText(type, path2) {
118974
- const label = type === "image" ? "Image" : "Video";
119790
+ const label = type === "image" ? "Image" : type === "video" ? "Video" : "PDF";
118975
119791
  return `[${label}: source: ${path2}]`;
118976
119792
  }
119793
+ function isPdfBlock(block) {
119794
+ return block.type === "file" && block.mediaType.split(";", 1)[0]?.trim().toLowerCase() === "application/pdf";
119795
+ }
118977
119796
  function cloneContentBlock3(block) {
118978
119797
  if (block.type === "image" || block.type === "video" || block.type === "file") {
118979
119798
  return { ...block, source: block.source ? { ...block.source } : void 0 };
@@ -119395,15 +120214,38 @@ function buildContextHistoryEntries(contextResult) {
119395
120214
  }
119396
120215
 
119397
120216
  // ../core/dist/runtime/methods/context-refresh.js
119398
- function refreshContextModelSnapshot(runtime) {
120217
+ function captureContextConfigurationSnapshot(runtime, modelRef2 = runtime.defaultModelRef) {
120218
+ return {
120219
+ language: runtime.config.language,
120220
+ modelRef: { ...modelRef2 },
120221
+ ...runtime.config.outputStyle ? { outputStyle: { ...runtime.config.outputStyle } } : {}
120222
+ };
120223
+ }
120224
+ function isContextConfigurationCurrent(runtime, modelRef2 = runtime.defaultModelRef) {
120225
+ const snapshot = runtime.contextConfigurationSnapshot;
120226
+ if (!snapshot)
120227
+ return false;
120228
+ const currentModel = runtime.config.envInfo?.currentModel;
120229
+ const modelIsCurrent = currentModel === void 0 || formatModelRef(snapshot.modelRef) === formatModelRef(modelRef2);
120230
+ const currentOutputStyle = runtime.config.outputStyle;
120231
+ const snapshotOutputStyle = snapshot.outputStyle;
120232
+ const outputStyleIsCurrent = currentOutputStyle?.name === snapshotOutputStyle?.name && currentOutputStyle?.prompt === snapshotOutputStyle?.prompt && currentOutputStyle?.keepCodingInstructions === snapshotOutputStyle?.keepCodingInstructions;
120233
+ return modelIsCurrent && snapshot.language === runtime.config.language && outputStyleIsCurrent;
120234
+ }
120235
+ function refreshContextModelSnapshotIfStale(runtime, modelRef2 = runtime.defaultModelRef) {
120236
+ if (isContextConfigurationCurrent(runtime, modelRef2))
120237
+ return;
120238
+ refreshContextModelSnapshot(runtime, modelRef2);
120239
+ }
120240
+ function refreshContextModelSnapshot(runtime, modelRef2 = runtime.defaultModelRef) {
119399
120241
  if (!runtime.contextBuilder || !runtime.contextInitialized) {
119400
120242
  if (runtime.contextBuilder) {
119401
- runtime.contextBuilder = runtime.createContextBuilderFromSnapshot(runtime.createConfigOnlyContextSnapshot(runtime.workingDirectory), runtime.memoryRoot, { memoryIndexContent: runtime.memoryIndexContent, persistEnvInfo: false });
120243
+ runtime.contextBuilder = runtime.createContextBuilderFromSnapshot(runtime.createConfigOnlyContextSnapshot(runtime.workingDirectory), runtime.memoryRoot, { memoryIndexContent: runtime.memoryIndexContent, modelRef: modelRef2, persistEnvInfo: false });
119402
120244
  }
119403
120245
  return;
119404
120246
  }
119405
120247
  const contextSnapshot = runtime.contextSourceSnapshot ?? runtime.createConfigOnlyContextSnapshot(runtime.workingDirectory);
119406
- runtime.contextBuilder = runtime.createContextBuilderFromSnapshot(contextSnapshot, runtime.memoryRoot, { memoryIndexContent: runtime.memoryIndexContent });
120248
+ runtime.contextBuilder = runtime.createContextBuilderFromSnapshot(contextSnapshot, runtime.memoryRoot, { memoryIndexContent: runtime.memoryIndexContent, modelRef: modelRef2 });
119407
120249
  const effectiveContextResult = runtime.contextBuilder.build();
119408
120250
  const activeEntries = runtime.messageHistory.borrowReadOnlyRuntimeEntries();
119409
120251
  const conversationEntries = activeEntries.slice(countContextPrefixMessages(activeEntries));
@@ -119412,6 +120254,7 @@ function refreshContextModelSnapshot(runtime) {
119412
120254
  ...buildContextHistoryEntries(effectiveContextResult),
119413
120255
  ...conversationEntries
119414
120256
  ]);
120257
+ runtime.contextConfigurationSnapshot = captureContextConfigurationSnapshot(runtime, modelRef2);
119415
120258
  }
119416
120259
 
119417
120260
  // ../core/dist/runtime/helpers/tool-allowlist.js
@@ -119785,7 +120628,9 @@ function updateConfig(patch) {
119785
120628
  this.config.modelRef = patch.modelRef;
119786
120629
  this.defaultModelRef = patch.modelRef;
119787
120630
  refreshBranchAwareBuiltInTools(this);
119788
- refreshContextModelSnapshot(this);
120631
+ if (!this.activeTurn) {
120632
+ refreshContextModelSnapshot(this);
120633
+ }
119789
120634
  }
119790
120635
  if ("modelInputMediaCapabilities" in patch) {
119791
120636
  this.config.modelInputMediaCapabilities = patch.modelInputMediaCapabilities;
@@ -119795,11 +120640,15 @@ function updateConfig(patch) {
119795
120640
  }
119796
120641
  if (patch.language !== void 0) {
119797
120642
  this.config.language = patch.language;
119798
- refreshContextModelSnapshot(this);
120643
+ if (!this.activeTurn) {
120644
+ refreshContextModelSnapshot(this);
120645
+ }
119799
120646
  }
119800
120647
  if ("outputStyle" in patch) {
119801
120648
  this.config.outputStyle = patch.outputStyle;
119802
- refreshContextModelSnapshot(this);
120649
+ if (!this.activeTurn) {
120650
+ refreshContextModelSnapshot(this);
120651
+ }
119803
120652
  }
119804
120653
  }
119805
120654
  function initializeSessionShellEnvironmentIfNeeded2(selection) {
@@ -119841,7 +120690,9 @@ function getTools(model) {
119841
120690
  if (this.cachedTools === null) {
119842
120691
  this.cachedTools = filterRuntimeVisibleTools.call(this, this.registry.toContracts());
119843
120692
  }
119844
- return this.cachedTools.filter((tool) => tool.name !== "WebSearch" || shouldExposeWebSearch.call(this, model));
120693
+ return this.cachedTools.filter((tool) => tool.name !== "WebSearch" || shouldExposeWebSearch.call(this, model)).map((tool) => projectToolModelContract(tool, this.registry.get(tool.name), {
120694
+ model
120695
+ }));
119845
120696
  }
119846
120697
  function invalidateToolCache() {
119847
120698
  this.cachedTools = null;
@@ -120596,6 +121447,7 @@ async function drainPendingInput(options) {
120596
121447
  const inputSizes = pendingInputs.map((pendingInput2) => measureUtf8Bytes(pendingInput2.input));
120597
121448
  const queuedDurationsMs = pendingInputs.map((pendingInput2) => drainedAt - pendingInput2.queuedAt.getTime());
120598
121449
  const messageIds = [];
121450
+ const runtimeEntries = [];
120599
121451
  const drainedInputs = [];
120600
121452
  for (const pendingInput2 of pendingInputs) {
120601
121453
  const messageId = createMessageId();
@@ -120609,7 +121461,9 @@ async function drainPendingInput(options) {
120609
121461
  turnId: options.activeTurn.turnId,
120610
121462
  workingDirectory: this.workingDirectory
120611
121463
  });
120612
- this.messageHistory.addUser(buildUserContentFromTurn(pendingInput2.input, resolvedAttachments), realUserRuntimeMetadata());
121464
+ const runtimeEntry = createRuntimeUserEntry(buildUserContentFromTurn(pendingInput2.input, resolvedAttachments), realUserRuntimeMetadata());
121465
+ this.messageHistory.addEntries([runtimeEntry]);
121466
+ runtimeEntries.push(runtimeEntry);
120613
121467
  await this.persistUserPrompt(messageId, pendingInput2.input, resolvedAttachments, drainTraceContext, {
120614
121468
  steerDelivery: delivery,
120615
121469
  sessionInputId: pendingInput2.id,
@@ -120659,6 +121513,7 @@ async function drainPendingInput(options) {
120659
121513
  latestMessageId: messageIds.at(-1),
120660
121514
  pendingInputIds,
120661
121515
  queryIds,
121516
+ runtimeEntries,
120662
121517
  ...toolDisallowlist.length > 0 ? { toolDisallowlist } : {}
120663
121518
  };
120664
121519
  }
@@ -121141,6 +121996,7 @@ async function drainPendingRuntimeCommandsForActiveLoop() {
121141
121996
  const commands = this.runtimeCommandQueue.getByMaxPriority("next");
121142
121997
  const consumedCommandIds = [];
121143
121998
  const messageIds = [];
121999
+ const runtimeEntries = [];
121144
122000
  for (const command of commands) {
121145
122001
  if (command.mode !== "task-notification" && command.mode !== "subagent-message") {
121146
122002
  continue;
@@ -121163,11 +122019,13 @@ async function drainPendingRuntimeCommandsForActiveLoop() {
121163
122019
  }
121164
122020
  consumedCommandIds.push(removed.id);
121165
122021
  messageIds.push(messageId);
122022
+ runtimeEntries.push(createRuntimeUserEntry(removed.text, legacySyntheticRuntimeMetadata()));
121166
122023
  }
121167
122024
  return {
121168
122025
  consumedCommandIds,
121169
122026
  drained: consumedCommandIds.length,
121170
- messageIds
122027
+ messageIds,
122028
+ runtimeEntries
121171
122029
  };
121172
122030
  }
121173
122031
 
@@ -123980,6 +124838,7 @@ function createDefaultSubagentPort(deps) {
123980
124838
  // HTTP client port,导致工具在真正发请求前抛出配置错误,而不是网络请求失败。
123981
124839
  httpClientPort: deps.httpClientPort,
123982
124840
  imageProcessorPort: deps.imageProcessorPort,
124841
+ pdfDocumentPort: deps.pdfDocumentPort,
123983
124842
  memoryRoot: persistentMemory?.rootDir,
123984
124843
  mcpPort: childMcpAccess.port,
123985
124844
  skillPort: childSkillPort,
@@ -124543,7 +125402,7 @@ async function getSkillCatalog(traceContext) {
124543
125402
  function createContextBuilderFromSnapshot(snapshot, memoryRoot, options = {}) {
124544
125403
  const envInfo = {
124545
125404
  ...snapshot.envInfo,
124546
- currentModel: formatModelRef(this.defaultModelRef)
125405
+ currentModel: formatModelRef(options.modelRef ?? this.defaultModelRef)
124547
125406
  };
124548
125407
  if (options.persistEnvInfo !== false) {
124549
125408
  this.config.envInfo = envInfo;
@@ -124689,6 +125548,7 @@ function initializeMessageHistoryFromContext(contextBuilder, traceContext) {
124689
125548
  const contextResult = contextBuilder.build();
124690
125549
  this.latestContextBuildResult = contextResult;
124691
125550
  this.messageHistory.init(buildContextHistoryEntries(contextResult));
125551
+ this.contextConfigurationSnapshot = captureContextConfigurationSnapshot(this);
124692
125552
  this.logger?.debug("Context built", {
124693
125553
  ...traceContextToLogContext2(traceContext),
124694
125554
  event: "context.built",
@@ -124919,6 +125779,83 @@ function getOrCreateReasoningBlock(input) {
124919
125779
  return block;
124920
125780
  }
124921
125781
 
125782
+ // ../core/dist/runtime/methods/turn-output-token-continuation.js
125783
+ var OUTPUT_TOKEN_CONTINUE_PROMPT = "Output token limit hit. Resume directly \u2014 no apology, no recap of what you were doing. Pick up mid-thought if that is where the cut happened. Break remaining work into smaller pieces.";
125784
+ var OUTPUT_TOKEN_LIMIT_ERROR_MESSAGE = "The model's response exceeded the output token maximum.";
125785
+ var MAX_OUTPUT_TOKEN_CONTINUATIONS = 3;
125786
+ var OUTPUT_LIMIT_RAW_REASONS = /* @__PURE__ */ new Set([
125787
+ "max_tokens",
125788
+ "max_output_tokens",
125789
+ "model_context_window_exceeded"
125790
+ ]);
125791
+ function classifyOutputTokenContinuation(input) {
125792
+ if (input.toolCallCount > 0)
125793
+ return "none";
125794
+ if (!isOutputTokenLimitFinishReason(input.finishReason, input.rawFinishReason)) {
125795
+ return "none";
125796
+ }
125797
+ return input.continuationCount < MAX_OUTPUT_TOKEN_CONTINUATIONS ? "continue" : "exhausted";
125798
+ }
125799
+ function isOutputTokenLimitFinishReason(finishReason, rawFinishReason) {
125800
+ return finishReason === "length" || OUTPUT_LIMIT_RAW_REASONS.has(rawFinishReason ?? "");
125801
+ }
125802
+ function createOutputTokenContinuationEntry() {
125803
+ return {
125804
+ ...createRuntimeUserEntry(OUTPUT_TOKEN_CONTINUE_PROMPT),
125805
+ queryScope: "output_token_continuation"
125806
+ };
125807
+ }
125808
+ function isOutputTokenContinuationEntry(entry) {
125809
+ return entry.kind !== "attachment" && entry.queryScope === "output_token_continuation";
125810
+ }
125811
+ function filterOutputTokenContinuationEntries(entries) {
125812
+ const firstContinuation = entries.findIndex(isOutputTokenContinuationEntry);
125813
+ if (firstContinuation < 0)
125814
+ return entries;
125815
+ return entries.filter((entry) => !isOutputTokenContinuationEntry(entry));
125816
+ }
125817
+ function preserveCanonicalContextPrefix(currentCanonicalEntries, turnLocalEntries) {
125818
+ return [
125819
+ ...currentCanonicalEntries.slice(0, countContextPrefixMessages(currentCanonicalEntries)),
125820
+ ...turnLocalEntries.slice(countContextPrefixMessages(turnLocalEntries))
125821
+ ];
125822
+ }
125823
+ function appendTurnRequestEntries(state, entries) {
125824
+ if (entries.length === 0)
125825
+ return;
125826
+ state.entries = [...state.entries, ...entries];
125827
+ }
125828
+ function commitTurnRequestEntries(runtime, state, entries) {
125829
+ if (entries.length === 0)
125830
+ return;
125831
+ runtime.messageHistory.addEntries(entries);
125832
+ appendTurnRequestEntries(state, entries);
125833
+ }
125834
+ function commitAssistantToTurnRequest(runtime, state, result, toolCalls) {
125835
+ const reasoning = result.reasoning?.filter(hasAssistantReasoningContent);
125836
+ const hasAssistantContent = state.modelResponse.length > 0 || (reasoning?.length ?? 0) > 0 || (toolCalls?.length ?? 0) > 0;
125837
+ if (!hasAssistantContent)
125838
+ return false;
125839
+ const modelRef2 = state.model ? { providerId: state.model.providerId, modelId: state.model.modelId } : result.model;
125840
+ commitTurnRequestEntries(runtime, state.turnRequestState, [
125841
+ createRuntimeAssistantEntry(state.modelResponse, toolCalls, reasoning, modelRef2, toTokenUsageInfo(result.usage))
125842
+ ]);
125843
+ return true;
125844
+ }
125845
+ function hasAssistantReasoningContent(reasoning) {
125846
+ return reasoning.text.length > 0 || Object.keys(reasoning.providerOptions ?? {}).length > 0;
125847
+ }
125848
+ function appendOutputTokenContinuation(state) {
125849
+ appendTurnRequestEntries(state, [createOutputTokenContinuationEntry()]);
125850
+ state.outputTokenContinuationCount += 1;
125851
+ }
125852
+ function completeOutputTokenRecovery(state) {
125853
+ state.outputTokenContinuationCount = 0;
125854
+ }
125855
+ function finishOutputTokenRecovery(state) {
125856
+ completeOutputTokenRecovery(state);
125857
+ }
125858
+
124922
125859
  // ../core/dist/runtime/methods/model.js
124923
125860
  var TOOL_INPUT_STREAM_DELTA_FALLBACK_FLUSH_CHARS = 4096;
124924
125861
  function hasToolInputLineBreak(value) {
@@ -125272,7 +126209,8 @@ async function runModelTextRequest(options) {
125272
126209
  }
125273
126210
  await streamingEventQueue.drain();
125274
126211
  const rawFinishReason = readRawFinishReason(providerMetadata);
125275
- if (isContextExceededFinishReason(finishReason, rawFinishReason)) {
126212
+ const outputTokenLimit = isOutputTokenLimitFinishReason(finishReason, rawFinishReason);
126213
+ if (toolCalls.length === 0 && !outputTokenLimit && isContextExceededFinishReason(finishReason, rawFinishReason)) {
125276
126214
  this.logger?.warn("Model stream ended with provider context overflow", {
125277
126215
  ...traceContextToLogContext2(options.traceContext),
125278
126216
  event: "model.runtime.stream.context_exceeded",
@@ -125286,7 +126224,7 @@ async function runModelTextRequest(options) {
125286
126224
  });
125287
126225
  throw createModelContextExceededFinishError({ finishReason, rawFinishReason });
125288
126226
  }
125289
- if (isSuspiciousEmptyModelResult(finishReason, text.length, toolCalls.length, usage)) {
126227
+ if (!outputTokenLimit && isSuspiciousEmptyModelResult(finishReason, text.length, toolCalls.length, usage)) {
125290
126228
  this.logger?.warn("Model stream ended with suspicious empty completion", {
125291
126229
  ...traceContextToLogContext2(options.traceContext),
125292
126230
  event: "model.runtime.stream.suspicious_empty",
@@ -125512,8 +126450,8 @@ function compactCategoryBreakdown(value) {
125512
126450
  if (!Array.isArray(value)) {
125513
126451
  return void 0;
125514
126452
  }
125515
- return value.filter(isRecord18).map((category) => {
125516
- const contributors = Array.isArray(category.contributors) ? category.contributors.filter(isRecord18) : [];
126453
+ return value.filter(isRecord19).map((category) => {
126454
+ const contributors = Array.isArray(category.contributors) ? category.contributors.filter(isRecord19) : [];
125517
126455
  return {
125518
126456
  ...pickDefined(category, [
125519
126457
  "chars",
@@ -125577,7 +126515,7 @@ function contributorSortValue(contributor) {
125577
126515
  function arrayLength(value) {
125578
126516
  return Array.isArray(value) ? value.length : void 0;
125579
126517
  }
125580
- function isRecord18(value) {
126518
+ function isRecord19(value) {
125581
126519
  return typeof value === "object" && value !== null && !Array.isArray(value);
125582
126520
  }
125583
126521
 
@@ -125713,11 +126651,11 @@ function buildContextUsageBreakdownFromSnapshot(snapshot) {
125713
126651
  const categories = Array.isArray(snapshot.categories) ? snapshot.categories : [];
125714
126652
  const breakdown = [];
125715
126653
  for (const category of categories) {
125716
- if (!isRecord19(category)) {
126654
+ if (!isRecord20(category)) {
125717
126655
  continue;
125718
126656
  }
125719
126657
  const source = contextUsageBreakdownSource(category.source);
125720
- const chars = nonNegativeInteger2(category.chars);
126658
+ const chars = nonNegativeInteger3(category.chars);
125721
126659
  if (!source || chars === void 0 || chars <= 0) {
125722
126660
  continue;
125723
126661
  }
@@ -125733,7 +126671,7 @@ function buildContextUsageCategory(name, source, metric) {
125733
126671
  percentTokens: 0
125734
126672
  };
125735
126673
  }
125736
- function isRecord19(value) {
126674
+ function isRecord20(value) {
125737
126675
  return typeof value === "object" && value !== null && !Array.isArray(value);
125738
126676
  }
125739
126677
  function contextUsageBreakdownSource(value) {
@@ -125742,7 +126680,7 @@ function contextUsageBreakdownSource(value) {
125742
126680
  }
125743
126681
  return CONTEXT_USAGE_BREAKDOWN_SOURCES.has(value) ? value : void 0;
125744
126682
  }
125745
- function nonNegativeInteger2(value) {
126683
+ function nonNegativeInteger3(value) {
125746
126684
  if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
125747
126685
  return void 0;
125748
126686
  }
@@ -125836,7 +126774,7 @@ function sumMetrics(values, confidence) {
125836
126774
 
125837
126775
  // ../core/dist/memory/recall/manifest.js
125838
126776
  var import_yaml2 = __toESM(require_dist2(), 1);
125839
- import { basename as basename6, relative as relative6, sep as sep4 } from "node:path";
126777
+ import { basename as basename7, relative as relative6, sep as sep4 } from "node:path";
125840
126778
 
125841
126779
  // ../core/dist/memory/recall/types.js
125842
126780
  var MEMORY_RECALL_TYPES = ["user", "feedback", "project", "reference"];
@@ -125907,7 +126845,7 @@ async function collectMemoryPaths(fileSystem, directory, signal) {
125907
126845
  return paths;
125908
126846
  }
125909
126847
  function isMemoryCandidate(filePath) {
125910
- return filePath.endsWith(".md") && basename6(filePath) !== "MEMORY.md";
126848
+ return filePath.endsWith(".md") && basename7(filePath) !== "MEMORY.md";
125911
126849
  }
125912
126850
  async function readManifestEntry(fileSystem, rootDir, filePath, signal) {
125913
126851
  const [stat2, preview] = await Promise.all([
@@ -125937,10 +126875,10 @@ function parseMemoryFrontmatter(content) {
125937
126875
  } catch {
125938
126876
  return {};
125939
126877
  }
125940
- if (!isRecord20(parsed))
126878
+ if (!isRecord21(parsed))
125941
126879
  return {};
125942
126880
  const description = typeof parsed.description === "string" ? parsed.description : void 0;
125943
- const metadata = isRecord20(parsed.metadata) ? parsed.metadata : void 0;
126881
+ const metadata = isRecord21(parsed.metadata) ? parsed.metadata : void 0;
125944
126882
  const typeCandidate = metadata?.type ?? parsed.type;
125945
126883
  const type = isMemoryRecallType(typeCandidate) ? typeCandidate : void 0;
125946
126884
  return {
@@ -125948,7 +126886,7 @@ function parseMemoryFrontmatter(content) {
125948
126886
  ...type ? { type } : {}
125949
126887
  };
125950
126888
  }
125951
- function isRecord20(value) {
126889
+ function isRecord21(value) {
125952
126890
  return typeof value === "object" && value !== null && !Array.isArray(value);
125953
126891
  }
125954
126892
  function isMemoryRecallType(value) {
@@ -126080,7 +127018,7 @@ ${formatMemoryManifest(manifest)}`,
126080
127018
  }
126081
127019
  function parseSelectorResponse(text) {
126082
127020
  const parsed = JSON.parse(text);
126083
- if (!isRecord21(parsed))
127021
+ if (!isRecord22(parsed))
126084
127022
  return void 0;
126085
127023
  if (Object.keys(parsed).some((key) => key !== "selected_memories" && key !== "selected_knowledge_ids")) {
126086
127024
  return void 0;
@@ -126095,7 +127033,7 @@ function parseSelectorResponse(text) {
126095
127033
  selectedKnowledgeIds: parsed.selected_knowledge_ids ? [...parsed.selected_knowledge_ids] : []
126096
127034
  };
126097
127035
  }
126098
- function isRecord21(value) {
127036
+ function isRecord22(value) {
126099
127037
  return typeof value === "object" && value !== null && !Array.isArray(value);
126100
127038
  }
126101
127039
  function isStringArray(value) {
@@ -126229,20 +127167,20 @@ function startProjectMemoryRecallPrefetch(runtime, input, retrievalBranch) {
126229
127167
  }
126230
127168
  function consumeSettledProjectMemoryRecall(runtime, retrievalBranch) {
126231
127169
  if (retrievalBranch !== "semantic-recall")
126232
- return;
127170
+ return void 0;
126233
127171
  const prefetch = runtime.memoryRecallPrefetch;
126234
127172
  if (!prefetch || !prefetch.settled || prefetch.consumed)
126235
- return;
127173
+ return void 0;
126236
127174
  prefetch.consumed = true;
126237
127175
  const eligibleEntries = filterMemorySelections({
126238
- manifest: runtime.memoryRecallState.manifest ?? prefetch.memories.map(({ entry }) => entry),
127176
+ manifest: runtime.memoryRecallState.manifest ?? prefetch.memories.map(({ entry: entry2 }) => entry2),
126239
127177
  readFileState: runtime.readFileState,
126240
127178
  recalledPaths: runtime.memoryRecallState.recalledPaths,
126241
- selectedFilenames: prefetch.memories.map(({ entry }) => entry.filename)
127179
+ selectedFilenames: prefetch.memories.map(({ entry: entry2 }) => entry2.filename)
126242
127180
  });
126243
127181
  const memories = matchPrefetchedMemories(prefetch.memories, eligibleEntries);
126244
127182
  if (memories.length === 0)
126245
- return;
127183
+ return void 0;
126246
127184
  const readAt = /* @__PURE__ */ new Date();
126247
127185
  for (const memory of memories) {
126248
127186
  runtime.readFileState.set(createReadFileStateKey(memory.filePath, void 0, memory.limit), {
@@ -126257,8 +127195,10 @@ function consumeSettledProjectMemoryRecall(runtime, retrievalBranch) {
126257
127195
  sizeBytes: memory.sizeBytes
126258
127196
  });
126259
127197
  }
126260
- runtime.messageHistory.addAttachment("relevant_memory", formatRelevantMemoryAttachment(memories));
127198
+ const entry = systemReminderAttachmentEntry("relevant_memory", formatRelevantMemoryAttachment(memories));
127199
+ runtime.messageHistory.addEntries([entry]);
126261
127200
  recordRecalledMemories(runtime.memoryRecallState, memories);
127201
+ return entry;
126262
127202
  }
126263
127203
  function disposeProjectMemoryRecallPrefetch(runtime) {
126264
127204
  const prefetch = runtime.memoryRecallPrefetch;
@@ -126716,6 +127656,125 @@ function readPersistedWorkspaceEvent(value) {
126716
127656
  return data;
126717
127657
  }
126718
127658
 
127659
+ // ../core/dist/runtime/methods/turn-model-step-usage.js
127660
+ async function recordMainTurnModelUsage(runtime, state, input) {
127661
+ await recordModelUsageFact(runtime, {
127662
+ assistantMessageId: input.assistantMessageId,
127663
+ error: input.error,
127664
+ events: state.events,
127665
+ // Bug 根因:运行中切模会立即更新 defaultModelRef;usage 若在 await 后重新读取它,
127666
+ // 就会把旧请求的 token 归到新模型。这里只消费 model step 开始时的不可变快照。
127667
+ model: input.model,
127668
+ networkEventStartIndex: input.networkEventStartIndex,
127669
+ parentUserMessageId: state.currentUserMessageId,
127670
+ querySource: querySourceForTask(runtime.config.taskType),
127671
+ result: input.result,
127672
+ startedAt: input.startedAt,
127673
+ status: input.status,
127674
+ toolCallCount: input.toolCallCount,
127675
+ traceContext: input.modelTraceContext
127676
+ });
127677
+ }
127678
+ function querySourceForTask(taskType) {
127679
+ if (taskType === "subagent_child")
127680
+ return "subagent";
127681
+ if (taskType === "workflow_child" || taskType === "nested_workflow_child")
127682
+ return "workflow_child";
127683
+ return "main_turn";
127684
+ }
127685
+ function findLatestCommittedAssistantUsage(sourceEntries) {
127686
+ for (let messageIndex = sourceEntries.length - 1; messageIndex >= 0; messageIndex--) {
127687
+ const entry = sourceEntries[messageIndex];
127688
+ if (!entry || entry.kind === "attachment" || entry.message.role !== "assistant")
127689
+ continue;
127690
+ const baseline = persistedTokenUsageBaseline(entry.tokens);
127691
+ if (baseline)
127692
+ return { messageIndex, baseline };
127693
+ }
127694
+ return void 0;
127695
+ }
127696
+ function mainTurnCacheHitAggregateFromMessages(input) {
127697
+ const activeMessageIds = new Set(input.activeMessages.map((message) => message.info.id));
127698
+ return input.persistedMessages.reduce((aggregate, message) => {
127699
+ if (!activeMessageIds.has(message.info.id) || message.info.role !== "assistant" || message.info.summary) {
127700
+ return aggregate;
127701
+ }
127702
+ const inputTokens = nonNegativeInteger4(message.info.tokens.input) ?? 0;
127703
+ const cacheReadTokens = nonNegativeInteger4(message.info.tokens.cache.read) ?? 0;
127704
+ const cacheWriteTokens = nonNegativeInteger4(message.info.tokens.cache.write) ?? 0;
127705
+ if (inputTokens <= 0 && cacheReadTokens <= 0 && cacheWriteTokens <= 0) {
127706
+ return aggregate;
127707
+ }
127708
+ return {
127709
+ requestCount: aggregate.requestCount + 1,
127710
+ totalInputTokens: aggregate.totalInputTokens + inputTokens,
127711
+ totalCacheReadTokens: aggregate.totalCacheReadTokens + cacheReadTokens,
127712
+ totalCacheWriteTokens: aggregate.totalCacheWriteTokens + cacheWriteTokens
127713
+ };
127714
+ }, {
127715
+ requestCount: 0,
127716
+ totalInputTokens: 0,
127717
+ totalCacheReadTokens: 0,
127718
+ totalCacheWriteTokens: 0
127719
+ });
127720
+ }
127721
+ function recordMainTurnCacheHitUsage(runtime, usage) {
127722
+ if (!usage) {
127723
+ return void 0;
127724
+ }
127725
+ const inputTokens = modelUsageInputWindowTokens(usage) ?? 0;
127726
+ const cacheReadTokens = nonNegativeInteger4(usage.cacheReadTokens) ?? 0;
127727
+ const cacheWriteTokens = nonNegativeInteger4(usage.cacheWriteTokens) ?? 0;
127728
+ if (inputTokens <= 0 && cacheReadTokens <= 0 && cacheWriteTokens <= 0) {
127729
+ return void 0;
127730
+ }
127731
+ runtime.mainTurnCacheHitAggregate = {
127732
+ requestCount: runtime.mainTurnCacheHitAggregate.requestCount + 1,
127733
+ totalInputTokens: runtime.mainTurnCacheHitAggregate.totalInputTokens + inputTokens,
127734
+ totalCacheReadTokens: runtime.mainTurnCacheHitAggregate.totalCacheReadTokens + cacheReadTokens,
127735
+ totalCacheWriteTokens: runtime.mainTurnCacheHitAggregate.totalCacheWriteTokens + cacheWriteTokens
127736
+ };
127737
+ const aggregate = runtime.mainTurnCacheHitAggregate;
127738
+ return {
127739
+ inputTokens,
127740
+ cacheReadTokens,
127741
+ cacheWriteTokens,
127742
+ latestHitRate: inputTokens > 0 ? cacheReadTokens / inputTokens : null,
127743
+ hitRate: aggregate.totalInputTokens > 0 ? aggregate.totalCacheReadTokens / aggregate.totalInputTokens : null,
127744
+ hitRateRequestCount: aggregate.requestCount,
127745
+ totalInputTokens: aggregate.totalInputTokens,
127746
+ totalCacheReadTokens: aggregate.totalCacheReadTokens,
127747
+ totalCacheWriteTokens: aggregate.totalCacheWriteTokens
127748
+ };
127749
+ }
127750
+ function modelUsageInputWindowTokens(usage) {
127751
+ if (!usage)
127752
+ return void 0;
127753
+ const inputTokens = positiveInteger3(usage.inputTokens);
127754
+ if (inputTokens !== void 0) {
127755
+ return inputTokens;
127756
+ }
127757
+ const totalTokens = positiveInteger3(usage.totalTokens);
127758
+ if (totalTokens !== void 0) {
127759
+ const outputTokens = nonNegativeInteger4(usage.outputTokens) ?? 0;
127760
+ return Math.max(0, totalTokens - outputTokens);
127761
+ }
127762
+ const cacheTokens = (nonNegativeInteger4(usage.cacheReadTokens) ?? 0) + (nonNegativeInteger4(usage.cacheWriteTokens) ?? 0);
127763
+ return cacheTokens > 0 ? cacheTokens : void 0;
127764
+ }
127765
+ function positiveInteger3(value) {
127766
+ if (value === void 0 || !Number.isFinite(value))
127767
+ return void 0;
127768
+ const integer3 = Math.floor(value);
127769
+ return integer3 > 0 ? integer3 : void 0;
127770
+ }
127771
+ function nonNegativeInteger4(value) {
127772
+ if (value === void 0 || !Number.isFinite(value))
127773
+ return void 0;
127774
+ const integer3 = Math.floor(value);
127775
+ return integer3 >= 0 ? integer3 : void 0;
127776
+ }
127777
+
126719
127778
  // ../core/dist/runtime/methods/resume.js
126720
127779
  function toScheduleState(schedule) {
126721
127780
  return {
@@ -126842,7 +127901,10 @@ async function resumeFromStore(options) {
126842
127901
  if (resolvedMode !== void 0) {
126843
127902
  this.config.mode = resolvedMode;
126844
127903
  }
126845
- this.mainTurnCacheHitAggregate = mainTurnCacheHitAggregateFromMessages(activeMessages);
127904
+ this.mainTurnCacheHitAggregate = mainTurnCacheHitAggregateFromMessages({
127905
+ activeMessages,
127906
+ persistedMessages: messages
127907
+ });
126846
127908
  this.turnNumber = activeMessages.filter((message) => message.info.role === "user" && !message.info.summary).length;
126847
127909
  this.sessionPersisted = true;
126848
127910
  await syncPersistedSessionTitleForResume.call(this, {
@@ -126964,35 +128026,6 @@ function extractPersistedEnvInfo(messages) {
126964
128026
  }
126965
128027
  return void 0;
126966
128028
  }
126967
- function mainTurnCacheHitAggregateFromMessages(messages) {
126968
- return messages.reduce((aggregate, message) => {
126969
- if (message.info.role !== "assistant" || message.info.summary) {
126970
- return aggregate;
126971
- }
126972
- const inputTokens = nonNegativeInteger3(message.info.tokens.input);
126973
- const cacheReadTokens = nonNegativeInteger3(message.info.tokens.cache.read);
126974
- const cacheWriteTokens = nonNegativeInteger3(message.info.tokens.cache.write);
126975
- if (inputTokens <= 0 && cacheReadTokens <= 0 && cacheWriteTokens <= 0) {
126976
- return aggregate;
126977
- }
126978
- return {
126979
- requestCount: aggregate.requestCount + 1,
126980
- totalInputTokens: aggregate.totalInputTokens + inputTokens,
126981
- totalCacheReadTokens: aggregate.totalCacheReadTokens + cacheReadTokens,
126982
- totalCacheWriteTokens: aggregate.totalCacheWriteTokens + cacheWriteTokens
126983
- };
126984
- }, {
126985
- requestCount: 0,
126986
- totalInputTokens: 0,
126987
- totalCacheReadTokens: 0,
126988
- totalCacheWriteTokens: 0
126989
- });
126990
- }
126991
- function nonNegativeInteger3(value) {
126992
- if (value === void 0 || !Number.isFinite(value))
126993
- return 0;
126994
- return Math.max(0, Math.floor(value));
126995
- }
126996
128029
  async function readSessionTodosForContext(traceContext) {
126997
128030
  if (!this.sessionStore) {
126998
128031
  return [];
@@ -127153,8 +128186,10 @@ async function runStopHooks(response, toolCallCount, traceContext, signal, stopH
127153
128186
  }
127154
128187
  function injectHookAdditionalContextIntoMessageHistory(eventName, additionalContexts) {
127155
128188
  if (additionalContexts.length === 0)
127156
- return;
127157
- this.messageHistory.addAttachment("hook_context", formatLifecycleHookAdditionalContextBody(eventName, additionalContexts));
128189
+ return void 0;
128190
+ const entry = systemReminderAttachmentEntry("hook_context", formatLifecycleHookAdditionalContextBody(eventName, additionalContexts));
128191
+ this.messageHistory.addEntries([entry]);
128192
+ return entry;
127158
128193
  }
127159
128194
  function shouldContinueAfterStopHooks(result, continuationCount) {
127160
128195
  return result.stopShouldContinue === true && result.additionalContexts.length > 0 && continuationCount < MAX_STOP_HOOK_CONTINUATIONS;
@@ -127414,17 +128449,18 @@ async function drainInlineGuideForNextRequest(runtime, state) {
127414
128449
  events: state.events,
127415
128450
  traceContext: state.turnTraceContext
127416
128451
  });
127417
- if ((drained?.pendingInputIds.length ?? 0) === 0)
128452
+ if (!drained || drained.pendingInputIds.length === 0)
127418
128453
  return false;
127419
128454
  state.drainedSteerForNextRequest = drained;
127420
- state.currentUserMessageId = drained?.latestMessageId ?? state.currentUserMessageId;
127421
- const nextQueryId = drained?.queryIds?.[0];
128455
+ appendTurnRequestEntries(state.turnRequestState, drained.runtimeEntries);
128456
+ state.currentUserMessageId = drained.latestMessageId ?? state.currentUserMessageId;
128457
+ const nextQueryId = drained.queryIds?.[0];
127422
128458
  if (nextQueryId) {
127423
128459
  state.turnTraceContext = { ...state.turnTraceContext, queryId: nextQueryId };
127424
128460
  }
127425
- if ((drained?.toolDisallowlist?.length ?? 0) > 0) {
128461
+ if ((drained.toolDisallowlist?.length ?? 0) > 0) {
127426
128462
  state.toolDisallowlist = [
127427
- .../* @__PURE__ */ new Set([...state.toolDisallowlist ?? [], ...drained?.toolDisallowlist ?? []])
128463
+ .../* @__PURE__ */ new Set([...state.toolDisallowlist ?? [], ...drained.toolDisallowlist ?? []])
127428
128464
  ];
127429
128465
  }
127430
128466
  state.repeatedToolCallSignature = void 0;
@@ -127437,7 +128473,9 @@ async function handleToolCallAnomalyWarnings(runtime, state, options) {
127437
128473
  const budgetWarning = detectToolCallBudgetWarning(state.toolCallCount, options.toolCalls.length, state, runtime.config.modelAnomalyGuard);
127438
128474
  if (budgetWarning) {
127439
128475
  if (budgetWarning.warningInjected) {
127440
- runtime.messageHistory.addAttachment("model_anomaly", buildToolCallBudgetReminderBody(budgetWarning.observedCount));
128476
+ commitTurnRequestEntries(runtime, state.turnRequestState, [
128477
+ systemReminderAttachmentEntry("model_anomaly", buildToolCallBudgetReminderBody(budgetWarning.observedCount))
128478
+ ]);
127441
128479
  }
127442
128480
  const warningEvent = runtime.createEvent(SessionEventType.ModelAnomalyWarning, {
127443
128481
  category: "tool_call_budget",
@@ -127452,7 +128490,9 @@ async function handleToolCallAnomalyWarnings(runtime, state, options) {
127452
128490
  const repeatedWarnings = detectRepeatedToolCallWarnings(options.toolCalls, state, runtime.config.modelAnomalyGuard);
127453
128491
  for (const warning of repeatedWarnings) {
127454
128492
  if (warning.warningInjected) {
127455
- runtime.messageHistory.addAttachment("model_anomaly", buildRepeatedToolCallReminderBody(warning.toolName, warning.observedCount));
128493
+ commitTurnRequestEntries(runtime, state.turnRequestState, [
128494
+ systemReminderAttachmentEntry("model_anomaly", buildRepeatedToolCallReminderBody(warning.toolName, warning.observedCount))
128495
+ ]);
127456
128496
  }
127457
128497
  const warningEvent = runtime.createEvent(SessionEventType.ModelAnomalyWarning, {
127458
128498
  category: "repeated_tool_call",
@@ -127485,9 +128525,9 @@ async function emitNestedModelUsageEvents(runtime, input) {
127485
128525
  }
127486
128526
  }
127487
128527
  function extractNestedModelUsage(output) {
127488
- if (!isRecord22(output) || !isRecord22(output.modelUsage))
128528
+ if (!isRecord23(output) || !isRecord23(output.modelUsage))
127489
128529
  return void 0;
127490
- const serverToolUse = isRecord22(output.modelUsage.serverToolUse) ? {
128530
+ const serverToolUse = isRecord23(output.modelUsage.serverToolUse) ? {
127491
128531
  webFetchRequests: numberProperty2(output.modelUsage.serverToolUse, "webFetchRequests"),
127492
128532
  webSearchRequests: numberProperty2(output.modelUsage.serverToolUse, "webSearchRequests")
127493
128533
  } : void 0;
@@ -127505,7 +128545,7 @@ function numberProperty2(record3, key) {
127505
128545
  const value = record3[key];
127506
128546
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
127507
128547
  }
127508
- function isRecord22(value) {
128548
+ function isRecord23(value) {
127509
128549
  return typeof value === "object" && value !== null && !Array.isArray(value);
127510
128550
  }
127511
128551
 
@@ -127856,7 +128896,9 @@ async function executeToolCallsForModelStep(state, options) {
127856
128896
  success: result.success,
127857
128897
  contentLength: content.length
127858
128898
  });
127859
- this.messageHistory.addToolResult(result.toolCallId, result.toolName, modelContentForToolResult(result), result.success, isError);
128899
+ commitTurnRequestEntries(this, state.turnRequestState, [
128900
+ createRuntimeToolResultEntry(result.toolCallId, result.toolName, modelContentForToolResult(result), isError)
128901
+ ]);
127860
128902
  try {
127861
128903
  await this.emitFileMutationCheckpoint({
127862
128904
  abortSignal: state.turnAbortSignal,
@@ -127996,27 +129038,86 @@ async function enqueueFollowUpUserInputFromToolResult(state, result, traceContex
127996
129038
  }
127997
129039
 
127998
129040
  // ../core/dist/runtime/methods/turn-stop.js
127999
- async function finishModelStepWithoutToolCalls(state, options) {
128000
- const model = state.model;
128001
- if (!model) {
128002
- throw new Error("Model-backed turn stop requires the loop Model");
129041
+ function captureAssistantPersistenceAnchor(runtime) {
129042
+ return {
129043
+ latestAssistantMessageId: runtime.latestAssistantMessageId,
129044
+ latestAssistantTurnId: runtime.latestAssistantTurnId,
129045
+ latestConversationMessageId: runtime.latestConversationMessageId
129046
+ };
129047
+ }
129048
+ async function persistCompletedAssistantStep(runtime, state, options) {
129049
+ const modelRef2 = state.model ? { providerId: state.model.providerId, modelId: state.model.modelId } : options.result.model;
129050
+ let committed = commitAssistantToTurnRequest(runtime, state, options.result, void 0);
129051
+ if (!committed && options.includeEmptyAssistant) {
129052
+ commitTurnRequestEntries(runtime, state.turnRequestState, [
129053
+ createRuntimeAssistantEntry("", void 0, void 0, modelRef2, toTokenUsageInfo(options.result.usage))
129054
+ ]);
129055
+ committed = true;
128003
129056
  }
128004
- const modelRef2 = { providerId: model.providerId, modelId: model.modelId };
128005
- this.messageHistory.addAssistant(state.modelResponse, void 0, options.result.reasoning, modelRef2);
128006
- await this.persistPart({
129057
+ if (!committed) {
129058
+ if (runtime.sessionStore) {
129059
+ await runtime.sessionStore.removeMessage({
129060
+ sessionID: runtime.sessionId,
129061
+ messageID: options.assistantMessageId
129062
+ });
129063
+ }
129064
+ if (runtime.latestConversationMessageId === options.assistantMessageId) {
129065
+ runtime.latestConversationMessageId = options.assistantPersistenceAnchor.latestConversationMessageId;
129066
+ }
129067
+ if (runtime.latestAssistantMessageId === options.assistantMessageId) {
129068
+ runtime.latestAssistantMessageId = options.assistantPersistenceAnchor.latestAssistantMessageId;
129069
+ runtime.latestAssistantTurnId = options.assistantPersistenceAnchor.latestAssistantTurnId;
129070
+ }
129071
+ return false;
129072
+ }
129073
+ const persistedTokens = toTokenUsageInfo(options.result.usage);
129074
+ await runtime.persistPart({
128007
129075
  id: createPartId(),
128008
- sessionID: this.sessionId,
129076
+ sessionID: runtime.sessionId,
128009
129077
  messageID: options.assistantMessageId,
128010
129078
  type: "step-finish",
128011
129079
  reason: options.result.finishReason,
128012
129080
  cost: 0,
128013
- tokens: toTokenUsageInfo(options.result.usage)
129081
+ tokens: persistedTokens
128014
129082
  }, options.modelTraceContext);
128015
- await this.persistAssistantMessage(options.assistantMessageId, state.currentUserMessageId, options.assistantCreatedAt, {
129083
+ await runtime.persistAssistantMessage(options.assistantMessageId, state.currentUserMessageId, options.assistantCreatedAt, {
128016
129084
  completed: Date.now(),
128017
129085
  finish: options.result.finishReason,
128018
- tokens: toTokenUsageInfo(options.result.usage)
129086
+ tokens: persistedTokens
128019
129087
  }, options.modelTraceContext, modelRef2);
129088
+ return committed;
129089
+ }
129090
+ async function persistOutputTokenLimitErrorCarrier(runtime, state, options) {
129091
+ const messageId = createMessageId();
129092
+ const createdAt = Date.now();
129093
+ const tokens = emptyTokenUsageInfo();
129094
+ await runtime.persistAssistantMessage(messageId, state.currentUserMessageId, createdAt, void 0, options.modelTraceContext, options.modelRef);
129095
+ await runtime.persistPart({
129096
+ id: createPartId(),
129097
+ sessionID: runtime.sessionId,
129098
+ messageID: messageId,
129099
+ type: "step-finish",
129100
+ reason: options.finishReason,
129101
+ cost: 0,
129102
+ tokens
129103
+ }, options.modelTraceContext);
129104
+ await runtime.persistAssistantMessage(messageId, state.currentUserMessageId, createdAt, {
129105
+ completed: Date.now(),
129106
+ error: options.error,
129107
+ finish: options.finishReason,
129108
+ tokens
129109
+ }, options.modelTraceContext, options.modelRef);
129110
+ }
129111
+ async function finishModelStepWithoutToolCalls(state, options) {
129112
+ if (!state.model) {
129113
+ throw new Error("Model-backed turn stop requires the loop Model");
129114
+ }
129115
+ const assistantCommitted = await persistCompletedAssistantStep(this, state, {
129116
+ ...options,
129117
+ includeEmptyAssistant: true
129118
+ });
129119
+ if (assistantCommitted)
129120
+ recordModelHistoryRound(state);
128020
129121
  if (state.automationCreateLimitReached) {
128021
129122
  if (state.activeTurn) {
128022
129123
  await this.fallbackPendingGuidesToQueue({
@@ -128039,7 +129140,8 @@ async function finishModelStepWithoutToolCalls(state, options) {
128039
129140
  const stopHookResult = await this.runStopHooks(state.modelResponse, state.toolCallCount, state.turnTraceContext, state.turnAbortSignal, state.stopHookContinuationCount > 0);
128040
129141
  if (this.shouldContinueAfterStopHooks(stopHookResult, state.stopHookContinuationCount)) {
128041
129142
  state.stopHookContinuationCount += 1;
128042
- this.injectHookAdditionalContextIntoMessageHistory(HookEventName.Stop, stopHookResult.additionalContexts);
129143
+ const hookEntry = this.injectHookAdditionalContextIntoMessageHistory(HookEventName.Stop, stopHookResult.additionalContexts);
129144
+ appendTurnRequestEntries(state.turnRequestState, hookEntry ? [hookEntry] : []);
128043
129145
  state.turnMachine = new TurnMachineImpl(state.turnMachine.aggregateResults());
128044
129146
  return "continue";
128045
129147
  }
@@ -128166,7 +129268,9 @@ function createStreamingToolCoordinator(runtime, state, options) {
128166
129268
  state.modelStepCount += 1;
128167
129269
  recordModelHistoryRound(state);
128168
129270
  state.toolCallCount += streamedToolResults.length;
128169
- runtime.messageHistory.addAssistant("", toolCalls, void 0, options.modelRef);
129271
+ commitTurnRequestEntries(runtime, state.turnRequestState, [
129272
+ createRuntimeAssistantEntry("", toolCalls, void 0, options.modelRef)
129273
+ ]);
128170
129274
  state.turnMachine = new TurnMachineImpl(state.turnMachine.receiveModelResponse(""));
128171
129275
  await executeToolCallsForModelStep.call(runtime, state, {
128172
129276
  assistantCreatedAt,
@@ -128330,7 +129434,7 @@ async function collectCompletedResults(handles, toolCalls) {
128330
129434
  async function persistCancelledStreamSnapshot(runtime, options) {
128331
129435
  const completedAt = Date.now();
128332
129436
  for (const reasoning of options.snapshot.reasoning) {
128333
- if (!reasoning.text)
129437
+ if (!hasAssistantReasoningContent(reasoning))
128334
129438
  continue;
128335
129439
  await runtime.persistPart({
128336
129440
  id: createPartId(),
@@ -128361,119 +129465,6 @@ async function persistCancelledStreamSnapshot(runtime, options) {
128361
129465
  }, options.traceContext);
128362
129466
  }
128363
129467
 
128364
- // ../core/dist/runtime/methods/turn-model-step-usage.js
128365
- async function recordMainTurnModelUsage(runtime, state, input) {
128366
- await recordModelUsageFact(runtime, {
128367
- assistantMessageId: input.assistantMessageId,
128368
- error: input.error,
128369
- events: state.events,
128370
- // Bug 根因:运行中切模会立即更新 defaultModelRef;usage 若在 await 后重新读取它,
128371
- // 就会把旧请求的 token 归到新模型。这里只消费 model step 开始时的不可变快照。
128372
- model: input.model,
128373
- networkEventStartIndex: input.networkEventStartIndex,
128374
- parentUserMessageId: state.currentUserMessageId,
128375
- querySource: querySourceForTask(runtime.config.taskType),
128376
- result: input.result,
128377
- startedAt: input.startedAt,
128378
- status: input.status,
128379
- toolCallCount: input.toolCallCount,
128380
- traceContext: input.modelTraceContext
128381
- });
128382
- }
128383
- function querySourceForTask(taskType) {
128384
- if (taskType === "subagent_child")
128385
- return "subagent";
128386
- if (taskType === "workflow_child" || taskType === "nested_workflow_child")
128387
- return "workflow_child";
128388
- return "main_turn";
128389
- }
128390
- function captureProviderContextUsage(result, messageCount, model, traceContext) {
128391
- const inputTokens = modelUsageInputWindowTokens(result.usage);
128392
- if (inputTokens === void 0 || inputTokens <= 0) {
128393
- return void 0;
128394
- }
128395
- return {
128396
- cacheReadTokens: result.usage?.cacheReadTokens,
128397
- cacheWriteTokens: result.usage?.cacheWriteTokens,
128398
- contextUsageTokens: modelUsageContextTokens(result.usage),
128399
- inputTokens,
128400
- messageCount,
128401
- model: { providerId: model.providerId, modelId: model.modelId },
128402
- outputTokens: result.usage?.outputTokens,
128403
- recordedAt: Date.now(),
128404
- traceId: traceContext.traceId,
128405
- turnId: traceContext.turnId
128406
- };
128407
- }
128408
- function recordMainTurnCacheHitUsage(runtime, usage) {
128409
- if (!usage) {
128410
- return void 0;
128411
- }
128412
- const inputTokens = modelUsageInputWindowTokens(usage) ?? 0;
128413
- const cacheReadTokens = nonNegativeInteger4(usage.cacheReadTokens) ?? 0;
128414
- const cacheWriteTokens = nonNegativeInteger4(usage.cacheWriteTokens) ?? 0;
128415
- if (inputTokens <= 0 && cacheReadTokens <= 0 && cacheWriteTokens <= 0) {
128416
- return void 0;
128417
- }
128418
- runtime.mainTurnCacheHitAggregate = {
128419
- requestCount: runtime.mainTurnCacheHitAggregate.requestCount + 1,
128420
- totalInputTokens: runtime.mainTurnCacheHitAggregate.totalInputTokens + inputTokens,
128421
- totalCacheReadTokens: runtime.mainTurnCacheHitAggregate.totalCacheReadTokens + cacheReadTokens,
128422
- totalCacheWriteTokens: runtime.mainTurnCacheHitAggregate.totalCacheWriteTokens + cacheWriteTokens
128423
- };
128424
- const aggregate = runtime.mainTurnCacheHitAggregate;
128425
- return {
128426
- inputTokens,
128427
- cacheReadTokens,
128428
- cacheWriteTokens,
128429
- latestHitRate: inputTokens > 0 ? cacheReadTokens / inputTokens : null,
128430
- hitRate: aggregate.totalInputTokens > 0 ? aggregate.totalCacheReadTokens / aggregate.totalInputTokens : null,
128431
- hitRateRequestCount: aggregate.requestCount,
128432
- totalInputTokens: aggregate.totalInputTokens,
128433
- totalCacheReadTokens: aggregate.totalCacheReadTokens,
128434
- totalCacheWriteTokens: aggregate.totalCacheWriteTokens
128435
- };
128436
- }
128437
- function modelUsageContextTokens(usage) {
128438
- if (!usage)
128439
- return void 0;
128440
- const inputTokens = modelUsageInputWindowTokens(usage);
128441
- const outputTokens = nonNegativeInteger4(usage.outputTokens) ?? 0;
128442
- const contextTokens = (inputTokens ?? 0) + outputTokens;
128443
- if (contextTokens > 0) {
128444
- return contextTokens;
128445
- }
128446
- const totalTokens = positiveInteger2(usage.totalTokens);
128447
- return totalTokens;
128448
- }
128449
- function modelUsageInputWindowTokens(usage) {
128450
- if (!usage)
128451
- return void 0;
128452
- const inputTokens = positiveInteger2(usage.inputTokens);
128453
- if (inputTokens !== void 0) {
128454
- return inputTokens;
128455
- }
128456
- const totalTokens = positiveInteger2(usage.totalTokens);
128457
- if (totalTokens !== void 0) {
128458
- const outputTokens = nonNegativeInteger4(usage.outputTokens) ?? 0;
128459
- return Math.max(0, totalTokens - outputTokens);
128460
- }
128461
- const cacheTokens = (nonNegativeInteger4(usage.cacheReadTokens) ?? 0) + (nonNegativeInteger4(usage.cacheWriteTokens) ?? 0);
128462
- return cacheTokens > 0 ? cacheTokens : void 0;
128463
- }
128464
- function positiveInteger2(value) {
128465
- if (value === void 0 || !Number.isFinite(value))
128466
- return void 0;
128467
- const integer3 = Math.floor(value);
128468
- return integer3 > 0 ? integer3 : void 0;
128469
- }
128470
- function nonNegativeInteger4(value) {
128471
- if (value === void 0 || !Number.isFinite(value))
128472
- return void 0;
128473
- const integer3 = Math.floor(value);
128474
- return integer3 >= 0 ? integer3 : void 0;
128475
- }
128476
-
128477
129468
  // ../core/dist/runtime/methods/compact-log-context.js
128478
129469
  function autoCompactDecisionLogContext(decision) {
128479
129470
  return {
@@ -128497,11 +129488,59 @@ function autoCompactDecisionLogContext(decision) {
128497
129488
  };
128498
129489
  }
128499
129490
 
129491
+ // ../core/dist/runtime/methods/turn-model.js
129492
+ function captureTurnModelConfiguration(runtime, turnExecutionModel) {
129493
+ const captured = turnExecutionModel ?? {
129494
+ contextWindow: runtime.config.contextWindow,
129495
+ maxOutputTokens: runtime.config.maxOutputTokens,
129496
+ modelInputMediaCapabilities: runtime.config.modelInputMediaCapabilities,
129497
+ modelProviderOptions: runtime.config.modelProviderOptions,
129498
+ modelRef: runtime.defaultModelRef
129499
+ };
129500
+ const outputStyle = turnExecutionModel?.outputStyle ?? runtime.config.outputStyle;
129501
+ return {
129502
+ ...captured,
129503
+ modelRef: { ...captured.modelRef },
129504
+ ...outputStyle ? { outputStyle: { ...outputStyle } } : {}
129505
+ };
129506
+ }
129507
+ function createTurnModel(runtime, turnExecutionModel) {
129508
+ if (!runtime.modelFactory && !runtime.modelAdapter)
129509
+ return void 0;
129510
+ const modelRef2 = turnExecutionModel?.modelRef ?? runtime.defaultModelRef;
129511
+ const inputMediaCapabilities = turnExecutionModel ? {
129512
+ ...turnExecutionModel.modelInputMediaCapabilities,
129513
+ supportsPdf: turnExecutionModel.modelInputMediaCapabilities?.supportsPdf === true
129514
+ } : runtime.config.modelInputMediaCapabilities;
129515
+ const model = createRuntimeModel(runtime, {
129516
+ contextWindow: turnExecutionModel ? turnExecutionModel.contextWindow : runtime.config.contextWindow,
129517
+ inputMediaCapabilities,
129518
+ maxOutputTokens: turnExecutionModel ? turnExecutionModel.maxOutputTokens : runtime.config.maxOutputTokens,
129519
+ midConversationSystemMode: runtime.config.midConversationSystem?.mode,
129520
+ modelRef: modelRef2,
129521
+ providerOptions: turnExecutionModel ? turnExecutionModel.modelProviderOptions : runtime.config.modelProviderOptions
129522
+ });
129523
+ const executionModelRef2 = {
129524
+ ...modelRef2,
129525
+ providerId: model.providerId,
129526
+ modelId: model.modelId
129527
+ };
129528
+ return withModelInvocationContext(model, (request) => ({
129529
+ refreshRuntimeHeadersBeforeAttempt: createRefreshRuntimeHeadersBeforeModelAttempt(runtime, {
129530
+ abortSignal: request.abortSignal,
129531
+ modelRef: executionModelRef2,
129532
+ traceContext: getCurrentModelInvocationContext()?.traceContext ?? runtime.rootTraceContext
129533
+ })
129534
+ }));
129535
+ }
129536
+
128500
129537
  // ../core/dist/runtime/methods/compact.js
128501
129538
  async function executeManualCompact(input, customInstructions, turnId, turnTraceContext, abortSignal, inputId, turnExecutionModel) {
128502
129539
  const events = [];
128503
129540
  const startedAt = Date.now();
128504
129541
  const activeTurn = this.beginActiveTurn(turnId, turnTraceContext, "compact", false);
129542
+ const turnModelConfiguration = captureTurnModelConfiguration(this, turnExecutionModel);
129543
+ refreshContextModelSnapshotIfStale(this, turnModelConfiguration.modelRef);
128505
129544
  return runWithContextAsync(turnTraceContext, async () => {
128506
129545
  this.logger?.info("Compact started", {
128507
129546
  ...traceContextToLogContext2(turnTraceContext),
@@ -128528,7 +129567,7 @@ async function executeManualCompact(input, customInstructions, turnId, turnTrace
128528
129567
  compactReason: CompactReason.UserRequested,
128529
129568
  phase: CompactPhase.StandaloneTurn,
128530
129569
  ...inputId ? { sourceCommandId: inputId } : {},
128531
- ...turnExecutionModel ? { turnExecutionModel } : {}
129570
+ turnExecutionModel: turnModelConfiguration
128532
129571
  });
128533
129572
  throwIfTurnAborted(abortSignal);
128534
129573
  const turnUsage = createModelUsageSummaryFromEvents(events);
@@ -128625,12 +129664,14 @@ async function autoCompactIfNeeded(turnTraceContext, events, abortSignal, contex
128625
129664
  }),
128626
129665
  modelContextBudgetStrategy: this.config.modelContextBudgetStrategy
128627
129666
  };
128628
- const activeMessages = buildRuntimeProviderRequestMessages(this, {
128629
- entries: this.messageHistory.borrowReadOnlyRuntimeEntries(),
129667
+ const activeEntries = context.turnRequestState?.entries ?? this.messageHistory.borrowReadOnlyRuntimeEntries();
129668
+ const activeProjection = buildRuntimeProviderRequestMessages(this, {
129669
+ entries: activeEntries,
128630
129670
  applyCacheControl: false,
128631
129671
  model: context.model
128632
- }).messages;
128633
- const tokenOverride = buildProviderUsageTokenOverride(this.latestProviderContextUsage, activeMessages);
129672
+ });
129673
+ const { messages: activeMessages, sourceEntries } = activeProjection;
129674
+ const tokenOverride = buildProviderUsageTokenOverride(activeMessages, sourceEntries);
128634
129675
  const decision = shouldAutoCompact({
128635
129676
  messages: activeMessages,
128636
129677
  config: config3,
@@ -128688,12 +129729,16 @@ async function autoCompactIfNeeded(turnTraceContext, events, abortSignal, contex
128688
129729
  compactReason: context.compactReason,
128689
129730
  phase: context.phase,
128690
129731
  trigger: CompactTrigger.Auto,
129732
+ activeEntries,
128691
129733
  ...context.model ? { model: context.model } : {},
128692
129734
  ...context.turnExecutionModel ? { turnExecutionModel: context.turnExecutionModel } : {}
128693
129735
  });
128694
129736
  if (compactResult.outcome === "skipped") {
128695
129737
  return "skipped";
128696
129738
  }
129739
+ if (context.turnRequestState) {
129740
+ context.turnRequestState.entries = compactResult.entries;
129741
+ }
128697
129742
  this.autoCompactConsecutiveFailures = 0;
128698
129743
  this.logger?.info("Auto compact completed", {
128699
129744
  ...traceContextToLogContext2(turnTraceContext),
@@ -128724,28 +129769,28 @@ async function autoCompactIfNeeded(turnTraceContext, events, abortSignal, contex
128724
129769
  return "failed";
128725
129770
  }
128726
129771
  }
128727
- function buildProviderUsageTokenOverride(snapshot, messages) {
128728
- if (!snapshot || snapshot.inputTokens <= 0 || snapshot.messageCount > messages.length) {
129772
+ function buildProviderUsageTokenOverride(messages, sourceEntries) {
129773
+ const latestUsage = findLatestCommittedAssistantUsage(sourceEntries);
129774
+ if (!latestUsage || latestUsage.messageIndex >= messages.length) {
128729
129775
  return void 0;
128730
129776
  }
128731
- const providerContextTokenCount = snapshot.contextUsageTokens;
128732
- const providerOutputTokenCount = typeof snapshot.outputTokens === "number" && Number.isFinite(snapshot.outputTokens) ? Math.max(0, Math.floor(snapshot.outputTokens)) : 0;
128733
- const assistantCursorOffset = providerOutputTokenCount > 0 && messages[snapshot.messageCount]?.role === "assistant" ? 1 : 0;
128734
- const incrementalTokenCount = estimateMessageTokens(messages.slice(snapshot.messageCount + assistantCursorOffset));
128735
- const providerBaseTokenCount = snapshot.inputTokens + assistantCursorOffset * providerOutputTokenCount;
129777
+ const { baseline, messageIndex } = latestUsage;
129778
+ const incrementalStartIndex = baseline.contextUsageTokens === void 0 ? messageIndex : messageIndex + 1;
129779
+ const incrementalTokenCount = estimateMessageTokens(messages.slice(incrementalStartIndex));
129780
+ const providerBaseTokenCount = baseline.contextUsageTokens ?? baseline.inputTokens;
128736
129781
  return {
128737
129782
  baseTokenCount: providerBaseTokenCount,
128738
- cacheReadTokens: snapshot.cacheReadTokens,
128739
- cacheWriteTokens: snapshot.cacheWriteTokens,
128740
- contextUsageTokenCount: providerContextTokenCount,
129783
+ cacheReadTokens: baseline.cacheReadTokens,
129784
+ cacheWriteTokens: baseline.cacheWriteTokens,
129785
+ contextUsageTokenCount: baseline.contextUsageTokens,
128741
129786
  incrementalTokenCount,
128742
- outputTokens: snapshot.outputTokens,
129787
+ outputTokens: baseline.outputTokens,
128743
129788
  source: "provider_usage",
128744
129789
  tokenCount: providerBaseTokenCount + incrementalTokenCount
128745
129790
  };
128746
129791
  }
128747
- function estimateCurrentModelInputTokens(snapshot, messages) {
128748
- return buildProviderUsageTokenOverride(snapshot, messages)?.tokenCount ?? estimateMessageTokens(messages);
129792
+ function estimateCurrentModelInputTokens(messages, sourceEntries = []) {
129793
+ return buildProviderUsageTokenOverride(messages, sourceEntries)?.tokenCount ?? estimateMessageTokens(messages);
128749
129794
  }
128750
129795
  async function reactiveCompactAfterContextExceeded(originalError, turnTraceContext, events, abortSignal, context) {
128751
129796
  if (!this.modelFactory && !this.modelAdapter)
@@ -128763,11 +129808,13 @@ async function reactiveCompactAfterContextExceeded(originalError, turnTraceConte
128763
129808
  });
128764
129809
  return "skipped";
128765
129810
  }
128766
- const activeMessages = buildRuntimeProviderRequestMessages(this, {
128767
- entries: this.messageHistory.borrowReadOnlyRuntimeEntries(),
129811
+ const activeEntries = context?.activeEntries ?? context?.turnRequestState?.entries ?? this.messageHistory.borrowReadOnlyRuntimeEntries();
129812
+ const activeProjection = buildRuntimeProviderRequestMessages(this, {
129813
+ entries: activeEntries,
128768
129814
  applyCacheControl: false,
128769
129815
  model: context?.model
128770
- }).messages;
129816
+ });
129817
+ const { messages: activeMessages, sourceEntries } = activeProjection;
128771
129818
  if (!hasEnoughMessagesToCompact(activeMessages)) {
128772
129819
  this.logger?.warn("Reactive compact skipped because there is not enough history", {
128773
129820
  ...traceContextToLogContext2(turnTraceContext),
@@ -128781,7 +129828,7 @@ async function reactiveCompactAfterContextExceeded(originalError, turnTraceConte
128781
129828
  });
128782
129829
  return "skipped";
128783
129830
  }
128784
- const providerUsage = buildProviderUsageTokenOverride(this.latestProviderContextUsage, activeMessages);
129831
+ const tokenOverride = buildProviderUsageTokenOverride(activeMessages, sourceEntries);
128785
129832
  const contextWindow = context?.model?.properties.contextWindow ?? context?.turnExecutionModel?.contextWindow ?? this.config.contextWindow;
128786
129833
  this.logger?.warn("Reactive compact started after model context overflow", {
128787
129834
  ...traceContextToLogContext2(turnTraceContext),
@@ -128797,20 +129844,24 @@ async function reactiveCompactAfterContextExceeded(originalError, turnTraceConte
128797
129844
  const compactResult = await this.compactActiveConversation(void 0, turnTraceContext, events, {
128798
129845
  abortSignal,
128799
129846
  compactContextTelemetry: {
128800
- inputTokens: providerUsage?.tokenCount ?? estimateMessageTokens(activeMessages),
129847
+ inputTokens: tokenOverride?.tokenCount ?? estimateMessageTokens(activeMessages),
128801
129848
  policyContextWindowTokens: contextWindow !== void 0 && Number.isFinite(contextWindow) && contextWindow > 0 ? Math.floor(contextWindow) : DEFAULT_COMPACT_CONTEXT_WINDOW,
128802
- tokenSource: providerUsage?.source ?? "estimate"
129849
+ tokenSource: tokenOverride?.source ?? "estimate"
128803
129850
  },
128804
129851
  compactReason: CompactReason.ProviderOverflow,
128805
129852
  initialPromptTooLongCause: originalError,
128806
129853
  phase: CompactPhase.Reactive,
128807
129854
  trigger: CompactTrigger.Reactive,
129855
+ activeEntries,
128808
129856
  ...context?.model ? { model: context.model } : {},
128809
129857
  ...context?.turnExecutionModel ? { turnExecutionModel: context.turnExecutionModel } : {}
128810
129858
  });
128811
129859
  if (compactResult.outcome === "skipped") {
128812
129860
  return "skipped";
128813
129861
  }
129862
+ if (context?.turnRequestState) {
129863
+ context.turnRequestState.entries = compactResult.entries;
129864
+ }
128814
129865
  this.autoCompactConsecutiveFailures = 0;
128815
129866
  this.logger?.info("Reactive compact completed; retrying model request", {
128816
129867
  ...traceContextToLogContext2(turnTraceContext),
@@ -128848,7 +129899,7 @@ async function runModelBackedTurnStep(state, options) {
128848
129899
  return stepTelemetry.run(async () => {
128849
129900
  try {
128850
129901
  const result = await runModelBackedTurnStepImpl.call(this, state, options, assistantMessageId);
128851
- stepTelemetry.finishCompleted(result === "continue" ? "tool_requested" : "turn_completed");
129902
+ stepTelemetry.finishCompleted(result === "output_continuation" ? "model_completed" : result === "continue" ? "tool_requested" : "turn_completed");
128852
129903
  return result;
128853
129904
  } catch (error98) {
128854
129905
  if (isTurnCancellationError(error98, state.turnAbortSignal)) {
@@ -128868,6 +129919,7 @@ async function runModelBackedTurnStepImpl(state, options, assistantMessageId) {
128868
129919
  const modelStepIndex = state.modelStepCount;
128869
129920
  const modelStartedAt = Date.now();
128870
129921
  const assistantCreatedAt = modelStartedAt;
129922
+ const assistantPersistenceAnchor = captureAssistantPersistenceAnchor(this);
128871
129923
  const querySource = querySourceForTask(this.config.taskType);
128872
129924
  const executionModelRef2 = { providerId: model.providerId, modelId: model.modelId };
128873
129925
  const executionMaxOutputTokens = model.options.maxOutputTokens;
@@ -128894,7 +129946,7 @@ async function runModelBackedTurnStepImpl(state, options, assistantMessageId) {
128894
129946
  type: "step-start"
128895
129947
  }, modelTraceContext);
128896
129948
  const modelRequestEvent = this.createEvent(SessionEventType.ModelRequest, {
128897
- messages: options.messages,
129949
+ messages: options.recordedMessages,
128898
129950
  model: formatModelRef(executionModelRef2),
128899
129951
  modelRef: executionModelRef2,
128900
129952
  querySource,
@@ -128935,7 +129987,7 @@ async function runModelBackedTurnStepImpl(state, options, assistantMessageId) {
128935
129987
  maxOutputTokens: resolveModelStepMaxOutputTokens({
128936
129988
  baselineMaxOutputTokens,
128937
129989
  contextWindow: executionContextWindow,
128938
- estimatedCurrentUsage: estimateCurrentModelInputTokens(this.latestProviderContextUsage, options.messages),
129990
+ estimatedCurrentUsage: estimateCurrentModelInputTokens(options.messages, options.sourceEntries),
128939
129991
  modelContextBudgetStrategy: this.config.modelContextBudgetStrategy
128940
129992
  }),
128941
129993
  maxOutputTokensSource: "model-capability",
@@ -128954,7 +130006,6 @@ async function runModelBackedTurnStepImpl(state, options, assistantMessageId) {
128954
130006
  traceContext: modelTraceContext
128955
130007
  });
128956
130008
  throwIfTurnAborted(state.turnAbortSignal);
128957
- this.latestProviderContextUsage = captureProviderContextUsage(result, options.messages.length, model, modelTraceContext);
128958
130009
  } catch (error98) {
128959
130010
  let finalError = error98;
128960
130011
  await recordMainTurnModelUsage(this, state, {
@@ -128967,7 +130018,11 @@ async function runModelBackedTurnStepImpl(state, options, assistantMessageId) {
128967
130018
  status: state.turnAbortSignal.aborted ? "cancelled" : "error"
128968
130019
  });
128969
130020
  const failedRequestId = latestFailedModelRequestId ?? latestModelRequestId;
130021
+ const toolCallCountBeforeStreamRecovery = state.toolCallCount;
128970
130022
  if (await streamingToolCoordinator.recoverFromModelFailure(error98, assistantCreatedAt, failedRequestId ? { failedRequestId } : void 0)) {
130023
+ if (state.toolCallCount > toolCallCountBeforeStreamRecovery) {
130024
+ completeOutputTokenRecovery(state.turnRequestState);
130025
+ }
128971
130026
  return "continue";
128972
130027
  }
128973
130028
  const admissionRetryDelayMs = getStartPlanBusyAdmissionRetryDelayMs({
@@ -129021,13 +130076,20 @@ async function runModelBackedTurnStepImpl(state, options, assistantMessageId) {
129021
130076
  finalError = createStartPlanBusyAutoRetryExhaustedError(finalError);
129022
130077
  }
129023
130078
  await streamingToolCoordinator.abandon(state.turnAbortSignal.aborted ? "cancelled" : "model_failed");
129024
- if (state.turnAbortSignal.aborted) {
130079
+ if (state.turnAbortSignal.aborted && isTurnCancellationError(finalError, state.turnAbortSignal)) {
129025
130080
  await persistCancelledStreamSnapshot(this, {
129026
130081
  assistantCreatedAt,
129027
130082
  assistantMessageId,
129028
130083
  snapshot: latestStreamSnapshot,
129029
130084
  traceContext: modelTraceContext
129030
130085
  });
130086
+ const reasoning = latestStreamSnapshot.reasoning.filter(hasAssistantReasoningContent);
130087
+ if (latestStreamSnapshot.text.length > 0 || reasoning.length > 0) {
130088
+ commitTurnRequestEntries(this, state.turnRequestState, [
130089
+ createRuntimeAssistantEntry(latestStreamSnapshot.text, void 0, reasoning, state.model ? { providerId: state.model.providerId, modelId: state.model.modelId } : void 0)
130090
+ ]);
130091
+ recordModelHistoryRound(state);
130092
+ }
129031
130093
  }
129032
130094
  const finalErrorRecord = finalError && typeof finalError === "object" ? finalError : void 0;
129033
130095
  const persistedErrorCode = typeof finalErrorRecord?.code === "string" ? finalErrorRecord.code : void 0;
@@ -129048,19 +130110,20 @@ async function runModelBackedTurnStepImpl(state, options, assistantMessageId) {
129048
130110
  }
129049
130111
  }
129050
130112
  }, modelTraceContext, executionModelRef2);
129051
- if (isModelContextExceededError(finalError) && await recoverModelStepAfterContextExceeded.call(this, state, finalError, modelStepIndex)) {
130113
+ if (isModelContextExceededError(finalError) && await recoverModelStepAfterContextExceeded.call(this, state, finalError, modelStepIndex, options.requestEntries)) {
129052
130114
  return "continue";
129053
130115
  }
129054
130116
  throw finalError;
129055
130117
  }
129056
130118
  state.modelResponse = result.text;
129057
130119
  state.modelStepCount += 1;
129058
- recordModelHistoryRound(state);
129059
130120
  state.tokenCount += getModelUsageTotalTokens(result.usage);
129060
130121
  if (result.usage.cacheReadTokens && result.usage.cacheReadTokens > 0) {
129061
130122
  this.messageHistory.setCacheHit(result.usage.cacheReadTokens);
129062
130123
  }
129063
130124
  let toolCalls = this.extractToolCallsFromResult(result);
130125
+ const providerToolCallCount = toolCalls.length;
130126
+ const localTerminalResponse = state.automationCreateLimitReached === true;
129064
130127
  if (state.automationCreateLimitReached && toolCalls.length > 0) {
129065
130128
  this.logger?.warn("Ignored tool calls after automation create limit was reached", {
129066
130129
  event: "automation.create_limit.tool_calls_ignored",
@@ -129076,6 +130139,12 @@ async function runModelBackedTurnStepImpl(state, options, assistantMessageId) {
129076
130139
  const usage = result.usage ?? {};
129077
130140
  const responseLength = state.modelResponse.length;
129078
130141
  const rawFinishReason = readRawFinishReason(result.providerMetadata);
130142
+ const outputTokenContinuation = localTerminalResponse ? "none" : classifyOutputTokenContinuation({
130143
+ continuationCount: state.turnRequestState.outputTokenContinuationCount,
130144
+ finishReason: result.finishReason,
130145
+ rawFinishReason,
130146
+ toolCallCount: providerToolCallCount
130147
+ });
129079
130148
  this.logger?.info("Model response diagnostics", {
129080
130149
  ...traceContextToLogContext2(modelTraceContext),
129081
130150
  event: "model.response.diagnostics",
@@ -129094,17 +130163,17 @@ async function runModelBackedTurnStepImpl(state, options, assistantMessageId) {
129094
130163
  usageReasoningTokens: usage.reasoningTokens,
129095
130164
  usageTotalTokens: usage.totalTokens
129096
130165
  });
129097
- if (isContextExceededFinishReason(result.finishReason, rawFinishReason)) {
130166
+ if (!localTerminalResponse && outputTokenContinuation === "none" && toolCalls.length === 0 && isContextExceededFinishReason(result.finishReason, rawFinishReason)) {
129098
130167
  const contextError = createModelContextExceededFinishError({
129099
130168
  finishReason: result.finishReason,
129100
130169
  rawFinishReason
129101
130170
  });
129102
- if (await recoverModelStepAfterContextExceeded.call(this, state, contextError, modelStepIndex)) {
130171
+ if (await recoverModelStepAfterContextExceeded.call(this, state, contextError, modelStepIndex, options.requestEntries)) {
129103
130172
  return "continue";
129104
130173
  }
129105
130174
  throw contextError;
129106
130175
  }
129107
- if (isSuspiciousEmptyModelResult(result.finishReason, responseLength, toolCalls.length, usage)) {
130176
+ if (!localTerminalResponse && outputTokenContinuation === "none" && isSuspiciousEmptyModelResult(result.finishReason, responseLength, toolCalls.length, usage)) {
129108
130177
  this.logger?.warn("Model returned an empty non-stop result", {
129109
130178
  ...traceContextToLogContext2(modelTraceContext),
129110
130179
  event: "model.response.suspicious_empty",
@@ -129123,7 +130192,11 @@ async function runModelBackedTurnStepImpl(state, options, assistantMessageId) {
129123
130192
  rawFinishReason
129124
130193
  });
129125
130194
  }
130195
+ if (outputTokenContinuation !== "none")
130196
+ result.finishReason = "length";
129126
130197
  for (const reasoning of result.reasoning ?? []) {
130198
+ if (!hasAssistantReasoningContent(reasoning))
130199
+ continue;
129127
130200
  await this.persistPart({
129128
130201
  id: createPartId(),
129129
130202
  sessionID: this.sessionId,
@@ -129193,8 +130266,58 @@ async function runModelBackedTurnStepImpl(state, options, assistantMessageId) {
129193
130266
  });
129194
130267
  const executableToolCalls = toolCalls.filter((toolCall) => !toolCall.providerExecuted);
129195
130268
  const streamedToolResults = await streamingToolCoordinator.drain(executableToolCalls);
130269
+ if (outputTokenContinuation !== "none") {
130270
+ state.turnRequestState.entries = options.requestEntries;
130271
+ const assistantCommitted = await persistCompletedAssistantStep(this, state, {
130272
+ assistantPersistenceAnchor,
130273
+ assistantCreatedAt,
130274
+ assistantMessageId,
130275
+ includeEmptyAssistant: false,
130276
+ modelTraceContext,
130277
+ result
130278
+ });
130279
+ if (assistantCommitted)
130280
+ recordModelHistoryRound(state);
130281
+ if (outputTokenContinuation === "continue") {
130282
+ appendOutputTokenContinuation(state.turnRequestState);
130283
+ state.reactiveCompactAttemptedInCurrentModelStep = false;
130284
+ state.turnMachine = new TurnMachineImpl(state.turnMachine.aggregateResults());
130285
+ return "output_continuation";
130286
+ }
130287
+ const exhaustedError = createCoreError(CoreErrorType.ModelError, OUTPUT_TOKEN_LIMIT_ERROR_MESSAGE, {
130288
+ context: {
130289
+ providerCode: "model_output_limit_exceeded",
130290
+ reason: "model_output_limit_exceeded",
130291
+ source: "provider"
130292
+ },
130293
+ recoverable: true
130294
+ });
130295
+ const exhaustedErrorProjection = projectExecutionErrorPayload(exhaustedError, OUTPUT_TOKEN_LIMIT_ERROR_MESSAGE);
130296
+ completeOutputTokenRecovery(state.turnRequestState);
130297
+ await persistOutputTokenLimitErrorCarrier(this, state, {
130298
+ error: {
130299
+ name: exhaustedErrorProjection.code ?? exhaustedError.type,
130300
+ data: {
130301
+ ...exhaustedErrorProjection.code ? { code: exhaustedErrorProjection.code } : {},
130302
+ message: exhaustedErrorProjection.message,
130303
+ // 既有 cold hydration 用 retryable 恢复 UI recoverable;这里复用该字段,
130304
+ // 不为单一错误扩展 transcript/hydration schema。
130305
+ retryable: exhaustedError.recoverable,
130306
+ ...exhaustedErrorProjection.attribution ? { attribution: exhaustedErrorProjection.attribution } : {}
130307
+ }
130308
+ },
130309
+ finishReason: result.finishReason,
130310
+ modelRef: executionModelRef2,
130311
+ modelTraceContext
130312
+ });
130313
+ if (state.activeTurn)
130314
+ state.activeTurn.steerable = false;
130315
+ throw exhaustedError;
130316
+ }
130317
+ completeOutputTokenRecovery(state.turnRequestState);
129196
130318
  if (executableToolCalls.length === 0) {
129197
130319
  return await finishModelStepWithoutToolCalls.call(this, state, {
130320
+ assistantPersistenceAnchor,
129198
130321
  assistantCreatedAt,
129199
130322
  assistantMessageId,
129200
130323
  modelTraceContext,
@@ -129202,7 +130325,9 @@ async function runModelBackedTurnStepImpl(state, options, assistantMessageId) {
129202
130325
  });
129203
130326
  }
129204
130327
  state.toolCallCount += executableToolCalls.length;
129205
- this.messageHistory.addAssistant(state.modelResponse, executableToolCalls, result.reasoning, executionModelRef2);
130328
+ if (commitAssistantToTurnRequest(this, state, result, executableToolCalls)) {
130329
+ recordModelHistoryRound(state);
130330
+ }
129206
130331
  const toolStepResult = await executeToolCallsForModelStep.call(this, state, {
129207
130332
  assistantCreatedAt,
129208
130333
  assistantMessageId,
@@ -129219,7 +130344,7 @@ function buildAutomationCreateLimitFallback(input) {
129219
130344
  }
129220
130345
  return "The limit of 20 scheduled tasks has been reached, so no task was created. Manually delete an existing task on the Automations page, then try again.";
129221
130346
  }
129222
- async function recoverModelStepAfterContextExceeded(state, contextError, modelStepIndex) {
130347
+ async function recoverModelStepAfterContextExceeded(state, contextError, modelStepIndex, activeEntries) {
129223
130348
  if (state.reactiveCompactAttemptedInCurrentModelStep) {
129224
130349
  return false;
129225
130350
  }
@@ -129244,8 +130369,10 @@ async function recoverModelStepAfterContextExceeded(state, contextError, modelSt
129244
130369
  }
129245
130370
  state.reactiveCompactAttemptedInCurrentModelStep = true;
129246
130371
  const compactOutcome = await this.reactiveCompactAfterContextExceeded(contextError, state.turnTraceContext, state.events, state.turnAbortSignal, {
130372
+ activeEntries,
129247
130373
  modelStepIndex,
129248
130374
  rapidRefillCount: rapidRefill.consecutiveRapidRefills,
130375
+ turnRequestState: state.turnRequestState,
129249
130376
  ...state.model ? { model: state.model } : {},
129250
130377
  ...state.turnExecutionModel ? { turnExecutionModel: state.turnExecutionModel } : {}
129251
130378
  });
@@ -129523,6 +130650,7 @@ function createProjectMemoryAgentToolExecutor(runtime, context) {
129523
130650
  getWorkingDirectory: () => context.workingDirectory,
129524
130651
  getWorkspaceRoot: () => context.workspaceRoot,
129525
130652
  imageProcessorPort: runtime.imageProcessorPort,
130653
+ pdfDocumentPort: runtime.pdfDocumentPort,
129526
130654
  maxConcurrency: runtime.config.toolConcurrency?.maxConcurrency,
129527
130655
  modelConnectionPort: runtime.modelConnectionPort,
129528
130656
  model: context.model,
@@ -129566,23 +130694,27 @@ function formatProjectMemoryUpdate(update) {
129566
130694
  async function runRegularTurnLoop(state) {
129567
130695
  while (true) {
129568
130696
  throwIfTurnAborted(state.turnAbortSignal);
130697
+ const outputTokenRecoveryActive = state.turnRequestState.outputTokenContinuationCount > 0;
129569
130698
  const drainedSteerForNextRequest = state.drainedSteerForNextRequest;
129570
130699
  state.drainedSteerForNextRequest = void 0;
129571
- if (state.modelStepCount > 0) {
130700
+ if (state.modelStepCount > 0 && !outputTokenRecoveryActive) {
129572
130701
  const drainedRuntimeCommands = await this.drainPendingRuntimeCommandsForActiveLoop();
130702
+ appendTurnRequestEntries(state.turnRequestState, drainedRuntimeCommands.runtimeEntries);
129573
130703
  if (drainedRuntimeCommands.drained > 0) {
129574
130704
  state.repeatedToolCallSignature = void 0;
129575
130705
  state.repeatedToolCallStreakCount = 0;
129576
130706
  }
129577
130707
  }
129578
- if (state.completedRealToolResultBatch) {
130708
+ if (state.completedRealToolResultBatch && !outputTokenRecoveryActive) {
129579
130709
  state.completedRealToolResultBatch = false;
129580
- consumeSettledProjectMemoryRecall(this, ACTIVE_PROJECT_MEMORY_RETRIEVAL_BRANCH);
130710
+ const recallEntry = consumeSettledProjectMemoryRecall(this, ACTIVE_PROJECT_MEMORY_RETRIEVAL_BRANCH);
130711
+ appendTurnRequestEntries(state.turnRequestState, recallEntry ? [recallEntry] : []);
129581
130712
  }
129582
130713
  const compactPhase = state.modelStepCount === 0 ? CompactPhase.PreRequest : CompactPhase.MidTurn;
129583
130714
  await this.microcompactIfNeeded(state.turnTraceContext, state.events, state.turnAbortSignal, {
129584
130715
  modelStepIndex: state.modelStepCount,
129585
130716
  phase: compactPhase,
130717
+ turnRequestState: state.turnRequestState,
129586
130718
  ...state.model ? { model: state.model } : {},
129587
130719
  ...state.turnExecutionModel ? { turnExecutionModel: state.turnExecutionModel } : {}
129588
130720
  });
@@ -129593,6 +130725,7 @@ async function runRegularTurnLoop(state) {
129593
130725
  modelStepIndex: state.modelStepCount,
129594
130726
  phase: compactPhase,
129595
130727
  rapidRefill,
130728
+ turnRequestState: state.turnRequestState,
129596
130729
  ...state.model ? { model: state.model } : {},
129597
130730
  ...state.turnExecutionModel ? { turnExecutionModel: state.turnExecutionModel } : {}
129598
130731
  });
@@ -129613,18 +130746,24 @@ async function runRegularTurnLoop(state) {
129613
130746
  throwIfTurnAborted(state.turnAbortSignal);
129614
130747
  const turnDisallowedTools = buildTurnDisallowedTools(state);
129615
130748
  const tools2 = state.automationCreateLimitReached ? [] : turnDisallowedTools ? this.getTools(state.model).filter((tool) => !turnDisallowedTools.has(tool.name)) : this.getTools(state.model);
129616
- if (this.needsPlanModeExitReminder) {
130749
+ if (!outputTokenRecoveryActive && this.needsPlanModeExitReminder) {
129617
130750
  this.needsPlanModeExitReminder = false;
129618
- this.messageHistory.addAttachment("plan_mode_exit", buildPlanModeExitReminderBody());
130751
+ commitTurnRequestEntries(this, state.turnRequestState, [
130752
+ systemReminderAttachmentEntry("plan_mode_exit", buildPlanModeExitReminderBody())
130753
+ ]);
129619
130754
  }
129620
- const runtimeModeReminderBody = buildRuntimeModeReminderBody(this.messageHistory.borrowReadOnlyRuntimeEntries(), this.getMode());
130755
+ const runtimeModeReminderBody = outputTokenRecoveryActive ? null : buildRuntimeModeReminderBody(state.turnRequestState.entries, this.getMode());
129621
130756
  if (runtimeModeReminderBody) {
129622
- this.messageHistory.addAttachment("runtime_mode", runtimeModeReminderBody);
130757
+ commitTurnRequestEntries(this, state.turnRequestState, [
130758
+ systemReminderAttachmentEntry("runtime_mode", runtimeModeReminderBody)
130759
+ ]);
129623
130760
  }
129624
- if (tools2.some((tool) => tool.name === "TodoWrite") && shouldBuildTodoReminder(this.messageHistory.borrowReadOnlyRuntimeEntries())) {
130761
+ if (!outputTokenRecoveryActive && tools2.some((tool) => tool.name === "TodoWrite") && shouldBuildTodoReminder(state.turnRequestState.entries)) {
129625
130762
  const currentTodos = await this.readSessionTodosForContext(state.turnTraceContext);
129626
130763
  const reminderBody = buildTodoReminderBody(currentTodos);
129627
- this.messageHistory.addAttachment("todo_reminder", reminderBody);
130764
+ commitTurnRequestEntries(this, state.turnRequestState, [
130765
+ systemReminderAttachmentEntry("todo_reminder", reminderBody)
130766
+ ]);
129628
130767
  await this.persistSyntheticUserNoticeForSession({
129629
130768
  messageID: createMessageId(),
129630
130769
  metadata: { runtimeMessage: todoReminderRuntimeMetadata() },
@@ -129634,12 +130773,14 @@ async function runRegularTurnLoop(state) {
129634
130773
  traceContext: state.turnTraceContext
129635
130774
  });
129636
130775
  }
129637
- const outputStyleReminderBody = state.modelStepCount === 0 ? buildRuntimeOutputStyleReminderBody(this.config.outputStyle) : null;
130776
+ const outputStyleReminderBody = state.modelStepCount === 0 ? buildRuntimeOutputStyleReminderBody(state.turnOutputStyle) : null;
129638
130777
  if (outputStyleReminderBody) {
129639
- this.messageHistory.addAttachment("output_style", outputStyleReminderBody);
130778
+ commitTurnRequestEntries(this, state.turnRequestState, [
130779
+ systemReminderAttachmentEntry("output_style", outputStyleReminderBody)
130780
+ ]);
129640
130781
  }
129641
- const providerEntries = this.messageHistory.borrowReadOnlyRuntimeEntries();
129642
- const memoryUpdate = consumePendingProjectMemoryUpdate(this);
130782
+ const providerEntries = [...state.turnRequestState.entries];
130783
+ const memoryUpdate = outputTokenRecoveryActive ? void 0 : consumePendingProjectMemoryUpdate(this);
129643
130784
  const requestEntries = memoryUpdate ? [...providerEntries, memoryUpdate] : providerEntries;
129644
130785
  const providerProjection = buildRuntimeProviderRequestMessages(this, {
129645
130786
  entries: requestEntries,
@@ -129647,8 +130788,14 @@ async function runRegularTurnLoop(state) {
129647
130788
  model: state.model
129648
130789
  });
129649
130790
  const { messages } = providerProjection;
129650
- state.turnMachine = new TurnMachineImpl(state.turnMachine.startModelRequest(formatModelRef(state.model ? { providerId: state.model.providerId, modelId: state.model.modelId } : state.turnExecutionModel?.modelRef ?? this.defaultModelRef), messages));
129651
- this.logger?.debug("Model request started", {
130791
+ const recordableEntries = filterOutputTokenContinuationEntries(requestEntries);
130792
+ const recordableProjection = recordableEntries === requestEntries ? providerProjection : buildRuntimeProviderRequestMessages(this, {
130793
+ entries: recordableEntries,
130794
+ applyCacheControl: true,
130795
+ model: state.model
130796
+ });
130797
+ state.turnMachine = new TurnMachineImpl(state.turnMachine.startModelRequest(formatModelRef(state.model ? { providerId: state.model.providerId, modelId: state.model.modelId } : state.turnExecutionModel?.modelRef ?? this.defaultModelRef), recordableProjection.messages));
130798
+ this.logger?.info("Model request started", {
129652
130799
  ...traceContextToLogContext2(state.turnTraceContext),
129653
130800
  event: "model.request.started",
129654
130801
  module: "core.runtime",
@@ -129660,6 +130807,9 @@ async function runRegularTurnLoop(state) {
129660
130807
  drainedSteerForNextRequest,
129661
130808
  latestRealUserMessageIndex: providerProjection.diagnostics.latestRealUserMessageIndex,
129662
130809
  messages,
130810
+ sourceEntries: providerProjection.sourceEntries,
130811
+ recordedMessages: recordableProjection.messages,
130812
+ requestEntries,
129663
130813
  tools: tools2
129664
130814
  }) : await runFallbackTurnStep.call(this, state);
129665
130815
  if (result === "break") {
@@ -130905,33 +132055,6 @@ async function appendBrowserTurnScreenshot(runtime, state, assistantMessageId) {
130905
132055
  }
130906
132056
  }
130907
132057
 
130908
- // ../core/dist/runtime/methods/turn-model.js
130909
- function createTurnModel(runtime, turnExecutionModel) {
130910
- if (!runtime.modelFactory && !runtime.modelAdapter)
130911
- return void 0;
130912
- const modelRef2 = turnExecutionModel?.modelRef ?? runtime.defaultModelRef;
130913
- const model = createRuntimeModel(runtime, {
130914
- contextWindow: turnExecutionModel ? turnExecutionModel.contextWindow : runtime.config.contextWindow,
130915
- inputMediaCapabilities: turnExecutionModel ? turnExecutionModel.modelInputMediaCapabilities : runtime.config.modelInputMediaCapabilities,
130916
- maxOutputTokens: turnExecutionModel ? turnExecutionModel.maxOutputTokens : runtime.config.maxOutputTokens,
130917
- midConversationSystemMode: runtime.config.midConversationSystem?.mode,
130918
- modelRef: modelRef2,
130919
- providerOptions: turnExecutionModel ? turnExecutionModel.modelProviderOptions : runtime.config.modelProviderOptions
130920
- });
130921
- const executionModelRef2 = {
130922
- ...modelRef2,
130923
- providerId: model.providerId,
130924
- modelId: model.modelId
130925
- };
130926
- return withModelInvocationContext(model, (request) => ({
130927
- refreshRuntimeHeadersBeforeAttempt: createRefreshRuntimeHeadersBeforeModelAttempt(runtime, {
130928
- abortSignal: request.abortSignal,
130929
- modelRef: executionModelRef2,
130930
- traceContext: getCurrentModelInvocationContext()?.traceContext ?? runtime.rootTraceContext
130931
- })
130932
- }));
130933
- }
130934
-
130935
132058
  // ../core/dist/runtime/methods/turn.js
130936
132059
  var TARGET_RUN_HEARTBEAT_MS = 15e3;
130937
132060
  async function executeTurn(input, attachments, options) {
@@ -130979,6 +132102,30 @@ async function executeTurnCommand(input, attachments, options, startReservation)
130979
132102
  let userMessageId;
130980
132103
  let loopState;
130981
132104
  let shouldRetryTitleGenerationAfterTurn = false;
132105
+ let turnPhase = "queued";
132106
+ let turnFailureHandled = false;
132107
+ const startTurnPhase = (phase) => {
132108
+ turnPhase = phase;
132109
+ const startedAt = Date.now();
132110
+ this.logger?.info("Turn phase started", {
132111
+ ...traceContextToLogContext2(turnTraceContext),
132112
+ event: "turn.phase.started",
132113
+ module: "core.runtime",
132114
+ phase,
132115
+ status: "started"
132116
+ });
132117
+ return startedAt;
132118
+ };
132119
+ const completeTurnPhase = (phase, startedAt) => {
132120
+ this.logger?.info("Turn phase completed", {
132121
+ ...traceContextToLogContext2(turnTraceContext),
132122
+ durationMs: Date.now() - startedAt,
132123
+ event: "turn.phase.completed",
132124
+ module: "core.runtime",
132125
+ phase,
132126
+ status: "completed"
132127
+ });
132128
+ };
130982
132129
  const turnTelemetry = this.agentTelemetry.turn({
130983
132130
  inputSource: options?.inputSource,
130984
132131
  traceContext: turnTraceContext,
@@ -130986,9 +132133,13 @@ async function executeTurnCommand(input, attachments, options, startReservation)
130986
132133
  });
130987
132134
  const execute = () => runWithContextAsync(turnTraceContext, async () => {
130988
132135
  throwIfTurnAborted(turnAbortSignal);
132136
+ let phaseStartedAt = startTurnPhase("context_initialization");
130989
132137
  await this.ensureContextInitialized(turnTraceContext);
132138
+ completeTurnPhase("context_initialization", phaseStartedAt);
130990
132139
  throwIfTurnAborted(turnAbortSignal);
132140
+ phaseStartedAt = startTurnPhase("session_start_hooks");
130991
132141
  const sessionStartHookResult = await this.runSessionStartHooks("startup", turnTraceContext, turnAbortSignal);
132142
+ completeTurnPhase("session_start_hooks", phaseStartedAt);
130992
132143
  this.injectHookAdditionalContextIntoMessageHistory(HookEventName.SessionStart, sessionStartHookResult.additionalContexts);
130993
132144
  const compactInstructions = parseCompactCommand(input);
130994
132145
  if (compactInstructions !== null) {
@@ -130999,6 +132150,9 @@ async function executeTurnCommand(input, attachments, options, startReservation)
130999
132150
  return this.executeRewindCommand(input, rewindCommand, turnId, turnTraceContext, turnAbortSignal, options?.inputId);
131000
132151
  }
131001
132152
  activeTurn = this.beginActiveTurn(turnId, turnTraceContext, "regular", true);
132153
+ const turnModelConfiguration = captureTurnModelConfiguration(this, options?.turnExecutionModel);
132154
+ const explicitTurnExecutionModel = options?.turnExecutionModel;
132155
+ refreshContextModelSnapshotIfStale(this, turnModelConfiguration.modelRef);
131002
132156
  this.logger?.info("Turn started", {
131003
132157
  ...traceContextToLogContext2(turnTraceContext),
131004
132158
  event: "turn.started",
@@ -131007,8 +132161,12 @@ async function executeTurnCommand(input, attachments, options, startReservation)
131007
132161
  status: "started"
131008
132162
  });
131009
132163
  turnMachine = new TurnMachineImpl(turnMachine.start());
132164
+ phaseStartedAt = startTurnPhase("session_persistence");
131010
132165
  await this.ensureSessionPersisted(displayInput, turnTraceContext);
132166
+ completeTurnPhase("session_persistence", phaseStartedAt);
132167
+ phaseStartedAt = startTurnPhase("target_read");
131011
132168
  startedTarget = await this.readSessionTargetForContext(turnTraceContext);
132169
+ completeTurnPhase("target_read", phaseStartedAt);
131012
132170
  if (startedTarget?.status !== "active") {
131013
132171
  startedTarget = null;
131014
132172
  }
@@ -131032,14 +132190,18 @@ async function executeTurnCommand(input, attachments, options, startReservation)
131032
132190
  ...options?.intent ? { intent: options.intent } : {},
131033
132191
  ...attachmentMetas ? { attachments: attachmentMetas } : {}
131034
132192
  }, turnTraceContext);
132193
+ phaseStartedAt = startTurnPhase("turn_started_event");
131035
132194
  await this.appendEvent(turnStartedEvent, turnTraceContext);
132195
+ completeTurnPhase("turn_started_event", phaseStartedAt);
131036
132196
  events.push(turnStartedEvent);
132197
+ phaseStartedAt = startTurnPhase("target_accounting");
131037
132198
  startedTarget = await this.startTargetTurnAccounting({
131038
132199
  inputID: targetRunInputID,
131039
132200
  startedAtMs: turnStartedAtMs,
131040
132201
  startedTarget,
131041
132202
  traceContext: turnTraceContext
131042
132203
  });
132204
+ completeTurnPhase("target_accounting", phaseStartedAt);
131043
132205
  if (startedTarget && this.sessionStore?.heartbeatTargetRun) {
131044
132206
  targetRunHeartbeat = setInterval(() => {
131045
132207
  void this.trackResidencyBlockingWork(this.heartbeatTargetTurnAccounting({
@@ -131054,7 +132216,9 @@ async function executeTurnCommand(input, attachments, options, startReservation)
131054
132216
  }
131055
132217
  }
131056
132218
  try {
132219
+ phaseStartedAt = startTurnPhase("user_prompt_hooks");
131057
132220
  const userPromptHookResult = options?.skipUserPromptSubmitHooks ? { additionalContexts: [] } : await this.runUserPromptSubmitHooks(input, attachments, turnTraceContext, turnAbortSignal);
132221
+ completeTurnPhase("user_prompt_hooks", phaseStartedAt);
131058
132222
  if (userPromptHookResult.preventContinuation) {
131059
132223
  const response = userPromptHookResult.stopReason ?? "Prompt blocked by UserPromptSubmit hook.";
131060
132224
  if (activeTurn)
@@ -131152,7 +132316,7 @@ async function executeTurnCommand(input, attachments, options, startReservation)
131152
132316
  traceContext: turnTraceContext,
131153
132317
  turnAbortSignal
131154
132318
  }, ACTIVE_PROJECT_MEMORY_RETRIEVAL_BRANCH);
131155
- const loopModel = createTurnModel(this, options?.turnExecutionModel);
132319
+ const loopModel = createTurnModel(this, turnModelConfiguration);
131156
132320
  loopState = {
131157
132321
  activeTurn,
131158
132322
  ...options?.automationId ? { automationId: options.automationId } : {},
@@ -131172,19 +132336,29 @@ async function executeTurnCommand(input, attachments, options, startReservation)
131172
132336
  streamRecoveryRetryCount: 0,
131173
132337
  tokenCount: 0,
131174
132338
  toolCallCount: 0,
132339
+ turnRequestState: {
132340
+ // Turn 只借一次 canonical 成员集合,之后由显式 commit 推进;entry 本身
132341
+ // 遵循 MessageHistory 的不可变约定。
132342
+ entries: [...this.messageHistory.borrowReadOnlyRuntimeEntries()],
132343
+ outputTokenContinuationCount: 0
132344
+ },
131175
132345
  toolDisallowlist: options?.toolDisallowlist,
131176
132346
  traceId,
131177
132347
  turnAbortSignal,
131178
132348
  turnId,
131179
132349
  turnMachine,
131180
132350
  turnTraceContext,
131181
- ...options?.turnExecutionModel ? { turnExecutionModel: options.turnExecutionModel } : {},
132351
+ ...explicitTurnExecutionModel ? { turnExecutionModel: explicitTurnExecutionModel } : {},
132352
+ turnOutputStyle: turnModelConfiguration.outputStyle,
131182
132353
  userMessageId
131183
132354
  };
131184
132355
  openGoalStateChangeReminderDeferral(activeTurn);
132356
+ phaseStartedAt = startTurnPhase("regular_turn_loop");
131185
132357
  try {
131186
132358
  await runRegularTurnLoop.call(this, loopState);
132359
+ completeTurnPhase("regular_turn_loop", phaseStartedAt);
131187
132360
  } finally {
132361
+ finishOutputTokenRecovery(loopState.turnRequestState);
131188
132362
  await closeGoalStateChangeReminderDeferral.call(this, activeTurn, turnTraceContext);
131189
132363
  }
131190
132364
  turnMachine = loopState.turnMachine;
@@ -131253,6 +132427,7 @@ async function executeTurnCommand(input, attachments, options, startReservation)
131253
132427
  };
131254
132428
  return result;
131255
132429
  } catch (error98) {
132430
+ turnFailureHandled = true;
131256
132431
  const coreError = createTurnFailureError(error98, turnAbortSignal, "Turn execution failed");
131257
132432
  const preserveQueueAutoDrainOnCancel = coreError.type === CoreErrorType.TurnCancelled && this.activeForegroundExecution?.preserveQueueAutoDrainOnCancel === true;
131258
132433
  const finishedTarget = await this.finishTargetTurnAccounting({
@@ -131315,6 +132490,17 @@ async function executeTurnCommand(input, attachments, options, startReservation)
131315
132490
  turnTelemetry.finishCompleted("assistant_message");
131316
132491
  return result;
131317
132492
  }, (error98) => {
132493
+ if (!turnFailureHandled) {
132494
+ this.logger?.warn("Turn execution escaped lifecycle handler", {
132495
+ ...traceContextToLogContext2(turnTraceContext),
132496
+ durationMs: Date.now() - turnStartedAtMs,
132497
+ errorMessage: error98 instanceof Error ? error98.message : String(error98),
132498
+ event: "turn.lifecycle.unhandled_rejection",
132499
+ module: "core.runtime",
132500
+ phase: turnPhase,
132501
+ status: "failed"
132502
+ });
132503
+ }
131318
132504
  if (isTurnCancellationError(error98, turnAbortSignal)) {
131319
132505
  turnTelemetry.finishCancelled("abort_signal");
131320
132506
  } else {
@@ -131470,7 +132656,7 @@ async function microcompactIfNeeded(turnTraceContext, events, abortSignal, conte
131470
132656
  const useMidConversationSystem = context.model ? context.model.properties.supportsMidConversationSystem : resolveRuntimeMidConversationSystemCapability(this).useMidConversationSystem;
131471
132657
  const result = maybeLocalMicrocompactRuntimeEntries({
131472
132658
  config: microcompactConfig,
131473
- entries: this.messageHistory.borrowReadOnlyRuntimeEntries(),
132659
+ entries: context.turnRequestState?.entries ?? this.messageHistory.borrowReadOnlyRuntimeEntries(),
131474
132660
  lastAssistantCompletedAtMs: this.lastAssistantCompletedAtMs,
131475
132661
  useMidConversationSystem
131476
132662
  });
@@ -131488,8 +132674,11 @@ async function microcompactIfNeeded(turnTraceContext, events, abortSignal, conte
131488
132674
  });
131489
132675
  return;
131490
132676
  }
131491
- this.messageHistory.replaceMessages(result.entries);
131492
- this.latestProviderContextUsage = void 0;
132677
+ const recordableEntries = filterOutputTokenContinuationEntries(result.entries);
132678
+ this.messageHistory.replaceMessages(context.turnRequestState ? preserveCanonicalContextPrefix(this.messageHistory.borrowReadOnlyRuntimeEntries(), recordableEntries) : recordableEntries);
132679
+ if (context.turnRequestState) {
132680
+ context.turnRequestState.entries = result.entries;
132681
+ }
131493
132682
  const payload = {
131494
132683
  ...result.payload,
131495
132684
  traceId: turnTraceContext.traceId,
@@ -131913,7 +133102,9 @@ async function compactActiveConversationImpl(customInstructions, turnTraceContex
131913
133102
  providerId: compactModel.providerId,
131914
133103
  modelId: compactModel.modelId
131915
133104
  };
131916
- const activeEntries = [...this.messageHistory.borrowReadOnlyRuntimeEntries()];
133105
+ const activeEntries = [
133106
+ ...options.activeEntries ?? this.messageHistory.borrowReadOnlyRuntimeEntries()
133107
+ ];
131917
133108
  const useMidConversationSystem = compactModel.properties.supportsMidConversationSystem;
131918
133109
  const initialSelection = selectInitialCompactEntriesForActiveConversation({
131919
133110
  activeEntries,
@@ -131951,6 +133142,7 @@ async function compactActiveConversationImpl(customInstructions, turnTraceContex
131951
133142
  await persistCompactTimelineEvent(this, SessionEventType.CompactCompleted, skippedPayload, turnTraceContext, events);
131952
133143
  return {
131953
133144
  displayText: "Context is up to date; no compression needed",
133145
+ entries: activeEntries,
131954
133146
  outcome: "skipped",
131955
133147
  tokenCount: preCompactTokenCount
131956
133148
  };
@@ -132014,6 +133206,10 @@ async function compactActiveConversationImpl(customInstructions, turnTraceContex
132014
133206
  };
132015
133207
  while (true) {
132016
133208
  const requestMessages = buildCompactSummaryRequestMessages(entriesForSummary, compactPrompt, { useMidConversationSystem });
133209
+ const recordableEntries = filterOutputTokenContinuationEntries(entriesForSummary);
133210
+ const recordableRequestMessages = recordableEntries === entriesForSummary ? requestMessages : buildCompactSummaryRequestMessages(recordableEntries, compactPrompt, {
133211
+ useMidConversationSystem
133212
+ });
132017
133213
  const mediaPolicyProjection = projectMessagesForModelMediaPolicy(requestMessages, compactModel.properties);
132018
133214
  logMediaCapabilityProjection(this.logger, modelTraceContext, mediaPolicyProjection.capabilityProjection, {
132019
133215
  event: "compact.request.media_capability_projection",
@@ -132025,13 +133221,15 @@ async function compactActiveConversationImpl(customInstructions, turnTraceContex
132025
133221
  message: "Compact request media budget projection"
132026
133222
  });
132027
133223
  let projectedRequestMessages = mediaPolicyProjection.messages;
133224
+ let projectedRecordableMessages = recordableRequestMessages === requestMessages ? projectedRequestMessages : projectMessagesForModelMediaPolicy(recordableRequestMessages, compactModel.properties).messages;
132028
133225
  if (stripMediaForSummary) {
132029
133226
  const mediaProjection = projectCompactMediaForRetry(projectedRequestMessages);
132030
133227
  projectedRequestMessages = mediaProjection.messages;
133228
+ projectedRecordableMessages = recordableRequestMessages === requestMessages ? projectedRequestMessages : projectCompactMediaForRetry(projectedRecordableMessages).messages;
132031
133229
  logCompactMediaRetryProjection(this.logger, modelTraceContext, mediaProjection);
132032
133230
  }
132033
133231
  const modelRequestEvent = this.createEvent(SessionEventType.ModelRequest, {
132034
- messages: projectedRequestMessages,
133232
+ messages: projectedRecordableMessages,
132035
133233
  model: formatModelRef(executionModelRef2),
132036
133234
  modelRef: executionModelRef2,
132037
133235
  querySource: "compact",
@@ -132168,8 +133366,9 @@ async function compactActiveConversationImpl(customInstructions, turnTraceContex
132168
133366
  const summaryMessageContent = buildCompactSummaryMessage(persistedSummary, {
132169
133367
  suppressFollowup: true
132170
133368
  });
133369
+ const recordablePreservedEntries = filterOutputTokenContinuationEntries(preservedEntries);
132171
133370
  const preservedSegment = await buildCompactPreservedSegmentFromSession.call(this, {
132172
- preservedEntries,
133371
+ preservedEntries: recordablePreservedEntries,
132173
133372
  summaryMessageId
132174
133373
  });
132175
133374
  const postCompactEntries = buildPostCompactRuntimeEntries(activeEntries, {
@@ -132200,7 +133399,7 @@ async function compactActiveConversationImpl(customInstructions, turnTraceContex
132200
133399
  traceContext: turnTraceContext,
132201
133400
  trigger,
132202
133401
  ...currentSelection.groupsPreserved > 0 ? {
132203
- keptMessageCount: countCompactPreservedSessionMessages(preservedEntries)
133402
+ keptMessageCount: countCompactPreservedSessionMessages(recordablePreservedEntries)
132204
133403
  } : {},
132205
133404
  preservedSegment,
132206
133405
  truePostCompactTokenCount,
@@ -132227,12 +133426,13 @@ async function compactActiveConversationImpl(customInstructions, turnTraceContex
132227
133426
  });
132228
133427
  await persistCompactTimelineEvent(this, SessionEventType.CompactCompleted, compactCompletedPayload, turnTraceContext, events);
132229
133428
  this.latestConversationMessageId = summaryMessageId;
132230
- this.messageHistory.replaceMessages(postCompactEntries);
133429
+ const recordablePostCompactEntries = filterOutputTokenContinuationEntries(postCompactEntries);
133430
+ this.messageHistory.replaceMessages(options.activeEntries ? preserveCanonicalContextPrefix(this.messageHistory.borrowReadOnlyRuntimeEntries(), recordablePostCompactEntries) : recordablePostCompactEntries);
132231
133431
  this.readFileState.clear();
132232
133432
  resetProjectMemoryRecall(this);
132233
- this.latestProviderContextUsage = void 0;
132234
133433
  return {
132235
133434
  displayText: "Compacted",
133435
+ entries: postCompactEntries,
132236
133436
  outcome: "compacted",
132237
133437
  tokenCount: providerPostCompactTokenCount
132238
133438
  };
@@ -133004,40 +134204,15 @@ async function rebuildConversationDerivedState(options) {
133004
134204
  this.latestAssistantMessageId = latestAssistant?.info.id;
133005
134205
  this.latestAssistantTurnId = latestAssistant?.info.anchor?.turnId;
133006
134206
  this.lastAssistantCompletedAtMs = latestAssistant && "completed" in latestAssistant.info.time ? latestAssistant.info.time.completed : void 0;
133007
- this.latestProviderContextUsage = void 0;
133008
134207
  this.messageHistory.setCacheMiss();
133009
- this.mainTurnCacheHitAggregate = mainTurnCacheHitAggregateFromMessages2(activeMessages);
134208
+ this.mainTurnCacheHitAggregate = mainTurnCacheHitAggregateFromMessages({
134209
+ activeMessages,
134210
+ persistedMessages: options.persistedMessages
134211
+ });
133010
134212
  this.turnNumber = activeMessages.filter((message) => message.info.role === "user" && !message.info.summary).length;
133011
134213
  this.currentTurnFileChanges = /* @__PURE__ */ new Map();
133012
134214
  this.autoCompactConsecutiveFailures = 0;
133013
134215
  }
133014
- function mainTurnCacheHitAggregateFromMessages2(messages) {
133015
- return messages.reduce((aggregate, message) => {
133016
- if (message.info.role !== "assistant" || message.info.summary)
133017
- return aggregate;
133018
- const inputTokens = nonNegativeInteger5(message.info.tokens.input);
133019
- const cacheReadTokens = nonNegativeInteger5(message.info.tokens.cache.read);
133020
- const cacheWriteTokens = nonNegativeInteger5(message.info.tokens.cache.write);
133021
- if (inputTokens <= 0 && cacheReadTokens <= 0 && cacheWriteTokens <= 0)
133022
- return aggregate;
133023
- return {
133024
- requestCount: aggregate.requestCount + 1,
133025
- totalInputTokens: aggregate.totalInputTokens + inputTokens,
133026
- totalCacheReadTokens: aggregate.totalCacheReadTokens + cacheReadTokens,
133027
- totalCacheWriteTokens: aggregate.totalCacheWriteTokens + cacheWriteTokens
133028
- };
133029
- }, {
133030
- requestCount: 0,
133031
- totalInputTokens: 0,
133032
- totalCacheReadTokens: 0,
133033
- totalCacheWriteTokens: 0
133034
- });
133035
- }
133036
- function nonNegativeInteger5(value) {
133037
- if (value === void 0 || !Number.isFinite(value))
133038
- return 0;
133039
- return Math.max(0, Math.floor(value));
133040
- }
133041
134216
  function isRewindableUserPrompt(message) {
133042
134217
  return message.info.role === "user" && !message.info.summary;
133043
134218
  }
@@ -135462,6 +136637,14 @@ var SUMMARY_SESSION_EVENT_TYPES = /* @__PURE__ */ new Set([
135462
136637
  SessionEventType.StreamingToolLedgerUpdated,
135463
136638
  SessionEventType.ToolCallProgress
135464
136639
  ]);
136640
+ var LIFECYCLE_SESSION_EVENT_TYPES = /* @__PURE__ */ new Set([
136641
+ SessionEventType.SessionTitleUpdated,
136642
+ SessionEventType.TurnStarted,
136643
+ SessionEventType.ModelRequest,
136644
+ SessionEventType.ModelComplete,
136645
+ SessionEventType.TurnComplete,
136646
+ SessionEventType.TurnError
136647
+ ]);
135465
136648
  var sessionEventAppendAggregates = /* @__PURE__ */ new WeakMap();
135466
136649
  function createEvent(type, payload, traceContext) {
135467
136650
  return createSessionEvent(type, this.sessionId, payload, {
@@ -135470,21 +136653,63 @@ function createEvent(type, payload, traceContext) {
135470
136653
  });
135471
136654
  }
135472
136655
  async function appendEvent(event, traceContext) {
135473
- const storedEvent = await this.eventStore.append(event);
135474
- await persistDurableSessionEvent.call(this, storedEvent, traceContext);
135475
- await recordToolUsageFromEvent(this, storedEvent, traceContext);
135476
- await this.notifyEventSinks(storedEvent, traceContext);
135477
- if (recordSessionEventAppendAggregate.call(this, storedEvent, traceContext)) {
135478
- return;
136656
+ const shouldLogLifecycle = LIFECYCLE_SESSION_EVENT_TYPES.has(event.type);
136657
+ const startedAt = Date.now();
136658
+ if (shouldLogLifecycle) {
136659
+ this.logger?.info("Session event persistence started", {
136660
+ ...traceContextToLogContext2(traceContext),
136661
+ event: "session.event.persistence.started",
136662
+ module: "core.runtime",
136663
+ sessionEventType: event.type,
136664
+ status: "started"
136665
+ });
136666
+ }
136667
+ let phase = "event_store.append";
136668
+ try {
136669
+ const storedEvent = await this.eventStore.append(event);
136670
+ phase = "session_event.persist_durable";
136671
+ await persistDurableSessionEvent.call(this, storedEvent, traceContext);
136672
+ phase = "session_event.record_usage";
136673
+ await recordToolUsageFromEvent(this, storedEvent, traceContext);
136674
+ phase = "session_event.notify_sinks";
136675
+ await this.notifyEventSinks(storedEvent, traceContext);
136676
+ if (shouldLogLifecycle) {
136677
+ this.logger?.info("Session event persistence completed", {
136678
+ ...traceContextToLogContext2(traceContext),
136679
+ durationMs: Date.now() - startedAt,
136680
+ event: "session.event.persistence.completed",
136681
+ module: "core.runtime",
136682
+ sessionEventSequenceNumber: storedEvent.sequenceNumber,
136683
+ sessionEventType: storedEvent.type,
136684
+ status: "completed"
136685
+ });
136686
+ }
136687
+ if (recordSessionEventAppendAggregate.call(this, storedEvent, traceContext)) {
136688
+ return;
136689
+ }
136690
+ flushSessionEventAppendAggregates.call(this, traceContext, "low_frequency_event");
136691
+ this.logger?.debug("Session event appended", {
136692
+ ...traceContextToLogContext2(traceContext),
136693
+ event: "event_store.appended",
136694
+ module: "core.runtime",
136695
+ sessionEventSequenceNumber: storedEvent.sequenceNumber,
136696
+ sessionEventType: storedEvent.type
136697
+ });
136698
+ } catch (error98) {
136699
+ if (shouldLogLifecycle) {
136700
+ this.logger?.warn("Session event persistence failed", {
136701
+ ...traceContextToLogContext2(traceContext),
136702
+ durationMs: Date.now() - startedAt,
136703
+ errorMessage: error98 instanceof Error ? error98.message : String(error98),
136704
+ event: "session.event.persistence.failed",
136705
+ module: "core.runtime",
136706
+ phase,
136707
+ sessionEventType: event.type,
136708
+ status: "failed"
136709
+ });
136710
+ }
136711
+ throw error98;
135479
136712
  }
135480
- flushSessionEventAppendAggregates.call(this, traceContext, "low_frequency_event");
135481
- this.logger?.debug("Session event appended", {
135482
- ...traceContextToLogContext2(traceContext),
135483
- event: "event_store.appended",
135484
- module: "core.runtime",
135485
- sessionEventSequenceNumber: storedEvent.sequenceNumber,
135486
- sessionEventType: storedEvent.type
135487
- });
135488
136713
  }
135489
136714
  function recordSessionEventAppendAggregate(event, traceContext) {
135490
136715
  if (!SUMMARY_SESSION_EVENT_TYPES.has(event.type)) {
@@ -135802,42 +137027,75 @@ async function notifyEventSinks(event, traceContext) {
135802
137027
  async function ensureSessionPersisted(input, traceContext) {
135803
137028
  if (!this.sessionStore || this.sessionPersisted)
135804
137029
  return;
135805
- const directory = this.workingDirectory;
135806
- const persistedWorkspacePath = this.config.workspacePath ?? directory;
135807
- const title = titleFromInput(input);
135808
- const workspaceIdentity = this.config.memory?.workspaceIdentity?.trim();
135809
- await this.sessionStore.createSession({
135810
- id: this.sessionId,
135811
- projectID: projectIdFromDirectory(directory),
135812
- // Memory workspaceIdentity 是上游提供的不透明隔离键。这里只做类型品牌化,
135813
- // 不能调用会改写字符串的 ID 生成器,否则恢复后的 Memory root 会发生漂移。
135814
- workspaceID: this.config.workspaceIdentity ?? workspaceIdentity,
135815
- parentID: this.config.parentSessionId,
135816
- traceID: traceContext.traceId,
135817
- taskType: this.config.taskType,
135818
- slug: slugify3(this.sessionId),
135819
- directory: persistedWorkspacePath,
135820
- path: persistedWorkspacePath,
135821
- title,
135822
- titleSource: "first_input",
135823
- version: this.appVersion,
135824
- permission: {
135825
- mode: this.config.mode ?? "build"
135826
- }
135827
- });
135828
- await persistSessionShellEnvironmentSnapshot(this, traceContext);
135829
- this.sessionPersisted = true;
135830
- this.logger?.debug("Session persisted", {
137030
+ const startedAt = Date.now();
137031
+ let phase = "session_store.create";
137032
+ this.logger?.info("Session persistence started", {
135831
137033
  ...traceContextToLogContext2(traceContext),
135832
- event: "session.persisted",
137034
+ event: "session.persistence.started",
135833
137035
  module: "core.runtime",
135834
- status: "completed"
137036
+ sessionId: this.sessionId,
137037
+ status: "started"
135835
137038
  });
135836
- await this.appendEvent(this.createEvent(SessionEventType.SessionTitleUpdated, {
135837
- previousTitle: "",
135838
- source: "first_input",
135839
- title
135840
- }, traceContext), traceContext);
137039
+ try {
137040
+ const directory = this.workingDirectory;
137041
+ const persistedWorkspacePath = this.config.workspacePath ?? directory;
137042
+ const title = titleFromInput(input);
137043
+ const workspaceIdentity = this.config.memory?.workspaceIdentity?.trim();
137044
+ await this.sessionStore.createSession({
137045
+ id: this.sessionId,
137046
+ projectID: projectIdFromDirectory(directory),
137047
+ // Memory workspaceIdentity 是上游提供的不透明隔离键。这里只做类型品牌化,
137048
+ // 不能调用会改写字符串的 ID 生成器,否则恢复后的 Memory root 会发生漂移。
137049
+ workspaceID: this.config.workspaceIdentity ?? workspaceIdentity,
137050
+ parentID: this.config.parentSessionId,
137051
+ traceID: traceContext.traceId,
137052
+ taskType: this.config.taskType,
137053
+ slug: slugify3(this.sessionId),
137054
+ directory: persistedWorkspacePath,
137055
+ path: persistedWorkspacePath,
137056
+ title,
137057
+ titleSource: "first_input",
137058
+ version: this.appVersion,
137059
+ permission: {
137060
+ mode: this.config.mode ?? "build"
137061
+ }
137062
+ });
137063
+ phase = "session_shell_snapshot";
137064
+ await persistSessionShellEnvironmentSnapshot(this, traceContext);
137065
+ this.sessionPersisted = true;
137066
+ this.logger?.debug("Session persisted", {
137067
+ ...traceContextToLogContext2(traceContext),
137068
+ event: "session.persisted",
137069
+ module: "core.runtime",
137070
+ status: "completed"
137071
+ });
137072
+ phase = "session_title_event";
137073
+ await this.appendEvent(this.createEvent(SessionEventType.SessionTitleUpdated, {
137074
+ previousTitle: "",
137075
+ source: "first_input",
137076
+ title
137077
+ }, traceContext), traceContext);
137078
+ this.logger?.info("Session persistence completed", {
137079
+ ...traceContextToLogContext2(traceContext),
137080
+ durationMs: Date.now() - startedAt,
137081
+ event: "session.persistence.completed",
137082
+ module: "core.runtime",
137083
+ sessionId: this.sessionId,
137084
+ status: "completed"
137085
+ });
137086
+ } catch (error98) {
137087
+ this.logger?.warn("Session persistence failed", {
137088
+ ...traceContextToLogContext2(traceContext),
137089
+ durationMs: Date.now() - startedAt,
137090
+ errorMessage: error98 instanceof Error ? error98.message : String(error98),
137091
+ event: "session.persistence.failed",
137092
+ module: "core.runtime",
137093
+ phase,
137094
+ sessionId: this.sessionId,
137095
+ status: "failed"
137096
+ });
137097
+ throw error98;
137098
+ }
135841
137099
  }
135842
137100
 
135843
137101
  // ../core/dist/runtime/methods/compact-persistence.js
@@ -137225,6 +138483,7 @@ function createRuntimeToolExecutor(runtime, deps, hookRunner) {
137225
138483
  fileSystemPort: deps.fileSystemPort,
137226
138484
  httpClientPort: deps.httpClientPort,
137227
138485
  imageProcessorPort: deps.imageProcessorPort,
138486
+ pdfDocumentPort: deps.pdfDocumentPort,
137228
138487
  modelConnectionPort: runtime.modelConnectionPort,
137229
138488
  embeddedSearchBackend: runtime.config.embeddedSearchBackend,
137230
138489
  nativeSearchEnhancementsEnabled: runtime.config.nativeSearchEnhancementsEnabled,
@@ -137588,6 +138847,7 @@ var AgentRuntime = class {
137588
138847
  cachedTools = null;
137589
138848
  contextBuilder = null;
137590
138849
  contextInitialized = false;
138850
+ contextConfigurationSnapshot;
137591
138851
  contextSourceSnapshot;
137592
138852
  latestContextBuildResult;
137593
138853
  memoryRoot;
@@ -137611,6 +138871,7 @@ var AgentRuntime = class {
137611
138871
  executionPort;
137612
138872
  fileSystemPort;
137613
138873
  imageProcessorPort;
138874
+ pdfDocumentPort;
137614
138875
  skillLoadOutcome;
137615
138876
  workingDirectory;
137616
138877
  workspaceRoot;
@@ -137621,7 +138882,6 @@ var AgentRuntime = class {
137621
138882
  latestConversationMessageId;
137622
138883
  latestAssistantMessageId;
137623
138884
  latestAssistantTurnId;
137624
- latestProviderContextUsage;
137625
138885
  mainTurnCacheHitAggregate = {
137626
138886
  requestCount: 0,
137627
138887
  totalInputTokens: 0,
@@ -137712,6 +138972,7 @@ var AgentRuntime = class {
137712
138972
  this.executionPort = deps.executionPort;
137713
138973
  this.fileSystemPort = deps.fileSystemPort;
137714
138974
  this.imageProcessorPort = deps.imageProcessorPort;
138975
+ this.pdfDocumentPort = deps.pdfDocumentPort;
137715
138976
  this.subagentPort = deps.subagentPort ?? runtime.createDefaultSubagentPort(deps);
137716
138977
  this.registry = deps.toolRegistry ?? createToolRegistry();
137717
138978
  this.workspaceRoot = this.workingDirectory;
@@ -138024,6 +139285,7 @@ function toMcpRunResult(run) {
138024
139285
  const textParts = [];
138025
139286
  const responseMeta = { ...run.responseMeta };
138026
139287
  delete responseMeta[ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY];
139288
+ const hasResponseMeta = Object.keys(responseMeta).length > 0;
138027
139289
  const browserScreenshotContentIndices = run.browserScreenshotImageIndices;
138028
139290
  if (run.error) {
138029
139291
  textParts.push(run.error.message);
@@ -138041,12 +139303,9 @@ function toMcpRunResult(run) {
138041
139303
  { type: "text", text: textParts.join("\n") || "(no output)" }
138042
139304
  ],
138043
139305
  ...run.error ? { isError: true } : {},
138044
- ...run.error || run.responseMeta || (run.images?.length ?? 0) > 0 ? {
139306
+ ...hasResponseMeta || (run.images?.length ?? 0) > 0 ? {
138045
139307
  _meta: {
138046
139308
  ...responseMeta,
138047
- ...run.error ? {
138048
- [ZCODE_MCP_ERROR_PRESENTATION_META_KEY]: ZCODE_MCP_ERROR_PRESENTATION_MESSAGE_ONLY
138049
- } : {},
138050
139309
  ...(run.images?.length ?? 0) > 0 ? { "zcode/nodeReplEmittedImage": true } : {},
138051
139310
  ...browserScreenshotContentIndices && browserScreenshotContentIndices.length > 0 ? {
138052
139311
  [ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY]: browserScreenshotContentIndices
@@ -138058,7 +139317,7 @@ function toMcpRunResult(run) {
138058
139317
 
138059
139318
  // src/mcp/tool-contract.ts
138060
139319
  var NODE_REPL_DEFAULT_TIMEOUT_MS = 6e4;
138061
- var NODE_REPL_SERVER_VERSION = "0.4.1";
139320
+ var NODE_REPL_SERVER_VERSION = "0.4.2";
138062
139321
  var NODE_REPL_SERVER_INSTRUCTIONS = `Browser Use only. Use \`js\` to run JavaScript in a fresh Node-backed kernel only when the Browser Use skill instructs you to control a browser. Do not use this server for non-browser tasks, including general-purpose JavaScript, filesystem, shell, package inspection, or data processing. Calls default to a ${NODE_REPL_DEFAULT_TIMEOUT_MS} ms timeout. Always provide \`title\` as a short user-facing description in the user's language. Every \`js\` call starts fresh; reconstruct browser wrappers and recover persistent tabs from current BrowserControl facts. Use \`js_add_node_module_dir\` before dynamic imports when a skill provides a package directory.`;
138063
139322
  var JS_TOOL_DESCRIPTION = `Browser Use only. Run JavaScript in a fresh Node-backed kernel with top-level await only as instructed by the Browser Use skill to control a browser. Do not use it as a general-purpose JavaScript runtime or for filesystem, shell, package inspection, data processing, or other non-browser work. Always provide the required \`title\` as a short user-facing description in the user's language without implementation terms. If \`timeout_ms\` is omitted, execution times out after ${NODE_REPL_DEFAULT_TIMEOUT_MS} ms. If the code may take more than 30000 ms including all awaited operations, you MUST set \`timeout_ms\` to at least the estimated total runtime plus 15000 ms; split the work into multiple calls if that exceeds the 120000 ms maximum. Use \`nodeRepl.cwd\`, \`nodeRepl.homeDir\`, \`nodeRepl.tmpDir\`, \`nodeRepl.requestMeta\`, \`nodeRepl.setResponseMeta(meta)\`, \`nodeRepl.write(value)\`, and \`await nodeRepl.emitImage(imageLike)\`. Global bindings and module cache do not persist across calls. Use dynamic imports such as \`await import("pkg")\` and bootstrap Browser Use in every call.`;
138064
139323
  var JS_RESET_DESCRIPTION = "Browser Use only. Compatibility barrier for callers that still request a JavaScript kernel reset. Every `js` call already starts in a fresh kernel, so this does not clear per-session module search roots.";
@@ -138224,7 +139483,7 @@ function createNodeReplMcpRuntime(input = {}) {
138224
139483
  const args = parseToolInput(jsAddModuleDirInputSchema, request.params.arguments, name);
138225
139484
  if (!isAbsolute11(args.path)) invalidParams(`${name}: path must be absolute`);
138226
139485
  const normalized = resolve10(args.path);
138227
- if (basename7(normalized) !== "node_modules") {
139486
+ if (basename8(normalized) !== "node_modules") {
138228
139487
  invalidParams(`${name}: path must name a node_modules directory`);
138229
139488
  }
138230
139489
  return await serialized(sessionKey, async () => {