@codexhost/cli-darwin-x64 0.21.0 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +1 -1
  2. package/app/codexhost-distribution.json +1 -1
  3. package/app/console-server.mjs +3333 -249
  4. package/app/console-web.js +9884 -2837
  5. package/app/desktop-controller.mjs +3139 -310
  6. package/app/host-runtime.mjs +6652 -2111
  7. package/app/plugins/antigravity/plugin.mjs +1796 -1338
  8. package/app/plugins/claude-code/plugin.mjs +1272 -238
  9. package/app/plugins/codebuddy/plugin.mjs +588 -109
  10. package/app/plugins/codex-usage/plugin.mjs +533 -88
  11. package/app/plugins/copilot/plugin.mjs +533 -88
  12. package/app/plugins/cursor-cli/plugin.mjs +588 -109
  13. package/app/plugins/deepseek-harness/plugin.mjs +875 -218
  14. package/app/plugins/devin/plugin.mjs +533 -88
  15. package/app/plugins/grok/plugin.mjs +778 -272
  16. package/app/plugins/hermes/plugin.mjs +533 -88
  17. package/app/plugins/kimi-code/plugin.mjs +533 -88
  18. package/app/plugins/kiro-cli/plugin.mjs +533 -88
  19. package/app/plugins/omp/plugin.mjs +640 -110
  20. package/app/plugins/opencode/plugin.mjs +533 -88
  21. package/app/plugins/pi/plugin.mjs +657 -116
  22. package/app/plugins/qoder/plugin.mjs +533 -88
  23. package/app/plugins/qoder-cn/plugin.mjs +533 -88
  24. package/app/plugins/qwen-code/plugin.mjs +533 -88
  25. package/app/plugins/workbuddy/plugin.mjs +646 -120
  26. package/app/plugins/zcode/plugin.mjs +540 -95
  27. package/app/renderer-extension.js +12947 -4450
  28. package/app/web/assets/index-Dyh1KzAB.js +201 -0
  29. package/app/web/codexhost-settings.js +9794 -2934
  30. package/app/web/index.html +1 -1
  31. package/app/web/plugins/deepseek-ai__dsh-api-remotes/client.js +1 -1
  32. package/app/web/plugins/deepseek-ai__dsh-api-session-controller/client.js +69 -69
  33. package/app/web/plugins/deepseek-ai__dsh-client-ui-chat/client.js +74 -74
  34. package/app/web/plugins/deepseek-ai__dsh-client-ui-codexhost/client.js +3 -3
  35. package/app/web/plugins/deepseek-ai__dsh-client-ui-conversation/client.js +90 -90
  36. package/app/web/plugins/deepseek-ai__dsh-client-ui-model-selection/client.js +2 -2
  37. package/app/web/plugins/deepseek-ai__dsh-client-ui-sidebar-browser/client.js +1 -1
  38. package/app/web/plugins/deepseek-ai__dsh-client-ui-tool/client.js +79 -79
  39. package/app/web-modules/licenses/werift-NOTICES.txt +123 -0
  40. package/app/web-modules/licenses/werift-libwebrtc-NOTICES.txt +58 -0
  41. package/app/web-modules/server.mjs +34958 -2911
  42. package/bin/codexhost +0 -0
  43. package/libexec/codexhost-shim +0 -0
  44. package/libexec/codexhost-updater +0 -0
  45. package/package.json +1 -1
  46. package/app/web/assets/index-BdmZfTRW.js +0 -201
@@ -1600,14 +1600,14 @@ function prefixIssues(path13, issues) {
1600
1600
  return iss;
1601
1601
  });
1602
1602
  }
