@liberseek/boft-cli-linux-x64 0.7.6 → 0.7.7

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.
@@ -19918,6 +19918,72 @@ var harnessDisplaySetSchema = external_exports.strictObject({
19918
19918
  initializeOnly: external_exports.boolean().optional()
19919
19919
  });
19920
19920
 
19921
+ // packages/shared-contracts/dist/ids.js
19922
+ var opaqueIdSchema = external_exports.string().refine((value2) => value2.trim().length > 0, {
19923
+ message: "Identifier must not be empty or whitespace"
19924
+ });
19925
+ var harnessIdSchema = opaqueIdSchema.brand();
19926
+ var hostThreadIdSchema = opaqueIdSchema.brand();
19927
+ var hostTurnIdSchema = opaqueIdSchema.brand();
19928
+ var hostItemIdSchema = opaqueIdSchema.brand();
19929
+ var hostInteractionIdSchema = opaqueIdSchema.brand();
19930
+
19931
+ // packages/shared-contracts/dist/harness-plugins.js
19932
+ var HARNESS_PLUGIN_API_VERSION = 1;
19933
+ var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
19934
+ var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
19935
+ var HARNESS_PLUGIN_LIMIT = 128;
19936
+ var harnessPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u).refine((id2) => id2 !== "codex", "The official Codex identity is reserved").pipe(harnessIdSchema);
19937
+ var relativeResourceSchema = external_exports.string().min(1).max(512).refine((value2) => !/[\\\u0000:#?]/u.test(value2) && !value2.startsWith("/") && !value2.split("/").some((part) => part === ".." || part === ""), "Plugin resources must be relative paths inside the plugin");
19938
+ var documentationUrlSchema = external_exports.url().refine((value2) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value2), "Plugin documentation links must be credential-free HTTPS URLs");
19939
+ var pluginPresentationShape = {
19940
+ id: harnessPluginIdSchema,
19941
+ name: external_exports.string().trim().min(1).max(128),
19942
+ version: external_exports.string().min(1).max(128),
19943
+ /** The factory accepts a persisted local entrypoint through its construction context. */
19944
+ launchCommand: external_exports.literal(true).optional(),
19945
+ links: external_exports.object({
19946
+ documentation: documentationUrlSchema.optional(),
19947
+ installation: documentationUrlSchema.optional()
19948
+ }).strict().optional()
19949
+ };
19950
+ var harnessPluginManifestSchema = external_exports.object({
19951
+ manifestVersion: external_exports.literal(1),
19952
+ ...pluginPresentationShape,
19953
+ adapterApiVersion: external_exports.number().int().positive(),
19954
+ entry: relativeResourceSchema,
19955
+ icon: relativeResourceSchema.optional()
19956
+ }).strict();
19957
+ 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);
19958
+ var harnessPluginDescriptorSchema = external_exports.object({
19959
+ ...pluginPresentationShape,
19960
+ icon: harnessPluginIconSchema.optional()
19961
+ }).strict();
19962
+ var harnessPluginListParamsSchema = external_exports.object({}).strict();
19963
+ var harnessPluginListResultSchema = external_exports.object({
19964
+ plugins: external_exports.array(harnessPluginDescriptorSchema).max(HARNESS_PLUGIN_LIMIT)
19965
+ }).strict();
19966
+ var harnessPluginConfigurationSchema = external_exports.object({
19967
+ version: external_exports.literal(1),
19968
+ enabled: external_exports.array(harnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
19969
+ }).strict().refine((value2) => new Set(value2.enabled).size === value2.enabled.length, {
19970
+ message: "Enabled plugin IDs must be unique",
19971
+ path: ["enabled"]
19972
+ });
19973
+
19974
+ // packages/shared-contracts/dist/harness-long-context.js
19975
+ var HARNESS_LONG_CONTEXT_GET_METHOD = "codexhost/harness/long-context/get";
19976
+ var HARNESS_LONG_CONTEXT_SET_METHOD = "codexhost/harness/long-context/set";
19977
+ var harnessLongContextGetSchema = external_exports.object({
19978
+ harnessId: harnessPluginIdSchema
19979
+ }).strict();
19980
+ var harnessLongContextSetSchema = harnessLongContextGetSchema.extend({
19981
+ enabled: external_exports.boolean()
19982
+ });
19983
+ var harnessLongContextSchema = external_exports.object({
19984
+ enabled: external_exports.boolean()
19985
+ }).strict();
19986
+
19921
19987
  // packages/shared-contracts/dist/console.js
19922
19988
  var consoleAnnouncementSchema = external_exports.strictObject({
19923
19989
  title: external_exports.string().trim().min(1).max(200),
@@ -19935,8 +20001,11 @@ var CONSOLE_HOST_METHODS = Object.freeze([
19935
20001
  "codexhost/harness/display-settings/get",
19936
20002
  "codexhost/harness/display-settings/set",
19937
20003
  "codexhost/harness/inspect",
20004
+ "codexhost/harness/installation",
19938
20005
  "codexhost/harness/launch-settings/get",
19939
20006
  "codexhost/harness/launch-settings/set",
20007
+ HARNESS_LONG_CONTEXT_GET_METHOD,
20008
+ HARNESS_LONG_CONTEXT_SET_METHOD,
19940
20009
  "codexhost/harness/web-ui/open",
19941
20010
  "codexhost/harness/accounts/sources",
19942
20011
  "codexhost/harness/accounts/list",
@@ -20001,16 +20070,6 @@ var loadedSessionsSchema = external_exports.array(external_exports.strictObject(
20001
20070
  inactiveMs: external_exports.number().nonnegative()
20002
20071
  }));
20003
20072
 
20004
- // packages/shared-contracts/dist/ids.js
20005
- var opaqueIdSchema = external_exports.string().refine((value2) => value2.trim().length > 0, {
20006
- message: "Identifier must not be empty or whitespace"
20007
- });
20008
- var harnessIdSchema = opaqueIdSchema.brand();
20009
- var hostThreadIdSchema = opaqueIdSchema.brand();
20010
- var hostTurnIdSchema = opaqueIdSchema.brand();
20011
- var hostItemIdSchema = opaqueIdSchema.brand();
20012
- var hostInteractionIdSchema = opaqueIdSchema.brand();
20013
-
20014
20073
  // packages/shared-contracts/dist/manual-compaction.js
20015
20074
  var THREAD_MANUAL_COMPACTION_STARTED_METHOD = "codexhost/thread/manual-compaction/started";
20016
20075
  var threadManualCompactionStartedSchema = external_exports.strictObject({
@@ -20550,49 +20609,6 @@ var threadOwnershipListResultSchema = external_exports.object({
20550
20609
  }
20551
20610
  });
20552
20611
 
20553
- // packages/shared-contracts/dist/harness-plugins.js
20554
- var HARNESS_PLUGIN_API_VERSION = 1;
20555
- var HARNESS_PLUGIN_MANIFEST_MAX_BYTES = 32 * 1024;
20556
- var HARNESS_PLUGIN_ICON_MAX_BYTES = 128 * 1024;
20557
- var HARNESS_PLUGIN_LIMIT = 128;
20558
- var harnessPluginIdSchema = external_exports.string().min(1).max(128).regex(/^[a-z][a-z0-9]*(?:[._-][a-z0-9]+)*$/u).refine((id2) => id2 !== "codex", "The official Codex identity is reserved").pipe(harnessIdSchema);
20559
- var relativeResourceSchema = external_exports.string().min(1).max(512).refine((value2) => !/[\\\u0000:#?]/u.test(value2) && !value2.startsWith("/") && !value2.split("/").some((part) => part === ".." || part === ""), "Plugin resources must be relative paths inside the plugin");
20560
- var documentationUrlSchema = external_exports.url().refine((value2) => /^https:\/\/[^/?#@]+(?:[/?#]|$)/iu.test(value2), "Plugin documentation links must be credential-free HTTPS URLs");
20561
- var pluginPresentationShape = {
20562
- id: harnessPluginIdSchema,
20563
- name: external_exports.string().trim().min(1).max(128),
20564
- version: external_exports.string().min(1).max(128),
20565
- /** The factory accepts a persisted local entrypoint through its construction context. */
20566
- launchCommand: external_exports.literal(true).optional(),
20567
- links: external_exports.object({
20568
- documentation: documentationUrlSchema.optional(),
20569
- installation: documentationUrlSchema.optional()
20570
- }).strict().optional()
20571
- };
20572
- var harnessPluginManifestSchema = external_exports.object({
20573
- manifestVersion: external_exports.literal(1),
20574
- ...pluginPresentationShape,
20575
- adapterApiVersion: external_exports.number().int().positive(),
20576
- entry: relativeResourceSchema,
20577
- icon: relativeResourceSchema.optional()
20578
- }).strict();
20579
- 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);
20580
- var harnessPluginDescriptorSchema = external_exports.object({
20581
- ...pluginPresentationShape,
20582
- icon: harnessPluginIconSchema.optional()
20583
- }).strict();
20584
- var harnessPluginListParamsSchema = external_exports.object({}).strict();
20585
- var harnessPluginListResultSchema = external_exports.object({
20586
- plugins: external_exports.array(harnessPluginDescriptorSchema).max(HARNESS_PLUGIN_LIMIT)
20587
- }).strict();
20588
- var harnessPluginConfigurationSchema = external_exports.object({
20589
- version: external_exports.literal(1),
20590
- enabled: external_exports.array(harnessPluginIdSchema).max(HARNESS_PLUGIN_LIMIT)
20591
- }).strict().refine((value2) => new Set(value2.enabled).size === value2.enabled.length, {
20592
- message: "Enabled plugin IDs must be unique",
20593
- path: ["enabled"]
20594
- });
20595
-
20596
20612
  // packages/shared-contracts/dist/harness-route.js
20597
20613
  var HARNESS_PLUGIN_ROUTE_PREFIX = "codexhost/plugin-v1@";
20598
20614
  var MAX_ROUTE_LENGTH = 4096;
@@ -20644,7 +20660,7 @@ var harnessLaunchSettingsSchema = external_exports.object({
20644
20660
  var HARNESS_INSTALLATION_METHOD = "codexhost/harness/installation";
20645
20661
  var harnessInstallationParamsSchema = external_exports.object({
20646
20662
  harnessId: harnessIdSchema,
20647
- action: external_exports.enum(["check", "update"])
20663
+ action: external_exports.enum(["check", "update", "install"])
20648
20664
  }).strict();
20649
20665
  var harnessInstallationStateSchema = external_exports.object({
20650
20666
  currentVersion: external_exports.string().min(1).max(128),
@@ -21207,6 +21223,7 @@ var HarnessInstallationError = class extends Error {
21207
21223
  }
21208
21224
  code;
21209
21225
  };
21226
+ var installing = /* @__PURE__ */ new WeakMap();
21210
21227
  async function handleHarnessInstallation(params, adapters) {
21211
21228
  const parsed = harnessInstallationParamsSchema.safeParse(params);
21212
21229
  if (!parsed.success)
@@ -21217,16 +21234,74 @@ async function handleHarnessInstallation(params, adapters) {
21217
21234
  -32078,
21218
21235
  "Harness version management is unavailable on this Host"
21219
21236
  );
21237
+ const install = adapter.install?.bind(adapter);
21238
+ const installation = adapter.installation.bind(adapter);
21239
+ if (parsed.data.action === "install" && !install)
21240
+ throw new HarnessInstallationError(
21241
+ -32078,
21242
+ "Automatic installation is unavailable on this Host. Use the official installation guide."
21243
+ );
21220
21244
  try {
21245
+ const pending = installing.get(adapter);
21246
+ if (pending) return await pending;
21247
+ if (parsed.data.action === "install") {
21248
+ const operation = (async () => {
21249
+ const inspection = await adapter.inspect({ refresh: true });
21250
+ if (inspection.status !== "notInstalled")
21251
+ throw new Error("Harness is already installed or its state is uncertain");
21252
+ if (!install) throw new Error("Installation capability unavailable");
21253
+ await install();
21254
+ return harnessInstallationStateSchema.parse(await installation("check"));
21255
+ })();
21256
+ installing.set(adapter, operation);
21257
+ try {
21258
+ return await operation;
21259
+ } finally {
21260
+ installing.delete(adapter);
21261
+ }
21262
+ }
21221
21263
  return harnessInstallationStateSchema.parse(await adapter.installation(parsed.data.action));
21222
21264
  } catch {
21223
21265
  throw new HarnessInstallationError(
21224
21266
  -32077,
21225
- parsed.data.action === "update" ? "Harness update failed or its new version could not be confirmed. Check the native installation and check for updates again." : "Could not check Harness versions. Check the native installation and retry."
21267
+ parsed.data.action === "install" ? "Harness installation failed or its CLI version could not be confirmed. Check network access, prerequisites and installation permissions in the official guide, then diagnose the connection before retrying." : parsed.data.action === "update" ? "Harness update failed or its new version could not be confirmed. Check the native installation and check for updates again." : "Could not check Harness versions. Check the native installation and retry."
21226
21268
  );
21227
21269
  }
21228
21270
  }
21229
21271
 
21272
+ // packages/host-runtime/src/harness-long-context.ts
21273
+ var HarnessLongContextError = class extends Error {
21274
+ constructor(code, message) {
21275
+ super(message);
21276
+ this.code = code;
21277
+ this.name = "HarnessLongContextError";
21278
+ }
21279
+ code;
21280
+ };
21281
+ async function handleHarnessLongContext(method, params, adapters) {
21282
+ try {
21283
+ if (method === HARNESS_LONG_CONTEXT_SET_METHOD) {
21284
+ const parsed2 = harnessLongContextSetSchema.safeParse(params);
21285
+ if (!parsed2.success) throw new HarnessLongContextError(-32602, "Invalid 1M context request");
21286
+ const adapter2 = adapters.get(parsed2.data.harnessId);
21287
+ if (!adapter2?.setLongContext) {
21288
+ throw new HarnessLongContextError(-32078, "1M context is unavailable for this Harness");
21289
+ }
21290
+ return harnessLongContextSchema.parse(await adapter2.setLongContext(parsed2.data.enabled));
21291
+ }
21292
+ const parsed = harnessLongContextGetSchema.safeParse(params);
21293
+ if (!parsed.success) throw new HarnessLongContextError(-32602, "Invalid 1M context request");
21294
+ const adapter = adapters.get(parsed.data.harnessId);
21295
+ if (!adapter?.getLongContext) {
21296
+ throw new HarnessLongContextError(-32078, "1M context is unavailable for this Harness");
21297
+ }
21298
+ return harnessLongContextSchema.parse(await adapter.getLongContext());
21299
+ } catch (error51) {
21300
+ if (error51 instanceof HarnessLongContextError) throw error51;
21301
+ throw new HarnessLongContextError(-32077, "Could not read or save the 1M context setting");
21302
+ }
21303
+ }
21304
+
21230
21305
  // packages/host-runtime/src/account/codex-credential-export.ts
21231
21306
  import { createHash as createHash2 } from "node:crypto";
21232
21307
  import { readFile as readFile5 } from "node:fs/promises";
@@ -21856,7 +21931,12 @@ var storedTurnMappingV1Schema = external_exports.object({
21856
21931
  nativeTurnRef: nativeTurnRefSchema,
21857
21932
  nativeCheckpointRef: nativeCheckpointRefSchema.optional()
21858
21933
  }).strict();
21859
- var storedThreadRecordV1Schema = external_exports.object({
21934
+ var storedGitInfoV1Schema = external_exports.object({
21935
+ branch: nonBlankTextSchema6.max(4096).optional(),
21936
+ originUrl: nonBlankTextSchema6.max(16384).optional(),
21937
+ sha: nonBlankTextSchema6.max(1024).optional()
21938
+ }).strict();
21939
+ var storedThreadCoreV1Shape = {
21860
21940
  formatVersion: external_exports.literal(1),
21861
21941
  revision: external_exports.number().int().positive(),
21862
21942
  hostThreadId: storedHostThreadIdSchema,
@@ -21884,7 +21964,19 @@ var storedThreadRecordV1Schema = external_exports.object({
21884
21964
  turnMappings: external_exports.array(storedTurnMappingV1Schema),
21885
21965
  createdAt: isoDateSchema,
21886
21966
  updatedAt: isoDateSchema
21887
- }).strict().superRefine((record4, context) => {
21967
+ };
21968
+ var storedThreadMetadataFieldsShape = {
21969
+ projectId: nonBlankTextSchema6.max(1024).optional(),
21970
+ daybreakEnabled: external_exports.boolean().optional(),
21971
+ gitInfo: storedGitInfoV1Schema.optional()
21972
+ };
21973
+ var THREAD_METADATA_FIELDS = ["projectId", "daybreakEnabled", "gitInfo"];
21974
+ var storedThreadMetadataV1Schema = external_exports.object({
21975
+ formatVersion: external_exports.literal(1),
21976
+ hostThreadId: storedHostThreadIdSchema,
21977
+ ...storedThreadMetadataFieldsShape
21978
+ }).strict();
21979
+ function refineThreadRecord(record4, context) {
21888
21980
  if (record4.state === "ready" && !record4.nativeSessionRef) {
21889
21981
  context.addIssue({
21890
21982
  code: "custom",
@@ -21941,7 +22033,9 @@ var storedThreadRecordV1Schema = external_exports.object({
21941
22033
  }
21942
22034
  }
21943
22035
  }
21944
- });
22036
+ }
22037
+ var storedThreadCoreV1Schema = external_exports.object(storedThreadCoreV1Shape).strict().superRefine(refineThreadRecord);
22038
+ var storedThreadRecordV1Schema = external_exports.object({ ...storedThreadCoreV1Shape, ...storedThreadMetadataFieldsShape }).strict().superRefine(refineThreadRecord);
21945
22039
  var delegationStatusSchema = external_exports.enum([
21946
22040
  "creating",
21947
22041
  "running",
@@ -22060,6 +22154,83 @@ function nativeTurnKey(mapping) {
22060
22154
  function sameJson(left, right) {
22061
22155
  return JSON.stringify(left) === JSON.stringify(right);
22062
22156
  }
22157
+ function withoutUrlCredentials(value2) {
22158
+ let url2;
22159
+ try {
22160
+ url2 = new URL(value2);
22161
+ } catch {
22162
+ return withoutUnparsedUrlCredentials(value2);
22163
+ }
22164
+ if (!url2.host)
22165
+ return withoutUnparsedUrlCredentials(value2);
22166
+ const keepUser = url2.protocol === "ssh:" || url2.protocol === "git+ssh:";
22167
+ if (!url2.password && (keepUser || !url2.username))
22168
+ return value2;
22169
+ url2.password = "";
22170
+ if (!keepUser)
22171
+ url2.username = "";
22172
+ return url2.toString();
22173
+ }
22174
+ function withoutUnparsedUrlCredentials(value2) {
22175
+ const scheme = /^([a-z][a-z0-9+.-]*):\/\//i.exec(value2);
22176
+ const authorityStart = scheme ? scheme[0].length : 0;
22177
+ const authorityEnd = value2.slice(authorityStart).search(scheme ? /[/?#]/ : /\//);
22178
+ const authority = authorityEnd === -1 ? value2.slice(authorityStart) : value2.slice(authorityStart, authorityStart + authorityEnd);
22179
+ const at = scheme ? authority.lastIndexOf("@") : authority.indexOf("@");
22180
+ if (at === -1)
22181
+ return value2;
22182
+ const userInfo = authority.slice(0, at);
22183
+ const protocol = scheme?.[1]?.toLowerCase();
22184
+ const keepUser = scheme ? protocol === "ssh" || protocol === "git+ssh" : true;
22185
+ const kept = keepUser && !userInfo.includes(":") ? `${userInfo}@` : "";
22186
+ return value2.slice(0, authorityStart) + kept + value2.slice(authorityStart + at + 1);
22187
+ }
22188
+ function threadMetadataOf(record4) {
22189
+ const fields = Object.fromEntries(THREAD_METADATA_FIELDS.filter((name) => record4[name] !== void 0).map((name) => [
22190
+ name,
22191
+ record4[name]
22192
+ ]));
22193
+ if (Object.keys(fields).length === 0)
22194
+ return null;
22195
+ return { formatVersion: 1, hostThreadId: record4.hostThreadId, ...fields };
22196
+ }
22197
+ function withoutThreadMetadata(record4) {
22198
+ const { projectId, daybreakEnabled, gitInfo, ...core } = record4;
22199
+ void [projectId, daybreakEnabled, gitInfo];
22200
+ return core;
22201
+ }
22202
+ function withThreadMetadata(record4, metadata) {
22203
+ const core = withoutThreadMetadata(record4);
22204
+ for (const name of THREAD_METADATA_FIELDS) {
22205
+ if (metadata[name] !== void 0)
22206
+ Object.assign(core, { [name]: metadata[name] });
22207
+ }
22208
+ return core;
22209
+ }
22210
+ function applyThreadMetadataPatch(current, patch) {
22211
+ const next = { ...current };
22212
+ if (patch.projectId !== void 0) {
22213
+ if (patch.projectId === null)
22214
+ delete next.projectId;
22215
+ else
22216
+ next.projectId = patch.projectId;
22217
+ }
22218
+ if (patch.daybreakEnabled !== void 0)
22219
+ next.daybreakEnabled = patch.daybreakEnabled;
22220
+ if (patch.gitInfo !== void 0) {
22221
+ const gitInfo = {};
22222
+ for (const name of ["branch", "originUrl", "sha"]) {
22223
+ const value2 = patch.gitInfo[name] === void 0 ? current.gitInfo?.[name] : patch.gitInfo[name];
22224
+ if (value2)
22225
+ gitInfo[name] = name === "originUrl" ? withoutUrlCredentials(value2) : value2;
22226
+ }
22227
+ if (Object.keys(gitInfo).length === 0)
22228
+ delete next.gitInfo;
22229
+ else
22230
+ next.gitInfo = gitInfo;
22231
+ }
22232
+ return next;
22233
+ }
22063
22234
  function systemErrorCode2(error51) {
22064
22235
  return typeof error51 === "object" && error51 !== null && "code" in error51 ? String(error51.code) : null;
22065
22236
  }
@@ -22159,6 +22330,7 @@ var MappingStore = class {
22159
22330
  #directory;
22160
22331
  #instanceId;
22161
22332
  #lockPath;
22333
+ #metadataDirectory;
22162
22334
  #now;
22163
22335
  #quarantineDirectory;
22164
22336
  #sectionsDirectory;
@@ -22183,6 +22355,7 @@ var MappingStore = class {
22183
22355
  this.#backupsDirectory = path11.join(this.#directory, "backups");
22184
22356
  this.#quarantineDirectory = path11.join(this.#directory, "quarantine");
22185
22357
  this.#sectionsDirectory = path11.join(this.#directory, "sections");
22358
+ this.#metadataDirectory = path11.join(this.#directory, "thread-metadata");
22186
22359
  this.#lockPath = path11.join(this.#directory, "store.lock");
22187
22360
  this.#instanceId = options2.instanceId ?? randomUUID6();
22188
22361
  this.#now = options2.now ?? (() => /* @__PURE__ */ new Date());
@@ -22196,7 +22369,8 @@ var MappingStore = class {
22196
22369
  mkdir6(this.#delegationsDirectory, { recursive: true }),
22197
22370
  mkdir6(this.#backupsDirectory, { recursive: true }),
22198
22371
  mkdir6(this.#quarantineDirectory, { recursive: true }),
22199
- mkdir6(this.#sectionsDirectory, { recursive: true })
22372
+ mkdir6(this.#sectionsDirectory, { recursive: true }),
22373
+ mkdir6(this.#metadataDirectory, { recursive: true })
22200
22374
  ]);
22201
22375
  await this.#acquireLock();
22202
22376
  try {
@@ -22223,10 +22397,19 @@ var MappingStore = class {
22223
22397
  if (record4.state === "creating" && !record4.nativeSessionRef) {
22224
22398
  await rm7(primary, { force: true });
22225
22399
  await rm7(backup, { force: true });
22400
+ await rm7(this.#metadataPath(record4.hostThreadId), { force: true });
22226
22401
  continue;
22227
22402
  }
22403
+ const metadata = await this.#readMetadata(record4.hostThreadId);
22404
+ if (metadata) {
22405
+ record4 = withThreadMetadata(record4, metadata);
22406
+ } else if (threadMetadataOf(record4)) {
22407
+ await this.#writeMetadataFile(record4.hostThreadId, threadMetadataOf(record4));
22408
+ await this.#replaceFile(primary, record4, false);
22409
+ }
22228
22410
  this.#records.set(record4.hostThreadId, record4);
22229
22411
  }
22412
+ await Promise.all((await readdir3(this.#metadataDirectory)).filter((name) => name.endsWith(".json") && !this.#records.has(name.slice(0, -5))).map((name) => rm7(path11.join(this.#metadataDirectory, name), { force: true })));
22230
22413
  const delegationNames = (await readdir3(this.#delegationsDirectory)).filter((name) => name.endsWith(".json"));
22231
22414
  for (const name of delegationNames) {
22232
22415
  const file2 = path11.join(this.#delegationsDirectory, name);
@@ -22504,6 +22687,19 @@ var MappingStore = class {
22504
22687
  async setPinned(hostThreadId, isPinned) {
22505
22688
  return this.#update(hostThreadId, (current) => current.isPinned === isPinned ? null : { ...current, isPinned });
22506
22689
  }
22690
+ /**
22691
+ * Patch Desktop metadata. With `ifProjectId`, the patch applies only while the
22692
+ * stored assignment still equals it; otherwise the current record is returned.
22693
+ */
22694
+ async updateMetadata(hostThreadId, patch, options2 = {}) {
22695
+ return this.#update(hostThreadId, (current) => {
22696
+ if (options2.ifProjectId !== void 0 && current.projectId !== options2.ifProjectId) {
22697
+ return null;
22698
+ }
22699
+ const next = applyThreadMetadataPatch(current, patch);
22700
+ return sameJson(next, current) ? null : next;
22701
+ });
22702
+ }
22507
22703
  /** Section placements of stored External Threads, in insertion order. */
22508
22704
  async listSectionPlacements() {
22509
22705
  this.#requireInitialized();
@@ -22558,7 +22754,8 @@ var MappingStore = class {
22558
22754
  return;
22559
22755
  await Promise.all([
22560
22756
  rm7(this.#recordPath(hostThreadId), { force: true }),
22561
- rm7(this.#backupPath(hostThreadId), { force: true })
22757
+ rm7(this.#backupPath(hostThreadId), { force: true }),
22758
+ rm7(this.#metadataPath(hostThreadId), { force: true })
22562
22759
  ]);
22563
22760
  this.#records.delete(hostThreadId);
22564
22761
  this.#rebuildIndexes();
@@ -22596,6 +22793,15 @@ var MappingStore = class {
22596
22793
  });
22597
22794
  this.#validateGlobal(next, hostThreadId);
22598
22795
  await this.#replaceFile(this.#recordPath(hostThreadId), next, true);
22796
+ const metadata = threadMetadataOf(next);
22797
+ if (!sameJson(threadMetadataOf(current), metadata)) {
22798
+ try {
22799
+ await this.#writeMetadataFile(hostThreadId, metadata);
22800
+ } catch (error51) {
22801
+ await this.#replaceFile(this.#recordPath(hostThreadId), current, false).catch(() => void 0);
22802
+ throw error51;
22803
+ }
22804
+ }
22599
22805
  this.#records.set(hostThreadId, next);
22600
22806
  this.#rebuildIndexes();
22601
22807
  result = cloneRecord(next);
@@ -22645,7 +22851,7 @@ var MappingStore = class {
22645
22851
  try {
22646
22852
  await this.#beforeReplace?.(cloneRecord(record4));
22647
22853
  handle = await open6(temp, "wx", constants2.S_IRUSR | constants2.S_IWUSR);
22648
- await handle.writeFile(`${JSON.stringify(record4, null, 2)}
22854
+ await handle.writeFile(`${JSON.stringify(withoutThreadMetadata(record4), null, 2)}
22649
22855
  `, "utf8");
22650
22856
  await handle.sync();
22651
22857
  await handle.close();
@@ -22664,6 +22870,52 @@ var MappingStore = class {
22664
22870
  });
22665
22871
  }
22666
22872
  }
22873
+ /** Atomically writes, or with null removes, a Thread's Desktop metadata file. */
22874
+ async #writeMetadataFile(hostThreadId, metadata) {
22875
+ const target = this.#metadataPath(hostThreadId);
22876
+ const temp = `${target}.tmp-${randomUUID6()}`;
22877
+ let handle = null;
22878
+ try {
22879
+ if (!metadata) {
22880
+ await rm7(target, { force: true });
22881
+ return;
22882
+ }
22883
+ handle = await open6(temp, "wx", constants2.S_IRUSR | constants2.S_IWUSR);
22884
+ await handle.writeFile(`${JSON.stringify(metadata, null, 2)}
22885
+ `, "utf8");
22886
+ await handle.sync();
22887
+ await handle.close();
22888
+ handle = null;
22889
+ await rename6(temp, target);
22890
+ } catch (error51) {
22891
+ await handle?.close().catch(() => void 0);
22892
+ await rm7(temp, { force: true }).catch(() => void 0);
22893
+ throw new MappingStoreError("IO_ERROR", "Thread metadata atomic replacement failed", {
22894
+ cause: error51
22895
+ });
22896
+ }
22897
+ }
22898
+ /** Reads a Thread's metadata file; an invalid file is quarantined rather than blocking the Thread. */
22899
+ async #readMetadata(hostThreadId) {
22900
+ const file2 = this.#metadataPath(hostThreadId);
22901
+ let text2;
22902
+ try {
22903
+ text2 = await readFile9(file2, "utf8");
22904
+ } catch (error51) {
22905
+ if (systemErrorCode2(error51) === "ENOENT")
22906
+ return null;
22907
+ throw error51;
22908
+ }
22909
+ try {
22910
+ const parsed = storedThreadMetadataV1Schema.parse(JSON.parse(text2));
22911
+ if (parsed.hostThreadId !== hostThreadId)
22912
+ throw new Error("Thread ID mismatch");
22913
+ return parsed;
22914
+ } catch {
22915
+ await rename6(file2, path11.join(this.#quarantineDirectory, `${hostThreadId}.json.${this.#now().getTime()}.invalid-metadata`)).catch(() => void 0);
22916
+ return null;
22917
+ }
22918
+ }
22667
22919
  async #replaceDelegationFile(record4) {
22668
22920
  const target = this.#delegationPath(record4.delegationId);
22669
22921
  const temp = `${target}.tmp-${randomUUID6()}`;
@@ -22699,16 +22951,18 @@ var MappingStore = class {
22699
22951
  return parsed.data;
22700
22952
  }
22701
22953
  async #cleanupResidue() {
22702
- const [threadNames, delegationNames, sectionNames, rootNames] = await Promise.all([
22954
+ const [threadNames, delegationNames, sectionNames, rootNames, metadataNames] = await Promise.all([
22703
22955
  readdir3(this.#threadsDirectory),
22704
22956
  readdir3(this.#delegationsDirectory),
22705
22957
  readdir3(this.#sectionsDirectory),
22706
- readdir3(this.#directory)
22958
+ readdir3(this.#directory),
22959
+ readdir3(this.#metadataDirectory)
22707
22960
  ]);
22708
22961
  await Promise.all([
22709
22962
  ...threadNames.filter((name) => name.includes(".tmp-")).map((name) => rm7(path11.join(this.#threadsDirectory, name), { force: true })),
22710
22963
  ...delegationNames.filter((name) => name.includes(".tmp-")).map((name) => rm7(path11.join(this.#delegationsDirectory, name), { force: true })),
22711
22964
  ...sectionNames.filter((name) => name.includes(".tmp-")).map((name) => rm7(path11.join(this.#sectionsDirectory, name), { force: true })),
22965
+ ...metadataNames.filter((name) => name.includes(".tmp-")).map((name) => rm7(path11.join(this.#metadataDirectory, name), { force: true })),
22712
22966
  // Renamed aside by #acquireLock; nothing reads them back, and they accumulate one per run.
22713
22967
  ...rootNames.filter((name) => name.startsWith(`${path11.basename(this.#lockPath)}.stale-`)).map((name) => rm7(path11.join(this.#directory, name), { force: true }))
22714
22968
  ]);
@@ -22819,6 +23073,9 @@ var MappingStore = class {
22819
23073
  get #sectionPlacementsPath() {
22820
23074
  return path11.join(this.#sectionsDirectory, "placements.json");
22821
23075
  }
23076
+ #metadataPath(hostThreadId) {
23077
+ return path11.join(this.#metadataDirectory, `${hostThreadId}.json`);
23078
+ }
22822
23079
  #backupPath(hostThreadId) {
22823
23080
  return path11.join(this.#backupsDirectory, `${hostThreadId}.json`);
22824
23081
  }
@@ -25389,6 +25646,7 @@ var THREAD_LIST_FIELDS = /* @__PURE__ */ new Set([
25389
25646
  "limit",
25390
25647
  "modelProviders",
25391
25648
  "parentThreadId",
25649
+ "projectId",
25392
25650
  "searchTerm",
25393
25651
  "sectionId",
25394
25652
  "sortDirection",
@@ -25545,6 +25803,7 @@ function decodeThreadListRequest(request) {
25545
25803
  if (parentThreadId !== null && ancestorThreadId !== null) {
25546
25804
  throw new Error("thread/list cannot combine parentThreadId and ancestorThreadId");
25547
25805
  }
25806
+ const projectId = params.projectId === void 0 ? void 0 : nullableText(params.projectId, "thread/list params.projectId");
25548
25807
  const searchTerm = nullableText(params.searchTerm, "thread/list params.searchTerm");
25549
25808
  const sectionId = params.sectionId === void 0 ? void 0 : nullableText(params.sectionId, "thread/list params.sectionId");
25550
25809
  const sortKey = decodeSortKey(params.sortKey);
@@ -25563,6 +25822,7 @@ function decodeThreadListRequest(request) {
25563
25822
  isPinned,
25564
25823
  modelProviders,
25565
25824
  parentThreadId,
25825
+ ...projectId === void 0 ? {} : { projectId },
25566
25826
  searchTerm,
25567
25827
  ...sectionId === void 0 ? {} : { sectionId },
25568
25828
  ...sortKey === "section_position" ? { sortDirection: sortDirection2 } : {},
@@ -25595,6 +25855,7 @@ function decodeThreadListRequest(request) {
25595
25855
  modelProviders,
25596
25856
  parentThreadId,
25597
25857
  ancestorThreadId,
25858
+ projectId,
25598
25859
  searchTerm,
25599
25860
  sectionId,
25600
25861
  sortDirection: sortDirection2,
@@ -25651,6 +25912,21 @@ function decodeThreadArchiveRequest(request) {
25651
25912
  }
25652
25913
  return { threadId: params.threadId };
25653
25914
  }
25915
+ var THREAD_METADATA_UPDATE_FIELDS = /* @__PURE__ */ new Set([
25916
+ "threadId",
25917
+ "projectId",
25918
+ "daybreakEnabled",
25919
+ "gitInfo"
25920
+ ]);
25921
+ var GIT_INFO_FIELDS = /* @__PURE__ */ new Set(["branch", "originUrl", "sha"]);
25922
+ function nonBlankTextOrNull(value2, name) {
25923
+ if (value2 === null)
25924
+ return null;
25925
+ if (typeof value2 !== "string" || value2.trim().length === 0) {
25926
+ throw new Error(`${name} must be non-empty text or null`);
25927
+ }
25928
+ return value2;
25929
+ }
25654
25930
  function decodeThreadMetadataUpdateRequest(request) {
25655
25931
  if (request.method !== "thread/metadata/update")
25656
25932
  return null;
@@ -25658,31 +25934,48 @@ function decodeThreadMetadataUpdateRequest(request) {
25658
25934
  if (typeof params.threadId !== "string" || params.threadId.length === 0) {
25659
25935
  throw new Error("thread/metadata/update params.threadId must be non-empty text");
25660
25936
  }
25661
- const isPinned = nullableBoolean(params.isPinned, "thread/metadata/update params.isPinned");
25662
- let gitInfo;
25663
- if (params.gitInfo === null) {
25664
- gitInfo = null;
25665
- } else if (params.gitInfo !== void 0) {
25937
+ const decoded = {
25938
+ threadId: params.threadId,
25939
+ unsupportedFields: Object.keys(params).filter((name) => !THREAD_METADATA_UPDATE_FIELDS.has(name)).sort()
25940
+ };
25941
+ if (params.isPinned !== void 0) {
25942
+ decoded.isPinned = nullableBoolean(params.isPinned, "thread/metadata/update params.isPinned");
25943
+ }
25944
+ const projectId = nullableText(params.projectId, "thread/metadata/update params.projectId");
25945
+ if (projectId !== null) {
25946
+ decoded.projectId = projectId.length === 0 ? null : nonBlankTextOrNull(projectId, "thread/metadata/update params.projectId");
25947
+ }
25948
+ const daybreakEnabled = nullableBoolean(params.daybreakEnabled, "thread/metadata/update params.daybreakEnabled");
25949
+ if (daybreakEnabled !== null)
25950
+ decoded.daybreakEnabled = daybreakEnabled;
25951
+ if (params.gitInfo !== void 0 && params.gitInfo !== null) {
25666
25952
  if (!isRecord8(params.gitInfo)) {
25667
25953
  throw new Error("thread/metadata/update params.gitInfo must be an object or null");
25668
25954
  }
25669
- gitInfo = {};
25955
+ const gitInfo = {};
25670
25956
  for (const name of ["branch", "originUrl", "sha"]) {
25671
25957
  const value2 = params.gitInfo[name];
25672
- if (value2 !== void 0 && value2 !== null && typeof value2 !== "string") {
25673
- throw new Error(`thread/metadata/update params.gitInfo.${name} must be text or null`);
25958
+ if (value2 !== void 0) {
25959
+ gitInfo[name] = nonBlankTextOrNull(value2, `thread/metadata/update params.gitInfo.${name}`);
25674
25960
  }
25675
- if (value2 !== void 0)
25676
- gitInfo[name] = value2;
25677
25961
  }
25962
+ decoded.gitInfo = gitInfo;
25963
+ for (const name of Object.keys(params.gitInfo)) {
25964
+ if (!GIT_INFO_FIELDS.has(name))
25965
+ decoded.unsupportedFields.push(`gitInfo.${name}`);
25966
+ }
25967
+ decoded.unsupportedFields.sort();
25678
25968
  }
25679
- const decoded = { threadId: params.threadId };
25680
- if (params.isPinned !== void 0)
25681
- decoded.isPinned = isPinned;
25682
- if (params.gitInfo !== void 0)
25683
- decoded.gitInfo = gitInfo ?? null;
25684
25969
  return decoded;
25685
25970
  }
25971
+ function observeDeletedProject(value2) {
25972
+ if (!isRecord8(value2) || value2.method !== "project/changed" || "id" in value2)
25973
+ return null;
25974
+ const params = value2.params;
25975
+ if (!isRecord8(params) || params.changeType !== "deleted")
25976
+ return null;
25977
+ return typeof params.projectId === "string" && params.projectId.length > 0 ? params.projectId : null;
25978
+ }
25686
25979
  function optionalCursor(value2, name) {
25687
25980
  if (value2 === void 0 || value2 === null)
25688
25981
  return null;
@@ -26815,6 +27108,9 @@ var ExternalThreadRepository = class {
26815
27108
  setPinned(hostThreadId, isPinned) {
26816
27109
  return this.store.setPinned(hostThreadId, isPinned);
26817
27110
  }
27111
+ updateMetadata(hostThreadId, patch, options2) {
27112
+ return this.store.updateMetadata(hostThreadId, patch, options2);
27113
+ }
26818
27114
  removeProvisional(hostThreadId) {
26819
27115
  return this.store.removeProvisional(hostThreadId);
26820
27116
  }
@@ -27057,13 +27353,19 @@ function externalThreadValue(input) {
27057
27353
  turns: input.turns,
27058
27354
  preview: previewText,
27059
27355
  name: record4.title || null,
27060
- gitInfo: null,
27356
+ gitInfo: record4.gitInfo ? {
27357
+ branch: record4.gitInfo.branch ?? null,
27358
+ originUrl: record4.gitInfo.originUrl ?? null,
27359
+ sha: record4.gitInfo.sha ?? null
27360
+ } : null,
27061
27361
  forkedFromId: record4.forkSource?.hostThreadId ?? null,
27062
27362
  parentThreadId: record4.subagent?.parentHostThreadId ?? null,
27063
27363
  ephemeral: record4.ephemeral,
27064
27364
  canAcceptDirectInput: record4.subagent ? false : input.loaded === false ? null : true,
27065
27365
  historyMode: record4.historyMode,
27066
27366
  isPinned: record4.isPinned,
27367
+ projectId: record4.projectId ?? null,
27368
+ daybreakEnabled: record4.daybreakEnabled ?? null,
27067
27369
  ...threadSectionFields(input.placement),
27068
27370
  agentNickname: record4.subagent ? record4.title || null : null,
27069
27371
  agentRole: record4.subagent?.role ?? null,
@@ -31318,6 +31620,7 @@ function includesExternalRecord(record4, query, byId, sectionId) {
31318
31620
  return false;
31319
31621
  }
31320
31622
  if (record4.archived !== query.archived) return false;
31623
+ if (query.projectId !== void 0 && (record4.projectId ?? null) !== query.projectId) return false;
31321
31624
  if (query.cwd !== null && !query.cwd.includes(record4.cwd)) return false;
31322
31625
  if (query.modelProviders !== null && query.modelProviders.length > 0 && !query.modelProviders.includes("codexhost")) {
31323
31626
  return false;
@@ -32635,6 +32938,28 @@ var AppServerHost = class {
32635
32938
  });
32636
32939
  return;
32637
32940
  }
32941
+ if (request.method === HARNESS_LONG_CONTEXT_GET_METHOD || request.method === HARNESS_LONG_CONTEXT_SET_METHOD) {
32942
+ this.#dispatchDesktopRequest(async () => {
32943
+ await this.#waitForPlugins();
32944
+ try {
32945
+ const result = await handleHarnessLongContext(
32946
+ request.method,
32947
+ request.params,
32948
+ this.#externalAdapters
32949
+ );
32950
+ await this.#writer.json(rpcEnvelope(request, { result: jsonValueSchema.parse(result) }));
32951
+ } catch (error51) {
32952
+ await this.#writer.json(
32953
+ rpcError(
32954
+ request,
32955
+ error51 instanceof HarnessLongContextError ? error51.code : -32077,
32956
+ error51 instanceof HarnessLongContextError ? error51.message : "Could not read or save the 1M context setting"
32957
+ )
32958
+ );
32959
+ }
32960
+ });
32961
+ return;
32962
+ }
32638
32963
  if (request.method === "codexhost/harness/web-ui/open") {
32639
32964
  this.#dispatchDesktopRequest(() => this.#openHarnessWebUi(request));
32640
32965
  return;
@@ -32797,31 +33122,29 @@ var AppServerHost = class {
32797
33122
  return;
32798
33123
  }
32799
33124
  if (request.method === "thread/metadata/update") {
32800
- let threadId2;
32801
- let decoded;
33125
+ let update;
32802
33126
  try {
32803
- const parsed = decodeThreadMetadataUpdateRequest(request);
32804
- if (!parsed) throw new Error("Expected thread/metadata/update request");
32805
- decoded = parsed;
32806
- threadId2 = decoded.threadId;
33127
+ const decoded = decodeThreadMetadataUpdateRequest(request);
33128
+ if (!decoded) throw new Error("Expected thread/metadata/update request");
33129
+ update = decoded;
32807
33130
  } catch (error51) {
32808
33131
  await this.#writer.json(rpcError(request, -32602, errorMessage3(error51)));
32809
33132
  return;
32810
33133
  }
32811
- const location = await this.#locateExternalThread(threadId2);
33134
+ const location = await this.#locateExternalThread(update.threadId);
32812
33135
  if (await this.#writeResolutionError(request, location)) return;
32813
33136
  if (location.kind === "official") {
32814
33137
  await this.#forwardOfficialRequest(request, frame);
32815
33138
  return;
32816
33139
  }
32817
- if (location.kind !== "external") return;
32818
- if (decoded.isPinned === void 0 || decoded.gitInfo !== void 0) {
32819
- await this.#writer.json(
32820
- rpcError(request, -32078, "External Thread metadata updates are unsupported")
32821
- );
32822
- return;
33140
+ if (location.kind === "external") {
33141
+ const pinOnly = update.isPinned !== void 0 && update.unsupportedFields.length === 1 && update.unsupportedFields[0] === "isPinned" && update.projectId === void 0 && update.daybreakEnabled === void 0 && update.gitInfo === void 0;
33142
+ if (pinOnly) {
33143
+ await this.#setExternalThreadPinned(request, location, update.isPinned ?? false);
33144
+ } else {
33145
+ await this.#updateExternalThreadMetadata(request, location, update);
33146
+ }
32823
33147
  }
32824
- await this.#setExternalThreadPinned(request, location, decoded.isPinned ?? false);
32825
33148
  return;
32826
33149
  }
32827
33150
  let createRoute;
@@ -33148,6 +33471,12 @@ var AppServerHost = class {
33148
33471
  if (forwarded === parsed) await this.#writer.frame(input.frame);
33149
33472
  else await this.#writer.json(forwarded);
33150
33473
  this.#nativeAccountObserver?.observe(parsed);
33474
+ const deletedProjectId = observeDeletedProject(parsed);
33475
+ if (deletedProjectId) {
33476
+ await this.#clearDeletedProjectAssignments(deletedProjectId).catch(
33477
+ (error51) => this.#diagnose(error51)
33478
+ );
33479
+ }
33151
33480
  }
33152
33481
  async #requestOfficial(method, params) {
33153
33482
  return this.#officialRuntime.request(method, params);
@@ -33783,49 +34112,119 @@ var AppServerHost = class {
33783
34112
  return typeof thread.id === "string" ? { ...thread, ...await this.#externalSectionFields(thread.id) } : thread;
33784
34113
  }
33785
34114
  async #setExternalThreadArchived(request, location, archived) {
33786
- if (location.record.state !== "ready" || !location.record.nativeSessionRef) {
33787
- await this.#writer.json(rpcError(request, -32079, "External Native Session is unavailable"));
34115
+ const updated = await this.#persistExternalThreadRecord(
34116
+ request,
34117
+ location,
34118
+ (hostThreadId) => this.#repository.setArchived(hostThreadId, archived),
34119
+ "External Thread archive state could not be persisted"
34120
+ );
34121
+ if (!updated) return;
34122
+ await this.#writer.json(
34123
+ rpcEnvelope(request, { result: archived ? {} : { thread: updated.thread } })
34124
+ );
34125
+ await this.#writer.json({
34126
+ method: archived ? "thread/archived" : "thread/unarchived",
34127
+ params: { threadId: updated.record.hostThreadId }
34128
+ });
34129
+ }
34130
+ async #updateExternalThreadMetadata(request, location, update) {
34131
+ if (update.unsupportedFields.length > 0) {
34132
+ await this.#writer.json(
34133
+ rpcError(
34134
+ request,
34135
+ -32078,
34136
+ `External Thread metadata fields are unsupported: ${update.unsupportedFields.join(", ")}`
34137
+ )
34138
+ );
33788
34139
  return;
33789
34140
  }
34141
+ if (typeof update.projectId === "string") {
34142
+ const exists2 = await this.#requestOfficial("project/read", {
34143
+ projectId: update.projectId
34144
+ }).then(
34145
+ (response) => !isRecord15(response.error) && isRecord15(response.result) && isRecord15(response.result.project) && response.result.project.id === update.projectId,
34146
+ () => false
34147
+ );
34148
+ if (!exists2) {
34149
+ await this.#writer.json(rpcError(request, -32602, "Project is unavailable"));
34150
+ return;
34151
+ }
34152
+ }
34153
+ const patch = {
34154
+ ...update.projectId !== void 0 ? { projectId: update.projectId } : {},
34155
+ ...update.daybreakEnabled !== void 0 ? { daybreakEnabled: update.daybreakEnabled } : {},
34156
+ ...update.gitInfo !== void 0 ? { gitInfo: update.gitInfo } : {}
34157
+ };
34158
+ const previousProjectId = location.record.projectId ?? null;
34159
+ const updated = await this.#persistExternalThreadRecord(
34160
+ request,
34161
+ location,
34162
+ (hostThreadId) => this.#repository.updateMetadata(hostThreadId, patch),
34163
+ "External Thread metadata could not be persisted",
34164
+ true
34165
+ );
34166
+ if (!updated) return;
34167
+ await this.#writer.json(rpcEnvelope(request, { result: { thread: updated.thread } }));
34168
+ const projectId = updated.record.projectId ?? null;
34169
+ if (projectId !== previousProjectId) {
34170
+ await this.#writer.json({
34171
+ method: "thread/project/updated",
34172
+ params: { threadId: updated.record.hostThreadId, projectId }
34173
+ });
34174
+ }
34175
+ }
34176
+ /** Clear External assignments to a project official Codex reported as deleted. */
34177
+ async #clearDeletedProjectAssignments(projectId) {
34178
+ const records = await this.#repository.list();
34179
+ for (const record4 of records) {
34180
+ if (record4.projectId !== projectId) continue;
34181
+ const updated = await this.#repository.updateMetadata(
34182
+ record4.hostThreadId,
34183
+ { projectId: null },
34184
+ { ifProjectId: projectId }
34185
+ );
34186
+ if (updated.projectId !== void 0) continue;
34187
+ const loaded = this.#externalRuntime.get(updated.hostThreadId);
34188
+ if (loaded) this.#syncLoadedExternalThread(loaded, updated);
34189
+ await this.#writer.json({
34190
+ method: "thread/project/updated",
34191
+ params: { threadId: updated.hostThreadId, projectId: null }
34192
+ });
34193
+ }
34194
+ }
34195
+ #syncLoadedExternalThread(thread, record4) {
34196
+ const projected = externalThreadValue({
34197
+ record: record4,
34198
+ turns: [],
34199
+ sessionId: thread.sessionId,
34200
+ running: thread.running
34201
+ });
34202
+ thread.record = record4;
34203
+ thread.thread = { ...thread.thread, ...projected, turns: thread.thread.turns ?? [] };
34204
+ return projected;
34205
+ }
34206
+ async #persistExternalThreadRecord(request, location, write, failureMessage, allowProvisional = false) {
34207
+ const hasNativeSession = location.record.state === "ready" && location.record.nativeSessionRef !== void 0;
34208
+ if (!hasNativeSession && !(allowProvisional && location.thread)) {
34209
+ await this.#writer.json(rpcError(request, -32079, "External Native Session is unavailable"));
34210
+ return null;
34211
+ }
33790
34212
  const sessionId = location.thread?.sessionId ?? await this.#repository.sessionTreeId(location.record).catch(() => null);
33791
34213
  if (!sessionId) {
33792
34214
  await this.#writer.json(
33793
34215
  rpcError(request, -32081, "External Thread metadata could not be projected")
33794
34216
  );
33795
- return;
34217
+ return null;
33796
34218
  }
33797
34219
  let record4;
33798
34220
  try {
33799
- record4 = await this.#repository.setArchived(location.record.hostThreadId, archived);
34221
+ record4 = await write(location.record.hostThreadId);
33800
34222
  } catch {
33801
- await this.#writer.json(
33802
- rpcError(request, -32081, "External Thread archive state could not be persisted")
33803
- );
33804
- return;
33805
- }
33806
- const projected = externalThreadValue({
33807
- record: record4,
33808
- turns: [],
33809
- sessionId,
33810
- ...location.thread ? { running: location.thread.running } : { loaded: false }
33811
- });
33812
- if (location.thread) {
33813
- location.thread.record = record4;
33814
- location.thread.thread = {
33815
- ...location.thread.thread,
33816
- ...projected,
33817
- turns: location.thread.thread.turns ?? []
33818
- };
34223
+ await this.#writer.json(rpcError(request, -32081, failureMessage));
34224
+ return null;
33819
34225
  }
33820
- await this.#writer.json(
33821
- rpcEnvelope(request, {
33822
- result: archived ? {} : { thread: await this.#withExternalSection(projected) }
33823
- })
33824
- );
33825
- await this.#writer.json({
33826
- method: archived ? "thread/archived" : "thread/unarchived",
33827
- params: { threadId: record4.hostThreadId }
33828
- });
34226
+ const projected = location.thread ? this.#syncLoadedExternalThread(location.thread, record4) : externalThreadValue({ record: record4, turns: [], sessionId, loaded: false });
34227
+ return { record: record4, thread: await this.#withExternalSection(projected) };
33829
34228
  }
33830
34229
  /** 持久化置顶变更,并向 Desktop 返回更新后的 External Thread 投影。 */
33831
34230
  async #setExternalThreadPinned(request, location, isPinned) {