1603
- function unwrapMessage(message2) {
1604
- return typeof message2 === "string" ? message2 : message2?.message;
1603
+ function unwrapMessage(message3) {
1604
+ return typeof message3 === "string" ? message3 : message3?.message;
1605
1605
  }
1606
1606
  function finalizeIssue(iss, ctx, config2) {
1607
- const message2 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input";
1607
+ const message3 = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input";
1608
1608
  const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;
1609
1609
  rest.path ?? (rest.path = []);
1610
- rest.message = message2;
1610
+ rest.message = message3;
1611
1611
  if (ctx?.reportInput) {
1612
1612
  rest.input = _input;
1613
1613
  }
@@ -14928,6 +14928,87 @@ function date4(params) {
14928
14928
  // ../../../node_modules/zod/v4/classic/external.js
14929
14929
  config(en_default());
14930
14930
 
14931
+ // ../../shared-contracts/dist/ids.js
14932
+ var opaqueIdSchema = external_exports.string().refine((value) => value.trim().length > 0, {
14933
+ message: "Identifier must not be empty or whitespace"
14934
+ });
14935
+ var harnessIdSchema = opaqueIdSchema.brand();
14936
+ var hostThreadIdSchema = opaqueIdSchema.brand();
14937
+ var hostTurnIdSchema = opaqueIdSchema.brand();
14938
+ var hostItemIdSchema = opaqueIdSchema.brand();
14939
+ var hostInteractionIdSchema = opaqueIdSchema.brand();
14940
+
14941
+ // ../../shared-contracts/dist/harness-plugins.js
14942
+ var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
14943
+ var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
14944
+ var HARNESS_PLUGIN_LIMIT = 128;
14945
+ var installedPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u);
14946
+ var installedHarnessPluginIdSchema = installedPluginIdSchema.pipe(harnessIdSchema);
14947
+ var harnessPluginIdSchema = installedHarnessPluginIdSchema.refine((id) => id !== "codex", "The official Codex identity is reserved");
14948
+ var pluginRelativeResourceSchema = external_exports.string().min(1).max(512).refine((value) => !/[\\\u0000:#?]/u.test(value) && !value.startsWith("/") && !value.split("/").some((part) => part === ".." || part === ""), "Plugin resources must be relative paths inside the plugin");
14949
+ var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
14950
+ var localizedTextSchema = external_exports.object({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).strict();
14951
+ var harnessInstallationGuideSchema = external_exports.object({
14952
+ commands: external_exports.array(external_exports.object({ terminal: external_exports.string().max(256), command: external_exports.string().max(4096) }).strict()).max(8),
14953
+ before: localizedTextSchema.optional(),
14954
+ after: localizedTextSchema.optional(),
14955
+ downloads: external_exports.array(external_exports.object({ label: external_exports.string().max(128), url: documentationUrlSchema }).strict()).max(8).optional()
14956
+ }).strict();
14957
+ var pluginPresentationShape = {
14958
+ id: installedHarnessPluginIdSchema,
14959
+ name: external_exports.string().trim().min(1).max(128),
14960
+ version: external_exports.string().min(1).max(128),
14961
+ /** Capability-only plugin; omitted for existing session-capable plugins. */
14962
+ kind: external_exports.literal("usage").optional(),
14963
+ /** Original image styling or bounded vector paths; never arbitrary CSS/SVG markup. */
14964
+ iconStyle: external_exports.object({
14965
+ vector: external_exports.object({
14966
+ viewBox: external_exports.string().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),
14967
+ color: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),
14968
+ paths: external_exports.array(external_exports.object({
14969
+ d: external_exports.string().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),
14970
+ fillRule: external_exports.enum(["evenodd", "nonzero"]).optional(),
14971
+ fill: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()
14972
+ }).strict()).min(1).max(32)
14973
+ }).strict().optional(),
14974
+ background: external_exports.string().regex(/^#[a-f0-9]{6}$/iu).optional(),
14975
+ borderRadius: external_exports.number().min(0).max(50).optional(),
14976
+ paddingRatio: external_exports.number().min(0).max(0.25).optional()
14977
+ }).strict().optional(),
14978
+ installation: harnessInstallationGuideSchema.optional(),
14979
+ notice: localizedTextSchema.optional(),
14980
+ /** The factory accepts a persisted local entrypoint through its construction context. */
14981
+ launchCommand: external_exports.literal(true).optional(),
14982
+ links: external_exports.object({
14983
+ website: documentationUrlSchema.optional(),
14984
+ documentation: documentationUrlSchema.optional(),
14985
+ installation: documentationUrlSchema.optional()
14986
+ }).strict().optional()
14987
+ };
14988
+ var harnessPluginManifestSchema = external_exports.object({
14989
+ manifestVersion: external_exports.literal(1),
14990
+ ...pluginPresentationShape,
14991
+ adapterApiVersion: external_exports.number().int().positive(),
14992
+ entry: pluginRelativeResourceSchema,
14993
+ icon: pluginRelativeResourceSchema.optional()
14994
+ }).strict();
14995
+ var harnessPluginIconSchema = external_exports.string().max(Math.ceil(HARNESS_PLUGIN_ICON_MAX_BYTES / 3) * 4 + 64).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u);
14996
+ var harnessPluginDescriptorSchema = external_exports.object({
14997
+ ...pluginPresentationShape,
14998
+ icon: harnessPluginIconSchema.optional()
14999
+ }).strict();
15000
+ var harnessPluginListParamsSchema = external_exports.object({}).strict();
15001
+ var harnessPluginListResultSchema = external_exports.object({
15002
+ plugins: external_exports.array(harnessPluginDescriptorSchema.extend({ id: harnessPluginIdSchema })).max(HARNESS_PLUGIN_LIMIT)
15003
+ }).strict();
15004
+ var harnessPluginConfigurationSchema = external_exports.object({
15005
+ version: external_exports.literal(1),
15006
+ enabled: external_exports.array(installedHarnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
15007
+ }).strict().refine((value) => new Set(value.enabled).size === value.enabled.length, {
15008
+ message: "Enabled plugin IDs must be unique",
15009
+ path: ["enabled"]
15010
+ });
15011
+
14931
15012
  // ../../shared-contracts/dist/json-value.js
14932
15013
  function rejectExplicitUndefined(keys) {
14933
15014
  return (value, context) => {
@@ -14987,6 +15068,346 @@ var jsonValueSchema = nonCircularSchema.pipe(recursiveJsonValueSchema);
14987
15068
  var jsonArraySchema = nonCircularSchema.pipe(external_exports.array(recursiveJsonValueSchema));
14988
15069
  var jsonObjectSchema = nonCircularSchema.pipe(external_exports.record(external_exports.string(), recursiveJsonValueSchema));
14989
15070
 
15071
+ // ../../shared-contracts/dist/desktop-extensions.js
15072
+ var DESKTOP_EXTENSION_API_VERSION = 1;
15073
+ var DESKTOP_EXTENSION_LIMIT = 64;
15074
+ var DESKTOP_EXTENSION_ZIP_MAX_BYTES = 64 * 1024 * 1024;
15075
+ var DESKTOP_EXTENSION_ZIP_MAX_BASE64_LENGTH = 4 * Math.ceil(DESKTOP_EXTENSION_ZIP_MAX_BYTES / 3);
15076
+ var DESKTOP_EXTENSION_MANIFEST_MAX_BYTES = 128 * 1024;
15077
+ var DESKTOP_EXTENSION_SCRIPT_MAX_BYTES = 2 * 1024 * 1024;
15078
+ var DESKTOP_EXTENSION_STYLE_MAX_BYTES = 256 * 1024;
15079
+ var DESKTOP_EXTENSION_ICON_MAX_BYTES = 128 * 1024;
15080
+ var DESKTOP_EXTENSION_SCREENSHOT_LIMIT = 4;
15081
+ var DESKTOP_EXTENSION_SCREENSHOT_MAX_BYTES = 512 * 1024;
15082
+ var DESKTOP_EXTENSION_LIST_SCREENSHOTS_MAX_BYTES = 8 * 1024 * 1024;
15083
+ var DESKTOP_EXTENSION_SNAPSHOT_MAX_BYTES = 8 * 1024 * 1024;
15084
+ var DESKTOP_EXTENSION_ASSET_MAX_BYTES = 16 * 1024 * 1024;
15085
+ var DESKTOP_EXTENSION_SETTINGS_MAX_BYTES = 1024 * 1024;
15086
+ var desktopExtensionIdSchema = installedPluginIdSchema;
15087
+ var desktopExtensionSlotSchema = external_exports.enum([
15088
+ "sidebar.thread-layout",
15089
+ "sidebar.thread-badge",
15090
+ "appearance.theme"
15091
+ ]);
15092
+ var desktopExtensionCategorySchema = external_exports.enum([
15093
+ "appearance",
15094
+ "interface",
15095
+ "workflow",
15096
+ "analytics",
15097
+ "integrations",
15098
+ "tools"
15099
+ ]);
15100
+ var extensionName = external_exports.string().trim().min(1).max(128);
15101
+ function desktopExtensionScreenshotMimeType(resource) {
15102
+ switch (resource.match(/\.([^./]+)$/u)?.[1]?.toLowerCase()) {
15103
+ case "png":
15104
+ return "image/png";
15105
+ case "jpg":
15106
+ case "jpeg":
15107
+ return "image/jpeg";
15108
+ case "webp":
15109
+ return "image/webp";
15110
+ default:
15111
+ return void 0;
15112
+ }
15113
+ }
15114
+ function desktopExtensionAssetMimeType(resource) {
15115
+ switch (resource.match(/\.([^./]+)$/u)?.[1]?.toLowerCase()) {
15116
+ case "gif":
15117
+ return "image/gif";
15118
+ case "svg":
15119
+ return "image/svg+xml";
15120
+ case "woff2":
15121
+ return "font/woff2";
15122
+ case "json":
15123
+ return "application/json";
15124
+ case "css":
15125
+ return "text/css";
15126
+ default:
15127
+ return desktopExtensionScreenshotMimeType(resource);
15128
+ }
15129
+ }
15130
+ var hasPortableSegments = (resource) => resource.split("/").every((segment) => !/[. ]$/u.test(segment));
15131
+ var desktopExtensionAssetPathSchema = pluginRelativeResourceSchema.refine((resource) => hasPortableSegments(resource) && desktopExtensionAssetMimeType(resource) !== void 0, "Expected a relative Desktop extension asset path with a supported suffix");
15132
+ var imagePathSchema = pluginRelativeResourceSchema.refine((resource) => desktopExtensionScreenshotMimeType(resource) !== void 0 && hasPortableSegments(resource), "Images must be relative .png, .jpg, .jpeg, or .webp paths with no segments ending in a dot or space");
15133
+ var desktopExtensionHttpUrlSchema = external_exports.string().trim().max(2048).regex(/^https?:\/\/[^/?#\\\s]+/iu, "Expected an HTTP(S) URL").pipe(external_exports.url({ protocol: /^https?$/u })).refine((value) => {
15134
+ const { username, password } = new URL(value);
15135
+ return !username && !password && !/[\\\s]/u.test(value);
15136
+ }, "URL must not contain credentials, backslashes, or whitespace");
15137
+ function localizedText(text2) {
15138
+ return external_exports.strictObject({ en: text2, "zh-CN": text2 });
15139
+ }
15140
+ var desktopExtensionLocalizedTextSchema = localizedText(external_exports.string().trim().min(1));
15141
+ var categoriesSchema = external_exports.array(desktopExtensionCategorySchema).max(desktopExtensionCategorySchema.options.length).refine((categories) => new Set(categories).size === categories.length, "Duplicate categories");
15142
+ var slotsSchema = external_exports.array(desktopExtensionSlotSchema).max(desktopExtensionSlotSchema.options.length).refine((slots) => new Set(slots).size === slots.length, "Duplicate slots");
15143
+ var settingField = {
15144
+ key: external_exports.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u),
15145
+ label: desktopExtensionLocalizedTextSchema,
15146
+ description: desktopExtensionLocalizedTextSchema.optional()
15147
+ };
15148
+ var numericSetting = {
15149
+ ...settingField,
15150
+ step: external_exports.number().positive().optional(),
15151
+ default: external_exports.number().optional()
15152
+ };
15153
+ var settingOption = external_exports.strictObject({
15154
+ value: external_exports.string(),
15155
+ label: desktopExtensionLocalizedTextSchema
15156
+ });
15157
+ var desktopExtensionSettingFieldSchema = external_exports.discriminatedUnion("type", [
15158
+ external_exports.strictObject({
15159
+ ...settingField,
15160
+ type: external_exports.literal("boolean"),
15161
+ default: external_exports.boolean().optional()
15162
+ }),
15163
+ external_exports.strictObject({
15164
+ ...settingField,
15165
+ type: external_exports.literal("string"),
15166
+ placeholder: desktopExtensionLocalizedTextSchema.optional(),
15167
+ default: external_exports.string().optional()
15168
+ }),
15169
+ external_exports.strictObject({
15170
+ ...numericSetting,
15171
+ type: external_exports.literal("number"),
15172
+ min: external_exports.number().optional(),
15173
+ max: external_exports.number().optional()
15174
+ }),
15175
+ external_exports.strictObject({
15176
+ ...numericSetting,
15177
+ type: external_exports.literal("range"),
15178
+ min: external_exports.number(),
15179
+ max: external_exports.number()
15180
+ }),
15181
+ external_exports.strictObject({
15182
+ ...settingField,
15183
+ type: external_exports.literal("select"),
15184
+ options: external_exports.array(settingOption).min(1),
15185
+ default: external_exports.string().optional()
15186
+ })
15187
+ ]).superRefine((field3, ctx) => {
15188
+ const issue2 = (path13, message3) => ctx.addIssue({ code: "custom", path: [path13], message: message3 });
15189
+ if (field3.type === "number" || field3.type === "range") {
15190
+ const { min = -Infinity, max = Infinity, default: value } = field3;
15191
+ if (min > max)
15192
+ issue2("max", "Must be at least min");
15193
+ if (value !== void 0 && (value < min || value > max))
15194
+ issue2("default", "Must be within min and max");
15195
+ } else if (field3.type === "select") {
15196
+ const values = new Set(field3.options.map(({ value }) => value));
15197
+ if (values.size !== field3.options.length)
15198
+ issue2("options", "Duplicate option values");
15199
+ if (field3.default !== void 0 && !values.has(field3.default))
15200
+ issue2("default", "Must match an option value");
15201
+ }
15202
+ });
15203
+ var manifestHeader = external_exports.object({
15204
+ manifestVersion: external_exports.int().positive(),
15205
+ id: desktopExtensionIdSchema,
15206
+ name: external_exports.union([extensionName, localizedText(extensionName)]),
15207
+ version: external_exports.string().min(1).max(128),
15208
+ desktopApi: external_exports.int().positive()
15209
+ }).passthrough();
15210
+ var desktopExtensionManifestSchema = manifestHeader.extend({
15211
+ manifestVersion: external_exports.literal(1),
15212
+ desktopApi: external_exports.literal(DESKTOP_EXTENSION_API_VERSION),
15213
+ description: external_exports.strictObject({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).optional(),
15214
+ author: external_exports.string().trim().min(1).max(128).optional(),
15215
+ repository: desktopExtensionHttpUrlSchema.optional(),
15216
+ details: external_exports.strictObject({ en: external_exports.string().max(16384), "zh-CN": external_exports.string().max(16384).optional() }).optional(),
15217
+ icon: imagePathSchema.optional(),
15218
+ screenshots: external_exports.array(imagePathSchema).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).refine((screenshots) => new Set(screenshots).size === screenshots.length, "Duplicate screenshots").optional(),
15219
+ desktop: external_exports.strictObject({
15220
+ script: pluginRelativeResourceSchema,
15221
+ style: pluginRelativeResourceSchema.optional()
15222
+ }).optional(),
15223
+ backend: external_exports.strictObject({ script: pluginRelativeResourceSchema.refine(hasPortableSegments) }).optional(),
15224
+ slots: slotsSchema.default(() => []),
15225
+ settingsSchema: external_exports.array(desktopExtensionSettingFieldSchema).max(32).refine((fields) => new Set(fields.map(({ key }) => key)).size === fields.length, "Duplicate setting keys").optional(),
15226
+ categories: categoriesSchema.optional()
15227
+ }).strict().refine((manifest) => manifest.desktop !== void 0 || manifest.backend !== void 0, "Expected at least one desktop or backend entry");
15228
+ var desktopExtensionConfigurationSchema = external_exports.strictObject({
15229
+ version: external_exports.literal(1),
15230
+ revision: external_exports.int().nonnegative(),
15231
+ enabled: external_exports.array(desktopExtensionIdSchema).max(DESKTOP_EXTENSION_LIMIT).refine((ids) => new Set(ids).size === ids.length, "Duplicate extension IDs"),
15232
+ reloadToken: external_exports.uuid().optional()
15233
+ });
15234
+ var desktopExtensionHashSchema = external_exports.string().regex(/^[a-f0-9]{64}$/u);
15235
+ var desktopExtensionStatusSchema = external_exports.strictObject({
15236
+ state: external_exports.enum([
15237
+ "running",
15238
+ "disabled",
15239
+ "invalid",
15240
+ "incompatible",
15241
+ "conflict",
15242
+ "failed",
15243
+ "waiting"
15244
+ ]),
15245
+ hash: desktopExtensionHashSchema.optional(),
15246
+ error: external_exports.string().optional(),
15247
+ conflictWith: desktopExtensionIdSchema.optional()
15248
+ });
15249
+ var desktopExtensionsDiagnosticSchema = external_exports.strictObject({
15250
+ controllerPid: external_exports.int().positive(),
15251
+ targetId: external_exports.string().nullable(),
15252
+ updatedAt: external_exports.iso.datetime(),
15253
+ handledReloadToken: external_exports.uuid().optional(),
15254
+ extensions: external_exports.record(external_exports.string(), desktopExtensionStatusSchema)
15255
+ });
15256
+ var desktopExtensionTrustTierSchema = external_exports.enum(["official", "community"]);
15257
+ function isGitHubDesktopExtensionZipballUrl(url2) {
15258
+ return url2.origin === "https://api.github.com" && /^\/repos\/[\w-]+\/[\w.-]+\/zipball(?:\/[^/]+)?\/?$/u.test(url2.pathname);
15259
+ }
15260
+ var desktopExtensionZipUrlSchema = desktopExtensionHttpUrlSchema.refine((input) => {
15261
+ const url2 = new URL(input);
15262
+ return /\.zip$/iu.test(url2.pathname) || isGitHubDesktopExtensionZipballUrl(url2) || url2.origin === "https://github.com" && /^\/[\w-]+\/[\w.-]+\/zipball(?:\/.+)?\/?$/u.test(url2.pathname) || url2.origin === "https://codeload.github.com" && /^\/[\w-]+\/[\w.-]+\/(?:zip|zipball|legacy\.zip)\/.+$/u.test(url2.pathname);
15263
+ }, "Expected a .zip download URL or a GitHub zipball URL");
15264
+ var desktopExtensionCatalogEntrySchema = external_exports.strictObject({
15265
+ id: desktopExtensionIdSchema,
15266
+ version: external_exports.string().trim().min(1).max(128),
15267
+ name: desktopExtensionLocalizedTextSchema.extend({ en: extensionName, "zh-CN": extensionName }),
15268
+ description: localizedText(external_exports.string().trim().min(1).max(4096)),
15269
+ details: localizedText(external_exports.string().trim().min(1).max(16384)).optional(),
15270
+ author: external_exports.string().trim().min(1).max(128),
15271
+ repository: desktopExtensionHttpUrlSchema,
15272
+ stars: external_exports.number().int().min(0).optional(),
15273
+ downloads: external_exports.number().int().min(0).optional(),
15274
+ categories: categoriesSchema.optional(),
15275
+ trustTier: desktopExtensionTrustTierSchema.default("community"),
15276
+ icon: desktopExtensionHttpUrlSchema.optional(),
15277
+ screenshots: external_exports.array(desktopExtensionHttpUrlSchema).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).optional(),
15278
+ downloadUrl: desktopExtensionZipUrlSchema,
15279
+ sha256: desktopExtensionHashSchema,
15280
+ slots: slotsSchema.optional(),
15281
+ publishedAt: external_exports.string().optional(),
15282
+ updatedAt: external_exports.string().optional(),
15283
+ minCodexHostVersion: external_exports.string().optional()
15284
+ });
15285
+ var desktopExtensionCatalogSchema = external_exports.strictObject({
15286
+ schemaVersion: external_exports.literal(1),
15287
+ generatedAt: external_exports.string(),
15288
+ extensions: external_exports.array(desktopExtensionCatalogEntrySchema).refine((entries) => new Set(entries.map(({ id }) => id)).size === entries.length, "Duplicate extension IDs")
15289
+ });
15290
+ var DESKTOP_EXTENSIONS_ASSET_METHOD = "codexhost/desktop/extensions/asset";
15291
+ var DESKTOP_EXTENSIONS_SETTINGS_GET_METHOD = "codexhost/desktop/extensions/settings/get";
15292
+ var DESKTOP_EXTENSIONS_SETTINGS_SET_METHOD = "codexhost/desktop/extensions/settings/set";
15293
+ var DESKTOP_EXTENSIONS_BACKEND_INVOKE_METHOD = "codexhost/desktop/extensions/backend/invoke";
15294
+ var extensionIdParams = { id: desktopExtensionIdSchema };
15295
+ var desktopExtensionsAssetParamsSchema = external_exports.strictObject({
15296
+ ...extensionIdParams,
15297
+ path: desktopExtensionAssetPathSchema
15298
+ });
15299
+ var desktopExtensionsAssetResultSchema = external_exports.strictObject({
15300
+ mimeType: external_exports.string(),
15301
+ dataUrl: external_exports.string()
15302
+ });
15303
+ var desktopExtensionsSettingsGetParamsSchema = external_exports.strictObject(extensionIdParams);
15304
+ var desktopExtensionsSettingsSetParamsSchema = external_exports.strictObject({
15305
+ ...extensionIdParams,
15306
+ values: jsonObjectSchema
15307
+ });
15308
+ var desktopExtensionsSettingsResultSchema = external_exports.strictObject({ values: jsonObjectSchema });
15309
+ var desktopExtensionBackendMethodSchema = external_exports.string().trim().min(1).max(128);
15310
+ var desktopExtensionsBackendInvokeParamsSchema = external_exports.strictObject({
15311
+ ...extensionIdParams,
15312
+ method: desktopExtensionBackendMethodSchema,
15313
+ params: jsonValueSchema.optional()
15314
+ });
15315
+ var desktopExtensionsBackendInvokeResultSchema = external_exports.strictObject({
15316
+ result: jsonValueSchema
15317
+ });
15318
+
15319
+ // ../../shared-contracts/dist/desktop-extension-management.js
15320
+ var DESKTOP_EXTENSIONS_LIST_METHOD = "codexhost/desktop/extensions/list";
15321
+ var DESKTOP_EXTENSIONS_ENABLE_METHOD = "codexhost/desktop/extensions/enable";
15322
+ var DESKTOP_EXTENSIONS_DISABLE_METHOD = "codexhost/desktop/extensions/disable";
15323
+ var DESKTOP_EXTENSIONS_CATALOG_METHOD = "codexhost/desktop/extensions/catalog";
15324
+ var DESKTOP_EXTENSIONS_INSTALL_METHOD = "codexhost/desktop/extensions/install";
15325
+ var DESKTOP_EXTENSIONS_UNINSTALL_METHOD = "codexhost/desktop/extensions/uninstall";
15326
+ var DESKTOP_EXTENSIONS_RECOVER_METHOD = "codexhost/desktop/extensions/disable-all-and-reload";
15327
+ var DESKTOP_EXTENSION_MANAGEMENT_METHODS = [
15328
+ DESKTOP_EXTENSIONS_LIST_METHOD,
15329
+ DESKTOP_EXTENSIONS_ENABLE_METHOD,
15330
+ DESKTOP_EXTENSIONS_DISABLE_METHOD,
15331
+ DESKTOP_EXTENSIONS_RECOVER_METHOD,
15332
+ DESKTOP_EXTENSIONS_CATALOG_METHOD,
15333
+ DESKTOP_EXTENSIONS_INSTALL_METHOD,
15334
+ DESKTOP_EXTENSIONS_UNINSTALL_METHOD,
15335
+ DESKTOP_EXTENSIONS_ASSET_METHOD,
15336
+ DESKTOP_EXTENSIONS_SETTINGS_GET_METHOD,
15337
+ DESKTOP_EXTENSIONS_SETTINGS_SET_METHOD,
15338
+ DESKTOP_EXTENSIONS_BACKEND_INVOKE_METHOD
15339
+ ];
15340
+ var revisionSchema = external_exports.int().nonnegative();
15341
+ var desktopExtensionsListParamsSchema = external_exports.strictObject({});
15342
+ var desktopExtensionSelectionParamsSchema = external_exports.strictObject({
15343
+ id: desktopExtensionIdSchema,
15344
+ expectedRevision: revisionSchema
15345
+ });
15346
+ var desktopExtensionsRecoveryParamsSchema = external_exports.strictObject({
15347
+ expectedRevision: revisionSchema.optional()
15348
+ });
15349
+ var rasterDataUrlSchema = (maxBytes) => external_exports.string().max("data:image/jpeg;base64,".length + 4 * Math.ceil(maxBytes / 3)).regex(/^data:image\/(?:png|jpeg|webp);base64,[A-Za-z0-9+/]+={0,2}$/u);
15350
+ var desktopExtensionListItemSchema = external_exports.strictObject({
15351
+ // An invalid discovery can have a directory name that isn't a valid extension ID.
15352
+ id: external_exports.string().min(1),
15353
+ manifest: desktopExtensionManifestSchema.optional(),
15354
+ iconDataUrl: rasterDataUrlSchema(DESKTOP_EXTENSION_ICON_MAX_BYTES).optional(),
15355
+ screenshotDataUrls: external_exports.array(rasterDataUrlSchema(DESKTOP_EXTENSION_SCREENSHOT_MAX_BYTES)).max(DESKTOP_EXTENSION_SCREENSHOT_LIMIT).optional(),
15356
+ enabled: external_exports.boolean(),
15357
+ status: desktopExtensionStatusSchema
15358
+ });
15359
+ var desktopExtensionsListResultSchema = external_exports.strictObject({
15360
+ configuration: desktopExtensionConfigurationSchema,
15361
+ desktopConnected: external_exports.boolean(),
15362
+ diagnostics: external_exports.array(external_exports.string()),
15363
+ extensions: external_exports.array(desktopExtensionListItemSchema)
15364
+ });
15365
+ var desktopExtensionsCatalogParamsSchema = external_exports.strictObject({
15366
+ forceRefresh: external_exports.boolean().optional()
15367
+ });
15368
+ var desktopExtensionsCatalogResultSchema = external_exports.strictObject({
15369
+ catalogUrl: external_exports.string(),
15370
+ source: external_exports.enum(["remote", "fallback"]),
15371
+ fetchedAt: external_exports.string(),
15372
+ cached: external_exports.boolean(),
15373
+ extensions: desktopExtensionCatalogSchema.shape.extensions,
15374
+ error: external_exports.string().optional()
15375
+ });
15376
+ var desktopExtensionsInstallParamsSchema = external_exports.strictObject({
15377
+ source: external_exports.discriminatedUnion("type", [
15378
+ external_exports.strictObject({ type: external_exports.literal("catalog"), id: desktopExtensionIdSchema }),
15379
+ external_exports.strictObject({
15380
+ type: external_exports.literal("url"),
15381
+ url: desktopExtensionHttpUrlSchema,
15382
+ expectedSha256: desktopExtensionHashSchema.optional()
15383
+ }),
15384
+ external_exports.strictObject({
15385
+ type: external_exports.literal("zip-base64"),
15386
+ fileName: external_exports.string().trim().min(1).max(255),
15387
+ contentBase64: external_exports.string().min(4).max(DESKTOP_EXTENSION_ZIP_MAX_BASE64_LENGTH).refine((value) => value.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/u.test(value), "Expected standard padded base64")
15388
+ })
15389
+ ])
15390
+ });
15391
+ var desktopExtensionsInstallResultSchema = external_exports.strictObject({
15392
+ extensionId: desktopExtensionIdSchema,
15393
+ version: external_exports.string().min(1),
15394
+ replaced: external_exports.boolean(),
15395
+ installedPath: external_exports.string(),
15396
+ list: desktopExtensionsListResultSchema
15397
+ });
15398
+ var desktopExtensionsUninstallParamsSchema = external_exports.strictObject({
15399
+ id: desktopExtensionIdSchema
15400
+ });
15401
+ var desktopExtensionsUninstallResultSchema = external_exports.strictObject({
15402
+ removedId: desktopExtensionIdSchema,
15403
+ list: desktopExtensionsListResultSchema
15404
+ });
15405
+ var desktopExtensionMutationResultSchema = external_exports.discriminatedUnion("state", [
15406
+ external_exports.strictObject({ state: external_exports.literal("saved"), configuration: desktopExtensionConfigurationSchema }),
15407
+ external_exports.strictObject({ state: external_exports.literal("slot-conflict"), conflictWith: desktopExtensionIdSchema }),
15408
+ external_exports.strictObject({ state: external_exports.literal("revision-conflict"), revision: revisionSchema })
15409
+ ]);
15410
+
14990
15411
  // ../../shared-contracts/dist/errors.js
14991
15412
  var codexhostErrorSchema = external_exports.strictObject({
14992
15413
  code: external_exports.string().min(1),
@@ -15007,16 +15428,6 @@ var harnessLocalizationsSchema = external_exports.record(localeSchema, external_
15007
15428
  }).strict()).refine((entries) => Object.keys(entries).length <= 16, "Too many locales");
15008
15429
  var harnessLocalizedTextSchema = external_exports.record(localeSchema, displayText(4096)).refine((entries) => typeof entries.en === "string", "English fallback is required").refine((entries) => Object.keys(entries).length <= 16, "Too many locales");
15009
15430
 
15010
- // ../../shared-contracts/dist/ids.js
15011
- var opaqueIdSchema = external_exports.string().refine((value) => value.trim().length > 0, {
15012
- message: "Identifier must not be empty or whitespace"
15013
- });
15014
- var harnessIdSchema = opaqueIdSchema.brand();
15015
- var hostThreadIdSchema = opaqueIdSchema.brand();
15016
- var hostTurnIdSchema = opaqueIdSchema.brand();
15017
- var hostItemIdSchema = opaqueIdSchema.brand();
15018
- var hostInteractionIdSchema = opaqueIdSchema.brand();
15019
-
15020
15431
  // ../../shared-contracts/dist/harness-permission-modes.js
15021
15432
  var HARNESS_PERMISSION_MODE_ID_MAX_LENGTH = 128;
15022
15433
  var HARNESS_PERMISSION_MODE_LABEL_MAX_LENGTH = 256;
@@ -15216,6 +15627,13 @@ var accountCreditsSnapshotSchema = external_exports.object({
15216
15627
  productUsage: external_exports.array(accountCreditsProductUsageSchema).min(1).optional(),
15217
15628
  resetCredits: accountResetCreditsSchema.optional()
15218
15629
  }).strict();
15630
+ var accountBalanceSnapshotSchema = external_exports.object({
15631
+ amount: external_exports.number().finite().nonnegative(),
15632
+ /** ISO 4217 code as reported by the Provider, for example `CNY`. */
15633
+ currency: external_exports.string().trim().min(1).max(8),
15634
+ /** Native label when the Harness exposes several Billing Sources. */
15635
+ label: external_exports.string().trim().min(1).max(128).optional()
15636
+ }).strict();
15219
15637
  var threadUsageInspectionParamsSchema = external_exports.object({
15220
15638
  threadId: hostThreadIdSchema,
15221
15639
  refresh: external_exports.literal("exact").optional()
@@ -15224,7 +15642,10 @@ var threadUsageInspectionSchema = external_exports.object({
15224
15642
  threadId: hostThreadIdSchema,
15225
15643
  usage: threadUsageSnapshotSchema.nullable(),
15226
15644
  accountCredits: accountCreditsSnapshotSchema.optional(),
15227
- /** Whether this source can provide cached account quota independently of usage. */
15645
+ /** Prepaid funds for the Thread's Billing Source; shown only when no percentage quota exists. */
15646
+ accountBalance: accountBalanceSnapshotSchema.optional(),
15647
+ /** Whether this source can provide cached account quota (credits or a prepaid balance)
15648
+ * independently of usage. */
15228
15649
  accountCreditsSupported: external_exports.boolean().optional()
15229
15650
  }).strict();
15230
15651
 
@@ -15516,12 +15937,89 @@ var threadSteeringInspectResultSchema = external_exports.object({
15516
15937
  }).strict();
15517
15938
 
15518
15939
  // ../../shared-contracts/dist/thread-archive-confirm.js
15940
+ var THREAD_ARCHIVE_CONFIRM_METHOD = "codexhost/thread/archive/confirm";
15519
15941
  var threadArchiveConfirmParamsSchema = external_exports.object({ threadId: hostThreadIdSchema }).strict();
15520
15942
  var threadArchiveConfirmResultSchema = external_exports.object({ confirmed: external_exports.boolean() }).strict();
15521
15943
 
15522
15944
  // ../../shared-contracts/dist/client-channel.js
15523
15945
  var CLIENT_CHANNEL_VERSION = 1;
15524
15946
  var CLIENT_REQUEST_LIMIT_BYTES = 128 * 1024 * 1024;
15947
+ var CLIENT_CHANNEL_METHODS = [
15948
+ "codexhost/skills/list",
15949
+ "codexhost/voice/status",
15950
+ "codexhost/voice/transcribe",
15951
+ "codexhost/harness/display-settings/get",
15952
+ "codexhost/harness/display-settings/set",
15953
+ "codexhost/harness/display-settings/capabilities",
15954
+ "codexhost/harness/preferences/get",
15955
+ "codexhost/harness/preferences/patch",
15956
+ "thread/list",
15957
+ "codexhost/thread/catalog/read",
15958
+ "thread/read",
15959
+ "thread/resume",
15960
+ "thread/fork",
15961
+ "thread/turns/list",
15962
+ "thread/revert",
15963
+ "thread/items/list",
15964
+ "thread/start",
15965
+ "thread/name/set",
15966
+ "codexhost/thread/title/generate",
15967
+ "thread/archive",
15968
+ THREAD_ARCHIVE_CONFIRM_METHOD,
15969
+ "thread/unarchive",
15970
+ "turn/start",
15971
+ "turn/interrupt",
15972
+ "turn/steer",
15973
+ "thread/queue/list",
15974
+ "thread/queue/add",
15975
+ "thread/queue/update",
15976
+ "thread/queue/delete",
15977
+ "thread/queue/reorder",
15978
+ "thread/queue/start",
15979
+ "codexhost/thread/queue/send-now",
15980
+ "codexhost/workspace/read",
15981
+ "codexhost/thread/tree/read",
15982
+ "codexhost/thread/pins/list",
15983
+ "codexhost/thread/pins/set",
15984
+ "codexhost/harness/plugins/list",
15985
+ "codexhost/harness/inspect",
15986
+ "codexhost/thread/inspect",
15987
+ "codexhost/thread/usage/inspect",
15988
+ "codexhost/thread/ownership/list",
15989
+ "codexhost/thread/model/select",
15990
+ "codexhost/thread/thinking/select",
15991
+ "codexhost/thread/permission-mode/select",
15992
+ "codexhost/thread/commands/inspect",
15993
+ "codexhost/harness/commands/inspect",
15994
+ "codexhost/thread/command/execute",
15995
+ "codexhost/thread/fork",
15996
+ "codexhost/harness/session-import/sources",
15997
+ "codexhost/harness/session-import/list",
15998
+ "codexhost/harness/session-import/import",
15999
+ // Host settings shared across Desktop and Web.
16000
+ ...DESKTOP_EXTENSION_MANAGEMENT_METHODS,
16001
+ "codexhost/harness/installation",
16002
+ "codexhost/harness/installation/start",
16003
+ "codexhost/harness/installation/status",
16004
+ "codexhost/harness/launch-settings/get",
16005
+ "codexhost/harness/launch-settings/set",
16006
+ "codexhost/harness/web-ui/open",
16007
+ "codexhost/harness/accounts/sources",
16008
+ "codexhost/harness/accounts/list",
16009
+ "codexhost/harness/accounts/inspect",
16010
+ "codexhost/harness/credential-imports",
16011
+ "codexhost/account/list",
16012
+ "codexhost/account/refresh",
16013
+ "codexhost/account/usage/inspect",
16014
+ "codexhost/usage/model-prices/get",
16015
+ "codexhost/usage/model-prices/set",
16016
+ "codexhost/usage/model-prices/default",
16017
+ "codexhost/usage/statistics/get",
16018
+ "codexhost/update/check",
16019
+ "codexhost/update/start",
16020
+ "codexhost/update/status",
16021
+ "codexhost/sessions/loaded/list"
16022
+ ];
15525
16023
  var clientThreadPinsSchema = external_exports.object({ threadIds: external_exports.array(external_exports.string().min(1)) }).strict();
15526
16024
  var clientThreadPinParamsSchema = external_exports.object({ threadId: external_exports.string().min(1).max(1024), pinned: external_exports.boolean() }).strict();
15527
16025
  var clientThreadTreeReadParamsSchema = external_exports.object({}).strict();
@@ -15735,6 +16233,29 @@ var threadCatalogReadResultSchema = external_exports.object({
15735
16233
  officialCursor: external_exports.object({ live: external_exports.string().nullable(), archived: external_exports.string().nullable().optional() }).strict().optional()
15736
16234
  }).strict();
15737
16235
 
16236
+ // ../../shared-contracts/dist/thread-tree-watch.js
16237
+ var THREAD_TREE_MAX_NODES = 5e3;
16238
+ var threadTreeStatusSchema = external_exports.enum(["running", "waiting", "idle", "unknown"]);
16239
+ var threadTreeNodeSchema = external_exports.strictObject({
16240
+ harnessId: harnessIdSchema,
16241
+ title: external_exports.string().optional(),
16242
+ status: threadTreeStatusSchema,
16243
+ archived: external_exports.boolean()
16244
+ });
16245
+ var threadTreeSnapshotSchema = external_exports.strictObject({
16246
+ revision: external_exports.int().nonnegative(),
16247
+ parents: external_exports.record(hostThreadIdSchema, hostThreadIdSchema),
16248
+ nodes: external_exports.record(hostThreadIdSchema, threadTreeNodeSchema),
16249
+ truncated: external_exports.boolean()
16250
+ }).refine((snapshot) => Object.keys(snapshot.nodes).length <= THREAD_TREE_MAX_NODES, "Too many Thread tree nodes").refine(({ parents, nodes }) => Object.entries(parents).every(([child, parent]) => Object.hasOwn(nodes, child) && Object.hasOwn(nodes, parent)), "Missing Thread tree node");
16251
+ var subscriptionId = external_exports.string().min(1).max(128);
16252
+ var threadTreeWatchParamsSchema = external_exports.strictObject({});
16253
+ var threadTreeUnwatchParamsSchema = external_exports.strictObject({ subscriptionId });
16254
+ var threadTreeUnwatchResultSchema = external_exports.strictObject({});
16255
+ var threadTreeWatchResultSchema = threadTreeUnwatchParamsSchema.extend({
16256
+ snapshot: threadTreeSnapshotSchema
16257
+ });
16258
+
15738
16259
  // ../../shared-contracts/dist/voice.js
15739
16260
  var VOICE_AUDIO_MAX_BYTES = 10 * 1024 * 1024;
15740
16261
  var voiceAudioMimeTypeSchema = external_exports.string().regex(/^audio\/[a-z0-9.+-]+(?:\s*;[^\r\n]*)?$/i);
@@ -16365,13 +16886,6 @@ var threadManualCompactionStartedSchema = external_exports.strictObject({
16365
16886
  });
16366
16887
 
16367
16888
  // ../../shared-contracts/dist/harness-accounts.js
16368
- var accountBalanceSnapshotSchema = external_exports.object({
16369
- amount: external_exports.number().finite().nonnegative(),
16370
- /** ISO 4217 code as reported by the Provider, for example `CNY`. */
16371
- currency: external_exports.string().trim().min(1).max(8),
16372
- /** Native label when the Harness exposes several Billing Sources. */
16373
- label: external_exports.string().trim().min(1).max(128).optional()
16374
- }).strict();
16375
16889
  var harnessAccountSnapshotObject = external_exports.object({
16376
16890
  email: external_exports.string().trim().min(1).max(320).optional(),
16377
16891
  label: external_exports.string().trim().min(1).max(256).optional(),
@@ -16405,76 +16919,6 @@ var harnessAccountListResultSchema = external_exports.object({
16405
16919
  accounts: external_exports.array(requireReportedQuota(harnessAccountSnapshotObject.extend(harnessAccountIdentityShape))).max(128)
16406
16920
  }).strict();
16407
16921
 
16408
- // ../../shared-contracts/dist/harness-plugins.js
16409
- var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
16410
- var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
16411
- var HARNESS_PLUGIN_LIMIT = 128;
16412
- var installedHarnessPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u).pipe(harnessIdSchema);
16413
- var harnessPluginIdSchema = installedHarnessPluginIdSchema.refine((id) => id !== "codex", "The official Codex identity is reserved");
16414
- var relativeResourceSchema = external_exports.string().min(1).max(512).refine((value) => !/[\\\u0000:#?]/u.test(value) && !value.startsWith("/") && !value.split("/").some((part) => part === ".." || part === ""), "Plugin resources must be relative paths inside the plugin");
16415
- var documentationUrlSchema = external_exports.url().refine((value) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value), "Plugin documentation links must be credential-free HTTPS URLs");
16416
- var localizedTextSchema = external_exports.object({ en: external_exports.string().max(4096), "zh-CN": external_exports.string().max(4096).optional() }).strict();
16417
- var harnessInstallationGuideSchema = external_exports.object({
16418
- commands: external_exports.array(external_exports.object({ terminal: external_exports.string().max(256), command: external_exports.string().max(4096) }).strict()).max(8),
16419
- before: localizedTextSchema.optional(),
16420
- after: localizedTextSchema.optional(),
16421
- downloads: external_exports.array(external_exports.object({ label: external_exports.string().max(128), url: documentationUrlSchema }).strict()).max(8).optional()
16422
- }).strict();
16423
- var pluginPresentationShape = {
16424
- id: installedHarnessPluginIdSchema,
16425
- name: external_exports.string().trim().min(1).max(128),
16426
- version: external_exports.string().min(1).max(128),
16427
- /** Capability-only plugin; omitted for existing session-capable plugins. */
16428
- kind: external_exports.literal("usage").optional(),
16429
- /** Original image styling or bounded vector paths; never arbitrary CSS/SVG markup. */
16430
- iconStyle: external_exports.object({
16431
- vector: external_exports.object({
16432
- viewBox: external_exports.string().max(128).regex(/^-?\d+(?:\.\d+)?(?: +-?\d+(?:\.\d+)?){3}$/u),
16433
- color: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu),
16434
- paths: external_exports.array(external_exports.object({
16435
- d: external_exports.string().min(1).max(32768).regex(/^[MmLlHhVvCcSsQqTtAaZz\d.,+eE\s-]+$/u),
16436
- fillRule: external_exports.enum(["evenodd", "nonzero"]).optional(),
16437
- fill: external_exports.string().regex(/^(?:currentColor|#[a-f0-9]{6})$/iu).optional()
16438
- }).strict()).min(1).max(32)
16439
- }).strict().optional(),
16440
- background: external_exports.string().regex(/^#[a-f0-9]{6}$/iu).optional(),
16441
- borderRadius: external_exports.number().min(0).max(50).optional(),
16442
- paddingRatio: external_exports.number().min(0).max(0.25).optional()
16443
- }).strict().optional(),
16444
- installation: harnessInstallationGuideSchema.optional(),
16445
- notice: localizedTextSchema.optional(),
16446
- /** The factory accepts a persisted local entrypoint through its construction context. */
16447
- launchCommand: external_exports.literal(true).optional(),
16448
- links: external_exports.object({
16449
- website: documentationUrlSchema.optional(),
16450
- documentation: documentationUrlSchema.optional(),
16451
- installation: documentationUrlSchema.optional()
16452
- }).strict().optional()
16453
- };
16454
- var harnessPluginManifestSchema = external_exports.object({
16455
- manifestVersion: external_exports.literal(1),
16456
- ...pluginPresentationShape,
16457
- adapterApiVersion: external_exports.number().int().positive(),
16458
- entry: relativeResourceSchema,
16459
- icon: relativeResourceSchema.optional()
16460
- }).strict();
16461
- var harnessPluginIconSchema = external_exports.string().max(Math.ceil(HARNESS_PLUGIN_ICON_MAX_BYTES / 3) * 4 + 64).regex(/^data:image\/(?:png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/]+={0,2}$/u);
16462
- var harnessPluginDescriptorSchema = external_exports.object({
16463
- ...pluginPresentationShape,
16464
- icon: harnessPluginIconSchema.optional()
16465
- }).strict();
16466
- var harnessPluginListParamsSchema = external_exports.object({}).strict();
16467
- var harnessPluginListResultSchema = external_exports.object({
16468
- plugins: external_exports.array(harnessPluginDescriptorSchema.extend({ id: harnessPluginIdSchema })).max(HARNESS_PLUGIN_LIMIT)
16469
- }).strict();
16470
- var harnessPluginConfigurationSchema = external_exports.object({
16471
- version: external_exports.literal(1),
16472
- enabled: external_exports.array(installedHarnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
16473
- }).strict().refine((value) => new Set(value.enabled).size === value.enabled.length, {
16474
- message: "Enabled plugin IDs must be unique",
16475
- path: ["enabled"]
16476
- });
16477
-
16478
16922
  // ../../shared-contracts/dist/harness-route.js
16479
16923
  var harnessPluginRouteSchema = external_exports.object({
16480
16924
  harnessId: harnessPluginIdSchema,
@@ -16909,6 +17353,7 @@ var remoteSessionOperationSchema = external_exports.discriminatedUnion("kind", [
16909
17353
  message: "A history continuation requires its connection epoch"
16910
17354
  }).optional()
16911
17355
  }),
17356
+ external_exports.strictObject({ kind: external_exports.literal("usage"), ...thread, epoch: identity }),
16912
17357
  external_exports.strictObject({
16913
17358
  kind: external_exports.literal("configure"),
16914
17359
  ...thread,
@@ -17040,16 +17485,16 @@ var webUiExtensionRemoveSchema = external_exports.object({ id: webUiExtensionIdS
17040
17485
  var workspaceContractVersionSchema = external_exports.literal(WORKSPACE_CONTRACT_VERSION);
17041
17486
 
17042
17487
  // ../../harness-adapter/dist/approval.js
17043
- function invalidRequest(message2) {
17044
- return { code: "invalidRequest", message: message2, retryable: false };
17488
+ function invalidRequest(message3) {
17489
+ return { code: "invalidRequest", message: message3, retryable: false };
17045
17490
  }
17046
17491
  function validateHostApprovalResponse(interaction, response) {
17047
17492
  return interaction.actions.some(({ id }) => id === response.actionId) ? null : invalidRequest("Approval Response contains an undeclared action ID");
17048
17493
  }
17049
17494
 
17050
17495
  // ../../harness-adapter/dist/question.js
17051
- function invalidRequest2(message2) {
17052
- return { code: "invalidRequest", message: message2, retryable: false };
17496
+ function invalidRequest2(message3) {
17497
+ return { code: "invalidRequest", message: message3, retryable: false };
17053
17498
  }
17054
17499
  function validateHostQuestionResponse(interaction, response) {
17055
17500
  const questionIds = new Set(interaction.questions.map(({ id }) => id));
@@ -19262,8 +19707,8 @@ var Handled = {
19262
19707
  /**
19263
19708
  * Leaves a message unhandled so later handlers can process it.
19264
19709
  */
19265
- no(message2, retry = false) {
19266
- return { handled: false, message: message2, retry };
19710
+ no(message3, retry = false) {
19711
+ return { handled: false, message: message3, retry };
19267
19712
  }
19268
19713
  };
19269
19714
  function rejectedPromise(error51) {
@@ -19510,8 +19955,8 @@ var Connection = class {
19510
19955
  addDynamicHandler(handler) {
19511
19956
  this.dynamicHandlers.add(handler);
19512
19957
  if (this.retryQueue.length > 0) {
19513
- for (const message2 of this.retryQueue.splice(0)) {
19514
- void this.processIncomingMessage(message2).catch((error51) => this.close(error51));
19958
+ for (const message3 of this.retryQueue.splice(0)) {
19959
+ void this.processIncomingMessage(message3).catch((error51) => this.close(error51));
19515
19960
  }
19516
19961
  }
19517
19962
  return new HandlerRegistration(() => {
@@ -19690,12 +20135,12 @@ var Connection = class {
19690
20135
  }
19691
20136
  legacyHandler(requestHandler, notificationHandler) {
19692
20137
  return {
19693
- handleMessage: async (message2, cx) => {
19694
- if (message2.kind === "request") {
19695
- const result = await requestHandler(message2.method, message2.params, cx);
19696
- await message2.responder.respond(result);
20138
+ handleMessage: async (message3, cx) => {
20139
+ if (message3.kind === "request") {
20140
+ const result = await requestHandler(message3.method, message3.params, cx);
20141
+ await message3.responder.respond(result);
19697
20142
  } else {
19698
- await notificationHandler(message2.method, message2.params, cx);
20143
+ await notificationHandler(message3.method, message3.params, cx);
19699
20144
  }
19700
20145
  return Handled.yes();
19701
20146
  }
@@ -19708,17 +20153,17 @@ var Connection = class {
19708
20153
  this.receiveReader = reader;
19709
20154
  try {
19710
20155
  while (!this.abortController.signal.aborted) {
19711
- const { value: message2, done } = await reader.read();
20156
+ const { value: message3, done } = await reader.read();
19712
20157
  if (this.abortController.signal.aborted) {
19713
20158
  break;
19714
20159
  }
19715
20160
  if (done) {
19716
20161
  break;
19717
20162
  }
19718
- if (!message2) {
20163
+ if (!message3) {
19719
20164
  continue;
19720
20165
  }
19721
- this.receiveWireMessage(message2);
20166
+ this.receiveWireMessage(message3);
19722
20167
  }
19723
20168
  } finally {
19724
20169
  if (this.receiveReader === reader) {
@@ -19732,20 +20177,20 @@ var Connection = class {
19732
20177
  this.close(closeError);
19733
20178
  }
19734
20179
  }
19735
- receiveWireMessage(message2) {
19736
- if (Array.isArray(message2)) {
20180
+ receiveWireMessage(message3) {
20181
+ if (Array.isArray(message3)) {
19737
20182
  if (!this.allowBatches) {
19738
20183
  this.close(new TypeError("JSON-RPC batches are not supported on this connection"));
19739
20184
  return;
19740
20185
  }
19741
- this.receiveBatch(message2);
20186
+ this.receiveBatch(message3);
19742
20187
  return;
19743
20188
  }
19744
- if (!isRecord2(message2)) {
19745
- console.error("Invalid message", { message: message2 });
20189
+ if (!isRecord2(message3)) {
20190
+ console.error("Invalid message", { message: message3 });
19746
20191
  return;
19747
20192
  }
19748
- this.receiveMessage(message2);
20193
+ this.receiveMessage(message3);
19749
20194
  }
19750
20195
  receiveBatch(batch) {
19751
20196
  if (batch.length === 0) {
@@ -19758,9 +20203,9 @@ var Connection = class {
19758
20203
  return;
19759
20204
  }
19760
20205
  const responseBatch = isResponseBatch(batch);
19761
- const responseCount = responseBatch ? 0 : batch.reduce((count4, message2) => count4 + (isNotificationMessage(message2) ? 0 : 1), 0);
20206
+ const responseCount = responseBatch ? 0 : batch.reduce((count4, message3) => count4 + (isNotificationMessage(message3) ? 0 : 1), 0);
19762
20207
  let remaining = responseCount;
19763
- let remainingNotifications = batch.reduce((count4, message2) => count4 + (isNotificationMessage(message2) ? 1 : 0), 0);
20208
+ let remainingNotifications = batch.reduce((count4, message3) => count4 + (isNotificationMessage(message3) ? 1 : 0), 0);
19764
20209
  let responseSent = false;
19765
20210
  const responses = [];
19766
20211
  const sendResponsesIfReady = async () => {
@@ -19775,24 +20220,24 @@ var Connection = class {
19775
20220
  remaining -= 1;
19776
20221
  await sendResponsesIfReady();
19777
20222
  };
19778
- for (const message2 of batch) {
20223
+ for (const message3 of batch) {
19779
20224
  if (responseBatch) {
19780
- if (isResponseShapedMessage(message2)) {
19781
- this.receiveMessage(message2);
20225
+ if (isResponseShapedMessage(message3)) {
20226
+ this.receiveMessage(message3);
19782
20227
  }
19783
20228
  continue;
19784
20229
  }
19785
- if (!isRequestMessage(message2) && !isNotificationMessage(message2)) {
20230
+ if (!isRequestMessage(message3) && !isNotificationMessage(message3)) {
19786
20231
  void collectResponse({
19787
20232
  jsonrpc: "2.0",
19788
20233
  id: null,
19789
- error: RequestError.invalidRequest(message2).toErrorResponse()
20234
+ error: RequestError.invalidRequest(message3).toErrorResponse()
19790
20235
  }).catch(() => {
19791
20236
  });
19792
20237
  continue;
19793
20238
  }
19794
- const processing = this.receiveMessage(message2, isRequestMessage(message2) ? collectResponse : void 0);
19795
- if (isNotificationMessage(message2)) {
20239
+ const processing = this.receiveMessage(message3, isRequestMessage(message3) ? collectResponse : void 0);
20240
+ if (isNotificationMessage(message3)) {
19796
20241
  void processing.finally(() => {
19797
20242
  remainingNotifications -= 1;
19798
20243
  void sendResponsesIfReady().catch((error51) => this.close(error51));
@@ -19800,31 +20245,31 @@ var Connection = class {
19800
20245
  }
19801
20246
  }
19802
20247
  }
19803
- receiveMessage(message2, sendResponse) {
20248
+ receiveMessage(message3, sendResponse) {
19804
20249
  if (this.abortController.signal.aborted) {
19805
20250
  return Promise.resolve();
19806
20251
  }
19807
- if (!isRecord2(message2)) {
19808
- console.error("Invalid message", { message: message2 });
20252
+ if (!isRecord2(message3)) {
20253
+ console.error("Invalid message", { message: message3 });
19809
20254
  return Promise.resolve();
19810
20255
  }
19811
- if ("method" in message2) {
19812
- if (!("id" in message2)) {
19813
- this.handleProtocolNotification(message2);
20256
+ if ("method" in message3) {
20257
+ if (!("id" in message3)) {
20258
+ this.handleProtocolNotification(message3);
19814
20259
  }
19815
- return this.processIncomingMessage(this.toIncomingMessage(message2, sendResponse)).catch((error51) => this.close(error51));
19816
- } else if ("id" in message2) {
19817
- this.handleResponse(message2);
20260
+ return this.processIncomingMessage(this.toIncomingMessage(message3, sendResponse)).catch((error51) => this.close(error51));
20261
+ } else if ("id" in message3) {
20262
+ this.handleResponse(message3);
19818
20263
  } else {
19819
- console.error("Invalid message", { message: message2 });
20264
+ console.error("Invalid message", { message: message3 });
19820
20265
  }
19821
20266
  return Promise.resolve();
19822
20267
  }
19823
- async processIncomingMessage(message2) {
20268
+ async processIncomingMessage(message3) {
19824
20269
  if (this.abortController.signal.aborted) {
19825
20270
  return;
19826
20271
  }
19827
- let current = message2;
20272
+ let current = message3;
19828
20273
  let retry = false;
19829
20274
  try {
19830
20275
  for (const handler of [
@@ -19857,30 +20302,30 @@ var Connection = class {
19857
20302
  } else {
19858
20303
  const response = errorToResult(error51);
19859
20304
  if ("error" in response) {
19860
- console.error("Error handling notification", message2.raw, response.error);
20305
+ console.error("Error handling notification", message3.raw, response.error);
19861
20306
  }
19862
20307
  }
19863
20308
  }
19864
20309
  }
19865
- toIncomingMessage(message2, sendResponse) {
19866
- if ("id" in message2) {
20310
+ toIncomingMessage(message3, sendResponse) {
20311
+ if ("id" in message3) {
19867
20312
  const abortController = new AbortController();
19868
- this.incomingRequests.set(message2.id, abortController);
20313
+ this.incomingRequests.set(message3.id, abortController);
19869
20314
  const finishRequest = () => {
19870
- if (this.incomingRequests.get(message2.id) === abortController) {
19871
- this.incomingRequests.delete(message2.id);
20315
+ if (this.incomingRequests.get(message3.id) === abortController) {
20316
+ this.incomingRequests.delete(message3.id);
19872
20317
  }
19873
20318
  };
19874
20319
  return {
19875
20320
  kind: "request",
19876
- method: message2.method,
19877
- params: message2.params,
19878
- raw: message2,
20321
+ method: message3.method,
20322
+ params: message3.params,
20323
+ raw: message3,
19879
20324
  signal: abortController.signal,
19880
- responder: new RequestResponder(message2.id, (result) => {
20325
+ responder: new RequestResponder(message3.id, (result) => {
19881
20326
  const response = {
19882
20327
  jsonrpc: "2.0",
19883
- id: message2.id,
20328
+ id: message3.id,
19884
20329
  ...result
19885
20330
  };
19886
20331
  return sendResponse ? sendResponse(response) : this.sendWireMessage(response);
@@ -19889,9 +20334,9 @@ var Connection = class {
19889
20334
  }
19890
20335
  return {
19891
20336
  kind: "notification",
19892
- method: message2.method,
19893
- params: message2.params,
19894
- raw: message2
20337
+ method: message3.method,
20338
+ params: message3.params,
20339
+ raw: message3
19895
20340
  };
19896
20341
  }
19897
20342
  handleResponse(response) {
@@ -19904,18 +20349,18 @@ var Connection = class {
19904
20349
  } else if ("result" in response) {
19905
20350
  pendingResponse.resolve(response.result);
19906
20351
  } else {
19907
- const { code, message: message2, data } = response.error;
19908
- pendingResponse.reject(new RequestError(code, message2, data));
20352
+ const { code, message: message3, data } = response.error;
20353
+ pendingResponse.reject(new RequestError(code, message3, data));
19909
20354
  }
19910
20355
  } else {
19911
20356
  console.error("Got response to unknown request", response.id);
19912
20357
  }
19913
20358
  }
19914
- handleProtocolNotification(message2) {
19915
- if (message2.method !== CANCEL_REQUEST_METHOD) {
20359
+ handleProtocolNotification(message3) {
20360
+ if (message3.method !== CANCEL_REQUEST_METHOD) {
19916
20361
  return;
19917
20362
  }
19918
- const requestId = cancelRequestId(message2.params);
20363
+ const requestId = cancelRequestId(message3.params);
19919
20364
  if (requestId === void 0) {
19920
20365
  return;
19921
20366
  }
@@ -19928,7 +20373,7 @@ var Connection = class {
19928
20373
  closedReason() {
19929
20374
  return this.abortController.signal.reason ?? new Error("ACP connection closed");
19930
20375
  }
19931
- async sendWireMessage(message2) {
20376
+ async sendWireMessage(message3) {
19932
20377
  if (this.abortController.signal.aborted) {
19933
20378
  return rejectedPromise(this.closedReason());
19934
20379
  }
@@ -19938,7 +20383,7 @@ var Connection = class {
19938
20383
  }
19939
20384
  const writer = this.stream.writable.getWriter();
19940
20385
  try {
19941
- await writer.write(message2);
20386
+ await writer.write(message3);
19942
20387
  } finally {
19943
20388
  writer.releaseLock();
19944
20389
  }
@@ -19974,7 +20419,7 @@ var ConnectionBuilder = class {
19974
20419
  */
19975
20420
  onReceiveMessage(handler) {
19976
20421
  return this.withHandler({
19977
- handleMessage: async (message2, cx) => await handler(message2, cx) ?? Handled.no(message2),
20422
+ handleMessage: async (message3, cx) => await handler(message3, cx) ?? Handled.no(message3),
19978
20423
  describe: () => this.connectionName ?? "onReceiveMessage"
19979
20424
  });
19980
20425
  }
@@ -19983,12 +20428,12 @@ var ConnectionBuilder = class {
19983
20428
  */
19984
20429
  onReceiveRequest(method, parse3, handler) {
19985
20430
  return this.withHandler({
19986
- handleMessage: async (message2, cx) => {
19987
- if (message2.kind !== "request" || message2.method !== method) {
19988
- return Handled.no(message2);
20431
+ handleMessage: async (message3, cx) => {
20432
+ if (message3.kind !== "request" || message3.method !== method) {
20433
+ return Handled.no(message3);
19989
20434
  }
19990
- const request = parse3(message2.params);
19991
- return await handler(request, message2.responder, cx) ?? Handled.yes();
20435
+ const request = parse3(message3.params);
20436
+ return await handler(request, message3.responder, cx) ?? Handled.yes();
19992
20437
  },
19993
20438
  describe: () => `${this.connectionName ?? "request"}:${method}`
19994
20439
  });
@@ -19998,11 +20443,11 @@ var ConnectionBuilder = class {
19998
20443
  */
19999
20444
  onReceiveNotification(method, parse3, handler) {
20000
20445
  return this.withHandler({
20001
- handleMessage: async (message2, cx) => {
20002
- if (message2.kind !== "notification" || message2.method !== method) {
20003
- return Handled.no(message2);
20446
+ handleMessage: async (message3, cx) => {
20447
+ if (message3.kind !== "notification" || message3.method !== method) {
20448
+ return Handled.no(message3);
20004
20449
  }
20005
- const notification = parse3(message2.params);
20450
+ const notification = parse3(message3.params);
20006
20451
  return await handler(notification, cx) ?? Handled.yes();
20007
20452
  },
20008
20453
  describe: () => `${this.connectionName ?? "notification"}:${method}`
@@ -20027,8 +20472,8 @@ var RequestError = class _RequestError extends Error {
20027
20472
  * Additional JSON-RPC error data.
20028
20473
  */
20029
20474
  data;
20030
- constructor(code, message2, data) {
20031
- super(message2);
20475
+ constructor(code, message3, data) {
20476
+ super(message3);
20032
20477
  this.code = code;
20033
20478
  this.name = "RequestError";
20034
20479
  this.data = data;
@@ -20173,9 +20618,9 @@ function ndJsonStream(output, input) {
20173
20618
  const trimmedLine = textDecoder.decode(lineBytes).trim();
20174
20619
  if (trimmedLine) {
20175
20620
  try {
20176
- const message2 = JSON.parse(trimmedLine);
20177
- if (isRecord2(message2) || Array.isArray(message2)) {
20178
- controller.enqueue(message2);
20621
+ const message3 = JSON.parse(trimmedLine);
20622
+ if (isRecord2(message3) || Array.isArray(message3)) {
20623
+ controller.enqueue(message3);
20179
20624
  } else {
20180
20625
  console.warn("Skipping JSON line that is not an object:", trimmedLine);
20181
20626
  }
@@ -20235,8 +20680,8 @@ function ndJsonStream(output, input) {
20235
20680
  }
20236
20681
  });
20237
20682
  const writable = new WritableStream({
20238
- async write(message2) {
20239
- const content = JSON.stringify(message2) + "\n";
20683
+ async write(message3) {
20684
+ const content = JSON.stringify(message3) + "\n";
20240
20685
  const writer = output.getWriter();
20241
20686
  try {
20242
20687
  await writer.write(textEncoder.encode(content));
@@ -20723,11 +21168,11 @@ var ActiveSession = class _ActiveSession {
20723
21168
  async readText() {
20724
21169
  let output = "";
20725
21170
  for (; ; ) {
20726
- const message2 = await this.nextUpdate();
20727
- if (message2.kind === "stop") {
21171
+ const message3 = await this.nextUpdate();
21172
+ if (message3.kind === "stop") {
20728
21173
  return output;
20729
21174
  }
20730
- const { update } = message2;
21175
+ const { update } = message3;
20731
21176
  if (update.sessionUpdate === "agent_message_chunk" && update.content.type === "text") {
20732
21177
  output += update.content.text;
20733
21178
  }
@@ -20875,11 +21320,11 @@ function clientNotificationContext(params, agent, signal) {
20875
21320
  }
20876
21321
  var SessionUpdateRouter = class {
20877
21322
  activeSessions = /* @__PURE__ */ new Map();
20878
- handleMessage(message2) {
20879
- if (message2.kind !== "notification" || message2.method !== CLIENT_METHODS.session_update) {
20880
- return Handled.no(message2);
21323
+ handleMessage(message3) {
21324
+ if (message3.kind !== "notification" || message3.method !== CLIENT_METHODS.session_update) {
21325
+ return Handled.no(message3);
20881
21326
  }
20882
- const notification = zSessionNotification.parse(message2.params);
21327
+ const notification = zSessionNotification.parse(message3.params);
20883
21328
  const update = {
20884
21329
  kind: "session_update",
20885
21330
  notification,
@@ -20891,7 +21336,7 @@ var SessionUpdateRouter = class {
20891
21336
  session.enqueue(update);
20892
21337
  }
20893
21338
  }
20894
- return Handled.no(message2);
21339
+ return Handled.no(message3);
20895
21340
  }
20896
21341
  attach(response, updates) {
20897
21342
  const sessions = this.activeSessions.get(response.sessionId) ?? /* @__PURE__ */ new Set();
@@ -21036,7 +21481,7 @@ var ClientApp = class {
21036
21481
  this.builder.name(options.name);
21037
21482
  }
21038
21483
  this.builder.withHandler({
21039
- handleMessage: (message2, cx) => sessionUpdateRouter(cx).handleMessage(message2),
21484
+ handleMessage: (message3, cx) => sessionUpdateRouter(cx).handleMessage(message3),
21040
21485
  describe: () => "client-session-update-router"
21041
21486
  });
21042
21487
  }
@@ -21179,11 +21624,11 @@ function legacyClientApp(implementation) {
21179
21624
  }
21180
21625
  if (implementation.extMethod) {
21181
21626
  app[appBuilder]().withHandler({
21182
- handleMessage: async (message2) => {
21183
- if (message2.kind !== "request" || legacyClientRequestMethods.has(message2.method)) {
21184
- return Handled.no(message2);
21627
+ handleMessage: async (message3) => {
21628
+ if (message3.kind !== "request" || legacyClientRequestMethods.has(message3.method)) {
21629
+ return Handled.no(message3);
21185
21630
  }
21186
- await message2.responder.respond(await implementation.extMethod(message2.method, message2.params));
21631
+ await message3.responder.respond(await implementation.extMethod(message3.method, message3.params));
21187
21632
  return Handled.yes();
21188
21633
  },
21189
21634
  describe: () => "legacy-client-extension-request"
@@ -21191,11 +21636,11 @@ function legacyClientApp(implementation) {
21191
21636
  }
21192
21637
  if (implementation.extNotification) {
21193
21638
  app[appBuilder]().withHandler({
21194
- handleMessage: async (message2) => {
21195
- if (message2.kind !== "notification" || legacyClientNotificationMethods.has(message2.method)) {
21196
- return Handled.no(message2);
21639
+ handleMessage: async (message3) => {
21640
+ if (message3.kind !== "notification" || legacyClientNotificationMethods.has(message3.method)) {
21641
+ return Handled.no(message3);
21197
21642
  }
21198
- await implementation.extNotification(message2.method, message2.params);
21643
+ await implementation.extNotification(message3.method, message3.params);
21199
21644
  return Handled.yes();
21200
21645
  },
21201
21646
  describe: () => "legacy-client-extension-notification"
@@ -22250,9 +22695,9 @@ function extractString(record4, keys) {
22250
22695
  }
22251
22696
  for (const wrapper of ["input", "arguments", "params", "parameters"]) {
22252
22697
  if (isRecord3(record4[wrapper])) {
22253
- const nested = extractString(record4[wrapper], keys);
22254
- if (nested !== void 0)
22255
- return nested;
22698
+ const nested2 = extractString(record4[wrapper], keys);
22699
+ if (nested2 !== void 0)
22700
+ return nested2;
22256
22701
  }
22257
22702
  }
22258
22703
  return void 0;
@@ -22725,6 +23170,7 @@ var AntigravityToolTracker = class {
22725
23170
  };
22726
23171
  function projectReplayedEventsToTurns(params) {
22727
23172
  const turns = [];
23173
+ const usedTurnKeys = new Set(params.knownTurnRefs?.map(({ nativeTurnKey }) => nativeTurnKey));
22728
23174
  let active;
22729
23175
  let userRun = false;
22730
23176
  let textItem;
@@ -22732,15 +23178,23 @@ function projectReplayedEventsToTurns(params) {
22732
23178
  const begin = () => {
22733
23179
  active?.tracker.finishPending({
22734
23180
  status: "cancelled",
22735
- reason: "No terminal tool status in ACP replay"
23181
+ reason: "No terminal tool status in native history"
22736
23182
  });
22737
23183
  const index = turns.length;
22738
23184
  const turnId = hostTurnIdSchema.parse(`turn-${index}`);
23185
+ let nativeTurnKey = params.knownTurnRefs?.[index]?.nativeTurnKey;
23186
+ if (nativeTurnKey === void 0) {
23187
+ let n = index;
23188
+ nativeTurnKey = `turn-${n}`;
23189
+ while (usedTurnKeys.has(nativeTurnKey))
23190
+ nativeTurnKey = `turn-${++n}`;
23191
+ usedTurnKeys.add(nativeTurnKey);
23192
+ }
22739
23193
  const turn = {
22740
23194
  nativeTurnRef: nativeTurnRefSchema.parse({
22741
23195
  harnessId: "antigravity",
22742
23196
  nativeSessionId: params.nativeSessionId,
22743
- nativeTurnKey: params.knownTurnRefs?.[index]?.nativeTurnKey ?? `turn-${index}`,
23197
+ nativeTurnKey,
22744
23198
  formatVersion: 1
22745
23199
  }),
22746
23200
  checkpoint: nativeCheckpointRefSchema.parse({
@@ -22751,7 +23205,7 @@ function projectReplayedEventsToTurns(params) {
22751
23205
  }),
22752
23206
  input: [],
22753
23207
  items: [],
22754
- outcome: { status: "unknown", reason: "ACP replay does not include prompt stop reasons" }
23208
+ outcome: { status: "unknown", reason: "Native history does not include prompt stop reasons" }
22755
23209
  };
22756
23210
  turns.push(turn);
22757
23211
  sequence = 0;
@@ -22811,7 +23265,7 @@ function projectReplayedEventsToTurns(params) {
22811
23265
  }
22812
23266
  active?.tracker.finishPending({
22813
23267
  status: "cancelled",
22814
- reason: "No terminal tool status in ACP replay"
23268
+ reason: "No terminal tool status in native history"
22815
23269
  });
22816
23270
  return turns;
22817
23271
  }
@@ -22849,8 +23303,8 @@ var AntigravityTransportError = class extends Error {
22849
23303
  kind;
22850
23304
  diagnostic;
22851
23305
  retryable;
22852
- constructor(kind, message2, options) {
22853
- super(message2, options);
23306
+ constructor(kind, message3, options) {
23307
+ super(message3, options);
22854
23308
  this.kind = kind;
22855
23309
  this.name = "AntigravityTransportError";
22856
23310
  this.diagnostic = options?.diagnostic;
@@ -22874,27 +23328,385 @@ var AntigravityTransportError = class extends Error {
22874
23328
  }
22875
23329
  };
22876
23330
 
22877
- // dist/fork.js
22878
- import { randomUUID } from "node:crypto";
22879
- import { access as access2, cp, mkdir, open, rm as rm2 } from "node:fs/promises";
22880
- import os3 from "node:os";
22881
- import path9 from "node:path";
22882
-
22883
- // dist/native-protobuf.js
22884
- function decodeVarint(buffer, start) {
22885
- let value = 0n;
22886
- for (let index = 0; index < 10; index++) {
22887
- const byte = buffer[start + index];
22888
- if (byte === void 0 || index === 9 && byte > 1)
22889
- return null;
22890
- value |= BigInt(byte & 127) << BigInt(index * 7);
22891
- if ((byte & 128) === 0)
22892
- return [value, start + index + 1];
22893
- }
22894
- return null;
22895
- }
22896
- function readProtoFields(blob) {
22897
- const fields = [];
23331
+ // dist/acp-transport.js
23332
+ var AntigravityAcpTransport = class {
23333
+ options;
23334
+ skipPermissions;
23335
+ #child = null;
23336
+ #connection = null;
23337
+ #initializing = null;
23338
+ #sessionId = null;
23339
+ #sessionHandler = null;
23340
+ #active = null;
23341
+ #promptRequestId;
23342
+ #callbacks = /* @__PURE__ */ new Set();
23343
+ #acceptedCallbacks = /* @__PURE__ */ new WeakSet();
23344
+ #acceptCallbacks = false;
23345
+ #promptInterrupted = null;
23346
+ #opening = null;
23347
+ #pendingEvents = [];
23348
+ #closed = false;
23349
+ #closing = null;
23350
+ #stderrRaw = "";
23351
+ get #stderr() {
23352
+ return sanitizeDiagnosticTail(this.#stderrRaw);
23353
+ }
23354
+ #faultSignal = new AbortController();
23355
+ constructor(options) {
23356
+ this.options = options;
23357
+ this.skipPermissions = options.skipPermissions === true;
23358
+ }
23359
+ get sessionId() {
23360
+ return this.#sessionId;
23361
+ }
23362
+ get isClosed() {
23363
+ return this.#closed;
23364
+ }
23365
+ setSessionEventHandler(handler) {
23366
+ this.#sessionHandler = handler;
23367
+ if (handler)
23368
+ for (const event of this.#pendingEvents.splice(0))
23369
+ handler(event);
23370
+ }
23371
+ initialize() {
23372
+ if (this.#closed)
23373
+ return Promise.reject(new AntigravityTransportError("unavailable", "Antigravity ACP is closed"));
23374
+ return this.#initializing ??= this.#start();
23375
+ }
23376
+ async #start() {
23377
+ try {
23378
+ const executable = resolveAntigravityExecutable(this.options);
23379
+ if (!executable)
23380
+ throw new AntigravityTransportError("notInstalled", "Antigravity CLI was not found");
23381
+ const invocation = commandInvocation(executable, this.skipPermissions ? ["acp", "--dangerously-skip-permissions"] : ["acp"], this.options.environment ?? process.env);
23382
+ const child = spawn(invocation.command, invocation.arguments, {
23383
+ cwd: this.options.cwd,
23384
+ env: this.options.environment ?? process.env,
23385
+ stdio: ["pipe", "pipe", "pipe"],
23386
+ windowsHide: true,
23387
+ windowsVerbatimArguments: invocation.windowsVerbatimArguments
23388
+ });
23389
+ this.#child = child;
23390
+ child.stderr.on("data", (chunk) => {
23391
+ this.#stderrRaw = (this.#stderrRaw + chunk.toString()).slice(-32e3);
23392
+ });
23393
+ child.on("error", (error51) => this.#fault(new AntigravityTransportError(error51.code === "ENOENT" ? "notInstalled" : "unavailable", error51.message, { diagnostic: this.#stderr })));
23394
+ child.on("exit", (code, signal) => this.#fault(new AntigravityTransportError("processExited", `Antigravity ACP exited (code ${code}, signal ${signal})`, { diagnostic: this.#stderr })));
23395
+ child.stdin.on("error", (error51) => this.#fault(this.#error(error51)));
23396
+ const stream = ndJsonStream2(
23397
+ Writable.toWeb(child.stdin),
23398
+ // Keep draining ACP stdout even when the consumer is slow.
23399
+ Readable.toWeb(child.stdout, {
23400
+ strategy: { highWaterMark: Infinity }
23401
+ })
23402
+ );
23403
+ const writer = stream.writable.getWriter();
23404
+ stream.writable = new WritableStream({
23405
+ write: (message3) => {
23406
+ if ("method" in message3 && message3.method === "session/prompt" && "id" in message3)
23407
+ this.#promptRequestId = message3.id;
23408
+ return writer.write(message3);
23409
+ },
23410
+ close: () => writer.close(),
23411
+ abort: (reason) => writer.abort(reason)
23412
+ });
23413
+ const nativeMethods = /* @__PURE__ */ new Set(["session/request_permission", "elicitation/create"]);
23414
+ const extensionPrefix = "_antigravity/";
23415
+ stream.readable = stream.readable.pipeThrough(new TransformStream({
23416
+ transform: (message3, controller) => {
23417
+ if ("method" in message3 && message3.method === "session/update") {
23418
+ const params = message3.params;
23419
+ this.#update(params.sessionId, params.update);
23420
+ return;
23421
+ }
23422
+ if ("method" in message3 && typeof message3.method === "string") {
23423
+ const method = message3.method.startsWith(extensionPrefix) ? message3.method.slice(extensionPrefix.length) : message3.method;
23424
+ if (nativeMethods.has(method)) {
23425
+ message3.method = extensionPrefix + method;
23426
+ if (this.#acceptCallbacks && "id" in message3 && typeof message3.params === "object" && message3.params !== null)
23427
+ this.#acceptedCallbacks.add(message3.params);
23428
+ }
23429
+ }
23430
+ if (!("method" in message3) && "id" in message3 && message3.id === this.#promptRequestId && ("result" in message3 || "error" in message3)) {
23431
+ this.#promptRequestId = void 0;
23432
+ this.#acceptCallbacks = false;
23433
+ this.#active?.onResponse?.();
23434
+ }
23435
+ controller.enqueue(message3);
23436
+ }
23437
+ }));
23438
+ const onElicitation = (request) => this.#callback(request, (handler) => handler.onElicitation(request), { action: "cancel" });
23439
+ const client2 = {
23440
+ sessionUpdate: ({ sessionId, update }) => this.#update(sessionId, update),
23441
+ requestPermission: (request) => this.#callback(request, (handler) => handler.onPermission(request), {
23442
+ outcome: { outcome: "cancelled" }
23443
+ }),
23444
+ unstable_createElicitation: onElicitation,
23445
+ extMethod: async (method, params) => {
23446
+ if (method === "_antigravity/session/request_permission")
23447
+ return await client2.requestPermission(params);
23448
+ if (method === "_antigravity/elicitation/create")
23449
+ return await onElicitation(params);
23450
+ throw new AntigravityTransportError("unsupported", `Unsupported ACP client method: ${method}`);
23451
+ }
23452
+ };
23453
+ const connection = new ClientSideConnection(() => client2, stream);
23454
+ this.#connection = connection;
23455
+ connection.signal.addEventListener("abort", () => this.#fault(new AntigravityTransportError("processExited", "Antigravity ACP connection closed", {
23456
+ diagnostic: this.#stderr
23457
+ })), { once: true });
23458
+ const response = await this.#request(connection.initialize({
23459
+ protocolVersion: 1,
23460
+ clientCapabilities: { elicitation: { form: {} } }
23461
+ }), "initialize");
23462
+ if (response.protocolVersion !== 1)
23463
+ throw new AntigravityTransportError("protocolError", `Unsupported ACP version ${response.protocolVersion}`);
23464
+ return response;
23465
+ } catch (error51) {
23466
+ await this.close();
23467
+ throw this.#error(error51);
23468
+ }
23469
+ }
23470
+ async openSession(input) {
23471
+ await this.initialize();
23472
+ if (this.#closed || !this.#connection || this.#active || this.#opening || this.#sessionId)
23473
+ throw new AntigravityTransportError("unavailable", "Close the current ACP session before opening another");
23474
+ const connection = this.#connection;
23475
+ const buffered = [];
23476
+ this.#opening = buffered;
23477
+ this.#pendingEvents = [];
23478
+ const params = {
23479
+ cwd: input.cwd,
23480
+ mcpServers: [],
23481
+ ...input.additionalDirectories?.length ? { additionalDirectories: input.additionalDirectories } : {},
23482
+ ...input.systemPromptAppend ? { _meta: { antigravity: { systemPrompt: { append: input.systemPromptAppend } } } } : {}
23483
+ };
23484
+ try {
23485
+ let request;
23486
+ if (input.kind === "create")
23487
+ request = connection.newSession(params);
23488
+ else {
23489
+ if (!input.sessionId)
23490
+ throw new AntigravityTransportError("protocolError", "Session ID required for resume");
23491
+ request = connection.resumeSession({ ...params, sessionId: input.sessionId });
23492
+ }
23493
+ const result = await this.#request(request, `session/${input.kind === "create" ? "new" : input.kind}`);
23494
+ const raw = result;
23495
+ const sessionId = raw.sessionId ?? input.sessionId;
23496
+ if (!sessionId)
23497
+ throw new AntigravityTransportError("protocolError", "Antigravity session/new returned no sessionId");
23498
+ this.#sessionId = sessionId;
23499
+ for (const entry of buffered)
23500
+ if (entry.sessionId === sessionId)
23501
+ this.#dispatch(entry.event);
23502
+ return {
23503
+ opened: {
23504
+ sessionId,
23505
+ ...raw.models ? { models: raw.models } : {},
23506
+ ...raw.modes ? { modes: raw.modes } : {},
23507
+ ...raw.configOptions ? { configOptions: raw.configOptions } : {},
23508
+ ...raw._meta?.antigravity?.tier ? { tier: raw._meta.antigravity.tier } : {}
23509
+ }
23510
+ };
23511
+ } finally {
23512
+ this.#opening = null;
23513
+ }
23514
+ }
23515
+ async setMode(modeId) {
23516
+ const { connection, sessionId } = this.#session();
23517
+ await this.#request(connection.setSessionMode({ sessionId, modeId }), "session/set_mode");
23518
+ }
23519
+ async setConfigOption(configId, value) {
23520
+ const { connection, sessionId } = this.#session();
23521
+ const response = await this.#request(connection.setSessionConfigOption({ sessionId, configId, value }), "session/set_config_option");
23522
+ return response.configOptions;
23523
+ }
23524
+ async prompt(parts, handler) {
23525
+ const { connection, sessionId } = this.#session();
23526
+ if (this.#active)
23527
+ throw new AntigravityTransportError("unavailable", "An ACP prompt is already active");
23528
+ this.#active = handler;
23529
+ this.#acceptCallbacks = true;
23530
+ const interrupted = new AbortController();
23531
+ this.#promptInterrupted = interrupted;
23532
+ try {
23533
+ return await this.#request(connection.prompt({ sessionId, prompt: [...parts] }), "session/prompt", null, interrupted.signal);
23534
+ } finally {
23535
+ this.#clearCallbacks();
23536
+ this.#acceptCallbacks = false;
23537
+ this.#active = null;
23538
+ this.#promptRequestId = void 0;
23539
+ this.#promptInterrupted = null;
23540
+ }
23541
+ }
23542
+ async cancel() {
23543
+ const { connection, sessionId } = this.#session();
23544
+ this.#acceptCallbacks = false;
23545
+ this.#clearCallbacks();
23546
+ await this.#request(connection.cancel({ sessionId }), "session/cancel");
23547
+ }
23548
+ async closeSession() {
23549
+ const sessionId = this.#sessionId;
23550
+ this.#sessionId = null;
23551
+ this.#acceptCallbacks = false;
23552
+ this.#promptInterrupted?.abort(new AntigravityTransportError("unavailable", "ACP session closed"));
23553
+ this.#active = null;
23554
+ this.#promptRequestId = void 0;
23555
+ this.#pendingEvents = [];
23556
+ this.#clearCallbacks();
23557
+ if (sessionId && this.#connection)
23558
+ await this.#request(this.#connection.closeSession({ sessionId }), "session/close", this.options.closeTimeoutMs ?? 2e3);
23559
+ }
23560
+ close() {
23561
+ if (this.#closing)
23562
+ return this.#closing;
23563
+ this.#closed = true;
23564
+ return this.#closing = this.#shutdown();
23565
+ }
23566
+ async #shutdown() {
23567
+ try {
23568
+ await this.closeSession();
23569
+ } catch (error51) {
23570
+ this.#stderrRaw = `${this.#stderrRaw}
23571
+ ${this.#error(error51).message}`.slice(-32e3);
23572
+ }
23573
+ this.#faultSignal.abort(new AntigravityTransportError("unavailable", "Antigravity ACP closed"));
23574
+ this.#opening = null;
23575
+ this.#sessionHandler = null;
23576
+ const child = this.#child;
23577
+ if (child && child.exitCode === null && child.signalCode === null && child.pid) {
23578
+ const exited = new Promise((resolve) => child.once("exit", () => resolve()));
23579
+ const timeout = this.options.closeTimeoutMs ?? 2e3;
23580
+ const term = setTimeout(() => child.kill("SIGTERM"), Math.max(1, timeout / 2));
23581
+ const kill = setTimeout(() => child.kill("SIGKILL"), Math.max(2, timeout));
23582
+ child.stdin.end();
23583
+ try {
23584
+ await exited;
23585
+ } finally {
23586
+ clearTimeout(term);
23587
+ clearTimeout(kill);
23588
+ }
23589
+ }
23590
+ this.#connection = null;
23591
+ this.#child = null;
23592
+ }
23593
+ #session() {
23594
+ if (this.#closed || !this.#connection || !this.#sessionId)
23595
+ throw new AntigravityTransportError("unavailable", "Antigravity ACP session is unavailable");
23596
+ return { connection: this.#connection, sessionId: this.#sessionId };
23597
+ }
23598
+ #update(sessionId, raw) {
23599
+ if (this.#closed)
23600
+ return;
23601
+ const event = projectAcpSessionUpdate(raw);
23602
+ if (!event)
23603
+ return;
23604
+ if (this.#opening) {
23605
+ this.#opening.push({ sessionId, event });
23606
+ return;
23607
+ }
23608
+ if (sessionId === this.#sessionId)
23609
+ this.#dispatch(event);
23610
+ }
23611
+ #dispatch(event) {
23612
+ if (["config.update", "mode.update", "commands.update", "session.info", "usage.context"].includes(event.type) || // The wire request bounds foreground updates; the handler may still
23613
+ // be present to let the SDK finish processing earlier callbacks.
23614
+ this.#promptRequestId === void 0 && !this.#opening) {
23615
+ if (this.#sessionHandler)
23616
+ this.#sessionHandler(event);
23617
+ else
23618
+ this.#pendingEvents.push(event);
23619
+ } else
23620
+ this.#active?.onEvent(event);
23621
+ }
23622
+ async #callback(request, invoke, cancelled) {
23623
+ const active = this.#active;
23624
+ if (!active || !this.#acceptedCallbacks.delete(request) || !("sessionId" in request) || request.sessionId !== this.#sessionId || this.#closed)
23625
+ return cancelled;
23626
+ let cancel;
23627
+ const cancellation = new Promise((resolve) => {
23628
+ cancel = () => resolve(cancelled);
23629
+ });
23630
+ this.#callbacks.add(cancel);
23631
+ try {
23632
+ return await Promise.race([invoke(active), cancellation]);
23633
+ } finally {
23634
+ this.#callbacks.delete(cancel);
23635
+ }
23636
+ }
23637
+ #clearCallbacks() {
23638
+ this.#acceptedCallbacks = /* @__PURE__ */ new WeakSet();
23639
+ for (const cancel of this.#callbacks)
23640
+ cancel();
23641
+ this.#callbacks.clear();
23642
+ }
23643
+ async #request(promise2, operation, timeoutMs = this.options.commandTimeoutMs ?? 3e4, signal) {
23644
+ let timer;
23645
+ let abort;
23646
+ const signals = [this.#faultSignal.signal, ...signal ? [signal] : []];
23647
+ const interrupted = new Promise((_, reject) => {
23648
+ abort = () => reject(signal?.aborted ? signal.reason : this.#faultSignal.signal.reason);
23649
+ if (signals.some((candidate) => candidate.aborted))
23650
+ abort();
23651
+ else
23652
+ for (const candidate of signals)
23653
+ candidate.addEventListener("abort", abort, { once: true });
23654
+ if (timeoutMs !== null)
23655
+ timer = setTimeout(() => reject(new AntigravityTransportError("unavailable", `${operation} timed out after ${timeoutMs}ms`, { diagnostic: this.#stderr })), timeoutMs);
23656
+ });
23657
+ try {
23658
+ return await Promise.race([promise2, interrupted]);
23659
+ } catch (error51) {
23660
+ const normalized = this.#error(error51);
23661
+ if (normalized.kind === "unavailable" && normalized.message.includes("timed out"))
23662
+ void this.close();
23663
+ throw normalized;
23664
+ } finally {
23665
+ clearTimeout(timer);
23666
+ for (const candidate of signals)
23667
+ candidate.removeEventListener("abort", abort);
23668
+ }
23669
+ }
23670
+ #error(error51) {
23671
+ if (error51 instanceof AntigravityTransportError)
23672
+ return error51;
23673
+ const message3 = sanitizeDiagnosticTail(error51 instanceof Error ? error51.message : String(error51));
23674
+ const code = error51?.code;
23675
+ return new AntigravityTransportError(code === -32e3 || /auth|login|sign[ -]?in|unauthenticated/iu.test(message3) ? "authenticationRequired" : "unavailable", message3, { cause: error51, diagnostic: this.#stderr });
23676
+ }
23677
+ #fault(error51) {
23678
+ if (this.#closed || this.#faultSignal.signal.aborted)
23679
+ return;
23680
+ this.#faultSignal.abort(error51);
23681
+ this.#clearCallbacks();
23682
+ void this.close();
23683
+ this.options.onFault?.(error51);
23684
+ }
23685
+ };
23686
+
23687
+ // dist/acp-usage.js
23688
+ import { createReadStream } from "node:fs";
23689
+ import path7 from "node:path";
23690
+ import { createInterface } from "node:readline";
23691
+
23692
+ // dist/native-request-timing.js
23693
+ import path6 from "node:path";
23694
+
23695
+ // dist/native-protobuf.js
23696
+ function decodeVarint(buffer, start) {
23697
+ let value = 0n;
23698
+ for (let index = 0; index < 10; index++) {
23699
+ const byte = buffer[start + index];
23700
+ if (byte === void 0 || index === 9 && byte > 1)
23701
+ return null;
23702
+ value |= BigInt(byte & 127) << BigInt(index * 7);
23703
+ if ((byte & 128) === 0)
23704
+ return [value, start + index + 1];
23705
+ }
23706
+ return null;
23707
+ }
23708
+ function readProtoFields(blob) {
23709
+ const fields = [];
22898
23710
  let offset = 0;
22899
23711
  while (offset < blob.length) {
22900
23712
  if (fields.length >= 1e4)
@@ -22931,207 +23743,7 @@ function readProtoFields(blob) {
22931
23743
  return fields;
22932
23744
  }
22933
23745
 
22934
- // dist/native-trajectory-metadata.js
22935
- var DEFAULT_CLI_PROJECT_ID = "default-cli-project";
22936
- function encodeVarint(value) {
22937
- const bytes = [];
22938
- let remaining = value >>> 0;
22939
- while (remaining >= 128) {
22940
- bytes.push(remaining & 127 | 128);
22941
- remaining >>>= 7;
22942
- }
22943
- bytes.push(remaining);
22944
- return Buffer.from(bytes);
22945
- }
22946
- function encodeLengthDelimited(fieldNumber, payload) {
22947
- return Buffer.concat([
22948
- encodeVarint(fieldNumber << 3 | 2),
22949
- encodeVarint(payload.length),
22950
- Buffer.from(payload)
22951
- ]);
22952
- }
22953
- function minimalTrajectoryMetadataBlob(cascadeId, projectId = DEFAULT_CLI_PROJECT_ID) {
22954
- return Buffer.concat([
22955
- encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")),
22956
- encodeLengthDelimited(18, Buffer.from(projectId, "utf8"))
22957
- ]);
22958
- }
22959
- function minimalRawSummaryBlob(trajectoryId, metadataBlob) {
22960
- return Buffer.concat([
22961
- encodeLengthDelimited(4, Buffer.from(trajectoryId, "utf8")),
22962
- Buffer.from([40, 1]),
22963
- encodeLengthDelimited(17, metadataBlob),
22964
- Buffer.from([176, 1, 4])
22965
- ]);
22966
- }
22967
- function rewriteTrajectoryMetadataCascadeId(blob, cascadeId) {
22968
- const chunks = [];
22969
- let offset = 0;
22970
- let wroteCascadeId = false;
22971
- let hasProjectId = false;
22972
- while (offset < blob.length) {
22973
- const fieldStart = offset;
22974
- const tagParsed = decodeVarint(blob, offset);
22975
- if (!tagParsed)
22976
- return null;
22977
- const [tag, afterTag] = tagParsed;
22978
- if (tag < 8n || tag > 0xffffffffn)
22979
- return null;
22980
- const fieldNumber = Number(tag >> 3n);
22981
- const wireType = Number(tag & 7n);
22982
- if (fieldNumber === 6 && wireType !== 2)
22983
- return null;
22984
- offset = afterTag;
22985
- if (wireType === 0) {
22986
- const valParsed = decodeVarint(blob, offset);
22987
- if (!valParsed)
22988
- return null;
22989
- offset = valParsed[1];
22990
- } else if (wireType === 1) {
22991
- if (offset + 8 > blob.length)
22992
- return null;
22993
- offset += 8;
22994
- } else if (wireType === 2) {
22995
- const lenParsed = decodeVarint(blob, offset);
22996
- if (!lenParsed)
22997
- return null;
22998
- const [length, afterLen] = lenParsed;
22999
- if (length > BigInt(blob.length - afterLen))
23000
- return null;
23001
- offset = afterLen + Number(length);
23002
- if (fieldNumber === 6) {
23003
- if (!wroteCascadeId) {
23004
- chunks.push(encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")));
23005
- wroteCascadeId = true;
23006
- }
23007
- continue;
23008
- }
23009
- if (fieldNumber === 18)
23010
- hasProjectId = true;
23011
- } else if (wireType === 5) {
23012
- if (offset + 4 > blob.length)
23013
- return null;
23014
- offset += 4;
23015
- } else {
23016
- return null;
23017
- }
23018
- chunks.push(Buffer.from(blob.subarray(fieldStart, offset)));
23019
- }
23020
- if (!wroteCascadeId) {
23021
- chunks.push(encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")));
23022
- }
23023
- if (!hasProjectId) {
23024
- chunks.push(encodeLengthDelimited(18, Buffer.from(DEFAULT_CLI_PROJECT_ID, "utf8")));
23025
- }
23026
- return Buffer.concat(chunks);
23027
- }
23028
-
23029
- // dist/native-turn-boundaries.js
23030
- import { access } from "node:fs/promises";
23031
- async function readNativeTurnCount(dbPath) {
23032
- await access(dbPath);
23033
- const { DatabaseSync } = await import("node:sqlite");
23034
- const db = new DatabaseSync(dbPath, { readOnly: true });
23035
- try {
23036
- const row = db.prepare("SELECT count(*) AS n FROM steps WHERE step_type = 14").get();
23037
- return Number(row?.n ?? 0);
23038
- } finally {
23039
- db.close();
23040
- }
23041
- }
23042
- function nativeHistoryError(error51) {
23043
- const missing = error51?.code === "ENOENT";
23044
- return {
23045
- code: missing ? "sessionNotFound" : "nativeFailure",
23046
- message: missing ? "Antigravity native conversation database was not found" : "Cannot read or derive Antigravity native history",
23047
- retryable: false
23048
- };
23049
- }
23050
-
23051
- // dist/usage-statistics.js
23052
- import { lstat, opendir } from "node:fs/promises";
23053
- import os2 from "node:os";
23054
- import path8 from "node:path";
23055
-
23056
- // ../../harness-adapter/dist/usage-statistics.js
23057
- import { createReadStream } from "node:fs";
23058
- import { createInterface } from "node:readline";
23059
- var HarnessUsageSourceChangedError = class extends Error {
23060
- code = "HARNESS_USAGE_SOURCE_CHANGED";
23061
- /** Plugins may bundle their own copy of this contract, so instanceof is insufficient. */
23062
- static is(error51) {
23063
- return typeof error51 === "object" && error51 !== null && "code" in error51 && error51.code === "HARNESS_USAGE_SOURCE_CHANGED";
23064
- }
23065
- };
23066
- var MAX_SESSION_ID_LENGTH = 512;
23067
- var MAX_CWD_LENGTH = 4096;
23068
- var MAX_SESSION_TITLE_LENGTH = 200;
23069
- function usageSessionTitle(value) {
23070
- if (typeof value !== "string")
23071
- return void 0;
23072
- const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
23073
- if (!normalized)
23074
- return void 0;
23075
- if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
23076
- return normalized;
23077
- let title = "";
23078
- for (const character of normalized) {
23079
- if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
23080
- break;
23081
- title += character;
23082
- }
23083
- return `${title.trimEnd()}…`;
23084
- }
23085
- function sessionIdOk(value) {
23086
- return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
23087
- }
23088
- function cwdOk(value) {
23089
- return typeof value === "string" && value.length > 0 && value.length <= MAX_CWD_LENGTH && !value.includes("\0") && (value.startsWith("/") || /^[A-Za-z]:[\\/]/u.test(value) || value.startsWith("\\\\"));
23090
- }
23091
- function withUsageSession(entry, session) {
23092
- const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
23093
- const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
23094
- const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
23095
- if (sessionId === void 0 && cwd === void 0)
23096
- return entry;
23097
- return {
23098
- ...entry,
23099
- ...sessionId !== void 0 ? { sessionId } : {},
23100
- ...cwd !== void 0 ? { cwd } : {},
23101
- ...sessionTitle !== void 0 ? { sessionTitle } : {}
23102
- };
23103
- }
23104
- async function* jsonlRecords(file2, marker, signal) {
23105
- const lines = createInterface({
23106
- input: createReadStream(file2, { encoding: "utf8", signal }),
23107
- crlfDelay: Infinity
23108
- });
23109
- for await (const line of lines) {
23110
- if (!line.includes(marker))
23111
- continue;
23112
- let value;
23113
- try {
23114
- value = JSON.parse(line);
23115
- } catch {
23116
- continue;
23117
- }
23118
- if (typeof value === "object" && value !== null && !Array.isArray(value)) {
23119
- yield value;
23120
- }
23121
- }
23122
- }
23123
- function nativeTimeMs(value) {
23124
- const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
23125
- return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
23126
- }
23127
-
23128
- // dist/acp-usage.js
23129
- import { createReadStream as createReadStream2 } from "node:fs";
23130
- import path7 from "node:path";
23131
- import { createInterface as createInterface2 } from "node:readline";
23132
-
23133
23746
  // dist/native-request-timing.js
23134
- import path6 from "node:path";
23135
23747
  var MAX_METADATA_BYTES = 8 * 1024 * 1024;
23136
23748
  var NANOSECONDS_PER_MS = 1000000n;
23137
23749
  var MAX_MS = BigInt(Number.MAX_SAFE_INTEGER);
@@ -23388,9 +24000,6 @@ var AntigravitySessionUsageTracker = class {
23388
24000
  this.#home = options.homedir;
23389
24001
  this.#expectedInitialTurns = options.expectedInitialTurns ?? 0;
23390
24002
  this.#file = path7.join(options.homedir, ".gemini", "antigravity-cli", "brain", options.nativeSessionId, ".system_generated", "logs", "transcript.jsonl");
23391
- if (options.initialContextUsedTokens !== void 0 && options.initialContextWindowTokens !== void 0) {
23392
- this.recordContextWindow(options.initialContextUsedTokens, options.initialContextWindowTokens);
23393
- }
23394
24003
  }
23395
24004
  currentUsage() {
23396
24005
  const recorded = [...this.#requests].sort(([left], [right]) => left - right).map(([, request]) => request);
@@ -23558,8 +24167,8 @@ var AntigravitySessionUsageTracker = class {
23558
24167
  }
23559
24168
  async #read(signal, withTimings = true) {
23560
24169
  signal?.throwIfAborted();
23561
- const stream = createReadStream2(this.#file, { encoding: "utf8", signal });
23562
- const lines = createInterface2({ input: stream, crlfDelay: Infinity });
24170
+ const stream = createReadStream(this.#file, { encoding: "utf8", signal });
24171
+ const lines = createInterface({ input: stream, crlfDelay: Infinity });
23563
24172
  const result = {
23564
24173
  steps: /* @__PURE__ */ new Map(),
23565
24174
  toolCallSteps: /* @__PURE__ */ new Set(),
@@ -23626,771 +24235,566 @@ var AntigravitySessionUsageTracker = class {
23626
24235
  }
23627
24236
  };
23628
24237
 
23629
- // dist/usage-statistics.js
23630
- function count3(value) {
23631
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
23632
- }
23633
- function antigravityHome(environment) {
23634
- return (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os2.homedir();
23635
- }
23636
- function transcriptPath(brainRoot, conversationId) {
23637
- return path8.join(brainRoot, conversationId, ".system_generated", "logs", "transcript.jsonl");
23638
- }
23639
- function isMissing(error51) {
23640
- const code = error51?.code;
23641
- return code === "ENOENT" || code === "ENOTDIR";
23642
- }
23643
- async function lstatIfPresent(target2) {
23644
- try {
23645
- return await lstat(target2);
23646
- } catch (error51) {
23647
- if (isMissing(error51))
23648
- return null;
23649
- throw error51;
23650
- }
23651
- }
23652
- async function transcriptFingerprint(file2) {
23653
- const logs = path8.dirname(file2);
23654
- for (const directory of [path8.dirname(logs), logs]) {
23655
- if (!(await lstatIfPresent(directory))?.isDirectory())
23656
- return null;
23657
- }
23658
- const info = await lstatIfPresent(file2);
23659
- return info?.isFile() && info.size > 0 ? `${info.ino}:${info.size}:${info.mtimeMs}` : null;
23660
- }
23661
- async function listTranscripts(brainRoot, signal) {
23662
- signal.throwIfAborted();
23663
- const conversations = await opendir(brainRoot).catch((error51) => {
23664
- if (error51.code === "ENOENT")
23665
- return null;
23666
- throw error51;
23667
- });
23668
- if (!conversations)
23669
- return [];
23670
- const sources = [];
23671
- for await (const entry of conversations) {
23672
- signal.throwIfAborted();
23673
- if (!entry.isDirectory())
23674
- continue;
23675
- const file2 = transcriptPath(brainRoot, entry.name);
23676
- const fingerprint = await transcriptFingerprint(file2);
23677
- if (fingerprint)
23678
- sources.push({ id: file2, fingerprint });
23679
- }
23680
- return sources;
23681
- }
23682
- async function readAntigravityUsage(file2, signal) {
23683
- const sessionId = path8.basename(path8.resolve(file2, "..", "..", ".."));
23684
- const requests = /* @__PURE__ */ new Map();
23685
- for await (const record4 of jsonlRecords(file2, '"input_tokens"', signal)) {
23686
- if (record4.type !== "PLANNER_RESPONSE")
23687
- continue;
23688
- const step = count3(record4.step_index);
23689
- const input = count3(record4.input_tokens);
23690
- const output = count3(record4.output_tokens);
23691
- const cached2 = count3(record4.cache_read_tokens);
23692
- const at = nativeTimeMs(record4.created_at);
23693
- if (step === null || input === null || output === null || at === null)
23694
- continue;
23695
- const identity2 = normalizeAntigravityUsageModel(record4.model);
23696
- requests.set(step, withUsageSession({
23697
- id: `${String(record4.created_at)}:${step}:${input}:${cached2 ?? "-"}:${output}`,
23698
- occurredAtMs: at,
23699
- ...identity2,
23700
- inputTokens: input + (cached2 ?? 0),
23701
- ...cached2 !== null ? {
23702
- cachedInputTokens: cached2,
23703
- ...hasImplicitZeroCacheWrite(identity2) ? { cacheWriteInputTokens: 0 } : {}
23704
- } : {},
23705
- outputTokens: output
23706
- }, { sessionId }));
23707
- }
23708
- return [...requests.values()];
23709
- }
23710
- function createAntigravityUsageStatistics(environment) {
23711
- const brainRoot = nativeBrainRoot(antigravityHome(environment));
23712
- let listed = /* @__PURE__ */ new Map();
23713
- return Object.freeze({
23714
- async listSources(signal) {
23715
- const sources = await listTranscripts(brainRoot, signal);
23716
- listed = new Map(sources.map(({ id, fingerprint }) => [id, fingerprint]));
23717
- return sources;
23718
- },
23719
- async readSource(id, signal) {
23720
- const expected = listed.get(id);
23721
- let entries;
23722
- try {
23723
- entries = await readAntigravityUsage(id, signal);
23724
- } catch (error51) {
23725
- if (expected !== void 0 && isMissing(error51)) {
23726
- throw new HarnessUsageSourceChangedError("Antigravity transcript disappeared before reading; refresh to retry");
23727
- }
23728
- throw error51;
23729
- }
23730
- if (expected !== void 0 && await transcriptFingerprint(id) !== expected) {
23731
- throw new HarnessUsageSourceChangedError("Antigravity transcript changed while reading; refresh to retry");
23732
- }
23733
- return entries;
23734
- }
23735
- });
24238
+ // dist/delegation.js
24239
+ var DELEGATION_ENVIRONMENT_KEYS = [
24240
+ "CODEXHOST_CLI_PATH",
24241
+ "CODEXHOST_RUNTIME_ENDPOINT",
24242
+ "CODEXHOST_RUNTIME_TOKEN",
24243
+ "CODEXHOST_THREAD_ID"
24244
+ ];
24245
+ var ANTIGRAVITY_DELEGATION_INSTRUCTIONS = `This Antigravity Session runs inside codexhost.
24246
+ When the user requests cross-Harness delegation, use the executable specified by the CODEXHOST_CLI_PATH environment variable through your native shell tool. Start with --help and harness list, then use delegate start and thread send/read/wait/cancel as documented. Use --format compact for results. Keep the inherited CODEXHOST_RUNTIME_ENDPOINT, CODEXHOST_RUNTIME_TOKEN and CODEXHOST_THREAD_ID environment variables for every call; they identify this Runtime and parent Thread. Never print their values, substitute another executable, or delegate without user authorization. Native Antigravity subagents are separate from cross-Harness delegation.`;
24247
+ function antigravityDelegationInstructions(environment) {
24248
+ return DELEGATION_ENVIRONMENT_KEYS.every((key) => environment[key]) ? ANTIGRAVITY_DELEGATION_INSTRUCTIONS : void 0;
23736
24249
  }
23737
24250
 
23738
24251
  // dist/fork.js
23739
- function nativeConversationDbPath(id, home = os3.homedir()) {
23740
- return path9.join(home, ".gemini", "antigravity-cli", "conversations", `${id}.db`);
23741
- }
23742
- function nativeConversationSummariesDbPath(home = os3.homedir()) {
23743
- return path9.join(home, ".gemini", "antigravity-cli", "conversation_summaries.db");
24252
+ import { randomUUID } from "node:crypto";
24253
+ import { access as access2, cp, mkdir, open, rm as rm2 } from "node:fs/promises";
24254
+ import os3 from "node:os";
24255
+ import path9 from "node:path";
24256
+
24257
+ // dist/native-trajectory-metadata.js
24258
+ var DEFAULT_CLI_PROJECT_ID = "default-cli-project";
24259
+ function encodeVarint(value) {
24260
+ const bytes = [];
24261
+ let remaining = value >>> 0;
24262
+ while (remaining >= 128) {
24263
+ bytes.push(remaining & 127 | 128);
24264
+ remaining >>>= 7;
24265
+ }
24266
+ bytes.push(remaining);
24267
+ return Buffer.from(bytes);
23744
24268
  }
23745
- function nativeBrainRoot(home = os3.homedir()) {
23746
- return path9.join(home, ".gemini", "antigravity-cli", "brain");
24269
+ function encodeLengthDelimited(fieldNumber, payload) {
24270
+ return Buffer.concat([
24271
+ encodeVarint(fieldNumber << 3 | 2),
24272
+ encodeVarint(payload.length),
24273
+ Buffer.from(payload)
24274
+ ]);
23747
24275
  }
23748
- function nativeBrainDirPath(id, home = os3.homedir()) {
23749
- return path9.join(nativeBrainRoot(home), id);
24276
+ function minimalTrajectoryMetadataBlob(cascadeId, projectId = DEFAULT_CLI_PROJECT_ID) {
24277
+ return Buffer.concat([
24278
+ encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")),
24279
+ encodeLengthDelimited(18, Buffer.from(projectId, "utf8"))
24280
+ ]);
23750
24281
  }
23751
- function validNativeSessionRef(ref, harnessId2) {
23752
- return nativeSessionRefSchema.safeParse(ref).success && ref.harnessId === harnessId2 && /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(ref.nativeSessionId);
24282
+ function minimalRawSummaryBlob(trajectoryId, metadataBlob) {
24283
+ return Buffer.concat([
24284
+ encodeLengthDelimited(4, Buffer.from(trajectoryId, "utf8")),
24285
+ Buffer.from([40, 1]),
24286
+ encodeLengthDelimited(17, metadataBlob),
24287
+ Buffer.from([176, 1, 4])
24288
+ ]);
23753
24289
  }
23754
- async function cloneNativeConversationDb(sourceId, derivedId, retainedTurnsCountOrHome, homeOption = os3.homedir()) {
23755
- if (![sourceId, derivedId].every((id) => /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(id)))
23756
- throw new Error("Invalid native conversation ID");
23757
- const home = typeof retainedTurnsCountOrHome === "string" ? retainedTurnsCountOrHome : homeOption;
23758
- const retained = typeof retainedTurnsCountOrHome === "number" ? retainedTurnsCountOrHome : void 0;
23759
- const sourcePath = nativeConversationDbPath(sourceId, home);
23760
- const targetPath2 = nativeConversationDbPath(derivedId, home);
23761
- await access2(sourcePath);
23762
- const { DatabaseSync, backup } = await import("node:sqlite");
23763
- const source = new DatabaseSync(sourcePath, { readOnly: true });
23764
- let owned = false;
23765
- try {
23766
- source.exec("BEGIN");
23767
- const count4 = Number(source.prepare("SELECT count(*) AS n FROM steps WHERE step_type = 14").get()?.n ?? 0);
23768
- if (retained !== void 0 && (!Number.isSafeInteger(retained) || retained < 0 || retained > count4))
23769
- throw new Error("Invalid retained native Turn count");
23770
- await mkdir(path9.dirname(targetPath2), { recursive: true });
23771
- const reservation = await open(targetPath2, "wx");
23772
- owned = true;
23773
- await reservation.close();
23774
- await backup(source, targetPath2);
23775
- const target2 = new DatabaseSync(targetPath2);
23776
- try {
23777
- target2.exec("BEGIN IMMEDIATE");
23778
- target2.prepare("UPDATE trajectory_meta SET cascade_id = ?").run(derivedId);
23779
- const row = target2.prepare("SELECT data FROM trajectory_metadata_blob WHERE id = 'main'").get();
23780
- const blob = row?.data instanceof Uint8Array ? rewriteTrajectoryMetadataCascadeId(row.data, derivedId) : minimalTrajectoryMetadataBlob(derivedId);
23781
- if (!blob)
23782
- throw new Error("Invalid native trajectory metadata");
23783
- target2.prepare("INSERT OR REPLACE INTO trajectory_metadata_blob (id, data) VALUES ('main', ?)").run(blob);
23784
- if (retained !== void 0 && retained < count4) {
23785
- const boundary = target2.prepare("SELECT idx FROM steps WHERE step_type = 14 ORDER BY idx LIMIT 1 OFFSET ?").get(retained);
23786
- const cutoff = retained === 0 ? 0 : Number(boundary?.idx);
23787
- target2.prepare("DELETE FROM steps WHERE idx >= ?").run(cutoff);
23788
- for (const table of [
23789
- "gen_metadata",
23790
- "executor_metadata",
23791
- "parent_references",
23792
- "battle_mode_infos"
23793
- ]) {
23794
- if (target2.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(table))
23795
- target2.prepare(`DELETE FROM ${table} WHERE idx >= ?`).run(cutoff);
24290
+ function rewriteTrajectoryMetadataCascadeId(blob, cascadeId) {
24291
+ const chunks = [];
24292
+ let offset = 0;
24293
+ let wroteCascadeId = false;
24294
+ let hasProjectId = false;
24295
+ while (offset < blob.length) {
24296
+ const fieldStart = offset;
24297
+ const tagParsed = decodeVarint(blob, offset);
24298
+ if (!tagParsed)
24299
+ return null;
24300
+ const [tag, afterTag] = tagParsed;
24301
+ if (tag < 8n || tag > 0xffffffffn)
24302
+ return null;
24303
+ const fieldNumber = Number(tag >> 3n);
24304
+ const wireType = Number(tag & 7n);
24305
+ if (fieldNumber === 6 && wireType !== 2)
24306
+ return null;
24307
+ offset = afterTag;
24308
+ if (wireType === 0) {
24309
+ const valParsed = decodeVarint(blob, offset);
24310
+ if (!valParsed)
24311
+ return null;
24312
+ offset = valParsed[1];
24313
+ } else if (wireType === 1) {
24314
+ if (offset + 8 > blob.length)
24315
+ return null;
24316
+ offset += 8;
24317
+ } else if (wireType === 2) {
24318
+ const lenParsed = decodeVarint(blob, offset);
24319
+ if (!lenParsed)
24320
+ return null;
24321
+ const [length, afterLen] = lenParsed;
24322
+ if (length > BigInt(blob.length - afterLen))
24323
+ return null;
24324
+ offset = afterLen + Number(length);
24325
+ if (fieldNumber === 6) {
24326
+ if (!wroteCascadeId) {
24327
+ chunks.push(encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")));
24328
+ wroteCascadeId = true;
23796
24329
  }
24330
+ continue;
23797
24331
  }
23798
- target2.exec("COMMIT");
23799
- } finally {
23800
- target2.close();
24332
+ if (fieldNumber === 18)
24333
+ hasProjectId = true;
24334
+ } else if (wireType === 5) {
24335
+ if (offset + 4 > blob.length)
24336
+ return null;
24337
+ offset += 4;
24338
+ } else {
24339
+ return null;
23801
24340
  }
23802
- await registerDerivedSummary(sourceId, derivedId, home);
23803
- return true;
23804
- } catch (error51) {
23805
- if (owned)
23806
- await removeDerivedDb(derivedId, home);
23807
- throw error51;
23808
- } finally {
23809
- source.close();
24341
+ chunks.push(Buffer.from(blob.subarray(fieldStart, offset)));
23810
24342
  }
23811
- }
23812
- async function registerDerivedSummary(sourceId, derivedId, home) {
23813
- const summaryPath = nativeConversationSummariesDbPath(home);
23814
- try {
23815
- await access2(summaryPath);
23816
- } catch (error51) {
23817
- if (error51.code === "ENOENT")
23818
- return;
23819
- throw error51;
24343
+ if (!wroteCascadeId) {
24344
+ chunks.push(encodeLengthDelimited(6, Buffer.from(cascadeId, "utf8")));
23820
24345
  }
23821
- const { DatabaseSync } = await import("node:sqlite");
23822
- const summaries = new DatabaseSync(summaryPath);
23823
- try {
23824
- const template = summaries.prepare("SELECT * FROM conversation_summaries WHERE conversation_id = ?").get(sourceId);
23825
- if (!template)
23826
- return;
23827
- const derived = new DatabaseSync(nativeConversationDbPath(derivedId, home), { readOnly: true });
23828
- let row;
23829
- try {
23830
- const metadata = derived.prepare("SELECT data FROM trajectory_metadata_blob WHERE id = 'main'").get()?.data;
23831
- const trajectoryId = derived.prepare("SELECT trajectory_id FROM trajectory_meta LIMIT 1").get()?.trajectory_id;
23832
- row = {
23833
- ...template,
23834
- conversation_id: derivedId,
23835
- status: "CASCADE_RUN_STATUS_IDLE",
23836
- step_count: Number(derived.prepare("SELECT count(*) AS n FROM steps").get()?.n),
23837
- last_user_input_step_index: Number(derived.prepare("SELECT max(idx) AS idx FROM steps WHERE step_type = 14").get()?.idx ?? -1),
23838
- not_fully_idle: 0,
23839
- killed: 0,
23840
- last_modified_time: (/* @__PURE__ */ new Date()).toISOString(),
23841
- raw_summary: minimalRawSummaryBlob(String(trajectoryId), Buffer.from(metadata))
23842
- };
23843
- } finally {
23844
- derived.close();
23845
- }
23846
- const columns = Object.keys(template);
23847
- summaries.prepare(`INSERT INTO conversation_summaries (${columns.map((name) => `"${name.replaceAll('"', '""')}"`).join(",")}) VALUES (${columns.map(() => "?").join(",")})`).run(...columns.map((name) => row[name] ?? null));
23848
- } finally {
23849
- summaries.close();
24346
+ if (!hasProjectId) {
24347
+ chunks.push(encodeLengthDelimited(18, Buffer.from(DEFAULT_CLI_PROJECT_ID, "utf8")));
23850
24348
  }
24349
+ return Buffer.concat(chunks);
23851
24350
  }
23852
- async function removeDerivedSummary(id, home) {
23853
- try {
23854
- await access2(nativeConversationSummariesDbPath(home));
23855
- } catch (error51) {
23856
- if (error51.code === "ENOENT")
23857
- return;
23858
- throw error51;
23859
- }
24351
+
24352
+ // dist/native-turn-boundaries.js
24353
+ import { access } from "node:fs/promises";
24354
+ async function readNativeTurnCount(dbPath) {
24355
+ await access(dbPath);
23860
24356
  const { DatabaseSync } = await import("node:sqlite");
23861
- const db = new DatabaseSync(nativeConversationSummariesDbPath(home));
24357
+ const db = new DatabaseSync(dbPath, { readOnly: true });
23862
24358
  try {
23863
- db.prepare("DELETE FROM conversation_summaries WHERE conversation_id = ?").run(id);
24359
+ const row = db.prepare("SELECT count(*) AS n FROM steps WHERE step_type = 14").get();
24360
+ return Number(row?.n ?? 0);
23864
24361
  } finally {
23865
24362
  db.close();
23866
24363
  }
23867
24364
  }
23868
- async function removeDerivedDb(id, home) {
23869
- const file2 = nativeConversationDbPath(id, home);
23870
- await Promise.all([file2, `${file2}-wal`, `${file2}-shm`].map((target2) => rm2(target2, { force: true })));
23871
- }
23872
- async function copyNativeBrainDirIfExists(sourceId, derivedId, home = os3.homedir()) {
23873
- try {
23874
- await access2(nativeBrainDirPath(sourceId, home));
23875
- } catch (error51) {
23876
- if (error51.code === "ENOENT")
23877
- return false;
23878
- throw error51;
23879
- }
23880
- await cp(nativeBrainDirPath(sourceId, home), nativeBrainDirPath(derivedId, home), {
23881
- recursive: true,
23882
- errorOnExist: true,
23883
- force: false,
23884
- filter: (source) => path9.basename(source) !== ".system_generated"
23885
- });
23886
- return true;
24365
+ function nativeHistoryError(error51) {
24366
+ const missing = error51?.code === "ENOENT";
24367
+ return {
24368
+ code: missing ? "sessionNotFound" : "nativeFailure",
24369
+ message: missing ? "Antigravity native conversation database was not found" : "Cannot read or derive Antigravity native history",
24370
+ retryable: false
24371
+ };
23887
24372
  }
23888
- async function openDerivedAntigravitySession(options, input, sourceRef, retained) {
23889
- const environment = { ...options.adapterEnvironment, ...input.environment };
23890
- const home = antigravityHome(environment);
23891
- const derivedId = randomUUID();
23892
- let cloned = false;
23893
- try {
23894
- await cloneNativeConversationDb(sourceRef.nativeSessionId, derivedId, retained, home);
23895
- cloned = true;
23896
- await copyNativeBrainDirIfExists(sourceRef.nativeSessionId, derivedId, home);
23897
- const result = await options.openSession({
23898
- ...input,
23899
- environment,
23900
- nativeRef: { ...sourceRef, nativeSessionId: derivedId }
23901
- });
23902
- if (result.ok)
23903
- return result;
23904
- const cleanupFailure = await cleanup().then(() => void 0, () => "Derived native history cleanup failed");
23905
- return cleanupFailure ? { ok: false, error: { ...result.error, diagnostic: cleanupFailure } } : result;
23906
- } catch (error51) {
23907
- const cleanupFailure = await cleanup().then(() => void 0, () => "Derived native history cleanup failed");
23908
- return {
23909
- ok: false,
23910
- error: {
23911
- ...nativeHistoryError(error51),
23912
- ...cleanupFailure ? { diagnostic: cleanupFailure } : {}
23913
- }
23914
- };
24373
+
24374
+ // dist/usage-statistics.js
24375
+ import { lstat, opendir } from "node:fs/promises";
24376
+ import os2 from "node:os";
24377
+ import path8 from "node:path";
24378
+
24379
+ // ../../harness-adapter/dist/usage-statistics.js
24380
+ import { createReadStream as createReadStream2 } from "node:fs";
24381
+ import { createInterface as createInterface2 } from "node:readline";
24382
+ var HarnessUsageSourceChangedError = class extends Error {
24383
+ code = "HARNESS_USAGE_SOURCE_CHANGED";
24384
+ /** Plugins may bundle their own copy of this contract, so instanceof is insufficient. */
24385
+ static is(error51) {
24386
+ return typeof error51 === "object" && error51 !== null && "code" in error51 && error51.code === "HARNESS_USAGE_SOURCE_CHANGED";
23915
24387
  }
23916
- async function cleanup() {
23917
- if (!cloned)
23918
- return;
23919
- await Promise.all([
23920
- removeDerivedDb(derivedId, home),
23921
- rm2(nativeBrainDirPath(derivedId, home), { recursive: true, force: true }),
23922
- removeDerivedSummary(derivedId, home)
23923
- ]);
24388
+ };
24389
+ var MAX_SESSION_ID_LENGTH = 512;
24390
+ var MAX_CWD_LENGTH = 4096;
24391
+ var MAX_SESSION_TITLE_LENGTH = 200;
24392
+ function usageSessionTitle(value) {
24393
+ if (typeof value !== "string")
24394
+ return void 0;
24395
+ const normalized = value.replaceAll("\0", "").replaceAll(/\s+/gu, " ").trim();
24396
+ if (!normalized)
24397
+ return void 0;
24398
+ if (normalized.length <= MAX_SESSION_TITLE_LENGTH)
24399
+ return normalized;
24400
+ let title = "";
24401
+ for (const character of normalized) {
24402
+ if (title.length + character.length >= MAX_SESSION_TITLE_LENGTH)
24403
+ break;
24404
+ title += character;
23924
24405
  }
24406
+ return `${title.trimEnd()}…`;
23925
24407
  }
23926
- async function forkAntigravitySession(options) {
23927
- const { input, harnessId: harnessId2 } = options;
23928
- if (!validNativeSessionRef(input.sourceRef, harnessId2))
23929
- return {
23930
- ok: false,
23931
- error: {
23932
- code: "invalidRequest",
23933
- message: "Invalid Antigravity source Native Session",
23934
- retryable: false
23935
- }
23936
- };
23937
- const checkpoint = nativeCheckpointRefSchema.safeParse(input.checkpoint);
23938
- if (!checkpoint.success || checkpoint.data.harnessId !== harnessId2 || checkpoint.data.nativeSessionId !== input.sourceRef.nativeSessionId)
23939
- return checkpointError();
23940
- if (options.sourceSession?.isActive)
23941
- return {
23942
- ok: false,
23943
- error: {
23944
- code: "sessionBusy",
23945
- message: "Source Session is busy",
23946
- retryable: true
23947
- }
23948
- };
23949
- const match = /^turn-(0|[1-9]\d*)$/u.exec(checkpoint.data.checkpointId);
23950
- if (!match)
23951
- return checkpointError();
23952
- try {
23953
- const count4 = await readNativeTurnCount(nativeConversationDbPath(input.sourceRef.nativeSessionId, antigravityHome({ ...options.adapterEnvironment, ...input.environment })));
23954
- const index = Number(match[1]);
23955
- if (!Number.isSafeInteger(index) || index >= count4)
23956
- return checkpointError();
23957
- return openDerivedAntigravitySession(options, {
23958
- kind: "resume",
23959
- nativeRef: input.sourceRef,
23960
- cwd: input.cwd,
23961
- ...input.environment ? { environment: input.environment } : {}
23962
- }, input.sourceRef, index + 1);
23963
- } catch (error51) {
23964
- return { ok: false, error: nativeHistoryError(error51) };
23965
- }
24408
+ function sessionIdOk(value) {
24409
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION_ID_LENGTH;
23966
24410
  }
23967
- function checkpointError() {
24411
+ function cwdOk(value) {
24412
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_CWD_LENGTH && !value.includes("\0") && (value.startsWith("/") || /^[A-Za-z]:[\\/]/u.test(value) || value.startsWith("\\\\"));
24413
+ }
24414
+ function withUsageSession(entry, session) {
24415
+ const sessionId = sessionIdOk(session.sessionId) ? session.sessionId : void 0;
24416
+ const cwd = cwdOk(session.cwd) ? session.cwd : void 0;
24417
+ const sessionTitle = sessionId !== void 0 ? usageSessionTitle(session.title) : void 0;
24418
+ if (sessionId === void 0 && cwd === void 0)
24419
+ return entry;
23968
24420
  return {
23969
- ok: false,
23970
- error: {
23971
- code: "checkpointNotFound",
23972
- message: "Antigravity native Turn checkpoint not found",
23973
- retryable: false
23974
- }
24421
+ ...entry,
24422
+ ...sessionId !== void 0 ? { sessionId } : {},
24423
+ ...cwd !== void 0 ? { cwd } : {},
24424
+ ...sessionTitle !== void 0 ? { sessionTitle } : {}
23975
24425
  };
23976
24426
  }
23977
-
23978
- // dist/native-replay.js
23979
- async function readNativeReplaySize(sessionId, home) {
23980
- if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(sessionId))
23981
- throw new AntigravityTransportError("protocolError", "Invalid native Session ID");
23982
- const { DatabaseSync } = await import("node:sqlite");
23983
- const db = new DatabaseSync(nativeConversationDbPath(sessionId, home), { readOnly: true });
23984
- const size = { users: 0, text: 0, thought: 0, tools: 0 };
23985
- try {
23986
- for (const row of db.prepare("SELECT step_type, step_payload FROM steps WHERE step_type IN (14, 15) ORDER BY idx").iterate()) {
23987
- if (row.step_type === 14) {
23988
- size.users++;
23989
- continue;
23990
- }
23991
- const planner = row.step_payload instanceof Uint8Array ? readProtoFields(row.step_payload)?.find((field3) => field3.number === 20)?.value : void 0;
23992
- const fields = planner instanceof Uint8Array ? readProtoFields(planner) : null;
23993
- if (!fields)
23994
- throw new AntigravityTransportError("protocolError", "Cannot verify Antigravity history replay");
23995
- for (const field3 of fields) {
23996
- if (!(field3.value instanceof Uint8Array))
23997
- continue;
23998
- if (field3.number === 1)
23999
- size.text += Buffer.from(field3.value).toString("utf8").length;
24000
- if (field3.number === 3)
24001
- size.thought += Buffer.from(field3.value).toString("utf8").length;
24002
- if (field3.number === 7)
24003
- size.tools++;
24004
- }
24005
- }
24006
- return size;
24007
- } finally {
24008
- db.close();
24009
- }
24010
- }
24011
- function nativeReplayCompletion(expected) {
24012
- const received = {
24013
- users: 0,
24014
- text: 0,
24015
- thought: 0,
24016
- tools: 0,
24017
- usage: false,
24018
- sessionInfo: false
24019
- };
24020
- let resolve;
24021
- const complete = new Promise((done) => {
24022
- resolve = done;
24427
+ async function* jsonlRecords(file2, marker, signal) {
24428
+ const lines = createInterface2({
24429
+ input: createReadStream2(file2, { encoding: "utf8", signal }),
24430
+ crlfDelay: Infinity
24023
24431
  });
24024
- const check2 = () => {
24025
- if (received.users === expected.users && received.text === expected.text && received.thought === expected.thought && received.tools === expected.tools && received.usage && received.sessionInfo)
24026
- resolve();
24027
- };
24028
- check2();
24029
- return {
24030
- complete,
24031
- observe(event) {
24032
- if (event.type === "user.text")
24033
- received.users++;
24034
- if (event.type === "agent.text")
24035
- received.text += event.text.length;
24036
- if (event.type === "agent.thought")
24037
- received.thought += event.text.length;
24038
- if (event.type === "tool.call")
24039
- received.tools++;
24040
- if (event.type === "usage.context")
24041
- received.usage = true;
24042
- if (event.type === "session.info")
24043
- received.sessionInfo = true;
24044
- check2();
24432
+ for await (const line of lines) {
24433
+ if (!line.includes(marker))
24434
+ continue;
24435
+ let value;
24436
+ try {
24437
+ value = JSON.parse(line);
24438
+ } catch {
24439
+ continue;
24440
+ }
24441
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) {
24442
+ yield value;
24045
24443
  }
24046
- };
24444
+ }
24445
+ }
24446
+ function nativeTimeMs(value) {
24447
+ const time3 = typeof value === "number" ? value : typeof value === "string" ? Date.parse(value) : Number.NaN;
24448
+ return Number.isFinite(time3) && time3 > 0 ? Math.floor(time3) : null;
24047
24449
  }
24048
24450
 
24049
- // dist/acp-transport.js
24050
- var AntigravityAcpTransport = class {
24051
- options;
24052
- skipPermissions;
24053
- #child = null;
24054
- #connection = null;
24055
- #initializing = null;
24056
- #sessionId = null;
24057
- #sessionHandler = null;
24058
- #active = null;
24059
- #callbacks = /* @__PURE__ */ new Set();
24060
- #acceptCallbacks = false;
24061
- #promptInterrupted = null;
24062
- #opening = null;
24063
- #observeReplay = null;
24064
- #pendingEvents = [];
24065
- #closed = false;
24066
- #closing = null;
24067
- #stderrRaw = "";
24068
- get #stderr() {
24069
- return sanitizeDiagnosticTail(this.#stderrRaw);
24070
- }
24071
- #faultSignal = new AbortController();
24072
- constructor(options) {
24073
- this.options = options;
24074
- this.skipPermissions = options.skipPermissions === true;
24075
- }
24076
- get sessionId() {
24077
- return this.#sessionId;
24451
+ // dist/usage-statistics.js
24452
+ function count3(value) {
24453
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : null;
24454
+ }
24455
+ function antigravityHome(environment) {
24456
+ return (process.platform === "win32" ? environment.USERPROFILE : environment.HOME) || os2.homedir();
24457
+ }
24458
+ function transcriptPath(brainRoot, conversationId) {
24459
+ return path8.join(brainRoot, conversationId, ".system_generated", "logs", "transcript.jsonl");
24460
+ }
24461
+ function isMissing(error51) {
24462
+ const code = error51?.code;
24463
+ return code === "ENOENT" || code === "ENOTDIR";
24464
+ }
24465
+ async function lstatIfPresent(target2) {
24466
+ try {
24467
+ return await lstat(target2);
24468
+ } catch (error51) {
24469
+ if (isMissing(error51))
24470
+ return null;
24471
+ throw error51;
24078
24472
  }
24079
- get isClosed() {
24080
- return this.#closed;
24473
+ }
24474
+ async function transcriptFingerprint(file2) {
24475
+ const logs = path8.dirname(file2);
24476
+ for (const directory of [path8.dirname(logs), logs]) {
24477
+ if (!(await lstatIfPresent(directory))?.isDirectory())
24478
+ return null;
24081
24479
  }
24082
- setSessionEventHandler(handler) {
24083
- this.#sessionHandler = handler;
24084
- if (handler)
24085
- for (const event of this.#pendingEvents.splice(0))
24086
- handler(event);
24480
+ const info = await lstatIfPresent(file2);
24481
+ return info?.isFile() && info.size > 0 ? `${info.ino}:${info.size}:${info.mtimeMs}` : null;
24482
+ }
24483
+ async function listTranscripts(brainRoot, signal) {
24484
+ signal.throwIfAborted();
24485
+ const conversations = await opendir(brainRoot).catch((error51) => {
24486
+ if (error51.code === "ENOENT")
24487
+ return null;
24488
+ throw error51;
24489
+ });
24490
+ if (!conversations)
24491
+ return [];
24492
+ const sources = [];
24493
+ for await (const entry of conversations) {
24494
+ signal.throwIfAborted();
24495
+ if (!entry.isDirectory())
24496
+ continue;
24497
+ const file2 = transcriptPath(brainRoot, entry.name);
24498
+ const fingerprint = await transcriptFingerprint(file2);
24499
+ if (fingerprint)
24500
+ sources.push({ id: file2, fingerprint });
24087
24501
  }
24088
- initialize() {
24089
- if (this.#closed)
24090
- return Promise.reject(new AntigravityTransportError("unavailable", "Antigravity ACP is closed"));
24091
- return this.#initializing ??= this.#start();
24502
+ return sources;
24503
+ }
24504
+ async function readAntigravityUsage(file2, signal) {
24505
+ const sessionId = path8.basename(path8.resolve(file2, "..", "..", ".."));
24506
+ const requests = /* @__PURE__ */ new Map();
24507
+ for await (const record4 of jsonlRecords(file2, '"input_tokens"', signal)) {
24508
+ if (record4.type !== "PLANNER_RESPONSE")
24509
+ continue;
24510
+ const step = count3(record4.step_index);
24511
+ const input = count3(record4.input_tokens);
24512
+ const output = count3(record4.output_tokens);
24513
+ const cached2 = count3(record4.cache_read_tokens);
24514
+ const at = nativeTimeMs(record4.created_at);
24515
+ if (step === null || input === null || output === null || at === null)
24516
+ continue;
24517
+ const identity2 = normalizeAntigravityUsageModel(record4.model);
24518
+ requests.set(step, withUsageSession({
24519
+ id: `${String(record4.created_at)}:${step}:${input}:${cached2 ?? "-"}:${output}`,
24520
+ occurredAtMs: at,
24521
+ ...identity2,
24522
+ inputTokens: input + (cached2 ?? 0),
24523
+ ...cached2 !== null ? {
24524
+ cachedInputTokens: cached2,
24525
+ ...hasImplicitZeroCacheWrite(identity2) ? { cacheWriteInputTokens: 0 } : {}
24526
+ } : {},
24527
+ outputTokens: output
24528
+ }, { sessionId }));
24092
24529
  }
24093
- async #start() {
24094
- try {
24095
- const executable = resolveAntigravityExecutable(this.options);
24096
- if (!executable)
24097
- throw new AntigravityTransportError("notInstalled", "Antigravity CLI was not found");
24098
- const invocation = commandInvocation(executable, this.skipPermissions ? ["acp", "--dangerously-skip-permissions"] : ["acp"], this.options.environment ?? process.env);
24099
- const child = spawn(invocation.command, invocation.arguments, {
24100
- cwd: this.options.cwd,
24101
- env: this.options.environment ?? process.env,
24102
- stdio: ["pipe", "pipe", "pipe"],
24103
- windowsHide: true,
24104
- windowsVerbatimArguments: invocation.windowsVerbatimArguments
24105
- });
24106
- this.#child = child;
24107
- child.stderr.on("data", (chunk) => {
24108
- this.#stderrRaw = (this.#stderrRaw + chunk.toString()).slice(-32e3);
24109
- });
24110
- child.on("error", (error51) => this.#fault(new AntigravityTransportError(error51.code === "ENOENT" ? "notInstalled" : "unavailable", error51.message, { diagnostic: this.#stderr })));
24111
- child.on("exit", (code, signal) => this.#fault(new AntigravityTransportError("processExited", `Antigravity ACP exited (code ${code}, signal ${signal})`, { diagnostic: this.#stderr })));
24112
- child.stdin.on("error", (error51) => this.#fault(this.#error(error51)));
24113
- const stream = ndJsonStream2(Writable.toWeb(child.stdin), Readable.toWeb(child.stdout));
24114
- const nativeMethods = /* @__PURE__ */ new Set(["session/request_permission", "elicitation/create"]);
24115
- stream.readable = stream.readable.pipeThrough(new TransformStream({
24116
- transform: (message2, controller) => {
24117
- if ("method" in message2 && message2.method === "session/update") {
24118
- const params = message2.params;
24119
- this.#update(params.sessionId, params.update);
24120
- return;
24121
- }
24122
- if ("method" in message2 && nativeMethods.has(message2.method))
24123
- message2.method = `_antigravity/${message2.method}`;
24124
- controller.enqueue(message2);
24125
- }
24126
- }));
24127
- const onElicitation = (request) => this.#callback("sessionId" in request ? request.sessionId : void 0, (handler) => handler.onElicitation(request), { action: "cancel" });
24128
- const client2 = {
24129
- sessionUpdate: ({ sessionId, update }) => this.#update(sessionId, update),
24130
- requestPermission: (request) => this.#callback(request.sessionId, (handler) => handler.onPermission(request), {
24131
- outcome: { outcome: "cancelled" }
24132
- }),
24133
- unstable_createElicitation: onElicitation,
24134
- extMethod: async (method, params) => {
24135
- if (method === "_antigravity/session/request_permission")
24136
- return await client2.requestPermission(params);
24137
- if (method === "_antigravity/elicitation/create")
24138
- return await onElicitation(params);
24139
- throw new AntigravityTransportError("unsupported", `Unsupported ACP client method: ${method}`);
24530
+ return [...requests.values()];
24531
+ }
24532
+ function createAntigravityUsageStatistics(environment) {
24533
+ const brainRoot = nativeBrainRoot(antigravityHome(environment));
24534
+ let listed = /* @__PURE__ */ new Map();
24535
+ return Object.freeze({
24536
+ async listSources(signal) {
24537
+ const sources = await listTranscripts(brainRoot, signal);
24538
+ listed = new Map(sources.map(({ id, fingerprint }) => [id, fingerprint]));
24539
+ return sources;
24540
+ },
24541
+ async readSource(id, signal) {
24542
+ const expected = listed.get(id);
24543
+ let entries;
24544
+ try {
24545
+ entries = await readAntigravityUsage(id, signal);
24546
+ } catch (error51) {
24547
+ if (expected !== void 0 && isMissing(error51)) {
24548
+ throw new HarnessUsageSourceChangedError("Antigravity transcript disappeared before reading; refresh to retry");
24140
24549
  }
24141
- };
24142
- const connection = new ClientSideConnection(() => client2, stream);
24143
- this.#connection = connection;
24144
- connection.signal.addEventListener("abort", () => this.#fault(new AntigravityTransportError("processExited", "Antigravity ACP connection closed", {
24145
- diagnostic: this.#stderr
24146
- })), { once: true });
24147
- const response = await this.#request(connection.initialize({
24148
- protocolVersion: 1,
24149
- clientCapabilities: { elicitation: { form: {} } }
24150
- }), "initialize");
24151
- if (response.protocolVersion !== 1)
24152
- throw new AntigravityTransportError("protocolError", `Unsupported ACP version ${response.protocolVersion}`);
24153
- return response;
24154
- } catch (error51) {
24155
- await this.close();
24156
- throw this.#error(error51);
24550
+ throw error51;
24551
+ }
24552
+ if (expected !== void 0 && await transcriptFingerprint(id) !== expected) {
24553
+ throw new HarnessUsageSourceChangedError("Antigravity transcript changed while reading; refresh to retry");
24554
+ }
24555
+ return entries;
24157
24556
  }
24158
- }
24159
- async openSession(input) {
24160
- await this.initialize();
24161
- if (this.#closed || !this.#connection || this.#active || this.#opening || this.#sessionId)
24162
- throw new AntigravityTransportError("unavailable", "Close the current ACP session before opening another");
24163
- const connection = this.#connection;
24164
- const buffered = [];
24165
- this.#opening = buffered;
24166
- this.#pendingEvents = [];
24167
- const params = {
24168
- cwd: input.cwd,
24169
- mcpServers: [],
24170
- ...input.additionalDirectories?.length ? { additionalDirectories: input.additionalDirectories } : {},
24171
- ...input.systemPromptAppend ? { _meta: { antigravity: { systemPrompt: { append: input.systemPromptAppend } } } } : {}
24172
- };
24557
+ });
24558
+ }
24559
+
24560
+ // dist/fork.js
24561
+ function nativeConversationDbPath(id, home = os3.homedir()) {
24562
+ return path9.join(home, ".gemini", "antigravity-cli", "conversations", `${id}.db`);
24563
+ }
24564
+ function nativeConversationSummariesDbPath(home = os3.homedir()) {
24565
+ return path9.join(home, ".gemini", "antigravity-cli", "conversation_summaries.db");
24566
+ }
24567
+ function nativeBrainRoot(home = os3.homedir()) {
24568
+ return path9.join(home, ".gemini", "antigravity-cli", "brain");
24569
+ }
24570
+ function nativeBrainDirPath(id, home = os3.homedir()) {
24571
+ return path9.join(nativeBrainRoot(home), id);
24572
+ }
24573
+ function validNativeSessionRef(ref, harnessId2) {
24574
+ return nativeSessionRefSchema.safeParse(ref).success && ref.harnessId === harnessId2 && /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(ref.nativeSessionId);
24575
+ }
24576
+ async function cloneNativeConversationDb(sourceId, derivedId, retainedTurnsCountOrHome, homeOption = os3.homedir()) {
24577
+ if (![sourceId, derivedId].every((id) => /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(id)))
24578
+ throw new Error("Invalid native conversation ID");
24579
+ const home = typeof retainedTurnsCountOrHome === "string" ? retainedTurnsCountOrHome : homeOption;
24580
+ const retained = typeof retainedTurnsCountOrHome === "number" ? retainedTurnsCountOrHome : void 0;
24581
+ const sourcePath = nativeConversationDbPath(sourceId, home);
24582
+ const targetPath2 = nativeConversationDbPath(derivedId, home);
24583
+ await access2(sourcePath);
24584
+ const { DatabaseSync, backup } = await import("node:sqlite");
24585
+ const source = new DatabaseSync(sourcePath, { readOnly: true });
24586
+ let owned = false;
24587
+ try {
24588
+ source.exec("BEGIN");
24589
+ const count4 = Number(source.prepare("SELECT count(*) AS n FROM steps WHERE step_type = 14").get()?.n ?? 0);
24590
+ if (retained !== void 0 && (!Number.isSafeInteger(retained) || retained < 0 || retained > count4))
24591
+ throw new Error("Invalid retained native Turn count");
24592
+ await mkdir(path9.dirname(targetPath2), { recursive: true });
24593
+ const reservation = await open(targetPath2, "wx");
24594
+ owned = true;
24595
+ await reservation.close();
24596
+ await backup(source, targetPath2);
24597
+ const target2 = new DatabaseSync(targetPath2);
24173
24598
  try {
24174
- const replay = input.kind === "load" && input.sessionId ? nativeReplayCompletion(await readNativeReplaySize(input.sessionId, antigravityHome(this.options.environment ?? process.env))) : void 0;
24175
- this.#observeReplay = replay ? (sessionId2, event) => {
24176
- if (sessionId2 === input.sessionId)
24177
- replay.observe(event);
24178
- } : null;
24179
- let request;
24180
- if (input.kind === "create")
24181
- request = connection.newSession(params);
24182
- else {
24183
- if (!input.sessionId)
24184
- throw new AntigravityTransportError("protocolError", "Session ID required for resume/load");
24185
- const target2 = { ...params, sessionId: input.sessionId };
24186
- request = input.kind === "resume" ? connection.resumeSession(target2) : connection.loadSession(target2);
24599
+ target2.exec("BEGIN IMMEDIATE");
24600
+ target2.prepare("UPDATE trajectory_meta SET cascade_id = ?").run(derivedId);
24601
+ const row = target2.prepare("SELECT data FROM trajectory_metadata_blob WHERE id = 'main'").get();
24602
+ const blob = row?.data instanceof Uint8Array ? rewriteTrajectoryMetadataCascadeId(row.data, derivedId) : minimalTrajectoryMetadataBlob(derivedId);
24603
+ if (!blob)
24604
+ throw new Error("Invalid native trajectory metadata");
24605
+ target2.prepare("INSERT OR REPLACE INTO trajectory_metadata_blob (id, data) VALUES ('main', ?)").run(blob);
24606
+ if (retained !== void 0 && retained < count4) {
24607
+ const boundary = target2.prepare("SELECT idx FROM steps WHERE step_type = 14 ORDER BY idx LIMIT 1 OFFSET ?").get(retained);
24608
+ const cutoff = retained === 0 ? 0 : Number(boundary?.idx);
24609
+ target2.prepare("DELETE FROM steps WHERE idx >= ?").run(cutoff);
24610
+ for (const table of [
24611
+ "gen_metadata",
24612
+ "executor_metadata",
24613
+ "parent_references",
24614
+ "battle_mode_infos"
24615
+ ]) {
24616
+ if (target2.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(table))
24617
+ target2.prepare(`DELETE FROM ${table} WHERE idx >= ?`).run(cutoff);
24618
+ }
24187
24619
  }
24188
- const result = await this.#request(request, `session/${input.kind === "create" ? "new" : input.kind}`);
24189
- const raw = result;
24190
- const sessionId = raw.sessionId ?? input.sessionId;
24191
- if (!sessionId)
24192
- throw new AntigravityTransportError("protocolError", "Antigravity session/new returned no sessionId");
24193
- this.#sessionId = sessionId;
24194
- if (replay)
24195
- await this.#request(replay.complete, "session/load replay");
24196
- const events = buffered.filter((entry) => entry.sessionId === sessionId).map(({ event }) => event);
24197
- if (input.kind !== "load")
24198
- for (const event of events)
24199
- this.#dispatch(event);
24200
- return {
24201
- opened: {
24202
- sessionId,
24203
- ...raw.models ? { models: raw.models } : {},
24204
- ...raw.modes ? { modes: raw.modes } : {},
24205
- ...raw.configOptions ? { configOptions: raw.configOptions } : {},
24206
- ...raw._meta?.antigravity?.tier ? { tier: raw._meta.antigravity.tier } : {}
24207
- },
24208
- replayedEvents: input.kind === "load" ? events : []
24209
- };
24620
+ target2.exec("COMMIT");
24210
24621
  } finally {
24211
- this.#opening = null;
24212
- this.#observeReplay = null;
24622
+ target2.close();
24213
24623
  }
24624
+ await registerDerivedSummary(sourceId, derivedId, home);
24625
+ return true;
24626
+ } catch (error51) {
24627
+ if (owned)
24628
+ await removeDerivedDb(derivedId, home);
24629
+ throw error51;
24630
+ } finally {
24631
+ source.close();
24214
24632
  }
24215
- async setMode(modeId) {
24216
- const { connection, sessionId } = this.#session();
24217
- await this.#request(connection.setSessionMode({ sessionId, modeId }), "session/set_mode");
24218
- }
24219
- async setConfigOption(configId, value) {
24220
- const { connection, sessionId } = this.#session();
24221
- const response = await this.#request(connection.setSessionConfigOption({ sessionId, configId, value }), "session/set_config_option");
24222
- return response.configOptions;
24633
+ }
24634
+ async function registerDerivedSummary(sourceId, derivedId, home) {
24635
+ const summaryPath = nativeConversationSummariesDbPath(home);
24636
+ try {
24637
+ await access2(summaryPath);
24638
+ } catch (error51) {
24639
+ if (error51.code === "ENOENT")
24640
+ return;
24641
+ throw error51;
24223
24642
  }
24224
- async prompt(parts, handler) {
24225
- const { connection, sessionId } = this.#session();
24226
- if (this.#active)
24227
- throw new AntigravityTransportError("unavailable", "An ACP prompt is already active");
24228
- this.#active = handler;
24229
- this.#acceptCallbacks = true;
24230
- const interrupted = new AbortController();
24231
- this.#promptInterrupted = interrupted;
24643
+ const { DatabaseSync } = await import("node:sqlite");
24644
+ const summaries = new DatabaseSync(summaryPath);
24645
+ try {
24646
+ const template = summaries.prepare("SELECT * FROM conversation_summaries WHERE conversation_id = ?").get(sourceId);
24647
+ if (!template)
24648
+ return;
24649
+ const derived = new DatabaseSync(nativeConversationDbPath(derivedId, home), { readOnly: true });
24650
+ let row;
24232
24651
  try {
24233
- return await this.#request(connection.prompt({ sessionId, prompt: [...parts] }), "session/prompt", null, interrupted.signal);
24652
+ const metadata = derived.prepare("SELECT data FROM trajectory_metadata_blob WHERE id = 'main'").get()?.data;
24653
+ const trajectoryId = derived.prepare("SELECT trajectory_id FROM trajectory_meta LIMIT 1").get()?.trajectory_id;
24654
+ row = {
24655
+ ...template,
24656
+ conversation_id: derivedId,
24657
+ status: "CASCADE_RUN_STATUS_IDLE",
24658
+ step_count: Number(derived.prepare("SELECT count(*) AS n FROM steps").get()?.n),
24659
+ last_user_input_step_index: Number(derived.prepare("SELECT max(idx) AS idx FROM steps WHERE step_type = 14").get()?.idx ?? -1),
24660
+ not_fully_idle: 0,
24661
+ killed: 0,
24662
+ last_modified_time: (/* @__PURE__ */ new Date()).toISOString(),
24663
+ raw_summary: minimalRawSummaryBlob(String(trajectoryId), Buffer.from(metadata))
24664
+ };
24234
24665
  } finally {
24235
- this.#clearCallbacks();
24236
- this.#acceptCallbacks = false;
24237
- this.#active = null;
24238
- this.#promptInterrupted = null;
24239
- }
24240
- }
24241
- async cancel() {
24242
- const { connection, sessionId } = this.#session();
24243
- this.#acceptCallbacks = false;
24244
- this.#clearCallbacks();
24245
- await this.#request(connection.cancel({ sessionId }), "session/cancel");
24246
- }
24247
- async closeSession() {
24248
- const sessionId = this.#sessionId;
24249
- this.#sessionId = null;
24250
- this.#acceptCallbacks = false;
24251
- this.#promptInterrupted?.abort(new AntigravityTransportError("unavailable", "ACP session closed"));
24252
- this.#active = null;
24253
- this.#pendingEvents = [];
24254
- this.#clearCallbacks();
24255
- if (sessionId && this.#connection)
24256
- await this.#request(this.#connection.closeSession({ sessionId }), "session/close", this.options.closeTimeoutMs ?? 2e3);
24257
- }
24258
- close() {
24259
- if (this.#closing)
24260
- return this.#closing;
24261
- this.#closed = true;
24262
- return this.#closing = this.#shutdown();
24263
- }
24264
- async #shutdown() {
24265
- try {
24266
- await this.closeSession();
24267
- } catch (error51) {
24268
- this.#stderrRaw = `${this.#stderrRaw}
24269
- ${this.#error(error51).message}`.slice(-32e3);
24270
- }
24271
- this.#faultSignal.abort(new AntigravityTransportError("unavailable", "Antigravity ACP closed"));
24272
- this.#opening = null;
24273
- this.#sessionHandler = null;
24274
- const child = this.#child;
24275
- if (child && child.exitCode === null && child.signalCode === null && child.pid) {
24276
- const exited = new Promise((resolve) => child.once("exit", () => resolve()));
24277
- const timeout = this.options.closeTimeoutMs ?? 2e3;
24278
- const term = setTimeout(() => child.kill("SIGTERM"), Math.max(1, timeout / 2));
24279
- const kill = setTimeout(() => child.kill("SIGKILL"), Math.max(2, timeout));
24280
- child.stdin.end();
24281
- try {
24282
- await exited;
24283
- } finally {
24284
- clearTimeout(term);
24285
- clearTimeout(kill);
24286
- }
24666
+ derived.close();
24287
24667
  }
24288
- this.#connection = null;
24289
- this.#child = null;
24290
- }
24291
- #session() {
24292
- if (this.#closed || !this.#connection || !this.#sessionId)
24293
- throw new AntigravityTransportError("unavailable", "Antigravity ACP session is unavailable");
24294
- return { connection: this.#connection, sessionId: this.#sessionId };
24668
+ const columns = Object.keys(template);
24669
+ summaries.prepare(`INSERT INTO conversation_summaries (${columns.map((name) => `"${name.replaceAll('"', '""')}"`).join(",")}) VALUES (${columns.map(() => "?").join(",")})`).run(...columns.map((name) => row[name] ?? null));
24670
+ } finally {
24671
+ summaries.close();
24295
24672
  }
24296
- #update(sessionId, raw) {
24297
- if (this.#closed)
24298
- return;
24299
- const event = projectAcpSessionUpdate(raw);
24300
- if (!event)
24301
- return;
24302
- if (this.#opening) {
24303
- this.#opening.push({ sessionId, event });
24304
- this.#observeReplay?.(sessionId, event);
24673
+ }
24674
+ async function removeDerivedSummary(id, home) {
24675
+ try {
24676
+ await access2(nativeConversationSummariesDbPath(home));
24677
+ } catch (error51) {
24678
+ if (error51.code === "ENOENT")
24305
24679
  return;
24306
- }
24307
- if (sessionId === this.#sessionId)
24308
- this.#dispatch(event);
24309
- }
24310
- #dispatch(event) {
24311
- if (["config.update", "mode.update", "commands.update", "session.info", "usage.context"].includes(event.type)) {
24312
- if (this.#sessionHandler)
24313
- this.#sessionHandler(event);
24314
- else
24315
- this.#pendingEvents.push(event);
24316
- } else
24317
- this.#active?.onEvent(event);
24680
+ throw error51;
24318
24681
  }
24319
- async #callback(sessionId, invoke, cancelled) {
24320
- const active = this.#active;
24321
- if (!active || !this.#acceptCallbacks || sessionId !== this.#sessionId || this.#closed)
24322
- return cancelled;
24323
- let cancel;
24324
- const cancellation = new Promise((resolve) => {
24325
- cancel = () => resolve(cancelled);
24326
- });
24327
- this.#callbacks.add(cancel);
24328
- try {
24329
- return await Promise.race([invoke(active), cancellation]);
24330
- } finally {
24331
- this.#callbacks.delete(cancel);
24332
- }
24682
+ const { DatabaseSync } = await import("node:sqlite");
24683
+ const db = new DatabaseSync(nativeConversationSummariesDbPath(home));
24684
+ try {
24685
+ db.prepare("DELETE FROM conversation_summaries WHERE conversation_id = ?").run(id);
24686
+ } finally {
24687
+ db.close();
24333
24688
  }
24334
- #clearCallbacks() {
24335
- for (const cancel of this.#callbacks)
24336
- cancel();
24337
- this.#callbacks.clear();
24689
+ }
24690
+ async function removeDerivedDb(id, home) {
24691
+ const file2 = nativeConversationDbPath(id, home);
24692
+ await Promise.all([file2, `${file2}-wal`, `${file2}-shm`].map((target2) => rm2(target2, { force: true })));
24693
+ }
24694
+ async function copyNativeBrainDirIfExists(sourceId, derivedId, home = os3.homedir()) {
24695
+ try {
24696
+ await access2(nativeBrainDirPath(sourceId, home));
24697
+ } catch (error51) {
24698
+ if (error51.code === "ENOENT")
24699
+ return false;
24700
+ throw error51;
24338
24701
  }
24339
- async #request(promise2, operation, timeoutMs = this.options.commandTimeoutMs ?? 3e4, signal) {
24340
- let timer;
24341
- let abort;
24342
- const signals = [this.#faultSignal.signal, ...signal ? [signal] : []];
24343
- const interrupted = new Promise((_, reject) => {
24344
- abort = () => reject(signal?.aborted ? signal.reason : this.#faultSignal.signal.reason);
24345
- if (signals.some((candidate) => candidate.aborted))
24346
- abort();
24347
- else
24348
- for (const candidate of signals)
24349
- candidate.addEventListener("abort", abort, { once: true });
24350
- if (timeoutMs !== null)
24351
- timer = setTimeout(() => reject(new AntigravityTransportError("unavailable", `${operation} timed out after ${timeoutMs}ms`, { diagnostic: this.#stderr })), timeoutMs);
24702
+ await cp(nativeBrainDirPath(sourceId, home), nativeBrainDirPath(derivedId, home), {
24703
+ recursive: true,
24704
+ errorOnExist: true,
24705
+ force: false,
24706
+ filter: (source) => path9.basename(source) !== ".system_generated"
24707
+ });
24708
+ return true;
24709
+ }
24710
+ async function openDerivedAntigravitySession(options, input, sourceRef, retained) {
24711
+ const environment = { ...options.adapterEnvironment, ...input.environment };
24712
+ const home = antigravityHome(environment);
24713
+ const derivedId = randomUUID();
24714
+ let cloned = false;
24715
+ try {
24716
+ await cloneNativeConversationDb(sourceRef.nativeSessionId, derivedId, retained, home);
24717
+ cloned = true;
24718
+ await copyNativeBrainDirIfExists(sourceRef.nativeSessionId, derivedId, home);
24719
+ const result = await options.openSession({
24720
+ ...input,
24721
+ environment,
24722
+ nativeRef: { ...sourceRef, nativeSessionId: derivedId }
24352
24723
  });
24353
- try {
24354
- return await Promise.race([promise2, interrupted]);
24355
- } catch (error51) {
24356
- const normalized = this.#error(error51);
24357
- if (normalized.kind === "unavailable" && normalized.message.includes("timed out"))
24358
- void this.close();
24359
- throw normalized;
24360
- } finally {
24361
- clearTimeout(timer);
24362
- for (const candidate of signals)
24363
- candidate.removeEventListener("abort", abort);
24364
- }
24365
- }
24366
- #error(error51) {
24367
- if (error51 instanceof AntigravityTransportError)
24368
- return error51;
24369
- const message2 = sanitizeDiagnosticTail(error51 instanceof Error ? error51.message : String(error51));
24370
- const code = error51?.code;
24371
- return new AntigravityTransportError(code === -32e3 || /auth|login|sign[ -]?in|unauthenticated/iu.test(message2) ? "authenticationRequired" : "unavailable", message2, { cause: error51, diagnostic: this.#stderr });
24724
+ if (result.ok)
24725
+ return result;
24726
+ const cleanupFailure = await cleanup().then(() => void 0, () => "Derived native history cleanup failed");
24727
+ return cleanupFailure ? { ok: false, error: { ...result.error, diagnostic: cleanupFailure } } : result;
24728
+ } catch (error51) {
24729
+ const cleanupFailure = await cleanup().then(() => void 0, () => "Derived native history cleanup failed");
24730
+ return {
24731
+ ok: false,
24732
+ error: {
24733
+ ...nativeHistoryError(error51),
24734
+ ...cleanupFailure ? { diagnostic: cleanupFailure } : {}
24735
+ }
24736
+ };
24372
24737
  }
24373
- #fault(error51) {
24374
- if (this.#closed || this.#faultSignal.signal.aborted)
24738
+ async function cleanup() {
24739
+ if (!cloned)
24375
24740
  return;
24376
- this.#faultSignal.abort(error51);
24377
- this.#clearCallbacks();
24378
- void this.close();
24379
- this.options.onFault?.(error51);
24741
+ await Promise.all([
24742
+ removeDerivedDb(derivedId, home),
24743
+ rm2(nativeBrainDirPath(derivedId, home), { recursive: true, force: true }),
24744
+ removeDerivedSummary(derivedId, home)
24745
+ ]);
24380
24746
  }
24381
- };
24382
-
24383
- // dist/delegation.js
24384
- var DELEGATION_ENVIRONMENT_KEYS = [
24385
- "CODEXHOST_CLI_PATH",
24386
- "CODEXHOST_RUNTIME_ENDPOINT",
24387
- "CODEXHOST_RUNTIME_TOKEN",
24388
- "CODEXHOST_THREAD_ID"
24389
- ];
24390
- var ANTIGRAVITY_DELEGATION_INSTRUCTIONS = `This Antigravity Session runs inside codexhost.
24391
- When the user requests cross-Harness delegation, use the executable specified by the CODEXHOST_CLI_PATH environment variable through your native shell tool. Start with --help and harness list, then use delegate start and thread send/read/wait/cancel as documented. Use --format compact for results. Keep the inherited CODEXHOST_RUNTIME_ENDPOINT, CODEXHOST_RUNTIME_TOKEN and CODEXHOST_THREAD_ID environment variables for every call; they identify this Runtime and parent Thread. Never print their values, substitute another executable, or delegate without user authorization. Native Antigravity subagents are separate from cross-Harness delegation.`;
24392
- function antigravityDelegationInstructions(environment) {
24393
- return DELEGATION_ENVIRONMENT_KEYS.every((key) => environment[key]) ? ANTIGRAVITY_DELEGATION_INSTRUCTIONS : void 0;
24747
+ }
24748
+ async function forkAntigravitySession(options) {
24749
+ const { input, harnessId: harnessId2 } = options;
24750
+ if (!validNativeSessionRef(input.sourceRef, harnessId2))
24751
+ return {
24752
+ ok: false,
24753
+ error: {
24754
+ code: "invalidRequest",
24755
+ message: "Invalid Antigravity source Native Session",
24756
+ retryable: false
24757
+ }
24758
+ };
24759
+ const checkpoint = nativeCheckpointRefSchema.safeParse(input.checkpoint);
24760
+ if (!checkpoint.success || checkpoint.data.harnessId !== harnessId2 || checkpoint.data.nativeSessionId !== input.sourceRef.nativeSessionId)
24761
+ return checkpointError();
24762
+ if (options.sourceSession?.isActive)
24763
+ return {
24764
+ ok: false,
24765
+ error: {
24766
+ code: "sessionBusy",
24767
+ message: "Source Session is busy",
24768
+ retryable: true
24769
+ }
24770
+ };
24771
+ const match = /^turn-(0|[1-9]\d*)$/u.exec(checkpoint.data.checkpointId);
24772
+ if (!match)
24773
+ return checkpointError();
24774
+ try {
24775
+ const count4 = await readNativeTurnCount(nativeConversationDbPath(input.sourceRef.nativeSessionId, antigravityHome({ ...options.adapterEnvironment, ...input.environment })));
24776
+ const index = Number(match[1]);
24777
+ if (!Number.isSafeInteger(index) || index >= count4)
24778
+ return checkpointError();
24779
+ return openDerivedAntigravitySession(options, {
24780
+ kind: "resume",
24781
+ nativeRef: input.sourceRef,
24782
+ cwd: input.cwd,
24783
+ ...input.environment ? { environment: input.environment } : {}
24784
+ }, input.sourceRef, index + 1);
24785
+ } catch (error51) {
24786
+ return { ok: false, error: nativeHistoryError(error51) };
24787
+ }
24788
+ }
24789
+ function checkpointError() {
24790
+ return {
24791
+ ok: false,
24792
+ error: {
24793
+ code: "checkpointNotFound",
24794
+ message: "Antigravity native Turn checkpoint not found",
24795
+ retryable: false
24796
+ }
24797
+ };
24394
24798
  }
24395
24799
 
24396
24800
  // dist/model-catalog.js
@@ -24549,6 +24953,128 @@ function splitAntigravityModelAndEffort(rawModelId) {
24549
24953
  return { modelRef: harnessModelRefSchema.parse({ id: rawModelId.trim() }) };
24550
24954
  }
24551
24955
 
24956
+ // dist/native-replay.js
24957
+ var USER_INPUT = 14;
24958
+ var PLANNER_RESPONSE = 15;
24959
+ var ERROR_MESSAGE = 17;
24960
+ var GENERIC_TOOL = 132;
24961
+ var DONE = 3;
24962
+ var ERROR = 7;
24963
+ var IN_FLIGHT = /* @__PURE__ */ new Set([1, 2, 8, 9, 11]);
24964
+ function message2(payload) {
24965
+ const fields = payload instanceof Uint8Array ? readProtoFields(payload) : null;
24966
+ if (!fields)
24967
+ throw new Error("Invalid Antigravity history protobuf");
24968
+ return fields;
24969
+ }
24970
+ function messageField(fields, number4) {
24971
+ const field3 = fields.find((entry) => entry.number === number4 && entry.wire === 2);
24972
+ return field3?.value instanceof Uint8Array ? field3.value : void 0;
24973
+ }
24974
+ function nested(fields, number4) {
24975
+ const payload = messageField(fields, number4);
24976
+ return payload ? message2(payload) : [];
24977
+ }
24978
+ function textField(fields, number4) {
24979
+ const bytes = messageField(fields, number4);
24980
+ return bytes ? Buffer.from(bytes).toString("utf8") : "";
24981
+ }
24982
+ function argsValue(raw) {
24983
+ if (!raw)
24984
+ return void 0;
24985
+ try {
24986
+ return JSON.parse(raw);
24987
+ } catch {
24988
+ return raw;
24989
+ }
24990
+ }
24991
+ async function readNativeHistory(sessionId, home) {
24992
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/u.test(sessionId))
24993
+ throw new Error("Invalid native Session ID");
24994
+ const { DatabaseSync } = await import("node:sqlite");
24995
+ const db = new DatabaseSync(nativeConversationDbPath(sessionId, home), { readOnly: true });
24996
+ const events = [];
24997
+ const pendingCalls = /* @__PURE__ */ new Set();
24998
+ let turnCount = 0;
24999
+ const append = (type, text2) => {
25000
+ if (text2)
25001
+ events.push({ type, text: events.at(-1)?.type === type ? `
25002
+
25003
+ ${text2}` : text2 });
25004
+ };
25005
+ try {
25006
+ db.exec("BEGIN");
25007
+ if (db.prepare("PRAGMA user_version").get()?.user_version !== 1)
25008
+ throw new Error("Unsupported Antigravity history database version");
25009
+ for (const row of db.prepare(`SELECT step_type, status, step_payload FROM steps
25010
+ WHERE step_type IN (${USER_INPUT}, ${PLANNER_RESPONSE}, ${ERROR_MESSAGE}, ${GENERIC_TOOL})
25011
+ ORDER BY idx`).iterate()) {
25012
+ if (row.step_type === USER_INPUT)
25013
+ turnCount++;
25014
+ if (IN_FLIGHT.has(Number(row.status)))
25015
+ continue;
25016
+ const step = message2(row.step_payload);
25017
+ const number4 = row.step_type === USER_INPUT ? 19 : row.step_type === PLANNER_RESPONSE ? 20 : row.step_type === ERROR_MESSAGE ? 24 : 140;
25018
+ const body = message2(messageField(step, number4));
25019
+ switch (row.step_type) {
25020
+ case USER_INPUT: {
25021
+ const items = body.flatMap((field3) => field3.number === 3 && field3.wire === 2 ? [textField(message2(field3.value), 1)] : []);
25022
+ const text2 = items.join("") || textField(body, 2) || textField(body, 1);
25023
+ pendingCalls.clear();
25024
+ if (text2)
25025
+ events.push({ type: "user.text", text: text2 });
25026
+ break;
25027
+ }
25028
+ case PLANNER_RESPONSE: {
25029
+ append("agent.thought", textField(body, 3));
25030
+ append("agent.text", textField(body, 1));
25031
+ for (const field3 of body) {
25032
+ if (field3.number !== 7 || field3.wire !== 2)
25033
+ continue;
25034
+ const call = message2(field3.value);
25035
+ const toolCallId = textField(call, 1);
25036
+ const name = textField(call, 2);
25037
+ if (!toolCallId || !name)
25038
+ continue;
25039
+ pendingCalls.add(toolCallId);
25040
+ events.push({
25041
+ type: "tool.call",
25042
+ toolCallId,
25043
+ name,
25044
+ args: argsValue(textField(call, 3))
25045
+ });
25046
+ }
25047
+ break;
25048
+ }
25049
+ case ERROR_MESSAGE: {
25050
+ const warning = textField(nested(body, 3), 2);
25051
+ if (warning)
25052
+ append("agent.text", `⚠ ${warning}`);
25053
+ break;
25054
+ }
25055
+ case GENERIC_TOOL: {
25056
+ const toolCallId = textField(nested(nested(step, 5), 4), 1);
25057
+ if (!pendingCalls.delete(toolCallId))
25058
+ break;
25059
+ const error51 = nested(step, 31);
25060
+ const output = textField(nested(body, 2), 1) || textField(error51, 3) || textField(error51, 2) || textField(error51, 1);
25061
+ const status = row.status === DONE ? "completed" : row.status === ERROR ? "failed" : "cancelled";
25062
+ events.push({
25063
+ type: "tool.update",
25064
+ toolCallId,
25065
+ status,
25066
+ ...output ? { rawOutput: output } : {}
25067
+ });
25068
+ break;
25069
+ }
25070
+ }
25071
+ }
25072
+ return { events, turnCount };
25073
+ } finally {
25074
+ db.close();
25075
+ }
25076
+ }
25077
+
24552
25078
  // dist/permission-modes.js
24553
25079
  var ANTIGRAVITY_ACP_SESSION_MODES = ["default", "accept-edits", "auto", "plan"];
24554
25080
  var ANTIGRAVITY_DEFAULT_PERMISSION_MODE_ID = harnessPermissionModeIdSchema.parse("default");
@@ -24858,8 +25384,8 @@ import { fileURLToPath } from "node:url";
24858
25384
  // ../../harness-adapter/dist/session-import.js
24859
25385
  import { lstat as lstat2 } from "node:fs/promises";
24860
25386
  var SessionImportChangedError = class extends Error {
24861
- constructor(message2 = "Native Session changed during discovery; refresh and retry") {
24862
- super(message2);
25387
+ constructor(message3 = "Native Session changed during discovery; refresh and retry") {
25388
+ super(message3);
24863
25389
  this.name = "SessionImportChangedError";
24864
25390
  }
24865
25391
  };
@@ -25132,144 +25658,6 @@ var AntigravitySessionImport = class {
25132
25658
  }
25133
25659
  };
25134
25660
 
25135
- // dist/snapshot-reader-pool.js
25136
- var THREAD_SCOPED_ENV_KEYS = /* @__PURE__ */ new Set(["CODEXHOST_THREAD_ID"]);
25137
- function sanitizeReaderEnvironment(environment) {
25138
- const sanitized = {};
25139
- for (const [key, value] of Object.entries(environment)) {
25140
- if (value !== void 0 && !THREAD_SCOPED_ENV_KEYS.has(key)) {
25141
- sanitized[key] = value;
25142
- }
25143
- }
25144
- return sanitized;
25145
- }
25146
- function readerScopeKey(command, skipPermissions, environment) {
25147
- const entries = Object.entries(environment).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0);
25148
- return JSON.stringify([command ?? "", skipPermissions, entries]);
25149
- }
25150
- var AntigravitySnapshotReaderPool = class {
25151
- adapterOptions;
25152
- #lanes = /* @__PURE__ */ new Map();
25153
- #retiring = /* @__PURE__ */ new Set();
25154
- #retired = /* @__PURE__ */ new WeakSet();
25155
- #closed = false;
25156
- #closing;
25157
- constructor(adapterOptions) {
25158
- this.adapterOptions = adapterOptions;
25159
- }
25160
- loadSession(input) {
25161
- if (this.#closed || input.signal?.aborted) {
25162
- return Promise.reject(new AntigravityTransportError("unavailable", "Snapshot reader is closed"));
25163
- }
25164
- const environment = sanitizeReaderEnvironment(input.environment);
25165
- const key = readerScopeKey(this.adapterOptions.command, input.skipPermissions, environment);
25166
- let lane = this.#lanes.get(key);
25167
- if (!lane) {
25168
- lane = { transport: void 0, initialized: false, tail: Promise.resolve() };
25169
- this.#lanes.set(key, lane);
25170
- }
25171
- const currentLane = lane;
25172
- const run = currentLane.tail.then(() => this.#loadInLane(currentLane, input, environment));
25173
- currentLane.tail = run.then(() => void 0, () => void 0);
25174
- return run;
25175
- }
25176
- close() {
25177
- return this.#closing ??= this.#close().catch((error51) => {
25178
- this.#closing = void 0;
25179
- throw error51;
25180
- });
25181
- }
25182
- async #close() {
25183
- this.#closed = true;
25184
- for (const lane of this.#lanes.values()) {
25185
- if (lane.transport)
25186
- this.#retire(lane, lane.transport);
25187
- }
25188
- this.#lanes.clear();
25189
- await Promise.all(this.#retiring);
25190
- }
25191
- async #loadInLane(lane, input, environment) {
25192
- if (this.#closed || input.signal?.aborted) {
25193
- throw new AntigravityTransportError("unavailable", "Snapshot reader is closed");
25194
- }
25195
- let transport = lane.transport;
25196
- if (!transport || transport.isClosed) {
25197
- transport = this.#createTransport(lane, input.cwd, environment, input.skipPermissions);
25198
- lane.transport = transport;
25199
- lane.initialized = false;
25200
- }
25201
- if (!lane.initialized) {
25202
- try {
25203
- await transport.initialize();
25204
- lane.initialized = true;
25205
- } catch (error51) {
25206
- this.#retire(lane, transport);
25207
- throw error51;
25208
- }
25209
- }
25210
- if (this.#closed || transport.isClosed) {
25211
- this.#retire(lane, transport);
25212
- throw new AntigravityTransportError("unavailable", "Snapshot reader is closed");
25213
- }
25214
- if (input.signal?.aborted) {
25215
- throw new AntigravityTransportError("unavailable", "Snapshot read aborted");
25216
- }
25217
- try {
25218
- const { opened, replayedEvents } = await transport.openSession({
25219
- kind: "load",
25220
- sessionId: input.sessionId,
25221
- cwd: input.cwd
25222
- });
25223
- if (opened.sessionId !== input.sessionId) {
25224
- throw new AntigravityTransportError("protocolError", "Snapshot loaded a different Session");
25225
- }
25226
- await transport.closeSession();
25227
- if (this.#closed || transport.isClosed) {
25228
- this.#retire(lane, transport);
25229
- }
25230
- return { opened, replayedEvents };
25231
- } catch (error51) {
25232
- this.#retire(lane, transport);
25233
- throw error51;
25234
- }
25235
- }
25236
- #createTransport(lane, cwd, environment, skipPermissions) {
25237
- const options = {
25238
- cwd,
25239
- ...this.adapterOptions.command ? { command: this.adapterOptions.command } : {},
25240
- environment,
25241
- skipPermissions,
25242
- ...this.adapterOptions.commandTimeoutMs !== void 0 ? { commandTimeoutMs: this.adapterOptions.commandTimeoutMs } : {},
25243
- ...this.adapterOptions.closeTimeoutMs !== void 0 ? { closeTimeoutMs: this.adapterOptions.closeTimeoutMs } : {},
25244
- onFault: () => {
25245
- this.#retire(lane, transport);
25246
- }
25247
- };
25248
- const transport = this.adapterOptions.createTransport?.(options) ?? new AntigravityAcpTransport(options);
25249
- return transport;
25250
- }
25251
- #retire(lane, transport) {
25252
- if (lane.transport === transport) {
25253
- lane.transport = void 0;
25254
- lane.initialized = false;
25255
- }
25256
- if (this.#retired.has(transport))
25257
- return;
25258
- this.#retired.add(transport);
25259
- let raw;
25260
- try {
25261
- raw = transport.close();
25262
- } catch (error51) {
25263
- raw = Promise.reject(error51);
25264
- }
25265
- const tracked = raw.then(() => {
25266
- this.#retiring.delete(tracked);
25267
- });
25268
- this.#retiring.add(tracked);
25269
- void tracked.catch(() => void 0);
25270
- }
25271
- };
25272
-
25273
25661
  // dist/subagent-transcript.js
25274
25662
  import { open as open2, realpath } from "node:fs/promises";
25275
25663
  import path11 from "node:path";
@@ -25622,8 +26010,8 @@ var antigravitySessionCapabilities = {
25622
26010
  function ok(value) {
25623
26011
  return { ok: true, value };
25624
26012
  }
25625
- function err(code, message2, retryable = false) {
25626
- return { ok: false, error: { code, message: message2, retryable } };
26013
+ function err(code, message3, retryable = false) {
26014
+ return { ok: false, error: { code, message: message3, retryable } };
25627
26015
  }
25628
26016
  function normalizeAntigravityError(error51) {
25629
26017
  if (error51 instanceof AntigravityTransportError)
@@ -25633,11 +26021,11 @@ function normalizeAntigravityError(error51) {
25633
26021
  retryable: error51.retryable,
25634
26022
  ...error51.diagnostic ? { diagnostic: sanitizeDiagnosticTail(error51.diagnostic) } : {}
25635
26023
  };
25636
- const message2 = sanitizeDiagnosticTail(error51 instanceof Error ? error51.message : String(error51));
26024
+ const message3 = sanitizeDiagnosticTail(error51 instanceof Error ? error51.message : String(error51));
25637
26025
  const code = error51?.code;
25638
26026
  return {
25639
- code: code === "ENOENT" ? "notInstalled" : /authenticat|sign.?in|login|credential/iu.test(message2) ? "authenticationRequired" : "nativeFailure",
25640
- message: message2,
26027
+ code: code === "ENOENT" ? "notInstalled" : /authenticat|sign.?in|login|credential/iu.test(message3) ? "authenticationRequired" : "nativeFailure",
26028
+ message: message3,
25641
26029
  retryable: false
25642
26030
  };
25643
26031
  }
@@ -25741,6 +26129,9 @@ var AntigravitySession = class {
25741
26129
  #commands = ANTIGRAVITY_COMMAND_CATALOG;
25742
26130
  #turnCount = 0;
25743
26131
  #active;
26132
+ #lastCompletedTurnId;
26133
+ #background;
26134
+ #postPromptBackground = [];
25744
26135
  #pending = /* @__PURE__ */ new Map();
25745
26136
  #usage;
25746
26137
  #usageWork = Promise.resolve();
@@ -25838,7 +26229,7 @@ var AntigravitySession = class {
25838
26229
  return;
25839
26230
  }
25840
26231
  const ref = this.nativeRef ?? this.#options.nativeRef;
25841
- const { opened, replayedEvents } = await transport.openSession({
26232
+ const { opened } = await transport.openSession({
25842
26233
  kind: ref ? "resume" : "create",
25843
26234
  ...ref ? { sessionId: ref.nativeSessionId } : {},
25844
26235
  cwd: this.#options.cwd,
@@ -25853,17 +26244,8 @@ var AntigravitySession = class {
25853
26244
  if (!validNativeSessionRef({ harnessId, nativeSessionId: opened.sessionId, formatVersion: 1 }, harnessId))
25854
26245
  throw new AntigravityTransportError("protocolError", "Antigravity returned an invalid native Session ID");
25855
26246
  this.#applyOpened(opened, skip);
25856
- try {
25857
- this.#turnCount = await readNativeTurnCount(nativeConversationDbPath(opened.sessionId, antigravityHome(this.#options.environment)));
25858
- } catch {
25859
- this.#turnCount = Math.max(this.#turnCount, projectReplayedEventsToTurns({
25860
- nativeSessionId: opened.sessionId,
25861
- cwd: this.#options.cwd,
25862
- events: replayedEvents,
25863
- ...this.#options.knownTurnRefs ? { knownTurnRefs: this.#options.knownTurnRefs } : {}
25864
- }).length);
25865
- }
25866
- this.#initializeUsage(opened.sessionId, replayedEvents);
26247
+ this.#turnCount = await readNativeTurnCount(nativeConversationDbPath(opened.sessionId, antigravityHome(this.#options.environment))).catch(() => this.#turnCount);
26248
+ this.#initializeUsage(opened.sessionId);
25867
26249
  transport.setSessionEventHandler((event) => {
25868
26250
  if (this.#transport === transport && !this.#closed && !this.#faulted)
25869
26251
  this.#sessionEvent(event);
@@ -25893,15 +26275,13 @@ var AntigravitySession = class {
25893
26275
  throw error51;
25894
26276
  }
25895
26277
  }
25896
- #initializeUsage(nativeSessionId, events) {
26278
+ #initializeUsage(nativeSessionId) {
25897
26279
  if (this.#usage)
25898
26280
  return;
25899
- const context = events.findLast((event) => event.type === "usage.context");
25900
26281
  this.#usage = new AntigravitySessionUsageTracker({
25901
26282
  nativeSessionId,
25902
26283
  homedir: antigravityHome(this.#options.environment),
25903
- expectedInitialTurns: this.#turnCount,
25904
- ...context ? { initialContextUsedTokens: context.used, initialContextWindowTokens: context.size } : {}
26284
+ expectedInitialTurns: this.#turnCount
25905
26285
  });
25906
26286
  this.#usageWork = this.#replayUsage();
25907
26287
  }
@@ -26004,6 +26384,10 @@ var AntigravitySession = class {
26004
26384
  this.#applyConfig(confirmed);
26005
26385
  }
26006
26386
  #sessionEvent(event) {
26387
+ if (event.type === "agent.text" || event.type === "agent.thought") {
26388
+ this.#appendBackgroundText(event.type === "agent.text" ? "agentMessage" : "reasoning", event.text);
26389
+ return;
26390
+ }
26007
26391
  switch (event.type) {
26008
26392
  case "config.update":
26009
26393
  this.#applyConfig(event.configOptions);
@@ -26022,7 +26406,7 @@ var AntigravitySession = class {
26022
26406
  const usage = this.#usage?.recordContextWindow(event.used, event.size);
26023
26407
  if (usage)
26024
26408
  this.#emit({ type: "session.usage.changed", usage });
26025
- if (this.#active?.promptSubmitted)
26409
+ if (this.#active?.promptPhase === "submitted")
26026
26410
  void this.refreshUsage();
26027
26411
  break;
26028
26412
  }
@@ -26082,69 +26466,52 @@ var AntigravitySession = class {
26082
26466
  return err("invalidRequest", "Command accepts only a text argument");
26083
26467
  prompt = `${descriptor.invocation}${typeof args.text === "string" && args.text.trim() ? ` ${args.text.trim()}` : ""}`;
26084
26468
  }
26085
- return this.execute({
26469
+ return this.#startTurn({
26086
26470
  type: "turn.start",
26087
26471
  turnId: invocation.turnId,
26088
26472
  input: [{ type: "text", text: prompt }]
26089
- });
26473
+ }, true);
26090
26474
  }
26091
26475
  };
26092
26476
  }
26093
26477
  async readSnapshot() {
26094
26478
  if (this.#closed || this.#faulted)
26095
26479
  return err("invalidState", "Session is closed");
26096
- if (!this.nativeRef)
26480
+ const nativeRef = this.nativeRef;
26481
+ if (!nativeRef)
26097
26482
  return ok({ turns: [], state: { ...this.#state } });
26098
- const skip = this.#transport?.skipPermissions ?? (this.#options.unattended || this.#requested.permissionModeId === SKIP);
26483
+ const { nativeSessionId } = nativeRef;
26099
26484
  try {
26100
- const { opened, replayedEvents } = await this.#options.readerPool.loadSession({
26101
- sessionId: this.nativeRef.nativeSessionId,
26102
- cwd: this.#options.cwd,
26103
- environment: this.#options.environment,
26104
- skipPermissions: skip,
26105
- signal: this.#abort.signal
26106
- });
26485
+ const { events, turnCount } = await readNativeHistory(nativeSessionId, antigravityHome(this.#options.environment));
26107
26486
  if (this.#closed || this.#faulted)
26108
26487
  return err("invalidState", "Session is closed");
26109
26488
  const turns = projectReplayedEventsToTurns({
26110
- nativeSessionId: opened.sessionId,
26489
+ nativeSessionId,
26111
26490
  cwd: this.#options.cwd,
26112
- events: replayedEvents,
26491
+ events,
26113
26492
  ...this.#options.knownTurnRefs ? { knownTurnRefs: this.#options.knownTurnRefs } : {},
26114
26493
  ...this.#options.adapter.toolOutputLimit !== void 0 ? { outputLimit: this.#options.adapter.toolOutputLimit } : {}
26115
26494
  });
26116
- const turnCount = this.#transport ? this.#turnCount : await readNativeTurnCount(nativeConversationDbPath(opened.sessionId, antigravityHome(this.#options.environment))).catch(() => turns.length);
26117
- if (this.#closed || this.#faulted)
26118
- return err("invalidState", "Session is closed");
26119
26495
  if (!this.#transport) {
26120
26496
  this.#turnCount = turnCount;
26121
- this.#initializeUsage(opened.sessionId, replayedEvents);
26497
+ this.#initializeUsage(nativeSessionId);
26122
26498
  }
26123
26499
  return ok({ turns, ...this.#transport ? { state: { ...this.#state } } : {} });
26124
- } catch (error51) {
26500
+ } catch {
26125
26501
  if (this.#closed || this.#faulted)
26126
26502
  return err("invalidState", "Session is closed");
26127
- return { ok: false, error: normalizeAntigravityError(error51) };
26503
+ return err("nativeFailure", "Antigravity history unavailable");
26128
26504
  }
26129
26505
  }
26130
26506
  async execute(command) {
26507
+ if (command.type === "turn.start")
26508
+ return this.#startTurn(command, false);
26131
26509
  if (this.#closed || this.#faulted)
26132
26510
  return err("invalidState", "Session is closed");
26133
26511
  try {
26134
26512
  switch (command.type) {
26135
26513
  case "turn.steer":
26136
26514
  return unsupportedSteer("Antigravity ACP");
26137
- case "turn.start": {
26138
- if (this.#active || this.#configuring || this.#historyOperation)
26139
- return err("sessionBusy", "Session is busy", true);
26140
- if (!command.turnId || !command.input.length || !command.input.some((part) => typeof part.text === "string" && part.text.trim()))
26141
- return err("invalidRequest", "Prompt and Turn ID must not be empty");
26142
- const turn = { turnId: command.turnId, cancelled: false, ended: false };
26143
- this.#active = turn;
26144
- this.#emit({ type: "turn.started", turnId: turn.turnId });
26145
- void this.#runTurn(turn, command);
26146
- return ok({ turnId: command.turnId });
26147
- }
26148
26515
  case "turn.cancel": {
26149
26516
  const turn = this.#active;
26150
26517
  if (!turn || turn.turnId !== command.turnId)
@@ -26153,7 +26520,7 @@ var AntigravitySession = class {
26153
26520
  turn.cancelled = true;
26154
26521
  this.#closeInteractions("cancelled");
26155
26522
  try {
26156
- if (turn.promptSubmitted)
26523
+ if (turn.promptPhase === "submitted")
26157
26524
  await this.#transport?.cancel();
26158
26525
  } catch (error51) {
26159
26526
  this.handleTransportFault(new AntigravityTransportError("unavailable", "Native cancellation could not be confirmed", { cause: error51 }));
@@ -26171,6 +26538,31 @@ var AntigravitySession = class {
26171
26538
  return { ok: false, error: normalizeAntigravityError(error51) };
26172
26539
  }
26173
26540
  }
26541
+ #startTurn(command, catalogCommand) {
26542
+ if (this.#closed || this.#faulted)
26543
+ return err("invalidState", "Session is closed");
26544
+ if (this.#active || this.#configuring || this.#historyOperation)
26545
+ return err("sessionBusy", "Session is busy", true);
26546
+ if (!command.turnId || !command.input.length || !command.input.some((part) => typeof part.text === "string" && part.text.trim()))
26547
+ return err("invalidRequest", "Prompt and Turn ID must not be empty");
26548
+ try {
26549
+ this.#postPromptBackground.length = 0;
26550
+ const turn = {
26551
+ turnId: command.turnId,
26552
+ cancelled: false,
26553
+ ended: false,
26554
+ promptPhase: "notSubmitted"
26555
+ };
26556
+ this.#active = turn;
26557
+ this.#settleBackground({ status: "succeeded" });
26558
+ this.#lastCompletedTurnId = void 0;
26559
+ this.#emit({ type: "turn.started", turnId: turn.turnId });
26560
+ void this.#runTurn(turn, command, catalogCommand);
26561
+ return ok({ turnId: command.turnId });
26562
+ } catch (error51) {
26563
+ return { ok: false, error: normalizeAntigravityError(error51) };
26564
+ }
26565
+ }
26174
26566
  async #select(command) {
26175
26567
  if (this.#configuring || this.#historyOperation)
26176
26568
  return err("sessionBusy", "Configuration or history is changing", true);
@@ -26226,6 +26618,7 @@ var AntigravitySession = class {
26226
26618
  thinkingOptionId: this.#state.effectiveThinkingOptionId,
26227
26619
  permissionModeId: command.permissionModeId
26228
26620
  };
26621
+ this.#settleBackground({ status: "succeeded" });
26229
26622
  old.setSessionEventHandler(null);
26230
26623
  await old.close();
26231
26624
  this.#transport = void 0;
@@ -26253,7 +26646,7 @@ var AntigravitySession = class {
26253
26646
  this.#configuring = false;
26254
26647
  }
26255
26648
  }
26256
- async #runTurn(turn, command) {
26649
+ async #runTurn(turn, command, catalogCommand) {
26257
26650
  let outcome;
26258
26651
  let nativeTurnRef;
26259
26652
  try {
@@ -26284,8 +26677,11 @@ var AntigravitySession = class {
26284
26677
  if (!transport || !ref)
26285
26678
  throw new AntigravityTransportError("unavailable", "Native Session is not connected");
26286
26679
  this.#usage?.beginTurn();
26287
- turn.promptSubmitted = true;
26680
+ turn.promptPhase = "submitted";
26288
26681
  const result = await transport.prompt(promptParts(command), {
26682
+ onResponse: () => {
26683
+ turn.promptPhase = "returned";
26684
+ },
26289
26685
  onEvent: (event) => {
26290
26686
  if (!this.#isCurrent(turn) || turn.cancelled)
26291
26687
  return;
@@ -26309,7 +26705,7 @@ var AntigravitySession = class {
26309
26705
  return this.#question(turn, request);
26310
26706
  }
26311
26707
  });
26312
- turn.promptSubmitted = false;
26708
+ turn.promptPhase = "returned";
26313
26709
  const completedAtMs = Date.now();
26314
26710
  if (!this.#isCurrent(turn))
26315
26711
  return;
@@ -26326,7 +26722,7 @@ var AntigravitySession = class {
26326
26722
  try {
26327
26723
  count4 = await readNativeTurnCount(nativeConversationDbPath(ref.nativeSessionId, antigravityHome(this.#options.environment)));
26328
26724
  } catch {
26329
- count4 = outcome.status === "succeeded" ? before + 1 : before;
26725
+ count4 = !catalogCommand && outcome.status === "succeeded" ? before + 1 : before;
26330
26726
  }
26331
26727
  if (count4 > before) {
26332
26728
  const key = `turn-${count4 - 1}`;
@@ -26412,6 +26808,61 @@ var AntigravitySession = class {
26412
26808
  });
26413
26809
  turn.textItem = void 0;
26414
26810
  }
26811
+ /** Idle Harness output lands on the most recently completed user Turn. */
26812
+ #appendBackgroundText(type, text2) {
26813
+ if (!text2)
26814
+ return;
26815
+ if (this.#active) {
26816
+ if (this.#active.promptPhase === "returned") {
26817
+ if (!this.#active.ended && !this.#active.cancelled && !this.#opening && !this.#configuring && !this.#historyOperation)
26818
+ this.#postPromptBackground.push({ type, text: text2 });
26819
+ return;
26820
+ }
26821
+ return;
26822
+ }
26823
+ if (this.#opening || this.#configuring || this.#historyOperation)
26824
+ return;
26825
+ const turnId = this.#lastCompletedTurnId;
26826
+ if (!turnId) {
26827
+ return;
26828
+ }
26829
+ this.#background ??= { turnId, textItem: void 0 };
26830
+ const episode = this.#background;
26831
+ if (episode.turnId !== turnId || episode.textItem?.type !== type) {
26832
+ this.#settleBackground({ status: "succeeded" });
26833
+ this.#background = { turnId, textItem: void 0 };
26834
+ }
26835
+ const current = this.#background;
26836
+ if (!current.textItem) {
26837
+ current.textItem = { type, itemId: hostItemIdSchema.parse(randomUUID2()), text: "" };
26838
+ this.#emit({
26839
+ type: "item.background.started",
26840
+ turnId,
26841
+ item: { ...current.textItem }
26842
+ });
26843
+ }
26844
+ current.textItem.text += text2;
26845
+ this.#emit({
26846
+ type: "item.updated",
26847
+ turnId,
26848
+ itemId: current.textItem.itemId,
26849
+ update: { type: "text.append", text: text2 }
26850
+ });
26851
+ }
26852
+ /** Close the pending idle-output Item; the emitted content stays real output. */
26853
+ #settleBackground(outcome) {
26854
+ const episode = this.#background;
26855
+ if (!episode?.textItem) {
26856
+ this.#background = void 0;
26857
+ return;
26858
+ }
26859
+ this.#emit({
26860
+ type: "item.completed",
26861
+ turnId: episode.turnId,
26862
+ snapshot: { item: { ...episode.textItem }, outcome }
26863
+ });
26864
+ this.#background = void 0;
26865
+ }
26415
26866
  #finish(turn, outcome, nativeTurnRef) {
26416
26867
  if (!this.#isCurrent(turn))
26417
26868
  return;
@@ -26420,12 +26871,21 @@ var AntigravitySession = class {
26420
26871
  turn.tracker?.finishPending(outcome);
26421
26872
  turn.ended = true;
26422
26873
  this.#active = void 0;
26874
+ if (nativeTurnRef)
26875
+ this.#lastCompletedTurnId = turn.turnId;
26876
+ this.#settleBackground({ status: "succeeded" });
26423
26877
  this.#emit({
26424
26878
  type: "turn.completed",
26425
26879
  turnId: turn.turnId,
26426
26880
  ...nativeTurnRef ? { nativeTurnRef } : outcome.status === "succeeded" ? { ephemeral: true } : {},
26427
26881
  outcome
26428
26882
  });
26883
+ if (outcome.status === "succeeded" && !turn.cancelled && !this.#closed && !this.#faulted) {
26884
+ for (const entry of this.#postPromptBackground.splice(0))
26885
+ this.#appendBackgroundText(entry.type, entry.text);
26886
+ } else {
26887
+ this.#postPromptBackground.length = 0;
26888
+ }
26429
26889
  }
26430
26890
  #permission(turn, request) {
26431
26891
  const ref = this.nativeRef;
@@ -26532,9 +26992,11 @@ var AntigravitySession = class {
26532
26992
  return;
26533
26993
  this.#faulted = true;
26534
26994
  this.#abort.abort();
26995
+ this.#postPromptBackground.length = 0;
26535
26996
  this.#closeInteractions("cancelled");
26536
26997
  if (this.#active)
26537
26998
  this.#finish(this.#active, { status: "failed", error: normalizeAntigravityError(error51) });
26999
+ this.#settleBackground({ status: "succeeded" });
26538
27000
  this.#emit({ type: "session.faulted", error: normalizeAntigravityError(error51) });
26539
27001
  this.#channel.end();
26540
27002
  this.#subagents.stop();
@@ -26549,7 +27011,9 @@ var AntigravitySession = class {
26549
27011
  async #close() {
26550
27012
  this.#closed = true;
26551
27013
  this.#abort.abort();
27014
+ this.#postPromptBackground.length = 0;
26552
27015
  this.#closeInteractions("cancelled");
27016
+ this.#settleBackground({ status: "succeeded" });
26553
27017
  const active = this.#active;
26554
27018
  if (active)
26555
27019
  this.#finish(active, { status: "cancelled", reason: "Session closed" });
@@ -26582,7 +27046,6 @@ var AntigravityAdapter = class {
26582
27046
  usageStatistics;
26583
27047
  #environment;
26584
27048
  #sessions = /* @__PURE__ */ new Set();
26585
- #readerPool;
26586
27049
  #cache = /* @__PURE__ */ new Map();
26587
27050
  #inflight = /* @__PURE__ */ new Map();
26588
27051
  #abort = new AbortController();
@@ -26593,7 +27056,6 @@ var AntigravityAdapter = class {
26593
27056
  constructor(options = {}) {
26594
27057
  this.options = options;
26595
27058
  this.#environment = options.environment ?? process.env;
26596
- this.#readerPool = new AntigravitySnapshotReaderPool(this.options);
26597
27059
  this.sessionImport = new AntigravitySessionImport(this.#environment);
26598
27060
  this.usageStatistics = createAntigravityUsageStatistics(this.#environment);
26599
27061
  }
@@ -26734,7 +27196,6 @@ var AntigravityAdapter = class {
26734
27196
  ...input.kind === "resume" ? { nativeRef: input.nativeRef, knownTurnRefs: input.knownTurnRefs } : {},
26735
27197
  unattended,
26736
27198
  adapter: this.options,
26737
- readerPool: this.#readerPool,
26738
27199
  onClosed: (closed) => this.#sessions.delete(closed)
26739
27200
  });
26740
27201
  this.#sessions.add(session);
@@ -26809,10 +27270,7 @@ var AntigravityAdapter = class {
26809
27270
  this.#cache.clear();
26810
27271
  this.#inflight.clear();
26811
27272
  this.#quota = null;
26812
- await Promise.all([
26813
- ...[...this.#sessions].map((session) => session.close()),
26814
- this.#readerPool.close()
26815
- ]);
27273
+ await Promise.all([...this.#sessions].map((session) => session.close()));
26816
27274
  this.#sessions.clear();
26817
27275
  }
26818
27276
  };