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

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.
@@ -4475,10 +4475,10 @@ function mergeDefs(...defs) {
4475
4475
  function cloneDef(schema) {
4476
4476
  return mergeDefs(schema._zod.def);
4477
4477
  }
4478
- function getElementAtPath(obj, path4) {
4479
- if (!path4)
4478
+ function getElementAtPath(obj, path8) {
4479
+ if (!path8)
4480
4480
  return obj;
4481
- return path4.reduce((acc, key) => acc?.[key], obj);
4481
+ return path8.reduce((acc, key) => acc?.[key], obj);
4482
4482
  }
4483
4483
  function promiseAllObject(promisesObj) {
4484
4484
  const keys = Object.keys(promisesObj);
@@ -4887,11 +4887,11 @@ function explicitlyAborted(x, startIndex = 0) {
4887
4887
  }
4888
4888
  return false;
4889
4889
  }
4890
- function prefixIssues(path4, issues) {
4890
+ function prefixIssues(path8, issues) {
4891
4891
  return issues.map((iss) => {
4892
4892
  var _a3;
4893
4893
  (_a3 = iss).path ?? (_a3.path = []);
4894
- iss.path.unshift(path4);
4894
+ iss.path.unshift(path8);
4895
4895
  return iss;
4896
4896
  });
4897
4897
  }
@@ -5038,16 +5038,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
5038
5038
  }
5039
5039
  function formatError(error51, mapper = (issue2) => issue2.message) {
5040
5040
  const fieldErrors = { _errors: [] };
5041
- const processError = (error52, path4 = []) => {
5041
+ const processError = (error52, path8 = []) => {
5042
5042
  for (const issue2 of error52.issues) {
5043
5043
  if (issue2.code === "invalid_union" && issue2.errors.length) {
5044
- issue2.errors.map((issues) => processError({ issues }, [...path4, ...issue2.path]));
5044
+ issue2.errors.map((issues) => processError({ issues }, [...path8, ...issue2.path]));
5045
5045
  } else if (issue2.code === "invalid_key") {
5046
- processError({ issues: issue2.issues }, [...path4, ...issue2.path]);
5046
+ processError({ issues: issue2.issues }, [...path8, ...issue2.path]);
5047
5047
  } else if (issue2.code === "invalid_element") {
5048
- processError({ issues: issue2.issues }, [...path4, ...issue2.path]);
5048
+ processError({ issues: issue2.issues }, [...path8, ...issue2.path]);
5049
5049
  } else {
5050
- const fullpath = [...path4, ...issue2.path];
5050
+ const fullpath = [...path8, ...issue2.path];
5051
5051
  if (fullpath.length === 0) {
5052
5052
  fieldErrors._errors.push(mapper(issue2));
5053
5053
  } else {
@@ -5074,17 +5074,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
5074
5074
  }
5075
5075
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
5076
5076
  const result = { errors: [] };
5077
- const processError = (error52, path4 = []) => {
5077
+ const processError = (error52, path8 = []) => {
5078
5078
  var _a3, _b;
5079
5079
  for (const issue2 of error52.issues) {
5080
5080
  if (issue2.code === "invalid_union" && issue2.errors.length) {
5081
- issue2.errors.map((issues) => processError({ issues }, [...path4, ...issue2.path]));
5081
+ issue2.errors.map((issues) => processError({ issues }, [...path8, ...issue2.path]));
5082
5082
  } else if (issue2.code === "invalid_key") {
5083
- processError({ issues: issue2.issues }, [...path4, ...issue2.path]);
5083
+ processError({ issues: issue2.issues }, [...path8, ...issue2.path]);
5084
5084
  } else if (issue2.code === "invalid_element") {
5085
- processError({ issues: issue2.issues }, [...path4, ...issue2.path]);
5085
+ processError({ issues: issue2.issues }, [...path8, ...issue2.path]);
5086
5086
  } else {
5087
- const fullpath = [...path4, ...issue2.path];
5087
+ const fullpath = [...path8, ...issue2.path];
5088
5088
  if (fullpath.length === 0) {
5089
5089
  result.errors.push(mapper(issue2));
5090
5090
  continue;
@@ -5116,8 +5116,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
5116
5116
  }
5117
5117
  function toDotPath(_path) {
5118
5118
  const segs = [];
5119
- const path4 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
5120
- for (const seg of path4) {
5119
+ const path8 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
5120
+ for (const seg of path8) {
5121
5121
  if (typeof seg === "number")
5122
5122
  segs.push(`[${seg}]`);
5123
5123
  else if (typeof seg === "symbol")
@@ -17809,13 +17809,13 @@ function resolveRef(ref, ctx) {
17809
17809
  if (!ref.startsWith("#")) {
17810
17810
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
17811
17811
  }
17812
- const path4 = ref.slice(1).split("/").filter(Boolean);
17813
- if (path4.length === 0) {
17812
+ const path8 = ref.slice(1).split("/").filter(Boolean);
17813
+ if (path8.length === 0) {
17814
17814
  return ctx.rootSchema;
17815
17815
  }
17816
17816
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
17817
- if (path4[0] === defsKey) {
17818
- const key = path4[1];
17817
+ if (path8[0] === defsKey) {
17818
+ const key = path8[1];
17819
17819
  if (!key || !ctx.defs[key]) {
17820
17820
  throw new Error(`Reference not found: ${ref}`);
17821
17821
  }
@@ -18278,6 +18278,55 @@ var credentialImportsParamsSchema = external_exports.object({
18278
18278
  request: credentialImportsRequestSchema
18279
18279
  }).strict();
18280
18280
 
18281
+ // ../../shared-contracts/dist/harness-display-settings.js
18282
+ var harnessDisplayEntriesSchema = external_exports.array(external_exports.strictObject({
18283
+ agent: external_exports.string().min(1).max(128),
18284
+ section: external_exports.enum(["main", "more", "auto"])
18285
+ })).max(256).refine((entries) => new Set(entries.map((entry) => entry.agent)).size === entries.length, "Duplicate Harness IDs");
18286
+ var harnessDisplaySettingsSchema = external_exports.strictObject({
18287
+ entries: harnessDisplayEntriesSchema.nullable()
18288
+ });
18289
+ var harnessDisplayGetSchema = external_exports.strictObject({});
18290
+ var harnessDisplaySetSchema = external_exports.strictObject({
18291
+ entries: harnessDisplayEntriesSchema,
18292
+ /** Import legacy Desktop preferences only if no shared settings exist yet. */
18293
+ initializeOnly: external_exports.boolean().optional()
18294
+ });
18295
+
18296
+ // ../../shared-contracts/dist/console.js
18297
+ var consoleAnnouncementSchema = external_exports.strictObject({
18298
+ title: external_exports.string().trim().min(1).max(200),
18299
+ type: external_exports.enum(["info", "warning", "danger"]),
18300
+ body: external_exports.string().trim().min(1).max(16 * 1024)
18301
+ });
18302
+ var consoleOpenParamsSchema = external_exports.strictObject({});
18303
+ var consoleOpenResultSchema = external_exports.strictObject({
18304
+ /** The console address. */
18305
+ url: external_exports.string().max(2048).regex(/^http:\/\/(?:127\.0\.0\.1|localhost):\d{1,5}\/(?:\?.*)?$/u)
18306
+ });
18307
+ var CONSOLE_HOST_METHODS = Object.freeze([
18308
+ "codexhost/harness/plugins/list",
18309
+ "codexhost/harness/display-settings/get",
18310
+ "codexhost/harness/display-settings/set",
18311
+ "codexhost/harness/inspect",
18312
+ "codexhost/harness/launch-settings/get",
18313
+ "codexhost/harness/launch-settings/set",
18314
+ "codexhost/harness/web-ui/open",
18315
+ "codexhost/harness/accounts/sources",
18316
+ "codexhost/harness/accounts/list",
18317
+ "codexhost/harness/accounts/inspect",
18318
+ "codexhost/harness/credential-imports",
18319
+ "codexhost/harness/session-import/sources",
18320
+ "codexhost/harness/session-import/list",
18321
+ "codexhost/harness/session-import/import",
18322
+ "codexhost/account/list",
18323
+ "codexhost/account/refresh",
18324
+ "codexhost/account/usage/inspect",
18325
+ "codexhost/update/check",
18326
+ "codexhost/update/start",
18327
+ "codexhost/update/status"
18328
+ ]);
18329
+
18281
18330
  // ../../shared-contracts/dist/version.js
18282
18331
  var WORKSPACE_CONTRACT_VERSION = 1;
18283
18332
 
@@ -18331,6 +18380,12 @@ var hostTurnIdSchema = opaqueIdSchema.brand();
18331
18380
  var hostItemIdSchema = opaqueIdSchema.brand();
18332
18381
  var hostInteractionIdSchema = opaqueIdSchema.brand();
18333
18382
 
18383
+ // ../../shared-contracts/dist/manual-compaction.js
18384
+ var threadManualCompactionStartedSchema = external_exports.strictObject({
18385
+ threadId: hostThreadIdSchema,
18386
+ turnId: hostTurnIdSchema
18387
+ });
18388
+
18334
18389
  // ../../shared-contracts/dist/thread-usage.js
18335
18390
  var nonNegativeSafeIntegerSchema = external_exports.number().int().safe().nonnegative();
18336
18391
  var finiteNonNegativeNumberSchema = external_exports.number().finite().nonnegative();
@@ -18391,6 +18446,10 @@ var threadUsageSnapshotSchema = external_exports.object({
18391
18446
  var usagePercentSchema = external_exports.number().finite().min(0).max(100);
18392
18447
  var accountCreditsProductUsageSchema = external_exports.object({
18393
18448
  product: external_exports.string().min(1),
18449
+ used: external_exports.number().finite().nonnegative().optional(),
18450
+ // Zero is a real empty cap, not an absent field.
18451
+ limit: external_exports.number().finite().nonnegative().optional(),
18452
+ unit: external_exports.string().min(1).max(32).optional(),
18394
18453
  usagePercent: usagePercentSchema,
18395
18454
  resetsAt: external_exports.string().min(1).optional()
18396
18455
  }).strict();
@@ -18400,11 +18459,14 @@ var accountResetCreditsSchema = external_exports.object({
18400
18459
  expiresAt: external_exports.array(external_exports.string().min(1)).min(1).max(32).optional()
18401
18460
  }).strict();
18402
18461
  var accountCreditsSnapshotSchema = external_exports.object({
18462
+ used: external_exports.number().finite().nonnegative().optional(),
18463
+ // Zero is a real empty cap, not an absent field.
18464
+ limit: external_exports.number().finite().nonnegative().optional(),
18465
+ unit: external_exports.string().trim().min(1).max(32).optional(),
18403
18466
  /** Native label when the primary limit is scoped to a model or product group. */
18404
18467
  label: external_exports.string().min(1).optional(),
18405
18468
  usedPercent: usagePercentSchema.optional(),
18406
18469
  remaining: external_exports.number().finite().optional(),
18407
- unit: external_exports.string().trim().min(1).max(32).optional(),
18408
18470
  resetsAt: external_exports.string().min(1).optional(),
18409
18471
  periodType: external_exports.enum(["weekly", "monthly", "five_hour", "seven_day", "unknown"]),
18410
18472
  productUsage: external_exports.array(accountCreditsProductUsageSchema).min(1).optional(),
@@ -18435,12 +18497,27 @@ var threadUsageInspectionSchema = external_exports.object({
18435
18497
  }).strict();
18436
18498
 
18437
18499
  // ../../shared-contracts/dist/harness-accounts.js
18438
- var harnessAccountSnapshotSchema = external_exports.object({
18500
+ var accountBalanceSnapshotSchema = external_exports.object({
18501
+ amount: external_exports.number().finite().nonnegative(),
18502
+ /** ISO 4217 code as reported by the Provider, for example `CNY`. */
18503
+ currency: external_exports.string().trim().min(1).max(8),
18504
+ /** Native label when the Harness exposes several Billing Sources. */
18505
+ label: external_exports.string().trim().min(1).max(128).optional()
18506
+ }).strict();
18507
+ var harnessAccountSnapshotObject = external_exports.object({
18439
18508
  email: external_exports.string().trim().min(1).max(320).optional(),
18440
18509
  label: external_exports.string().trim().min(1).max(256).optional(),
18441
18510
  plan: external_exports.string().trim().min(1).max(128).optional(),
18442
- credits: accountCreditsSnapshotSchema
18511
+ credits: accountCreditsSnapshotSchema.optional(),
18512
+ balance: accountBalanceSnapshotSchema.optional()
18443
18513
  }).strict();
18514
+ function requireReportedQuota(schema) {
18515
+ return schema.refine((value) => {
18516
+ const reported = value;
18517
+ return reported.credits !== void 0 || reported.balance !== void 0;
18518
+ }, { message: "Account must report either credits or a balance" });
18519
+ }
18520
+ var harnessAccountSnapshotSchema = requireReportedQuota(harnessAccountSnapshotObject);
18444
18521
  var harnessAccountIdentityShape = {
18445
18522
  harnessId: harnessIdSchema,
18446
18523
  harnessName: external_exports.string().trim().min(1).max(128)
@@ -18451,11 +18528,13 @@ var harnessAccountSourceListResultSchema = external_exports.object({ sources: ex
18451
18528
  var harnessAccountInspectParamsSchema = external_exports.object({ harnessId: harnessIdSchema, refresh: external_exports.boolean().optional() }).strict();
18452
18529
  var harnessAccountInspectResultSchema = external_exports.object({
18453
18530
  ...harnessAccountIdentityShape,
18454
- account: harnessAccountSnapshotSchema.nullable()
18531
+ account: harnessAccountSnapshotSchema.nullable(),
18532
+ /** Every Billing Source from one Harness; `account` remains the first for older clients. */
18533
+ accounts: external_exports.array(harnessAccountSnapshotSchema).max(8).optional()
18455
18534
  }).strict();
18456
18535
  var harnessAccountListParamsSchema = external_exports.object({ refresh: external_exports.boolean().optional() }).strict();
18457
18536
  var harnessAccountListResultSchema = external_exports.object({
18458
- accounts: external_exports.array(harnessAccountSnapshotSchema.extend(harnessAccountIdentityShape)).max(128)
18537
+ accounts: external_exports.array(requireReportedQuota(harnessAccountSnapshotObject.extend(harnessAccountIdentityShape))).max(128)
18459
18538
  }).strict();
18460
18539
 
18461
18540
  // ../../shared-contracts/dist/json-value.js
@@ -18593,6 +18672,8 @@ var harnessModelSchema = external_exports.object({
18593
18672
  ref: harnessModelRefSchema,
18594
18673
  label: nonBlankTextSchema2.max(HARNESS_MODEL_LABEL_MAX_LENGTH),
18595
18674
  resolvedModelLabel: harnessResolvedModelLabelSchema.optional(),
18675
+ /** Optional opaque selection for this same Model with priority processing enabled. */
18676
+ fastModel: harnessModelRefSchema.optional(),
18596
18677
  supportedThinkingOptionIds: external_exports.array(harnessThinkingOptionIdSchema).optional()
18597
18678
  }).strict();
18598
18679
  var harnessThinkingOptionsSchema = external_exports.array(harnessThinkingOptionSchema).superRefine((options, context) => {
@@ -18625,6 +18706,16 @@ var harnessModelCatalogSchema = external_exports.object({
18625
18706
  });
18626
18707
  }
18627
18708
  refs.add(model.ref.id);
18709
+ if (model.fastModel) {
18710
+ if (refs.has(model.fastModel.id) || catalog.models.some((entry) => entry.ref.id === model.fastModel?.id)) {
18711
+ context.addIssue({
18712
+ code: "custom",
18713
+ message: "Fast Model refs must be distinct and unique",
18714
+ path: ["models", index, "fastModel"]
18715
+ });
18716
+ }
18717
+ refs.add(model.fastModel.id);
18718
+ }
18628
18719
  const supportedThinkingIds = /* @__PURE__ */ new Set();
18629
18720
  for (const [optionIndex, optionId] of (model.supportedThinkingOptionIds ?? []).entries()) {
18630
18721
  if (supportedThinkingIds.has(optionId)) {
@@ -18747,11 +18838,13 @@ var threadThinkingSelectParamsSchema = external_exports.object({
18747
18838
  thinkingOptionId: harnessThinkingOptionIdSchema
18748
18839
  }).strict();
18749
18840
  var threadInspectionParamsSchema = external_exports.object({
18750
- threadId: hostThreadIdSchema
18841
+ threadId: hostThreadIdSchema,
18842
+ includeReferenceCapability: external_exports.boolean().optional()
18751
18843
  }).strict();
18752
18844
  var codexThreadInspectionSchema = external_exports.object({
18753
18845
  owner: external_exports.literal("codex"),
18754
- locked: external_exports.literal(true)
18846
+ locked: external_exports.literal(true),
18847
+ supportsThreadReferences: external_exports.literal(true).optional()
18755
18848
  }).strict();
18756
18849
  var externalThreadInspectionSchema = external_exports.object({
18757
18850
  owner: external_exports.literal("external"),
@@ -18879,10 +18972,31 @@ var harnessLaunchSettingsSchema = external_exports.object({
18879
18972
  restartRequired: external_exports.boolean()
18880
18973
  }).strict();
18881
18974
 
18975
+ // ../../shared-contracts/dist/harness-installation.js
18976
+ var harnessInstallationParamsSchema = external_exports.object({
18977
+ harnessId: harnessIdSchema,
18978
+ action: external_exports.enum(["check", "update"])
18979
+ }).strict();
18980
+ var harnessInstallationStateSchema = external_exports.object({
18981
+ currentVersion: external_exports.string().min(1).max(128),
18982
+ latestVersion: external_exports.string().min(1).max(128),
18983
+ updateAvailable: external_exports.boolean(),
18984
+ canUpdate: external_exports.boolean(),
18985
+ message: external_exports.string().max(2048).optional()
18986
+ }).strict();
18987
+
18882
18988
  // ../../shared-contracts/dist/codex-accounts.js
18883
18989
  var accountIdSchema = external_exports.string().min(1).max(256).regex(/^[A-Za-z0-9._~-]+$/u);
18884
18990
  var nonBlankTextSchema3 = external_exports.string().trim().min(1);
18885
18991
  var codexAccountAuthKindSchema = external_exports.enum(["api", "chatgpt"]);
18992
+ var codexAccountSiteUrlPattern = /^https?:\/\/(?:\[[0-9a-fA-F:]+\]|[^/\s:@?#]+)(?::\d{1,5})?(?:[/?#][^\s]*)?$/u;
18993
+ function isCodexAccountSiteUrl(value) {
18994
+ return value.length > 0 && value.length <= 2048 && codexAccountSiteUrlPattern.test(value);
18995
+ }
18996
+ var externalUrlOpenParamsSchema = external_exports.object({
18997
+ url: external_exports.string().max(2048).refine(isCodexAccountSiteUrl, "External URL must be http(s)")
18998
+ }).strict();
18999
+ var externalUrlOpenResultSchema = external_exports.object({}).strict();
18886
19000
  var codexAccountPlanTypeSchema = external_exports.enum([
18887
19001
  "free",
18888
19002
  "go",
@@ -18908,7 +19022,8 @@ var codexAccountSchema = external_exports.object({
18908
19022
  email: external_exports.string().email().max(320).optional(),
18909
19023
  planType: codexAccountPlanTypeSchema.optional(),
18910
19024
  authKind: codexAccountAuthKindSchema.optional(),
18911
- authIdentity: nonBlankTextSchema3.max(256).optional()
19025
+ authIdentity: nonBlankTextSchema3.max(256).optional(),
19026
+ siteUrl: external_exports.string().refine(isCodexAccountSiteUrl, "Account site URL must be http(s)").optional()
18912
19027
  }).strict();
18913
19028
  var codexAccountPhaseSchema = external_exports.enum(["ready", "unavailable"]);
18914
19029
  var codexAccountListResultSchema = external_exports.object({
@@ -19490,12 +19605,12 @@ function environmentValue(environment, name) {
19490
19605
  return Object.entries(environment).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1];
19491
19606
  }
19492
19607
  function executableCandidates(command, environment) {
19493
- const targetPath = process.platform === "win32" ? path.win32 : path.posix;
19494
- if (targetPath.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
19608
+ const targetPath2 = process.platform === "win32" ? path.win32 : path.posix;
19609
+ if (targetPath2.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
19495
19610
  return [command];
19496
19611
  }
19497
- const extensions = process.platform === "win32" && targetPath.extname(command) === "" ? (environmentValue(environment, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").map((extension2) => extension2.trim()).filter(Boolean) : [""];
19498
- return (environmentValue(environment, "PATH") ?? "").split(targetPath.delimiter).map((directory) => directory.trim().replace(/^"|"$/gu, "")).filter(Boolean).flatMap((directory) => extensions.map((extension2) => targetPath.join(directory, command + extension2)));
19612
+ const extensions = process.platform === "win32" && targetPath2.extname(command) === "" ? (environmentValue(environment, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").map((extension2) => extension2.trim()).filter(Boolean) : [""];
19613
+ return (environmentValue(environment, "PATH") ?? "").split(targetPath2.delimiter).map((directory) => directory.trim().replace(/^"|"$/gu, "")).filter(Boolean).flatMap((directory) => extensions.map((extension2) => targetPath2.join(directory, command + extension2)));
19499
19614
  }
19500
19615
  function resolveExecutable(command, environment) {
19501
19616
  const accessMode = process.platform === "win32" ? constants.F_OK : constants.X_OK;
@@ -20891,7 +21006,8 @@ var ModernRemoteConnection = class {
20891
21006
  } catch (error51) {
20892
21007
  throw this.#transportFailure("DeepSeek Harness Web authentication failed", error51);
20893
21008
  }
20894
- if (response.status !== 303 || response.headers.get("location") !== "/") {
21009
+ const location = response.headers.get("location");
21010
+ if (response.status !== 303 || location !== "/" && location !== "./") {
20895
21011
  await cancelResponse(response);
20896
21012
  throw new ModernRemoteConnectionError(response.status === 401 || response.status === 403 ? "authenticationRequired" : "protocolError", "DeepSeek Harness Web rejected its bootstrap authentication exchange");
20897
21013
  }
@@ -21423,7 +21539,7 @@ function parseEvent(value, format = 0) {
21423
21539
  throw protocolError("journal event has invalid scalar fields");
21424
21540
  }
21425
21541
  assertJsonValue(value.data, "journal event data");
21426
- if (format === 3 && value.ignorable === true) {
21542
+ if (format >= 3 && value.ignorable === true) {
21427
21543
  if (Object.hasOwn(value, "sourceEventSeqs"))
21428
21544
  assertJsonValue(value.sourceEventSeqs, "journal event sourceEventSeqs");
21429
21545
  if (Object.hasOwn(value, "surfaceOp"))
@@ -21442,8 +21558,8 @@ function parseEvent(value, format = 0) {
21442
21558
  function parseSurfaceOp(value, format) {
21443
21559
  if (value === "append")
21444
21560
  return value;
21445
- const start = format === 3 ? "startSeq" : "start";
21446
- const end = format === 3 ? "endSeq" : "end";
21561
+ const start = format >= 3 ? "startSeq" : "start";
21562
+ const end = format >= 3 ? "endSeq" : "end";
21447
21563
  if (!isRecord3(value) || !hasExactKeys2(value, ["op", start, end]) || value.op !== "replace" || !isSeq(value[start]) || !isSeq(value[end])) {
21448
21564
  throw protocolError("journal event has an invalid surfaceOp");
21449
21565
  }
@@ -21613,16 +21729,16 @@ var Diff = class {
21613
21729
  }
21614
21730
  }
21615
21731
  }
21616
- addToPath(path4, added, removed, oldPosInc, options) {
21617
- const last = path4.lastComponent;
21732
+ addToPath(path8, added, removed, oldPosInc, options) {
21733
+ const last = path8.lastComponent;
21618
21734
  if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) {
21619
21735
  return {
21620
- oldPos: path4.oldPos + oldPosInc,
21736
+ oldPos: path8.oldPos + oldPosInc,
21621
21737
  lastComponent: { count: last.count + 1, added, removed, previousComponent: last.previousComponent }
21622
21738
  };
21623
21739
  } else {
21624
21740
  return {
21625
- oldPos: path4.oldPos + oldPosInc,
21741
+ oldPos: path8.oldPos + oldPosInc,
21626
21742
  lastComponent: { count: 1, added, removed, previousComponent: last }
21627
21743
  };
21628
21744
  }
@@ -21945,12 +22061,33 @@ function parseArguments(value) {
21945
22061
  return value;
21946
22062
  }
21947
22063
  }
22064
+ function contentText(value) {
22065
+ if (!isRecord4(value) || !Array.isArray(value.content))
22066
+ return "";
22067
+ return value.content.filter((block) => isRecord4(block) && block.type === "text" && typeof block.text === "string").map((block) => block.text).join("");
22068
+ }
21948
22069
  function projectToolResult(value, limit) {
21949
22070
  if (!isRecord4(value) || !isRecord4(value.source) || value.source.kind !== "tool")
21950
22071
  return null;
21951
22072
  const callId = value.source.callId;
21952
22073
  if (!nonBlankString(callId) || !Array.isArray(value.content))
21953
22074
  return null;
22075
+ if (value.role === "tool") {
22076
+ if (value.toolCallId !== callId || value.isError !== void 0 && typeof value.isError !== "boolean")
22077
+ return null;
22078
+ const text2 = contentText(value);
22079
+ const truncated2 = text2.length > limit;
22080
+ return {
22081
+ callId,
22082
+ failed: value.isError === true,
22083
+ ...text2 ? {
22084
+ output: {
22085
+ content: [{ type: "text", text: truncated2 ? text2.slice(0, limit) : text2 }],
22086
+ ...truncated2 ? { truncated: true } : {}
22087
+ }
22088
+ } : {}
22089
+ };
22090
+ }
21954
22091
  const resultBlocks = value.content.filter((block) => isRecord4(block) && block.type === "tool-result" && block.toolCallId === callId && Array.isArray(block.content));
21955
22092
  if (resultBlocks.length === 0)
21956
22093
  return null;
@@ -22066,6 +22203,12 @@ function projectTurnReason(value) {
22066
22203
  history: { status: "cancelled", reason: "Cancelled by user" }
22067
22204
  };
22068
22205
  }
22206
+ if (value.kind === "forked") {
22207
+ return {
22208
+ outcome: { status: "cancelled", reason: "Forked from parent Session" },
22209
+ history: { status: "cancelled", reason: "Forked from parent Session" }
22210
+ };
22211
+ }
22069
22212
  const error51 = {
22070
22213
  code: "nativeFailure",
22071
22214
  message: value.kind === "error" && isRecord4(value.error) && typeof value.error.message === "string" ? value.error.message : `DeepSeek Harness Turn ended with '${value.kind}'`,
@@ -22204,6 +22347,12 @@ function positiveInteger(value, label) {
22204
22347
  function nonNegativeInteger(value, label) {
22205
22348
  return boundedInteger(value, label, 0);
22206
22349
  }
22350
+ function nonNegativeFiniteNumber(value, label) {
22351
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
22352
+ fail(`${label} must be a finite number greater than or equal to 0`);
22353
+ }
22354
+ return value;
22355
+ }
22207
22356
  function nonNegativeSafeInteger2(value) {
22208
22357
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
22209
22358
  }
@@ -22904,13 +23053,219 @@ function matchesForkTail2(expectedPrefix, childEvents) {
22904
23053
  return childOwned.every((event) => event.type !== "turn/start" && event.type !== "session/end-seed");
22905
23054
  }
22906
23055
 
23056
+ // dist/profiles/v017.js
23057
+ function invalid2(label) {
23058
+ throw new ModernHistoryError("protocolError", `DSH V4 ${label} is malformed`);
23059
+ }
23060
+ function requiredFields(value, fields) {
23061
+ if (fields.some((field) => !Object.hasOwn(value, field)))
23062
+ invalid2("required fields");
23063
+ }
23064
+ function validateV4Content(value) {
23065
+ if (!Array.isArray(value))
23066
+ invalid2("content");
23067
+ for (const block of value) {
23068
+ if (!isRecord3(block) || block.type === "tool-result")
23069
+ invalid2("content block");
23070
+ if (block.type === "tool-addition" || block.type === "tool-removal") {
23071
+ requiredString(block.toolName, "tool change toolName");
23072
+ continue;
23073
+ }
23074
+ if (block.type === "image" && block.offloaded !== void 0 && block.offloaded !== true) {
23075
+ invalid2("image offloaded marker");
23076
+ }
23077
+ const ordinary = Object.fromEntries(Object.entries(block).filter(([key]) => key !== "offloaded"));
23078
+ const canonical = block.type === "text" || block.type === "reasoning" ? { type: block.type, text: block.text } : block.type === "image" || block.type === "file" ? { type: block.type, attachment: block.attachment } : block.type === "tool-call" ? { type: block.type, id: block.id, name: block.name, arguments: block.arguments } : ordinary;
23079
+ DEEPSEEK_V015_PROFILE.validateContent([canonical]);
23080
+ }
23081
+ }
23082
+ function validateV4Chunk(value) {
23083
+ DEEPSEEK_V015_PROFILE.validateChunk(value);
23084
+ if (!isRecord3(value))
23085
+ invalid2("assistant chunk");
23086
+ const blockType = value.type === "block-start" ? value.blockType : value.type === "block-end" && isRecord3(value.block) ? value.block.type : void 0;
23087
+ if (blockType === "tool-result" || blockType === "tool-addition" || blockType === "tool-removal") {
23088
+ invalid2("assistant tool-change block");
23089
+ }
23090
+ }
23091
+ function validateV4Stream(value) {
23092
+ for (const entry of expandV015AssistantStream(value))
23093
+ validateV4Chunk(entry.chunk);
23094
+ }
23095
+ function validateDeveloperMessage(event) {
23096
+ if (!isRecord3(event.data))
23097
+ invalid2("developer/message data");
23098
+ const data = event.data;
23099
+ requiredFields(data, ["turn", "step", "message"]);
23100
+ if (Object.hasOwn(data, "headerSeq") && !Number.isSafeInteger(data.headerSeq))
23101
+ invalid2("developer/message headerSeq");
23102
+ positiveInteger(data.turn, "developer/message turn");
23103
+ positiveInteger(data.step, "developer/message step");
23104
+ if (!isRecord3(data.message))
23105
+ invalid2("developer/message message");
23106
+ const message = data.message;
23107
+ requiredFields(message, ["id", "role", "content", "source"]);
23108
+ requiredString(message.id, "developer/message id");
23109
+ if (message.role !== "developer" || !isRecord3(message.source) || typeof message.source.kind !== "string" || !message.source.kind || message.source.kind === "plugin" || !Array.isArray(message.content)) {
23110
+ invalid2("developer/message role, source or content");
23111
+ }
23112
+ let additions = false;
23113
+ for (const block of message.content) {
23114
+ if (!isRecord3(block))
23115
+ invalid2("developer content block");
23116
+ if (block.type === "tool-addition" || block.type === "tool-removal") {
23117
+ requiredString(block.toolName, "developer toolName");
23118
+ additions ||= block.type === "tool-addition";
23119
+ } else {
23120
+ validateV4Content([block]);
23121
+ }
23122
+ }
23123
+ if (additions !== Object.hasOwn(data, "headerSeq") || additions && (!Number.isSafeInteger(data.headerSeq) || Object.is(data.headerSeq, -0) || data.headerSeq < 0 || data.headerSeq >= event.seq)) {
23124
+ invalid2("developer/message headerSeq");
23125
+ }
23126
+ }
23127
+ function matchesV4ForkTail(prefix, child) {
23128
+ if (!DEEPSEEK_V015_PROFILE.matchesForkTail(prefix, child))
23129
+ return false;
23130
+ const tail = child.slice(prefix.length + 1);
23131
+ const openTurn = prefix.reduce((turn, event) => event.type === "turn/start" ? event.data.turn : event.type === "turn/end" ? null : turn, null);
23132
+ const closer = tail.find((event) => event.type === "turn/end");
23133
+ if (openTurn === null)
23134
+ return closer === void 0 && !tail.some((event) => event.type === "step/end");
23135
+ return closer !== void 0 && isRecord3(closer.data) && closer.data.turn === openTurn && isRecord3(closer.data.reason) && closer.data.reason.kind === "forked";
23136
+ }
23137
+ var DEEPSEEK_V017_PROFILE = Object.freeze({
23138
+ ...DEEPSEEK_V015_PROFILE,
23139
+ version: "0.1.7-rc.1",
23140
+ checkpointPrefix: "v4-turn-end:",
23141
+ sessionFormatVersion: 4,
23142
+ matchesForkTail: matchesV4ForkTail,
23143
+ parseHeader(value, expected) {
23144
+ if (!isRecord3(value) || value.version !== 4)
23145
+ invalid2("journal header");
23146
+ if (value.delegationDepth !== void 0 && (!Number.isSafeInteger(value.delegationDepth) || Object.is(value.delegationDepth, -0) || value.delegationDepth < 0)) {
23147
+ invalid2("journal header delegationDepth");
23148
+ }
23149
+ const delegationDepth = value.delegationDepth ?? 0;
23150
+ DEEPSEEK_V015_PROFILE.parseHeader({ ...value, version: 3, delegationDepth }, expected);
23151
+ return { ...value, delegationDepth };
23152
+ },
23153
+ parseHistoryRecord: (value, remaining) => parseV015HistoryRecord(value, remaining, (event) => parseEvent(event, 4)),
23154
+ parseLiveItem: (value) => {
23155
+ const item = parseV015LiveItem(value, (event) => parseEvent(event, 4));
23156
+ if (item.type === "assistant-stream" && "frame" in item && item.frame.type === "chunk") {
23157
+ validateV4Chunk(item.frame.chunk);
23158
+ }
23159
+ return item;
23160
+ },
23161
+ parseAssistantBaseline(value) {
23162
+ const baseline = parseV015AssistantBaseline(value);
23163
+ if (baseline.activeAttempt)
23164
+ validateV4Stream(baseline.activeAttempt.stream);
23165
+ return baseline;
23166
+ },
23167
+ validateContent: validateV4Content,
23168
+ validateChunk: validateV4Chunk,
23169
+ validateEvent(event) {
23170
+ if (event.type === "developer/message") {
23171
+ validateDeveloperMessage(event);
23172
+ } else if (event.type === "system/message") {
23173
+ if (!isRecord3(event.data) || !isRecord3(event.data.message))
23174
+ invalid2("system/message");
23175
+ exactKeys2(event.data, ["turn", "step", "message"]);
23176
+ const message = event.data.message;
23177
+ requiredFields(message, ["id", "role", "content", "source"]);
23178
+ requiredString(message.id, "system/message id");
23179
+ if (message.role !== "system" || !isRecord3(message.source) || message.source.kind !== "system-prompt") {
23180
+ invalid2("system/message source");
23181
+ }
23182
+ validateV4Content(message.content);
23183
+ } else if (event.type === "image/offload") {
23184
+ if (!isRecord3(event.data))
23185
+ invalid2("image/offload");
23186
+ exactKeys2(event.data, ["targets"]);
23187
+ if (!Array.isArray(event.data.targets) || event.data.targets.length === 0)
23188
+ invalid2("image/offload targets");
23189
+ } else if (event.type === "workspace/changes") {
23190
+ if (!isRecord3(event.data))
23191
+ invalid2("workspace/changes");
23192
+ exactKeys2(event.data, ["turn"]);
23193
+ positiveInteger(event.data.turn, "workspace/changes turn");
23194
+ } else if (event.type === "tool/result") {
23195
+ if (!isRecord3(event.data))
23196
+ invalid2("tool/result");
23197
+ const message = event.data.message;
23198
+ if (event.data.error !== void 0 && (!isRecord3(message) || message.isError !== true)) {
23199
+ invalid2("tool/result error marker");
23200
+ }
23201
+ } else if (event.type === "request/header") {
23202
+ DEEPSEEK_V015_PROFILE.validateEvent(event);
23203
+ if (!isRecord3(event.data) || !isRecord3(event.data.header))
23204
+ invalid2("request/header");
23205
+ const tools = event.data.header.tools;
23206
+ if (tools !== void 0 && (!Array.isArray(tools) || tools.some((tool) => !isRecord3(tool) || tool.deferLoading !== void 0 && tool.deferLoading !== true))) {
23207
+ invalid2("request/header tools");
23208
+ }
23209
+ } else if (event.type === "assistant/message" || event.type === "assistant/attempt") {
23210
+ DEEPSEEK_V015_PROFILE.validateEvent(event);
23211
+ if (!isRecord3(event.data))
23212
+ invalid2("assistant settlement");
23213
+ validateV4Stream(event.data.stream);
23214
+ } else {
23215
+ DEEPSEEK_V015_PROFILE.validateEvent(event);
23216
+ }
23217
+ }
23218
+ });
23219
+
22907
23220
  // dist/profiles/profile.js
23221
+ var V4_MINIMUM = parseSemVer("0.1.7-rc.1");
23222
+ function parseSemVer(value) {
23223
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/u.exec(value);
23224
+ if (!match)
23225
+ return void 0;
23226
+ const prerelease = match[4] ? match[4].split(".").map((part) => /^\d+$/u.test(part) ? Number(part) : part) : [];
23227
+ return {
23228
+ major: Number(match[1]),
23229
+ minor: Number(match[2]),
23230
+ patch: Number(match[3]),
23231
+ prerelease
23232
+ };
23233
+ }
23234
+ function compareSemVer(left, right) {
23235
+ for (const key of ["major", "minor", "patch"]) {
23236
+ if (left[key] !== right[key])
23237
+ return left[key] > right[key] ? 1 : -1;
23238
+ }
23239
+ if (left.prerelease.length === 0 || right.prerelease.length === 0) {
23240
+ return left.prerelease.length === right.prerelease.length ? 0 : left.prerelease.length === 0 ? 1 : -1;
23241
+ }
23242
+ const length = Math.max(left.prerelease.length, right.prerelease.length);
23243
+ for (let index = 0; index < length; index += 1) {
23244
+ const leftPart = left.prerelease[index];
23245
+ const rightPart = right.prerelease[index];
23246
+ if (leftPart === void 0 || rightPart === void 0) {
23247
+ return leftPart === rightPart ? 0 : leftPart === void 0 ? -1 : 1;
23248
+ }
23249
+ if (leftPart === rightPart)
23250
+ continue;
23251
+ if (typeof leftPart === "number" && typeof rightPart === "string")
23252
+ return -1;
23253
+ if (typeof leftPart === "string" && typeof rightPart === "number")
23254
+ return 1;
23255
+ return leftPart > rightPart ? 1 : -1;
23256
+ }
23257
+ return 0;
23258
+ }
23259
+ function usesV4Profile(version2) {
23260
+ const parsed = parseSemVer(version2);
23261
+ return parsed !== void 0 && V4_MINIMUM !== void 0 && compareSemVer(parsed, V4_MINIMUM) >= 0;
23262
+ }
22908
23263
  function deepSeekModernProfile(version2) {
22909
- const base = /^0\.1\.2(?:-|\+|$)/u.test(version2) ? DEEPSEEK_V012_PROFILE : DEEPSEEK_V015_PROFILE;
23264
+ const base = /^0\.1\.2(?:-|\+|$)/u.test(version2) ? DEEPSEEK_V012_PROFILE : usesV4Profile(version2) ? DEEPSEEK_V017_PROFILE : DEEPSEEK_V015_PROFILE;
22910
23265
  return base.version === version2 ? base : Object.freeze({ ...base, version: version2 });
22911
23266
  }
22912
- function isDeepSeekV015(profile) {
22913
- return profile.sessionFormatVersion === 3;
23267
+ function hasDeepSeekModernStream(profile) {
23268
+ return profile.sessionFormatVersion >= 3;
22914
23269
  }
22915
23270
 
22916
23271
  // dist/modern/commands.js
@@ -22992,7 +23347,7 @@ async function callModernCommand(remote, endpoint, args, parse3, signal, timeout
22992
23347
  }
22993
23348
  }
22994
23349
  function executeModernCommand(remote, agentId, line, signal, profile = DEEPSEEK_V012_PROFILE) {
22995
- return callModernCommand(remote, "commands/execute", isDeepSeekV015(profile) ? { agentId, line, submittedAttachments: [] } : { agentId, line, images: [] }, parseModernCommandExecution, signal, null);
23350
+ return callModernCommand(remote, "commands/execute", profile.sessionFormatVersion !== 0 ? { agentId, line, submittedAttachments: [] } : { agentId, line, images: [] }, parseModernCommandExecution, signal, null);
22996
23351
  }
22997
23352
 
22998
23353
  // dist/modern/control-store.js
@@ -23264,13 +23619,15 @@ function parseSessionCollection(value, kind, sessions, maxSessions) {
23264
23619
  }
23265
23620
  }
23266
23621
  }
23267
- function parseBaseline(value, maxSessions, maxKeys) {
23268
- if (!isRecord6(value) || !hasExactKeys4(value, ["queues", "jobs", "projections"]) || !isPlainRecord3(value.projections)) {
23622
+ function parseBaseline(value, maxSessions, maxKeys, formatVersion) {
23623
+ if (!isRecord6(value) || !hasExactKeys4(value, formatVersion === 4 ? ["projections"] : ["queues", "jobs", "projections"]) || !isPlainRecord3(value.projections)) {
23269
23624
  throw storeError("protocolError", "DeepSeek Harness control stream emitted an invalid baseline");
23270
23625
  }
23271
23626
  const sessions = /* @__PURE__ */ new Set();
23272
- parseSessionCollection(value.queues, "queues", sessions, maxSessions);
23273
- parseSessionCollection(value.jobs, "jobs", sessions, maxSessions);
23627
+ if (formatVersion !== 4) {
23628
+ parseSessionCollection(value.queues, "queues", sessions, maxSessions);
23629
+ parseSessionCollection(value.jobs, "jobs", sessions, maxSessions);
23630
+ }
23274
23631
  const projections = /* @__PURE__ */ Object.create(null);
23275
23632
  for (const [sessionId, block] of Object.entries(value.projections)) {
23276
23633
  if (!validIdentifier(sessionId)) {
@@ -23284,12 +23641,15 @@ function parseBaseline(value, maxSessions, maxKeys) {
23284
23641
  }
23285
23642
  return { projections };
23286
23643
  }
23287
- function parseControlFrame(value, maxSessions, maxKeys) {
23644
+ function parseControlFrame(value, maxSessions, maxKeys, formatVersion) {
23288
23645
  if (!isRecord6(value) || typeof value.type !== "string") {
23289
23646
  throw storeError("protocolError", "DeepSeek Harness control stream emitted an invalid frame");
23290
23647
  }
23291
23648
  if (value.type === "baseline" && hasExactKeys4(value, ["type", "value"])) {
23292
- return { type: "baseline", value: parseBaseline(value.value, maxSessions, maxKeys) };
23649
+ return {
23650
+ type: "baseline",
23651
+ value: parseBaseline(value.value, maxSessions, maxKeys, formatVersion)
23652
+ };
23293
23653
  }
23294
23654
  if (value.type === "projection" && hasExactKeys4(value, ["type", "sessionId", "key", "value", "seq"]) && validIdentifier(value.sessionId) && validProjectionKey(value.key) && validSeq(value.seq)) {
23295
23655
  const projection = measureProjection(value.key, value.value);
@@ -23302,12 +23662,12 @@ function parseControlFrame(value, maxSessions, maxKeys) {
23302
23662
  bytes: projection.bytes
23303
23663
  };
23304
23664
  }
23305
- if (value.type === "queue" && hasExactKeys4(value, ["type", "sessionId", "items"]) && validIdentifier(value.sessionId) && Array.isArray(value.items) && value.items.length <= MAX_COLLECTION_ITEMS) {
23665
+ if (formatVersion !== 4 && value.type === "queue" && hasExactKeys4(value, ["type", "sessionId", "items"]) && validIdentifier(value.sessionId) && Array.isArray(value.items) && value.items.length <= MAX_COLLECTION_ITEMS) {
23306
23666
  for (const item of value.items)
23307
23667
  parseQueueItem(item);
23308
23668
  return { type: "queue", sessionId: value.sessionId };
23309
23669
  }
23310
- if (value.type === "jobs" && hasExactKeys4(value, ["type", "sessionId", "jobs"]) && validIdentifier(value.sessionId) && Array.isArray(value.jobs) && value.jobs.length <= MAX_COLLECTION_ITEMS) {
23670
+ if (formatVersion !== 4 && value.type === "jobs" && hasExactKeys4(value, ["type", "sessionId", "jobs"]) && validIdentifier(value.sessionId) && Array.isArray(value.jobs) && value.jobs.length <= MAX_COLLECTION_ITEMS) {
23311
23671
  for (const job of value.jobs)
23312
23672
  parseJob(job);
23313
23673
  return { type: "jobs", sessionId: value.sessionId };
@@ -23319,6 +23679,7 @@ function parseSeed(value, maxKeys) {
23319
23679
  }
23320
23680
  var ModernControlStore = class {
23321
23681
  #lifetime = new AbortController();
23682
+ #formatVersion;
23322
23683
  #maxKeys;
23323
23684
  #maxSessions;
23324
23685
  #maxWaiters;
@@ -23339,6 +23700,7 @@ var ModernControlStore = class {
23339
23700
  #readyResolve;
23340
23701
  constructor(source, options = {}) {
23341
23702
  this.#source = source;
23703
+ this.#formatVersion = options.profile?.sessionFormatVersion ?? 3;
23342
23704
  this.#maxSessions = positiveInteger3(options.maxSessions ?? DEFAULT_MAX_SESSIONS, "maxSessions");
23343
23705
  this.#maxKeys = positiveInteger3(options.maxKeysPerSession ?? DEFAULT_MAX_KEYS_PER_SESSION, "maxKeysPerSession");
23344
23706
  this.#maxWaiters = positiveInteger3(options.maxWaiters ?? DEFAULT_MAX_WAITERS, "maxWaiters");
@@ -23507,7 +23869,7 @@ var ModernControlStore = class {
23507
23869
  replaceBaseline(frame) {
23508
23870
  this.#assertUsable();
23509
23871
  try {
23510
- const parsed = parseControlFrame(frame, this.#maxSessions, this.#maxKeys);
23872
+ const parsed = parseControlFrame(frame, this.#maxSessions, this.#maxKeys, this.#formatVersion);
23511
23873
  if (parsed.type !== "baseline") {
23512
23874
  throw storeError("protocolError", "Control baseline replacement requires a baseline frame");
23513
23875
  }
@@ -23548,7 +23910,7 @@ var ModernControlStore = class {
23548
23910
  return;
23549
23911
  throw storeError(this.#opened ? "unavailable" : "protocolError", this.#opened ? "DeepSeek Harness control stream ended unexpectedly" : "DeepSeek Harness control stream ended before its baseline");
23550
23912
  }
23551
- const frame = parseControlFrame(next.value, this.#maxSessions, this.#maxKeys);
23913
+ const frame = parseControlFrame(next.value, this.#maxSessions, this.#maxKeys, this.#formatVersion);
23552
23914
  if (!generationOpened && frame.type !== "baseline") {
23553
23915
  throw storeError("protocolError", "DeepSeek Harness control stream omitted its baseline");
23554
23916
  }
@@ -24679,7 +25041,7 @@ function validateSecrets(value) {
24679
25041
  }
24680
25042
  return value;
24681
25043
  }
24682
- function parseDescribe(value) {
25044
+ function parseDescribe(value, profile) {
24683
25045
  assertBoundedJson2(value);
24684
25046
  if (!isPlainRecord4(value) || !exactKeys3(value, ["writable", "hasDocument", "namespaces"])) {
24685
25047
  throw permissionError("protocolError", "DeepSeek Harness returned an invalid settings response");
@@ -24693,7 +25055,7 @@ function parseDescribe(value) {
24693
25055
  const namespaceIds = [];
24694
25056
  const permissionNamespaces = [];
24695
25057
  for (const candidate of value.namespaces) {
24696
- if (!isPlainRecord4(candidate) || !exactKeys3(candidate, ["ns", "schema", "value", "applies", "secrets", "revision"], ["base", "user"]) || candidate.applies !== "live" && candidate.applies !== "restart" || !validRevision(candidate.revision)) {
25058
+ if (!isPlainRecord4(candidate) || !exactKeys3(candidate, profile.sessionFormatVersion === 4 ? ["ns", "autoGenerate", "schema", "value", "applies", "secrets", "revision"] : ["ns", "schema", "value", "applies", "secrets", "revision"], ["base", "user"]) || profile.sessionFormatVersion === 4 && typeof candidate.autoGenerate !== "boolean" || candidate.applies !== "live" && candidate.applies !== "restart" || !validRevision(candidate.revision)) {
24697
25059
  throw permissionError("protocolError", "DeepSeek Harness returned an invalid settings namespace");
24698
25060
  }
24699
25061
  const ns = nonBlankString2(candidate.ns, MAX_NAMESPACE_ID_LENGTH, "settings namespace id");
@@ -24731,7 +25093,7 @@ function permissionSection(value, requireDefault, knownIds, area) {
24731
25093
  }
24732
25094
  }
24733
25095
  }
24734
- function catalogFromNamespace(view) {
25096
+ function catalogFromNamespace(view, profile) {
24735
25097
  if (view.applies !== "live") {
24736
25098
  throw permissionError("protocolError", "DeepSeek Harness permission settings are not live");
24737
25099
  }
@@ -24750,10 +25112,14 @@ function catalogFromNamespace(view) {
24750
25112
  }
24751
25113
  const field = dictionary.defaultPreset;
24752
25114
  if (field.meta?.required !== true) {
25115
+ if (profile.sessionFormatVersion === 4)
25116
+ return null;
24753
25117
  throw permissionError("protocolError", "DeepSeek Harness permission default is not required");
24754
25118
  }
24755
25119
  const choices = field.type === "union" ? field.list : field.type === "const" ? [field] : void 0;
24756
25120
  if (!Array.isArray(choices) || choices.length === 0) {
25121
+ if (profile.sessionFormatVersion === 4)
25122
+ return null;
24757
25123
  throw permissionError("protocolError", "DeepSeek Harness permission schema has no preset choices");
24758
25124
  }
24759
25125
  if (choices.length > HARNESS_PERMISSION_MODE_CATALOG_MAX_LENGTH) {
@@ -24793,18 +25159,18 @@ function catalogFromNamespace(view) {
24793
25159
  throw permissionError("protocolError", "DeepSeek Harness returned an unusable permission catalog");
24794
25160
  }
24795
25161
  }
24796
- function parseModernPermissionModeCatalog(value) {
24797
- const permission = parseDescribe(value);
24798
- return permission ? catalogFromNamespace(permission) : null;
25162
+ function parseModernPermissionModeCatalog(value, profile = DEEPSEEK_V015_PROFILE) {
25163
+ const permission = parseDescribe(value, profile);
25164
+ return permission ? catalogFromNamespace(permission, profile) : null;
24799
25165
  }
24800
- async function loadModernPermissionModeCatalog(remote, signal) {
25166
+ async function loadModernPermissionModeCatalog(remote, signal, profile = DEEPSEEK_V015_PROFILE) {
24801
25167
  try {
24802
25168
  const result = await remote.call("settings/describe", {}, signal);
24803
25169
  if (!result.ok) {
24804
25170
  const safe = sanitizeModernRemoteFailure(result.error);
24805
25171
  throw permissionError("remoteError", `DeepSeek Harness settings/describe failed: ${safe.message}`, safe.code);
24806
25172
  }
24807
- return parseModernPermissionModeCatalog(result.value);
25173
+ return parseModernPermissionModeCatalog(result.value, profile);
24808
25174
  } catch (error51) {
24809
25175
  if (error51 instanceof ModernPermissionModeError)
24810
25176
  throw error51;
@@ -24860,8 +25226,10 @@ function parseProjectionValue(value, catalog) {
24860
25226
  }
24861
25227
  return current.data;
24862
25228
  }
24863
- function readModernPermissionModeState(row, catalog) {
25229
+ function readModernPermissionModeState(row, catalog, profile) {
24864
25230
  if (!catalog) {
25231
+ if (profile?.sessionFormatVersion === 4)
25232
+ return void 0;
24865
25233
  if (row) {
24866
25234
  throw permissionError("protocolError", "DeepSeek Harness exposed permissions without a settings catalog");
24867
25235
  }
@@ -24996,7 +25364,7 @@ function readModernConfigurationSnapshot(input) {
24996
25364
  throw configurationError("protocolError", "DeepSeek Harness control state is detached");
24997
25365
  }
24998
25366
  const model = readModernModelSelectionState(rows[MODERN_MODEL_SELECTION_PROJECTION_KEY], input.modelCatalog);
24999
- const permission = readModernPermissionModeState(rows[MODERN_PERMISSION_PROJECTION_KEY], input.permissionModes);
25367
+ const permission = readModernPermissionModeState(rows[MODERN_PERMISSION_PROJECTION_KEY], input.permissionModes, input.profile);
25000
25368
  return {
25001
25369
  model,
25002
25370
  state: stateForSelection(input.nativeRef, model.selection, input.modelCatalog, permission?.permissionModeId),
@@ -25971,10 +26339,14 @@ function parseQuestionOption(value) {
25971
26339
  };
25972
26340
  }
25973
26341
  function parseQuestionIntent(value) {
25974
- if (!isPlainRecord6(value) || !hasExactKeys5(value, ["kind", "approve"]) || value.kind !== "plan-review" || !nonBlankString3(value.approve)) {
26342
+ if (!isPlainRecord6(value) || !hasOnlyKeys(value, ["kind", "approve"], ["callId"]) || value.kind !== "plan-review" || !nonBlankString3(value.approve) || Object.hasOwn(value, "callId") && !nonBlankString3(value.callId)) {
25975
26343
  throw invalidFrame();
25976
26344
  }
25977
- return { kind: "plan-review", approve: value.approve };
26345
+ return {
26346
+ kind: "plan-review",
26347
+ approve: value.approve,
26348
+ ...typeof value.callId === "string" ? { callId: value.callId } : {}
26349
+ };
25978
26350
  }
25979
26351
  function parseQuestionAnswer(value) {
25980
26352
  if (!isPlainRecord6(value) || !hasExactKeys5(value, ["answers"]) || !Array.isArray(value.answers)) {
@@ -26758,6 +27130,13 @@ var KNOWN_EVENT_TYPES = /* @__PURE__ */ new Set([
26758
27130
  "user/message",
26759
27131
  "web/deepseek-search-llm-request"
26760
27132
  ]);
27133
+ var V4_EVENT_TYPES = /* @__PURE__ */ new Set(["developer/message", "image/offload", "workspace/changes"]);
27134
+ function knownEvent(type, profile) {
27135
+ return KNOWN_EVENT_TYPES.has(type) || profile.sessionFormatVersion === 4 && V4_EVENT_TYPES.has(type);
27136
+ }
27137
+ function surfaceEvent(type, profile) {
27138
+ return SURFACE_EVENT_TYPES.has(type) || profile.sessionFormatVersion === 4 && type === "developer/message";
27139
+ }
26761
27140
  var SURFACE_EVENT_TYPES = /* @__PURE__ */ new Set([
26762
27141
  "system/message",
26763
27142
  "user/message",
@@ -26776,7 +27155,10 @@ var ModernEventValidator = class {
26776
27155
  surface: [],
26777
27156
  pendingCalls: /* @__PURE__ */ new Set(),
26778
27157
  commandStates: /* @__PURE__ */ new Map(),
26779
- commandEventSeqs: /* @__PURE__ */ new Set()
27158
+ commandEventSeqs: /* @__PURE__ */ new Set(),
27159
+ requestHeaders: /* @__PURE__ */ new Map(),
27160
+ offloadedImages: /* @__PURE__ */ new Set(),
27161
+ toolCalls: /* @__PURE__ */ new Map()
26780
27162
  };
26781
27163
  constructor(maxEvents = MODERN_HISTORY_MAX_EVENTS, profile = DEEPSEEK_V012_PROFILE) {
26782
27164
  this.#maxEvents = boundedInteger(maxEvents, "maxEvents", 1);
@@ -26789,16 +27171,16 @@ var ModernEventValidator = class {
26789
27171
  if (event.seq !== trace.count)
26790
27172
  fail("Modern history is not a contiguous zero-based prefix");
26791
27173
  trace.count += 1;
26792
- if (isDeepSeekV015(this.#profile) && !KNOWN_EVENT_TYPES.has(event.type) && event.ignorable === true)
27174
+ if (hasDeepSeekModernStream(this.#profile) && !knownEvent(event.type, this.#profile) && event.ignorable === true)
26793
27175
  return;
26794
- if (!SURFACE_EVENT_TYPES.has(event.type)) {
27176
+ if (!surfaceEvent(event.type, this.#profile)) {
26795
27177
  if (event.surfaceOp !== void 0 || event.sourceEventSeqs !== void 0) {
26796
27178
  fail("Modern history has surface metadata on a log-only event");
26797
27179
  }
26798
27180
  } else if (event.surfaceOp === void 0) {
26799
27181
  fail("Modern history surface event omitted surfaceOp");
26800
27182
  }
26801
- if (!KNOWN_EVENT_TYPES.has(event.type)) {
27183
+ if (!knownEvent(event.type, this.#profile)) {
26802
27184
  if (event.ignorable === true)
26803
27185
  return;
26804
27186
  fail("Modern history contains an unknown required event");
@@ -26822,10 +27204,13 @@ var ModernEventValidator = class {
26822
27204
  case "turn/end": {
26823
27205
  exactKeys2(data, ["turn", "reason"]);
26824
27206
  const turn = positiveInteger(data.turn, "turn/end turn");
26825
- validateTurnReason(data.reason);
27207
+ validateTurnReason(data.reason, this.#profile);
26826
27208
  if (trace.openTurn !== turn || trace.openStep !== null) {
26827
27209
  fail("Modern history has an invalid turn/end boundary");
26828
27210
  }
27211
+ if (this.#profile.sessionFormatVersion === 4 && trace.toolCalls.size > 0) {
27212
+ fail("Modern history turn/end leaves unresolved tool calls");
27213
+ }
26829
27214
  trace.openTurn = null;
26830
27215
  trace.nextTurn += 1;
26831
27216
  return;
@@ -26842,6 +27227,9 @@ var ModernEventValidator = class {
26842
27227
  case "step/end": {
26843
27228
  exactKeys2(data, ["turn", "step"]);
26844
27229
  requireOpenStep(trace, data, "step/end");
27230
+ if (this.#profile.sessionFormatVersion === 4 && trace.toolCalls.size > 0) {
27231
+ fail("Modern history step/end leaves unresolved tool calls");
27232
+ }
26845
27233
  trace.openStep = null;
26846
27234
  trace.nextStep += 1;
26847
27235
  trace.pendingCalls.clear();
@@ -26850,6 +27238,10 @@ var ModernEventValidator = class {
26850
27238
  case "user/message":
26851
27239
  validateUserMessage(data, this.#profile);
26852
27240
  return;
27241
+ case "developer/message":
27242
+ requireOpenStep(trace, data, "developer/message");
27243
+ validateDeveloperHeader(event, trace);
27244
+ return;
26853
27245
  case "system/message":
26854
27246
  requireOpenStep(trace, data, "system/message");
26855
27247
  return;
@@ -26861,6 +27253,8 @@ var ModernEventValidator = class {
26861
27253
  case "assistant/message": {
26862
27254
  requireOpenStep(trace, data, "assistant/message");
26863
27255
  validateAssistantMessage(data.message, this.#profile);
27256
+ if (this.#profile.sessionFormatVersion === 4)
27257
+ registerV4ToolCalls(data.message, trace);
26864
27258
  if (data.interrupted !== void 0 && data.interrupted !== true) {
26865
27259
  fail("Modern history assistant/message has invalid interrupted marker");
26866
27260
  }
@@ -26874,10 +27268,18 @@ var ModernEventValidator = class {
26874
27268
  exactKeys2(data, ["turn", "step", "callId", "name", "arguments"]);
26875
27269
  requireOpenStep(trace, data, "tool/call");
26876
27270
  const callId = requiredString(data.callId, "tool/call callId");
26877
- requiredString(data.name, "tool/call name");
27271
+ const name = requiredString(data.name, "tool/call name");
26878
27272
  if (typeof data.arguments !== "string" || trace.pendingCalls.has(callId)) {
26879
27273
  fail("Modern history contains an invalid tool/call");
26880
27274
  }
27275
+ if (this.#profile.sessionFormatVersion === 4) {
27276
+ const tool = trace.toolCalls.get(callId);
27277
+ if (!tool || tool.started || tool.name !== name || tool.arguments !== data.arguments) {
27278
+ fail("Modern history tool/call does not match its advertised tool call");
27279
+ }
27280
+ tool.started = true;
27281
+ return;
27282
+ }
26881
27283
  trace.pendingCalls.add(callId);
26882
27284
  return;
26883
27285
  }
@@ -26885,10 +27287,16 @@ var ModernEventValidator = class {
26885
27287
  requiredOptionalKeys(data, ["turn", "step", "message"], ["error", "meta"]);
26886
27288
  const callId = validateToolResultMessage(data.message, this.#profile);
26887
27289
  if (data.error !== void 0)
26888
- validateToolError(data.error);
27290
+ validateToolError(data.error, this.#profile);
26889
27291
  if (event.surfaceOp === "append") {
26890
27292
  requireOpenStep(trace, data, "tool/result");
26891
- if (!trace.pendingCalls.delete(callId)) {
27293
+ if (this.#profile.sessionFormatVersion === 4) {
27294
+ const tool = trace.toolCalls.get(callId);
27295
+ if (!tool || !tool.started && !isV4ForkToolResult(data, event.sourceEventSeqs, event.seq)) {
27296
+ fail("Modern history contains an unmatched tool/result");
27297
+ }
27298
+ trace.toolCalls.delete(callId);
27299
+ } else if (!trace.pendingCalls.delete(callId)) {
26892
27300
  fail("Modern history contains an unmatched tool/result");
26893
27301
  }
26894
27302
  } else if (trace.openTurn === null) {
@@ -26900,6 +27308,7 @@ var ModernEventValidator = class {
26900
27308
  validateRequestHeader(data);
26901
27309
  if (trace.openTurn === null)
26902
27310
  fail("Modern history request/header is outside a Turn");
27311
+ trace.requestHeaders.set(event.seq, data.header);
26903
27312
  return;
26904
27313
  case "request/context":
26905
27314
  validateRequestContext(data, this.#profile);
@@ -26911,6 +27320,11 @@ var ModernEventValidator = class {
26911
27320
  return;
26912
27321
  case "session/end-seed":
26913
27322
  return;
27323
+ case "image/offload":
27324
+ validateImageOffload(data, trace);
27325
+ return;
27326
+ case "workspace/changes":
27327
+ return;
26914
27328
  case "agent-preset/selected":
26915
27329
  exactKeys2(data, ["agentPreset"]);
26916
27330
  requiredString(data.agentPreset, "agent-preset/selected agentPreset");
@@ -27040,20 +27454,113 @@ var ModernEventValidator = class {
27040
27454
  }
27041
27455
  }
27042
27456
  };
27457
+ function registerV4ToolCalls(value, trace) {
27458
+ if (!isRecord4(value) || !Array.isArray(value.content))
27459
+ return;
27460
+ for (const block of value.content) {
27461
+ if (!isRecord4(block) || block.type !== "tool-call")
27462
+ continue;
27463
+ const callId = requiredString(block.id, "assistant tool-call id");
27464
+ const name = requiredString(block.name, "assistant tool-call name");
27465
+ if (typeof block.arguments !== "string" || trace.toolCalls.has(callId)) {
27466
+ fail("Modern history assistant/message repeats an advertised tool call");
27467
+ }
27468
+ trace.toolCalls.set(callId, { name, arguments: block.arguments, started: false });
27469
+ }
27470
+ }
27471
+ function isV4ForkToolResult(data, sourceEventSeqs, seq) {
27472
+ if (!isRecord4(data.error) || data.error.name !== "ToolNotStartedError" || data.error.code !== "TOOL_NOT_STARTED" || !isRecord4(data.message) || data.message.role !== "tool" || data.message.isError !== true || !isRecord4(data.message.source) || data.message.source.kind !== "tool" || typeof data.message.source.callId !== "string" || data.message.toolCallId !== data.message.source.callId || typeof data.message.id !== "string" || data.message.id !== `forked-tool-result-${data.message.source.callId}-${seq}` || sourceEventSeqs !== void 0 || !Array.isArray(data.message.content) || data.message.content.length !== 1) {
27473
+ return false;
27474
+ }
27475
+ const content = data.message.content[0];
27476
+ return isRecord4(content) && content.type === "text" && typeof content.text === "string" && data.message.id.endsWith(`-${seq}`);
27477
+ }
27478
+ function validateDeveloperHeader(event, trace) {
27479
+ const data = event.data;
27480
+ if (data.headerSeq === void 0)
27481
+ return;
27482
+ const header = trace.requestHeaders.get(data.headerSeq);
27483
+ if (!header || !Array.isArray(header.tools)) {
27484
+ fail("Modern history developer/message references an invalid request/header");
27485
+ }
27486
+ const message = data.message;
27487
+ for (const block of message.content) {
27488
+ if (!isRecord4(block) || block.type !== "tool-addition")
27489
+ continue;
27490
+ const matching = header.tools.filter((tool) => isRecord4(tool) && tool.name === block.toolName);
27491
+ if (matching.length !== 1 || !isRecord4(matching[0]) || typeof matching[0].description !== "string" || !isRecord4(matching[0].parameters) || matching[0].deferLoading !== void 0 && matching[0].deferLoading !== true) {
27492
+ fail("Modern history developer/message references an invalid tool definition");
27493
+ }
27494
+ }
27495
+ }
27496
+ function strictIndex(value, label) {
27497
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0 || Object.is(value, -0)) {
27498
+ fail(`Modern history ${label} is malformed`);
27499
+ }
27500
+ return value;
27501
+ }
27502
+ function validateImageOffload(data, trace) {
27503
+ const seen = /* @__PURE__ */ new Set();
27504
+ for (const target of data.targets) {
27505
+ if (!isRecord4(target))
27506
+ fail("Modern history image/offload target is malformed");
27507
+ exactKeys2(target, ["seq", "imageIndexes"]);
27508
+ const seq = strictIndex(target.seq, "image/offload target seq");
27509
+ if (seen.has(seq))
27510
+ fail("Modern history image/offload repeats a target");
27511
+ seen.add(seq);
27512
+ const source = trace.surface.find((event) => event.seq === seq);
27513
+ if (!source || source.type !== "user/message" && source.type !== "tool/result") {
27514
+ fail("Modern history image/offload target is not a current message");
27515
+ }
27516
+ const sourceData = source.type === "user/message" ? source.data : source.data.message;
27517
+ const content = isRecord4(sourceData) ? sourceData.content : void 0;
27518
+ if (!Array.isArray(content) || !Array.isArray(target.imageIndexes) || !target.imageIndexes.length) {
27519
+ fail("Modern history image/offload indexes are malformed");
27520
+ }
27521
+ const images = [];
27522
+ const collectImages = (value) => {
27523
+ if (!Array.isArray(value))
27524
+ return;
27525
+ for (const block of value) {
27526
+ if (!isRecord4(block))
27527
+ continue;
27528
+ if (block.type === "image")
27529
+ images.push(block);
27530
+ if (Array.isArray(block.content))
27531
+ collectImages(block.content);
27532
+ }
27533
+ };
27534
+ collectImages(content);
27535
+ let previous = -1;
27536
+ for (const value of target.imageIndexes) {
27537
+ const index = strictIndex(value, "image/offload index");
27538
+ const image = images[index];
27539
+ if (index <= previous || !isRecord4(image) || image.offloaded === true || trace.offloadedImages.has(`${seq}:${index}`)) {
27540
+ fail("Modern history image/offload references an invalid image occurrence");
27541
+ }
27542
+ trace.offloadedImages.add(`${seq}:${index}`);
27543
+ previous = index;
27544
+ }
27545
+ }
27546
+ }
27043
27547
  function acceptSurfaceEvent(trace, event, profile) {
27044
- if (!SURFACE_EVENT_TYPES.has(event.type))
27548
+ if (!surfaceEvent(event.type, profile))
27045
27549
  return;
27046
27550
  const sources = event.sourceEventSeqs;
27047
- if (sources !== void 0 && (!Array.isArray(sources) || sources.some((seq) => !nonNegativeSafeInteger2(seq) || Object.is(seq, -0) || seq >= event.seq) || new Set(sources).size !== sources.length || sources.length === 0 && event.type !== "assistant/message")) {
27551
+ if (sources !== void 0 && (!Array.isArray(sources) || sources.some((seq) => !nonNegativeSafeInteger2(seq) || Object.is(seq, -0) || seq >= event.seq) || new Set(sources).size !== sources.length || sources.length === 0 && (profile.sessionFormatVersion === 4 || event.type !== "assistant/message"))) {
27048
27552
  fail("Modern history surface event has invalid sourceEventSeqs");
27049
27553
  }
27050
27554
  const op = event.surfaceOp;
27051
27555
  if (op === "append") {
27556
+ if (profile.sessionFormatVersion === 4 && event.type === "system/message" && trace.surface.length > 0 && !trace.surface.some((surface) => surface.type === "system/message")) {
27557
+ fail("Modern history system/message must remain the protected surface head");
27558
+ }
27052
27559
  trace.surface.push(event);
27053
27560
  return;
27054
27561
  }
27055
- const start = isDeepSeekV015(profile) ? "startSeq" : "start";
27056
- const end = isDeepSeekV015(profile) ? "endSeq" : "end";
27562
+ const start = hasDeepSeekModernStream(profile) ? "startSeq" : "start";
27563
+ const end = hasDeepSeekModernStream(profile) ? "endSeq" : "end";
27057
27564
  if (!isRecord4(op) || Reflect.ownKeys(op).length !== 3 || !Object.hasOwn(op, "op") || !Object.hasOwn(op, start) || !Object.hasOwn(op, end) || op.op !== "replace" || !nonNegativeSafeInteger2(op[start]) || Object.is(op[start], -0) || !nonNegativeSafeInteger2(op[end]) || Object.is(op[end], -0)) {
27058
27565
  fail("Modern history surface event has an invalid replacement operation");
27059
27566
  }
@@ -27071,17 +27578,20 @@ function acceptSurfaceEvent(trace, event, profile) {
27071
27578
  fail("Modern history system head may only be replaced by one system/message");
27072
27579
  }
27073
27580
  if (event.type === "tool/result") {
27074
- if (shadowed.length !== 1 || shadowed[0]?.type !== "tool/result" || !isDeepStrictEqual6(comparableToolResultData(shadowed[0]), comparableToolResultData(event))) {
27581
+ if (shadowed.length !== 1 || shadowed[0]?.type !== "tool/result" || !isDeepStrictEqual6(comparableToolResultData(shadowed[0], profile), comparableToolResultData(event, profile))) {
27075
27582
  fail("Modern history tool/result replacement changed more than result content");
27076
27583
  }
27077
27584
  }
27078
27585
  trace.surface.splice(startIndex, endIndex - startIndex + 1, event);
27079
27586
  }
27080
- function comparableToolResultData(event) {
27587
+ function comparableToolResultData(event, profile) {
27081
27588
  const data = event.data;
27082
- if (!isRecord4(data) || !isRecord4(data.message) || !Array.isArray(data.message.content) || !isRecord4(data.message.content[0])) {
27589
+ if (!isRecord4(data) || !isRecord4(data.message) || !Array.isArray(data.message.content) || profile.sessionFormatVersion !== 4 && !isRecord4(data.message.content[0])) {
27083
27590
  fail("Modern history tool/result replacement is malformed");
27084
27591
  }
27592
+ if (profile.sessionFormatVersion === 4) {
27593
+ return { ...data, message: { ...data.message, content: null } };
27594
+ }
27085
27595
  return {
27086
27596
  ...data,
27087
27597
  message: {
@@ -27104,6 +27614,8 @@ function resolveModernForkBoundary(events, checkpointId, profile = DEEPSEEK_V012
27104
27614
  if (atSeq === null || events[atSeq]?.seq !== atSeq || events[atSeq]?.type !== "turn/end") {
27105
27615
  return null;
27106
27616
  }
27617
+ if (profile.sessionFormatVersion === 4)
27618
+ return { atSeq, events: events.slice(0, atSeq + 1) };
27107
27619
  let cut = atSeq + 1;
27108
27620
  while (cut < events.length && events[cut]?.type !== "turn/start")
27109
27621
  cut += 1;
@@ -27152,7 +27664,7 @@ function projectModernHistory(input) {
27152
27664
  };
27153
27665
  for (const [index, event] of input.events.entries()) {
27154
27666
  validator.accept(event);
27155
- if (!KNOWN_EVENT_TYPES.has(event.type) || !isRecord4(event.data))
27667
+ if (!knownEvent(event.type, profile) || !isRecord4(event.data))
27156
27668
  continue;
27157
27669
  const data = event.data;
27158
27670
  switch (event.type) {
@@ -27163,6 +27675,7 @@ function projectModernHistory(input) {
27163
27675
  input: [],
27164
27676
  items: [],
27165
27677
  tools: /* @__PURE__ */ new Map(),
27678
+ advertisedTools: /* @__PURE__ */ new Map(),
27166
27679
  model: effectiveModel
27167
27680
  };
27168
27681
  break;
@@ -27241,7 +27754,7 @@ function projectModernHistory(input) {
27241
27754
  harnessId,
27242
27755
  nativeSessionId: input.sessionId,
27243
27756
  formatVersion: 1,
27244
- ...isDeepSeekV015(profile) ? { locator: { dshVersion: profile.version } } : {}
27757
+ ...hasDeepSeekModernStream(profile) ? { locator: { dshVersion: profile.version } } : {}
27245
27758
  });
27246
27759
  const state = {
27247
27760
  nativeRef,
@@ -27273,7 +27786,7 @@ function modernCheckpointRef(harnessId, sessionId, seq, profile = DEEPSEEK_V012_
27273
27786
  nativeSessionId: sessionId,
27274
27787
  checkpointId: `${profile.checkpointPrefix}${seq}`,
27275
27788
  formatVersion: 1,
27276
- ...isDeepSeekV015(profile) ? { locator: { dshVersion: profile.version } } : {}
27789
+ ...hasDeepSeekModernStream(profile) ? { locator: { dshVersion: profile.version } } : {}
27277
27790
  });
27278
27791
  }
27279
27792
  function modernItemId(sessionId, key) {
@@ -27281,6 +27794,13 @@ function modernItemId(sessionId, key) {
27281
27794
  }
27282
27795
  function projectAssistantMessage(turn, sessionId, data) {
27283
27796
  const message = data.message;
27797
+ if (Array.isArray(message.content)) {
27798
+ for (const block of message.content) {
27799
+ if (isRecord4(block) && block.type === "tool-call" && typeof block.id === "string" && typeof block.name === "string" && typeof block.arguments === "string") {
27800
+ turn.advertisedTools.set(block.id, { toolName: block.name, arguments: block.arguments });
27801
+ }
27802
+ }
27803
+ }
27284
27804
  const reasoning2 = contentByType(message.content, "reasoning");
27285
27805
  if (reasoning2) {
27286
27806
  const item = {
@@ -27313,15 +27833,32 @@ function projectToolCall(turn, sessionId, data, seq) {
27313
27833
  const itemIndex = turn.items.length;
27314
27834
  turn.items.push({ item, outcome: incompleteToolOutcome(item.toolName) });
27315
27835
  turn.tools.set(data.callId, { itemIndex, item, toolName: item.toolName });
27836
+ turn.advertisedTools.delete(data.callId);
27316
27837
  }
27317
27838
  function projectToolResultEvent(turn, sessionId, data, seq, limit) {
27318
27839
  const result = projectToolResult(data.message, limit);
27319
27840
  if (!result)
27320
27841
  fail("Modern history contains an unprojectable tool/result");
27321
- const tool = turn.tools.get(result.callId);
27322
- if (!tool)
27842
+ let tool = turn.tools.get(result.callId);
27843
+ if (!tool) {
27844
+ const advertised = turn.advertisedTools.get(result.callId);
27845
+ if (advertised && isForkedToolResult(data, result.callId, seq)) {
27846
+ const item2 = {
27847
+ type: "toolExecution",
27848
+ itemId: modernItemId(sessionId, `event:${seq}:tool`),
27849
+ toolName: advertised.toolName,
27850
+ arguments: parseArguments(advertised.arguments)
27851
+ };
27852
+ const itemIndex = turn.items.length;
27853
+ turn.items.push({ item: item2, outcome: incompleteToolOutcome(item2.toolName) });
27854
+ tool = { itemIndex, item: item2, toolName: item2.toolName };
27855
+ }
27856
+ }
27857
+ if (!tool) {
27323
27858
  fail("Modern history contains an unmatched projected tool/result");
27859
+ }
27324
27860
  turn.tools.delete(result.callId);
27861
+ turn.advertisedTools.delete(result.callId);
27325
27862
  const item = { ...tool.item, ...result.output ? { output: result.output } : {} };
27326
27863
  turn.items[tool.itemIndex] = {
27327
27864
  item,
@@ -27347,6 +27884,10 @@ function projectToolResultEvent(turn, sessionId, data, seq, limit) {
27347
27884
  }
27348
27885
  }
27349
27886
  }
27887
+ function isForkedToolResult(data, callId, seq) {
27888
+ const message = data.message;
27889
+ return isRecord4(data.error) && data.error.name === "ToolNotStartedError" && data.error.code === "TOOL_NOT_STARTED" && isRecord4(message) && message.role === "tool" && message.isError === true && message.toolCallId === callId && typeof message.id === "string" && message.id === `forked-tool-result-${callId}-${seq}`;
27890
+ }
27350
27891
  function finishIncompleteTools(turn, outcome) {
27351
27892
  for (const tool of turn.tools.values())
27352
27893
  turn.items[tool.itemIndex] = { item: tool.item, outcome };
@@ -27417,12 +27958,15 @@ function stepPosition(data, label) {
27417
27958
  };
27418
27959
  }
27419
27960
  function validateUserMessage(data, profile = DEEPSEEK_V012_PROFILE) {
27420
- exactKeys2(data, ["id", "role", "content", "source"]);
27961
+ if (profile.sessionFormatVersion === 4)
27962
+ requiredFields2(data, ["id", "role", "content", "source"]);
27963
+ else
27964
+ exactKeys2(data, ["id", "role", "content", "source"]);
27421
27965
  requiredString(data.id, "user/message id");
27422
27966
  if (data.role !== "user")
27423
27967
  fail("Modern history user/message has an invalid role");
27424
27968
  profile.validateContent(data.content);
27425
- if (!isRecord4(data.source) || !requiredString(data.source.kind, "user/message source kind")) {
27969
+ if (!isRecord4(data.source) || !requiredString(data.source.kind, "user/message source kind") || profile.sessionFormatVersion === 4 && data.source.kind === "plugin") {
27426
27970
  fail("Modern history user/message has an invalid source");
27427
27971
  }
27428
27972
  if (data.source.kind === "user" && data.source.rpcId !== void 0) {
@@ -27432,7 +27976,10 @@ function validateUserMessage(data, profile = DEEPSEEK_V012_PROFILE) {
27432
27976
  function validateAssistantMessage(value, profile = DEEPSEEK_V012_PROFILE) {
27433
27977
  if (!isRecord4(value))
27434
27978
  fail("Modern history assistant/message is malformed");
27435
- exactKeys2(value, ["id", "role", "content", "source"]);
27979
+ if (profile.sessionFormatVersion === 4)
27980
+ requiredFields2(value, ["id", "role", "content", "source"]);
27981
+ else
27982
+ exactKeys2(value, ["id", "role", "content", "source"]);
27436
27983
  requiredString(value.id, "assistant/message id");
27437
27984
  if (value.role !== "assistant")
27438
27985
  fail("Modern history assistant/message has an invalid role");
@@ -27444,6 +27991,19 @@ function validateAssistantMessage(value, profile = DEEPSEEK_V012_PROFILE) {
27444
27991
  function validateToolResultMessage(value, profile = DEEPSEEK_V012_PROFILE) {
27445
27992
  if (!isRecord4(value))
27446
27993
  fail("Modern history tool/result message is malformed");
27994
+ if (profile.sessionFormatVersion === 4) {
27995
+ requiredFields2(value, ["id", "role", "content", "source", "toolCallId"]);
27996
+ requiredString(value.id, "tool/result message id");
27997
+ if (value.role !== "tool" || !isRecord4(value.source) || value.source.kind !== "tool") {
27998
+ fail("Modern history tool/result message has an invalid role or source");
27999
+ }
28000
+ const callId2 = requiredString(value.source.callId, "tool/result source callId");
28001
+ if (value.toolCallId !== callId2 || value.isError !== void 0 && typeof value.isError !== "boolean") {
28002
+ fail("Modern history tool/result message has invalid callId or isError");
28003
+ }
28004
+ profile.validateContent(value.content);
28005
+ return callId2;
28006
+ }
27447
28007
  exactKeys2(value, ["id", "role", "content", "source"]);
27448
28008
  requiredString(value.id, "tool/result message id");
27449
28009
  if (value.role !== "user" || !isRecord4(value.source) || value.source.kind !== "tool") {
@@ -27464,6 +28024,11 @@ function validateToolResultMessage(value, profile = DEEPSEEK_V012_PROFILE) {
27464
28024
  }
27465
28025
  return callId;
27466
28026
  }
28027
+ function requiredFields2(value, fields) {
28028
+ if (fields.some((field) => !Object.hasOwn(value, field))) {
28029
+ fail("Modern history known event omitted a required field");
28030
+ }
28031
+ }
27467
28032
  function validateUsage(value) {
27468
28033
  if (!validUsage(value))
27469
28034
  fail("Modern history usage is malformed");
@@ -27487,7 +28052,7 @@ function validUsage(value) {
27487
28052
  }
27488
28053
  return fields.slice(2).every((field) => value[field] === void 0 || nonNegativeSafeInteger2(value[field]));
27489
28054
  }
27490
- function validateTurnReason(value) {
28055
+ function validateTurnReason(value, profile) {
27491
28056
  if (!isRecord4(value) || typeof value.kind !== "string") {
27492
28057
  fail("Modern history turn/end reason is malformed");
27493
28058
  }
@@ -27498,6 +28063,11 @@ function validateTurnReason(value) {
27498
28063
  case "interrupted":
27499
28064
  exactKeys2(value, ["kind"]);
27500
28065
  return;
28066
+ case "forked":
28067
+ if (profile.sessionFormatVersion !== 4)
28068
+ fail("Modern history contains an unknown Turn outcome");
28069
+ exactKeys2(value, ["kind"]);
28070
+ return;
27501
28071
  case "aborted":
27502
28072
  exactKeys2(value, ["kind", "reason"]);
27503
28073
  if (!isRecord4(value.reason) || typeof value.reason.kind !== "string") {
@@ -27552,7 +28122,7 @@ function validateRequestHeader(data) {
27552
28122
  }
27553
28123
  }
27554
28124
  function validateRequestContext(data, profile) {
27555
- requiredOptionalKeys(data, ["provider", "model"], isDeepSeekV015(profile) ? ["contextWindow", "systemPromptUpdate"] : ["contextWindow"]);
28125
+ requiredOptionalKeys(data, ["provider", "model"], hasDeepSeekModernStream(profile) ? ["contextWindow", "systemPromptUpdate"] : ["contextWindow"]);
27556
28126
  if (!nonBlankString(data.provider) || !nonBlankString(data.model)) {
27557
28127
  fail("Modern history request/context has an invalid Model route");
27558
28128
  }
@@ -27570,12 +28140,15 @@ function validateModelSelection(data) {
27570
28140
  fail("Modern history model/selection has invalid reasoningEffort");
27571
28141
  }
27572
28142
  }
27573
- function validateToolError(value) {
28143
+ function validateToolError(value, profile) {
27574
28144
  if (!isRecord4(value))
27575
28145
  fail("Modern history tool/result error is malformed");
27576
- exactKeys2(value, ["name", "code"]);
28146
+ requiredOptionalKeys(value, ["name", "code"], profile.sessionFormatVersion === 4 ? ["reason"] : []);
27577
28147
  requiredString(value.name, "tool/result error name");
27578
28148
  requiredString(value.code, "tool/result error code");
28149
+ if (value.reason !== void 0 && typeof value.reason !== "string") {
28150
+ fail("Modern history tool/result error reason is malformed");
28151
+ }
27579
28152
  }
27580
28153
  function validateInboxSplice(data, profile) {
27581
28154
  requiredOptionalKeys(data, ["target", "start", "inserted"], ["removedCount", "outcome"]);
@@ -27685,7 +28258,7 @@ function validateRetry(data) {
27685
28258
  requiredString(data.provider, "llm/retry provider");
27686
28259
  requiredString(data.policyKey, "llm/retry policyKey");
27687
28260
  positiveInteger(data.retry, "llm/retry retry");
27688
- nonNegativeInteger(data.delayMs, "llm/retry delayMs");
28261
+ nonNegativeFiniteNumber(data.delayMs, "llm/retry delayMs");
27689
28262
  if (mode === "normal")
27690
28263
  positiveInteger(data.maxRetries, "llm/retry maxRetries");
27691
28264
  validateLlmFailure(data.failure, "llm/retry failure");
@@ -27899,7 +28472,7 @@ function validateSubagentModelPolicy(data) {
27899
28472
  validateModelRoute(route, "subagent Model policy route");
27900
28473
  }
27901
28474
  function validateTeamEvent(type, data, profile) {
27902
- if (data.version !== (isDeepSeekV015(profile) ? 2 : 1))
28475
+ if (data.version !== (hasDeepSeekModernStream(profile) ? 2 : 1))
27903
28476
  fail("Modern history team event version is malformed");
27904
28477
  requiredString(data.teamId, "team event teamId");
27905
28478
  if (type === "team/message/delivered") {
@@ -28087,7 +28660,8 @@ var ModernHarnessSession = class {
28087
28660
  sessionId: this.#sessionId,
28088
28661
  nativeRef: projection.nativeRef,
28089
28662
  modelCatalog: this.#modelCatalog,
28090
- permissionModes: this.#permissionModes
28663
+ permissionModes: this.#permissionModes,
28664
+ profile: this.#profile
28091
28665
  });
28092
28666
  this.#nativeRef = projection.nativeRef;
28093
28667
  this.initialState = configuration.state;
@@ -28387,7 +28961,8 @@ ${question.detail}` : question.question;
28387
28961
  sessionId: this.#sessionId,
28388
28962
  nativeRef: this.#nativeRef,
28389
28963
  modelCatalog: this.#modelCatalog,
28390
- permissionModes: this.#permissionModes
28964
+ permissionModes: this.#permissionModes,
28965
+ profile: this.#profile
28391
28966
  });
28392
28967
  }
28393
28968
  #onConfigurationProjection() {
@@ -29025,6 +29600,9 @@ ${question.detail}` : question.question;
29025
29600
  if (attempt && !attempt.projected && active?.nativeTurn === attempt.turn && active.agent) {
29026
29601
  this.#cancelAgentItem(active);
29027
29602
  }
29603
+ if (attempt && active?.reasoning?.attemptId === attempt.attemptId) {
29604
+ this.#cancelReasoningItem(active);
29605
+ }
29028
29606
  this.#assistantAttempt = void 0;
29029
29607
  }
29030
29608
  #cancelAgentItem(active) {
@@ -29042,6 +29620,13 @@ ${question.detail}` : question.question;
29042
29620
  delete active.agent;
29043
29621
  this.#completeItem(active, agent.item, { status: "cancelled" });
29044
29622
  }
29623
+ #cancelReasoningItem(active) {
29624
+ const reasoning2 = active.reasoning;
29625
+ if (!reasoning2)
29626
+ return;
29627
+ delete active.reasoning;
29628
+ this.#completeItem(active, reasoning2.item, { status: "cancelled" });
29629
+ }
29045
29630
  #projectAssistantLiveChunks() {
29046
29631
  const attempt = this.#assistantAttempt;
29047
29632
  const active = this.#active;
@@ -29076,6 +29661,7 @@ ${question.detail}` : question.question;
29076
29661
  this.#projectAssistantLiveChunks();
29077
29662
  } else {
29078
29663
  this.#cancelAgentItem(active);
29664
+ this.#cancelReasoningItem(active);
29079
29665
  }
29080
29666
  attempt.projected = true;
29081
29667
  if (attempt.ended)
@@ -29295,6 +29881,7 @@ ${question.detail}` : question.question;
29295
29881
  input: [...input],
29296
29882
  autonomous,
29297
29883
  tools: /* @__PURE__ */ new Map(),
29884
+ reasoningOrdinal: 0,
29298
29885
  interactions: /* @__PURE__ */ new Set(),
29299
29886
  terminal: false,
29300
29887
  cancelAcknowledged: false
@@ -29350,6 +29937,9 @@ ${question.detail}` : question.question;
29350
29937
  if (event.surfaceOp === "append")
29351
29938
  this.#completeTool(active, data, event.seq);
29352
29939
  return;
29940
+ case "step/end":
29941
+ this.#cancelReasoningItem(active);
29942
+ return;
29353
29943
  case "turn/end":
29354
29944
  this.#finishTurn(buffer, active, data.reason, event.seq);
29355
29945
  return;
@@ -29361,7 +29951,7 @@ ${question.detail}` : question.question;
29361
29951
  if (chunk.type === "text-delta") {
29362
29952
  this.#appendAgent(active, chunk.text, step, attemptId);
29363
29953
  } else if (chunk.type === "reasoning-delta") {
29364
- this.#appendReasoning(active, chunk.text, step, startedAtMs);
29954
+ this.#appendReasoning(active, chunk.text, step, true, attemptId, false, startedAtMs);
29365
29955
  } else if (chunk.type === "usage" && !initialReplay) {
29366
29956
  this.#publishUsageChanges(active.turnId);
29367
29957
  }
@@ -29387,39 +29977,51 @@ ${question.detail}` : question.question;
29387
29977
  update: { type: "text.append", text }
29388
29978
  });
29389
29979
  }
29390
- #startReasoning(active, step) {
29980
+ #startReasoning(active, step, provisional, attemptId) {
29391
29981
  if (!active.reasoning) {
29982
+ const key = provisional ? `reasoning:provisional:${++active.reasoningOrdinal}` : "reasoning";
29392
29983
  const item = {
29393
29984
  type: "reasoning",
29394
- itemId: modernItemId(this.#sessionId, `turn:${active.nativeTurn}:step:${step}:reasoning`),
29985
+ itemId: modernItemId(this.#sessionId, `turn:${active.nativeTurn}:step:${step}:${key}`),
29395
29986
  text: ""
29396
29987
  };
29397
- active.reasoning = { item, text: "" };
29988
+ active.reasoning = {
29989
+ item,
29990
+ text: "",
29991
+ provisional,
29992
+ pendingLineBreaks: "",
29993
+ ...attemptId ? { attemptId } : {}
29994
+ };
29398
29995
  this.#emit({ type: "item.started", turnId: active.turnId, item });
29399
29996
  }
29400
29997
  return active.reasoning;
29401
29998
  }
29402
- #appendReasoning(active, text, step, startedAtMs) {
29999
+ #appendReasoning(active, text, step, provisional = false, attemptId, final = false, startedAtMs) {
29403
30000
  if (!text)
29404
30001
  return;
29405
- const reasoning2 = this.#startReasoning(active, step);
30002
+ const reasoning2 = this.#startReasoning(active, step, provisional, attemptId);
29406
30003
  if (startedAtMs !== void 0 && reasoning2.startedAtMs === void 0) {
29407
30004
  reasoning2.startedAtMs = startedAtMs;
29408
30005
  }
29409
- reasoning2.text += text;
30006
+ const candidate = final ? text : reasoning2.pendingLineBreaks + text;
30007
+ const appended = final ? candidate : candidate.replace(/[\r\n]+$/u, "");
30008
+ reasoning2.pendingLineBreaks = final ? "" : candidate.slice(appended.length);
30009
+ if (!appended)
30010
+ return;
30011
+ reasoning2.text += appended;
29410
30012
  reasoning2.item = { ...reasoning2.item, text: reasoning2.text };
29411
30013
  this.#emit({
29412
30014
  type: "item.updated",
29413
30015
  turnId: active.turnId,
29414
30016
  itemId: reasoning2.item.itemId,
29415
- update: { type: "text.append", text }
30017
+ update: { type: "text.append", text: appended }
29416
30018
  });
29417
30019
  }
29418
30020
  #completeAssistant(active, data, endedAtMs) {
29419
30021
  const message = data.message;
29420
30022
  const step = data.step;
29421
- const reasoning2 = contentText(message.content, "reasoning");
29422
- const text = contentText(message.content, "text");
30023
+ const reasoning2 = contentText2(message.content, "reasoning");
30024
+ const text = contentText2(message.content, "text");
29423
30025
  if (this.#profile.assistantStream && active.agent && !text.startsWith(active.agent.text)) {
29424
30026
  this.#cancelAgentItem(active);
29425
30027
  }
@@ -29434,48 +30036,26 @@ ${question.detail}` : question.question;
29434
30036
  }
29435
30037
  }
29436
30038
  /**
29437
- * Reconciles the streamed reasoning preview with the authoritative block-end
29438
- * text. A preview already started on the Host cannot be retracted: when the
29439
- * authoritative text matches or extends it, the preview completes as-is;
29440
- * when it diverges, the preview completes and the authoritative text
29441
- * restarts as its own Item. durationMs keeps native journal time
29442
- * (first reasoning delta → block end) whenever both are known.
30039
+ * Reconciles the streamed preview with the authoritative block-end text.
30040
+ * A diverging preview is cancelled; the journal text is what remains.
30041
+ * durationMs keeps native journal time (first reasoning delta → block end)
30042
+ * whenever both are known.
29443
30043
  */
29444
30044
  #completeReasoning(active, finalText, step, endedAtMs) {
30045
+ if (active.reasoning && !finalText.startsWith(active.reasoning.text)) {
30046
+ this.#cancelReasoningItem(active);
30047
+ }
30048
+ const suffix = finalText.slice(active.reasoning?.text.length ?? 0);
30049
+ if (suffix)
30050
+ this.#appendReasoning(active, suffix, step, false, void 0, true);
29445
30051
  const current = active.reasoning;
29446
- if (!current) {
29447
- if (!finalText)
29448
- return;
29449
- this.#appendReasoning(active, finalText, step);
29450
- const materialized = active.reasoning;
29451
- delete active.reasoning;
29452
- if (materialized) {
29453
- this.#completeItem(active, materialized.item, { status: "succeeded" });
29454
- }
30052
+ if (!current)
29455
30053
  return;
29456
- }
29457
30054
  const durationMs = current.startedAtMs === void 0 ? void 0 : Math.max(0, endedAtMs - current.startedAtMs);
29458
- if (finalText.startsWith(current.text)) {
29459
- this.#appendReasoning(active, finalText.slice(current.text.length), step);
29460
- const item = withReasoningDuration(current.item, durationMs);
29461
- delete active.reasoning;
29462
- this.#completeItem(active, item, { status: "succeeded" });
29463
- return;
29464
- }
29465
30055
  delete active.reasoning;
29466
30056
  this.#completeItem(active, withReasoningDuration(current.item, durationMs), {
29467
30057
  status: "succeeded"
29468
30058
  });
29469
- if (!finalText)
29470
- return;
29471
- const authoritative = {
29472
- type: "reasoning",
29473
- itemId: modernItemId(this.#sessionId, `turn:${active.nativeTurn}:step:${step}:reasoning:final`),
29474
- text: finalText,
29475
- ...durationMs === void 0 ? {} : { durationMs }
29476
- };
29477
- this.#emit({ type: "item.started", turnId: active.turnId, item: authoritative });
29478
- this.#completeItem(active, authoritative, { status: "succeeded" });
29479
30059
  }
29480
30060
  #completeAgentPrefix(active, finalText, step) {
29481
30061
  let current = active.agent;
@@ -29555,6 +30135,7 @@ ${question.detail}` : question.question;
29555
30135
  const projected = turnOutcome(reason);
29556
30136
  const itemOutcome2 = toItemOutcome(projected);
29557
30137
  this.#discardAssistantAttempt();
30138
+ this.#cancelReasoningItem(active);
29558
30139
  this.#closeActiveInteractions(active);
29559
30140
  this.#completeOpenItems(active, itemOutcome2);
29560
30141
  active.terminal = true;
@@ -29666,6 +30247,7 @@ ${question.detail}` : question.question;
29666
30247
  input: hostBound ? textInputs2(pending.command.input) : [...buffer.input],
29667
30248
  autonomous: !hostBound,
29668
30249
  tools: /* @__PURE__ */ new Map(),
30250
+ reasoningOrdinal: 0,
29669
30251
  interactions: /* @__PURE__ */ new Set(),
29670
30252
  terminal: false,
29671
30253
  cancelAcknowledged: false
@@ -30106,6 +30688,9 @@ function turnOutcome(reason) {
30106
30688
  if (reason.kind === "aborted") {
30107
30689
  return { status: "cancelled", reason: "Cancelled by user" };
30108
30690
  }
30691
+ if (reason.kind === "forked") {
30692
+ return { status: "cancelled", reason: "Forked from parent Session" };
30693
+ }
30109
30694
  return {
30110
30695
  status: "failed",
30111
30696
  error: {
@@ -30129,7 +30714,7 @@ function textInputs2(value) {
30129
30714
  function hasText(part) {
30130
30715
  return part.text.length > 0;
30131
30716
  }
30132
- function contentText(value, type) {
30717
+ function contentText2(value, type) {
30133
30718
  return Array.isArray(value) ? value.filter((block) => isRecord4(block) && block.type === type && typeof block.text === "string").map((block) => block.text).join("") : "";
30134
30719
  }
30135
30720
  function withReasoningDuration(item, durationMs) {
@@ -30239,17 +30824,17 @@ function boundedId(value, area) {
30239
30824
  function validUpdatedAt(value) {
30240
30825
  return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && value <= DEEPSEEK_MODERN_SESSION_UPDATED_AT_MAX && !Object.is(value, -0);
30241
30826
  }
30242
- function titleFromProjections(value) {
30827
+ function titleFromProjections(value, profile) {
30243
30828
  if (value === void 0)
30244
30829
  return null;
30245
- if (!isPlainRecord7(value) || !exactKeys5(value, ["asOfSeq", "values"]) || !Number.isSafeInteger(value.asOfSeq) || value.asOfSeq < -1 || !isPlainRecord7(value.values)) {
30830
+ if (!isPlainRecord7(value) || !exactKeys5(value, profile.sessionFormatVersion === 4 ? ["kind", "asOfSeq", "values"] : ["asOfSeq", "values"]) || profile.sessionFormatVersion === 4 && value.kind !== "cached" && value.kind !== "sequenced" || !Number.isSafeInteger(value.asOfSeq) || value.asOfSeq < -1 || !isPlainRecord7(value.values)) {
30246
30831
  throw sessionListError("protocolError", "DeepSeek Harness returned invalid Session list projections");
30247
30832
  }
30248
30833
  const title = value.values.title;
30249
30834
  return typeof title === "string" && title.trim().length > 0 && title.length <= DEEPSEEK_MODERN_SESSION_TITLE_MAX_LENGTH && !title.includes("\0") ? title : null;
30250
30835
  }
30251
- function parseSummary(value) {
30252
- if (!isPlainRecord7(value) || !exactKeys5(value, ["sessionId", "updatedAt", "running", "blank"], ["parentSessionId", "origin", "cwd", "projections"]) || typeof value.running !== "boolean" || typeof value.blank !== "boolean" || !validUpdatedAt(value.updatedAt)) {
30836
+ function parseSummary(value, profile) {
30837
+ if (!isPlainRecord7(value) || !exactKeys5(value, profile.sessionFormatVersion === 4 ? ["sessionId", "updatedAt", "agentAvailable", "running", "blank"] : ["sessionId", "updatedAt", "running", "blank"], ["parentSessionId", "origin", "cwd", "projections"]) || typeof value.running !== "boolean" || typeof value.blank !== "boolean" || profile.sessionFormatVersion === 4 && typeof value.agentAvailable !== "boolean" || !validUpdatedAt(value.updatedAt)) {
30253
30838
  throw sessionListError("protocolError", "DeepSeek Harness returned an invalid Session row");
30254
30839
  }
30255
30840
  const sessionId = boundedId(value.sessionId, "Session id");
@@ -30272,13 +30857,13 @@ function parseSummary(value) {
30272
30857
  blank: value.blank,
30273
30858
  ...value.origin === void 0 ? {} : { origin: value.origin },
30274
30859
  ...value.cwd === void 0 ? {} : { cwd: value.cwd },
30275
- title: titleFromProjections(value.projections)
30860
+ title: titleFromProjections(value.projections, profile)
30276
30861
  };
30277
30862
  }
30278
30863
  function isCanonicalAbsoluteCwd(value) {
30279
30864
  return value !== void 0 && value.trim().length > 0 && !value.includes("\0") && path2.isAbsolute(value) && path2.resolve(value) === value;
30280
30865
  }
30281
- function parseModernSessionCandidates(value) {
30866
+ function parseModernSessionCandidates(value, profile = DEEPSEEK_V015_PROFILE) {
30282
30867
  assertBoundedJson4(value);
30283
30868
  if (!isPlainRecord7(value) || !exactKeys5(value, ["items"]) || !Array.isArray(value.items)) {
30284
30869
  throw sessionListError("protocolError", "DeepSeek Harness returned an invalid Session list");
@@ -30288,7 +30873,7 @@ function parseModernSessionCandidates(value) {
30288
30873
  }
30289
30874
  const seen = /* @__PURE__ */ new Set();
30290
30875
  const summaries = value.items.map((item) => {
30291
- const summary = parseSummary(item);
30876
+ const summary = parseSummary(item, profile);
30292
30877
  if (seen.has(summary.sessionId)) {
30293
30878
  throw sessionListError("protocolError", "DeepSeek Harness returned duplicate Session identities");
30294
30879
  }
@@ -30310,14 +30895,14 @@ function parseModernSessionCandidates(value) {
30310
30895
  ];
30311
30896
  });
30312
30897
  }
30313
- async function loadModernSessionCandidates(remote, signal) {
30898
+ async function loadModernSessionCandidates(remote, signal, profile = DEEPSEEK_V015_PROFILE) {
30314
30899
  try {
30315
30900
  const result = await remote.call("session/list", { _request: {} }, signal);
30316
30901
  if (!result.ok) {
30317
30902
  const safe = sanitizeModernRemoteFailure(result.error);
30318
30903
  throw sessionListError("remoteError", `DeepSeek Harness session/list failed: ${safe.message}`, safe.code);
30319
30904
  }
30320
- return parseModernSessionCandidates(result.value);
30905
+ return parseModernSessionCandidates(result.value, profile);
30321
30906
  } catch (error51) {
30322
30907
  if (error51 instanceof ModernSessionListError)
30323
30908
  throw error51;
@@ -30386,6 +30971,7 @@ var ModernDeepSeekHarnessAdapter = class {
30386
30971
  onFault: (error51) => this.#fail(toHarnessError(error51, "unavailable"))
30387
30972
  });
30388
30973
  this.#control = new ModernControlStore(this.#connection, {
30974
+ profile: this.#profile,
30389
30975
  onFault: (error51) => this.#fail(toHarnessError(error51, "unavailable"))
30390
30976
  });
30391
30977
  this.#removeConnectionFaultListener = this.#connection.onFault((error51) => {
@@ -30458,7 +31044,7 @@ var ModernDeepSeekHarnessAdapter = class {
30458
31044
  try {
30459
31045
  await this.#connection.connect();
30460
31046
  this.#assertAccepting();
30461
- const candidates = await loadModernSessionCandidates(this.#connection, this.#lifetime.signal);
31047
+ const candidates = await loadModernSessionCandidates(this.#connection, this.#lifetime.signal, this.#profile);
30462
31048
  this.#assertAccepting();
30463
31049
  return { ok: true, value: candidates };
30464
31050
  } catch (error51) {
@@ -30554,7 +31140,7 @@ var ModernDeepSeekHarnessAdapter = class {
30554
31140
  this.#assertAccepting();
30555
31141
  if (forkExpectation) {
30556
31142
  await this.#verifyForkJournal(forkExpectation, journal, cwd);
30557
- if (isDeepSeekV015(this.#profile) && await clearInheritedForkInbox(this.#connection, journal, this.#lifetime.signal)) {
31143
+ if (hasDeepSeekModernStream(this.#profile) && await clearInheritedForkInbox(this.#connection, journal, this.#lifetime.signal)) {
30558
31144
  await journal.close();
30559
31145
  journal = await openModernJournal(this.#connection, { sessionId, cwd }, this.#journalOptions());
30560
31146
  await this.#verifyForkJournal(forkExpectation, journal, cwd);
@@ -30590,10 +31176,11 @@ var ModernDeepSeekHarnessAdapter = class {
30590
31176
  harnessId: this.harnessId,
30591
31177
  nativeSessionId: sessionId,
30592
31178
  formatVersion: 1,
30593
- ...isDeepSeekV015(this.#profile) ? { locator: { dshVersion: this.#profile.version } } : {}
31179
+ ...hasDeepSeekModernStream(this.#profile) ? { locator: { dshVersion: this.#profile.version } } : {}
30594
31180
  }),
30595
31181
  modelCatalog: catalog,
30596
- permissionModes
31182
+ permissionModes,
31183
+ profile: this.#profile
30597
31184
  });
30598
31185
  verifyCreateConfiguration(createConfiguration, openedConfiguration);
30599
31186
  if (createConfiguration?.unattended && !delegationPermissionIsApplied(journal.events)) {
@@ -30611,7 +31198,7 @@ var ModernDeepSeekHarnessAdapter = class {
30611
31198
  modelCatalog: catalog,
30612
31199
  permissionModes,
30613
31200
  sessionId,
30614
- ...isDeepSeekV015(this.#profile) ? { flushSession: () => this.#connection.flushSession(sessionId) } : {},
31201
+ ...hasDeepSeekModernStream(this.#profile) ? { flushSession: () => this.#connection.flushSession(sessionId) } : {},
30615
31202
  randomUUID: this.#dependencies.randomUUID,
30616
31203
  now: this.#dependencies.now,
30617
31204
  ...this.#options.toolOutputLimit === void 0 ? {} : { toolOutputLimit: this.#options.toolOutputLimit },
@@ -30753,7 +31340,7 @@ var ModernDeepSeekHarnessAdapter = class {
30753
31340
  }
30754
31341
  atSeq = boundary.atSeq;
30755
31342
  minimumSeedLength = boundary.events.length;
30756
- if (boundary.events.length < source.events.length) {
31343
+ if (this.#profile.sessionFormatVersion === 4 || boundary.events.length < source.events.length) {
30757
31344
  exactSeedLength = boundary.events.length;
30758
31345
  }
30759
31346
  } finally {
@@ -30846,7 +31433,7 @@ var ModernDeepSeekHarnessAdapter = class {
30846
31433
  }
30847
31434
  if (this.#permissionModesPromise)
30848
31435
  return this.#permissionModesPromise;
30849
- const operation = loadModernPermissionModeCatalog(this.#connection).then((catalog) => {
31436
+ const operation = loadModernPermissionModeCatalog(this.#connection, this.#lifetime.signal, this.#profile).then((catalog) => {
30850
31437
  this.#permissionModes = catalog;
30851
31438
  this.#permissionModesLoaded = true;
30852
31439
  return catalog;
@@ -31071,18 +31658,19 @@ function parseModernForkInput(input, profile) {
31071
31658
  function sessionLocatorMatches(locator, profile) {
31072
31659
  if (locator === void 0)
31073
31660
  return true;
31074
- if (!isDeepSeekV015(profile) || !isRecord8(locator) || Reflect.ownKeys(locator).length !== 1 || typeof locator.dshVersion !== "string") {
31661
+ if (!hasDeepSeekModernStream(profile) || !isRecord8(locator) || Reflect.ownKeys(locator).length !== 1 || typeof locator.dshVersion !== "string") {
31075
31662
  return false;
31076
31663
  }
31077
31664
  try {
31078
31665
  const { version: version2 } = classifyDeepSeekVersionOutput(locator.dshVersion);
31079
- return isDeepSeekV015(deepSeekModernProfile(version2));
31666
+ const original = deepSeekModernProfile(version2);
31667
+ return original.sessionFormatVersion === profile.sessionFormatVersion || profile.sessionFormatVersion === 4 && original.sessionFormatVersion === 3;
31080
31668
  } catch {
31081
31669
  return false;
31082
31670
  }
31083
31671
  }
31084
31672
  function checkpointLocatorMatches(locator, profile) {
31085
- return isDeepSeekV015(profile) ? profileLocatorMatches(locator, profile) : locator === void 0;
31673
+ return hasDeepSeekModernStream(profile) ? profileLocatorMatches(locator, profile) : locator === void 0;
31086
31674
  }
31087
31675
  function profileLocatorMatches(locator, profile) {
31088
31676
  return isRecord8(locator) && Reflect.ownKeys(locator).length === 1 && locator.dshVersion === profile.version;
@@ -31293,7 +31881,7 @@ var DeepSeekHarnessAdapter = class {
31293
31881
  harnessId: this.harnessId,
31294
31882
  nativeSessionId,
31295
31883
  formatVersion: 1,
31296
- ...this.#delegate && isDeepSeekV015(deepSeekModernProfile(this.#delegate.version)) ? { locator: { dshVersion: this.#delegate.version } } : {}
31884
+ ...this.#delegate && hasDeepSeekModernStream(deepSeekModernProfile(this.#delegate.version)) ? { locator: { dshVersion: this.#delegate.version } } : {}
31297
31885
  })
31298
31886
  }
31299
31887
  };
@@ -31651,17 +32239,478 @@ function closedError2() {
31651
32239
  };
31652
32240
  }
31653
32241
 
32242
+ // ../../harness-discovery/dist/environment.js
32243
+ import fs from "node:fs";
32244
+ import path4 from "node:path";
32245
+ function targetPath(platform) {
32246
+ return platform === "win32" ? path4.win32 : path4.posix;
32247
+ }
32248
+ function environmentValue2(environment, name) {
32249
+ const lowered = name.toLowerCase();
32250
+ for (const [key, value] of Object.entries(environment)) {
32251
+ if (key.toLowerCase() === lowered)
32252
+ return value;
32253
+ }
32254
+ return void 0;
32255
+ }
32256
+ function pathDelimiter(platform) {
32257
+ return platform === "win32" ? ";" : ":";
32258
+ }
32259
+ function pathDirectories(environment, platform) {
32260
+ return (environmentValue2(environment, "PATH") ?? "").split(pathDelimiter(platform)).map((directory) => directory.trim().replace(/^"|"$/gu, "")).filter(Boolean);
32261
+ }
32262
+ function executableExtensions(command, platform, environment) {
32263
+ if (platform !== "win32")
32264
+ return [""];
32265
+ if (targetPath(platform).extname(command) !== "")
32266
+ return [""];
32267
+ return (environmentValue2(environment, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").map((extension2) => extension2.trim()).filter(Boolean);
32268
+ }
32269
+ function isExecutableFile(filePath, platform) {
32270
+ try {
32271
+ fs.accessSync(filePath, platform === "win32" ? fs.constants.F_OK : fs.constants.X_OK);
32272
+ return fs.statSync(filePath).isFile();
32273
+ } catch {
32274
+ return false;
32275
+ }
32276
+ }
32277
+ function subdirectoryNames(directory) {
32278
+ try {
32279
+ return fs.readdirSync(directory, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
32280
+ } catch {
32281
+ return [];
32282
+ }
32283
+ }
32284
+ function newestFirst(names) {
32285
+ return [...names].sort((left, right) => right.localeCompare(left, void 0, { numeric: true }));
32286
+ }
32287
+
32288
+ // ../../harness-discovery/dist/invocation.js
32289
+ import path5 from "node:path";
32290
+ function commandInvocation(command, arguments_, environment, platform = process.platform) {
32291
+ const extension2 = path5.win32.extname(command).toLowerCase();
32292
+ if (platform !== "win32" || ![".cmd", ".bat"].includes(extension2)) {
32293
+ return { command, arguments: [...arguments_], windowsVerbatimArguments: false };
32294
+ }
32295
+ const quote = (value) => `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
32296
+ const commandLine = [command, ...arguments_].map(quote).join(" ");
32297
+ return {
32298
+ command: environmentValue2(environment, "ComSpec") ?? "cmd.exe",
32299
+ arguments: ["/d", "/v:off", "/s", "/c", `"${commandLine}"`],
32300
+ windowsVerbatimArguments: true
32301
+ };
32302
+ }
32303
+
32304
+ // ../../harness-discovery/dist/node-runtime.js
32305
+ import path6 from "node:path";
32306
+ function withNodeRuntimeOnPath(environment, runtimeExecutable = process.execPath, platform = process.platform) {
32307
+ const pathKey = Object.keys(environment).find((name) => name.toLowerCase() === "path") ?? "PATH";
32308
+ const delimiter = platform === "win32" ? ";" : ":";
32309
+ const runtimeDirectory = path6.dirname(runtimeExecutable);
32310
+ const directories = (environment[pathKey] ?? "").split(delimiter).filter(Boolean);
32311
+ const equal = platform === "win32" ? (value) => value.toLowerCase() : (value) => value;
32312
+ if (!directories.some((directory) => equal(directory) === equal(runtimeDirectory))) {
32313
+ directories.push(runtimeDirectory);
32314
+ }
32315
+ return { ...environment, [pathKey]: directories.join(delimiter) };
32316
+ }
32317
+
32318
+ // ../../harness-discovery/dist/resolve.js
32319
+ import os from "node:os";
32320
+
32321
+ // ../../harness-discovery/dist/version-managers.js
32322
+ function versionManagerBinaryDirectories(context) {
32323
+ const { platform, environment, home } = context;
32324
+ const list = context.subdirectories ?? subdirectoryNames;
32325
+ const pathFlavor = targetPath(platform);
32326
+ const value = (name) => environmentValue2(environment, name);
32327
+ const directories = [];
32328
+ const versioned = (root, ...tail) => {
32329
+ for (const version2 of newestFirst(list(root))) {
32330
+ directories.push(pathFlavor.join(root, version2, ...tail));
32331
+ }
32332
+ };
32333
+ if (platform === "win32") {
32334
+ const appData = value("APPDATA") ?? pathFlavor.join(home, "AppData", "Roaming");
32335
+ const localAppData = value("LOCALAPPDATA") ?? pathFlavor.join(home, "AppData", "Local");
32336
+ versioned(pathFlavor.join(appData, "nvm"));
32337
+ versioned(value("FNM_DIR") ?? pathFlavor.join(appData, "fnm", "node-versions"), "installation");
32338
+ directories.push(pathFlavor.join(localAppData, "Volta", "bin"));
32339
+ directories.push(pathFlavor.join(home, ".bun", "bin"));
32340
+ const pnpmHome2 = value("PNPM_HOME");
32341
+ if (pnpmHome2)
32342
+ directories.push(pnpmHome2);
32343
+ directories.push(pathFlavor.join(localAppData, "pnpm"));
32344
+ return directories;
32345
+ }
32346
+ versioned(pathFlavor.join(value("NVM_DIR") ?? pathFlavor.join(home, ".nvm"), "versions", "node"), "bin");
32347
+ const fnmRoots = [
32348
+ value("FNM_DIR"),
32349
+ pathFlavor.join(home, ".local", "share", "fnm"),
32350
+ pathFlavor.join(home, "Library", "Application Support", "fnm")
32351
+ ].filter((root) => root !== void 0);
32352
+ for (const root of fnmRoots) {
32353
+ versioned(pathFlavor.join(root, "node-versions"), "installation", "bin");
32354
+ }
32355
+ const voltaHome = value("VOLTA_HOME") ?? pathFlavor.join(home, ".volta");
32356
+ versioned(pathFlavor.join(voltaHome, "tools", "image", "node"), "bin");
32357
+ directories.push(pathFlavor.join(voltaHome, "bin"));
32358
+ const asdfHome = value("ASDF_DATA_DIR") ?? pathFlavor.join(home, ".asdf");
32359
+ versioned(pathFlavor.join(asdfHome, "installs", "nodejs"), "bin");
32360
+ directories.push(pathFlavor.join(asdfHome, "shims"));
32361
+ const nodenvHome = value("NODENV_ROOT") ?? pathFlavor.join(home, ".nodenv");
32362
+ versioned(pathFlavor.join(nodenvHome, "versions"), "bin");
32363
+ directories.push(pathFlavor.join(nodenvHome, "shims"));
32364
+ versioned(pathFlavor.join(value("N_PREFIX") ?? "/usr/local", "n", "versions", "node"), "bin");
32365
+ directories.push(pathFlavor.join(home, ".bun", "bin"));
32366
+ const pnpmHome = value("PNPM_HOME");
32367
+ if (pnpmHome)
32368
+ directories.push(pnpmHome);
32369
+ directories.push(pathFlavor.join(home, "Library", "pnpm"));
32370
+ directories.push(pathFlavor.join(home, ".local", "share", "pnpm"));
32371
+ for (const prefix of ["/opt/homebrew/opt", "/usr/local/opt"]) {
32372
+ for (const formula of newestFirst(list(prefix).filter((name) => name.startsWith("node@")))) {
32373
+ directories.push(pathFlavor.join(prefix, formula, "bin"));
32374
+ }
32375
+ }
32376
+ return directories;
32377
+ }
32378
+
32379
+ // ../../harness-discovery/dist/resolve.js
32380
+ var VERSION_MANAGER_ROOTS = "<version-managers>";
32381
+ function installRootExtensions(platform) {
32382
+ return platform === "win32" ? [".exe", ".cmd"] : [""];
32383
+ }
32384
+ function resolveHomeDirectory(input) {
32385
+ return input.homeDirectory ?? environmentValue2(input.environment, "HOME") ?? environmentValue2(input.environment, "USERPROFILE") ?? os.homedir();
32386
+ }
32387
+ function templateVariables(environment, platform, home) {
32388
+ const pathFlavor = targetPath(platform);
32389
+ return {
32390
+ HOME: home,
32391
+ USERPROFILE: home,
32392
+ APPDATA: environmentValue2(environment, "APPDATA") ?? pathFlavor.join(home, "AppData", "Roaming"),
32393
+ LOCALAPPDATA: environmentValue2(environment, "LOCALAPPDATA") ?? pathFlavor.join(home, "AppData", "Local")
32394
+ };
32395
+ }
32396
+ function joinTemplate(platform, value) {
32397
+ const pathFlavor = targetPath(platform);
32398
+ const segments = value.split("/");
32399
+ const head = segments[0] ?? "";
32400
+ const tail = segments.slice(1);
32401
+ if (head === "")
32402
+ return pathFlavor.join(pathFlavor.sep, ...tail);
32403
+ return tail.length === 0 ? head : pathFlavor.join(head, ...tail);
32404
+ }
32405
+ function expandInstallRoot(template, environment, platform, home) {
32406
+ const variables = templateVariables(environment, platform, home);
32407
+ let unresolved = false;
32408
+ const substituted = template.replace(/^~(?=\/|$)/u, home).replace(/\$\{(\w+)\}/gu, (_match, name) => {
32409
+ const value = variables[name] ?? environmentValue2(environment, name);
32410
+ if (value === void 0 || value === "") {
32411
+ unresolved = true;
32412
+ return "";
32413
+ }
32414
+ return value;
32415
+ });
32416
+ return unresolved ? void 0 : joinTemplate(platform, substituted);
32417
+ }
32418
+ function installRootDirectories(spec, input, dependencies, platform, home) {
32419
+ const templates = (platform === "win32" ? spec.installRoots?.windows : spec.installRoots?.posix) ?? [];
32420
+ const directories = [];
32421
+ for (const template of templates) {
32422
+ if (template === VERSION_MANAGER_ROOTS) {
32423
+ directories.push(...versionManagerBinaryDirectories({
32424
+ platform,
32425
+ environment: input.environment,
32426
+ home,
32427
+ ...dependencies.subdirectories ? { subdirectories: dependencies.subdirectories } : {}
32428
+ }));
32429
+ continue;
32430
+ }
32431
+ const directory = expandInstallRoot(template, input.environment, platform, home);
32432
+ if (directory !== void 0)
32433
+ directories.push(directory);
32434
+ }
32435
+ return directories;
32436
+ }
32437
+ function harnessCandidates(spec, input, dependencies = {}) {
32438
+ const platform = input.platform ?? process.platform;
32439
+ const pathFlavor = targetPath(platform);
32440
+ const configured = input.command ?? (spec.commandEnvironmentVariable ? environmentValue2(input.environment, spec.commandEnvironmentVariable) : void 0);
32441
+ const command = configured ?? spec.command;
32442
+ if (pathFlavor.isAbsolute(command) || command.includes("/") || command.includes("\\")) {
32443
+ return [{ candidate: command, source: "configured" }];
32444
+ }
32445
+ const candidates = [];
32446
+ const extensions = executableExtensions(command, platform, input.environment);
32447
+ for (const directory of pathDirectories(input.environment, platform)) {
32448
+ for (const extension2 of extensions) {
32449
+ candidates.push({
32450
+ candidate: pathFlavor.join(directory, command + extension2),
32451
+ source: "path"
32452
+ });
32453
+ }
32454
+ }
32455
+ if (configured !== void 0)
32456
+ return candidates;
32457
+ const home = resolveHomeDirectory(input);
32458
+ for (const directory of installRootDirectories(spec, input, dependencies, platform, home)) {
32459
+ for (const extension2 of installRootExtensions(platform)) {
32460
+ candidates.push({
32461
+ candidate: pathFlavor.join(directory, spec.command + extension2),
32462
+ source: "install-root"
32463
+ });
32464
+ }
32465
+ }
32466
+ return candidates;
32467
+ }
32468
+ function resolveHarnessExecutable(spec, input, dependencies = {}) {
32469
+ const platform = input.platform ?? process.platform;
32470
+ const isExecutable = dependencies.isExecutable ?? ((candidate) => isExecutableFile(candidate, platform));
32471
+ const runnable = spec.runnableCandidate ?? ((candidate) => candidate);
32472
+ const context = { platform, isExecutable };
32473
+ for (const { candidate, source } of harnessCandidates(spec, input, dependencies)) {
32474
+ const executable = runnable(candidate, context);
32475
+ if (executable !== void 0 && isExecutable(executable))
32476
+ return { executable, source };
32477
+ }
32478
+ return void 0;
32479
+ }
32480
+
32481
+ // ../../harness-discovery/dist/installation.js
32482
+ import { execFile } from "node:child_process";
32483
+ import { homedir } from "node:os";
32484
+ function runInstallationCommand(command, args, environment, timeout = 3e4) {
32485
+ const env = withNodeRuntimeOnPath(environment);
32486
+ const invocation = /\.[cm]?js$/i.test(command) ? commandInvocation(process.execPath, [command, ...args], env) : commandInvocation(command, args, env);
32487
+ return new Promise((resolve2, reject) => {
32488
+ const child = execFile(invocation.command, invocation.arguments, {
32489
+ env,
32490
+ cwd: env.HOME ?? env.USERPROFILE ?? homedir(),
32491
+ encoding: "utf8",
32492
+ timeout,
32493
+ killSignal: "SIGKILL",
32494
+ maxBuffer: 1024 * 1024,
32495
+ windowsHide: true,
32496
+ windowsVerbatimArguments: invocation.windowsVerbatimArguments
32497
+ }, (error51, stdout, stderr) => {
32498
+ if (error51)
32499
+ reject(new Error(error51.killed ? "Harness command timed out" : "Harness command failed; check the native installation and retry"));
32500
+ else
32501
+ resolve2((stdout || stderr).trim());
32502
+ });
32503
+ child.stdin?.end();
32504
+ });
32505
+ }
32506
+ function installationVersion(value) {
32507
+ if (typeof value !== "string" || !/^v?\d+(?:\.\d+){1,3}(?:-[\w.-]+)?(?:\+[\w.-]+)?$/.test(value.trim()))
32508
+ throw new Error("Harness returned an invalid version");
32509
+ return value.trim().replace(/^v/, "");
32510
+ }
32511
+ function versionFromOutput(output) {
32512
+ return installationVersion(output.match(/\b\d+(?:\.\d+){1,3}(?:-[\w.-]+)?(?:\+[\w.-]+)?\b/)?.[0]);
32513
+ }
32514
+ function newerInstallationVersion(current, latest) {
32515
+ const a = installationVersion(current).replace(/\+.*/, "");
32516
+ const b = installationVersion(latest).replace(/\+.*/, "");
32517
+ const coreA = a.replace(/-.*/, "").split(".").map(BigInt);
32518
+ const coreB = b.replace(/-.*/, "").split(".").map(BigInt);
32519
+ for (let i = 0; i < Math.max(coreA.length, coreB.length); i++) {
32520
+ if ((coreA[i] ?? 0n) !== (coreB[i] ?? 0n))
32521
+ return (coreB[i] ?? 0n) > (coreA[i] ?? 0n);
32522
+ }
32523
+ const preA = a.includes("-") ? a.slice(a.indexOf("-") + 1).split(".") : [];
32524
+ const preB = b.includes("-") ? b.slice(b.indexOf("-") + 1).split(".") : [];
32525
+ if (!preA.length || !preB.length)
32526
+ return !!preA.length && !preB.length;
32527
+ for (let i = 0; i < Math.max(preA.length, preB.length); i++) {
32528
+ const x = preA[i];
32529
+ const y = preB[i];
32530
+ if (x === y)
32531
+ continue;
32532
+ if (x === void 0 || y === void 0)
32533
+ return x === void 0;
32534
+ const numericX = /^\d+$/.test(x);
32535
+ const numericY = /^\d+$/.test(y);
32536
+ if (numericX && numericY) {
32537
+ if (BigInt(x) === BigInt(y))
32538
+ continue;
32539
+ return BigInt(y) > BigInt(x);
32540
+ }
32541
+ if (numericX !== numericY)
32542
+ return numericX;
32543
+ return y > x;
32544
+ }
32545
+ return false;
32546
+ }
32547
+ function createInstallationManager(options) {
32548
+ let checking;
32549
+ let updating;
32550
+ const check2 = () => checking ??= options.check().finally(() => {
32551
+ checking = void 0;
32552
+ });
32553
+ return (action) => {
32554
+ if (updating)
32555
+ return updating;
32556
+ if (action === "check")
32557
+ return check2();
32558
+ updating = (async () => {
32559
+ const before = await check2();
32560
+ if (!before.updateAvailable)
32561
+ return before;
32562
+ if (!before.canUpdate)
32563
+ throw new Error(before.message ?? "This installation cannot be updated automatically");
32564
+ await options.update(before);
32565
+ const after = await check2();
32566
+ if (after.currentVersion === before.currentVersion)
32567
+ throw new Error("The Harness version did not change; check the native updater and retry");
32568
+ return after;
32569
+ })().finally(() => {
32570
+ updating = void 0;
32571
+ });
32572
+ return updating;
32573
+ };
32574
+ }
32575
+ async function fetchInstallationText(url2) {
32576
+ const request = async () => {
32577
+ const response = await fetch(url2, { signal: AbortSignal.timeout(15e3) });
32578
+ if (!response.ok)
32579
+ throw new Error("Could not check the latest Harness version");
32580
+ return response.text();
32581
+ };
32582
+ try {
32583
+ return await request();
32584
+ } catch (error51) {
32585
+ if (error51 instanceof DOMException && (error51.name === "AbortError" || error51.name === "TimeoutError"))
32586
+ throw error51;
32587
+ return request();
32588
+ }
32589
+ }
32590
+
32591
+ // ../../harness-discovery/dist/npm-installation.js
32592
+ import { readFile, realpath } from "node:fs/promises";
32593
+ import path7 from "node:path";
32594
+ function referencesNpmBin(shim, name, bin) {
32595
+ if (bin.includes(".."))
32596
+ return false;
32597
+ const target = `node_modules/${name}/${bin.replace(/^\.\//, "")}`.toLowerCase();
32598
+ const text = shim.replaceAll("\\", "/").toLowerCase();
32599
+ return text.includes(`%dp0%/${target}"`) || text.includes(`%~dp0/${target}"`);
32600
+ }
32601
+ async function npmInstallation(command, packages, environment) {
32602
+ let selected = await realpath(command);
32603
+ if (process.platform === "win32" && /\.(cmd|bat)$/i.test(selected)) {
32604
+ const shim = (await readFile(selected, "utf8")).replaceAll("\\", "/");
32605
+ const root = path7.dirname(selected);
32606
+ for (const name of packages) {
32607
+ const directory2 = path7.join(root, "node_modules", ...name.split("/"));
32608
+ const metadata = await readFile(path7.join(directory2, "package.json"), "utf8").then((text) => JSON.parse(text)).catch(() => null);
32609
+ const bins = typeof metadata?.bin === "string" ? [metadata.bin] : Object.values(metadata?.bin ?? {});
32610
+ const bin = bins.find((entry) => referencesNpmBin(shim, name, entry));
32611
+ if (bin) {
32612
+ selected = await realpath(path7.join(directory2, bin));
32613
+ break;
32614
+ }
32615
+ }
32616
+ }
32617
+ let directory = path7.dirname(selected);
32618
+ for (let depth = 0; depth < 8; depth++) {
32619
+ const metadata = await readFile(path7.join(directory, "package.json"), "utf8").then((text) => JSON.parse(text)).catch(() => null);
32620
+ if (metadata?.name && packages.includes(metadata.name)) {
32621
+ const name = metadata.name;
32622
+ const currentVersion = installationVersion(metadata.version);
32623
+ const segments = name.split("/");
32624
+ let modules = directory;
32625
+ for (let index = 0; index < segments.length; index++)
32626
+ modules = path7.dirname(modules);
32627
+ const prefix = process.platform === "win32" ? path7.dirname(modules) : path7.dirname(path7.dirname(modules));
32628
+ const globalRoot = process.platform === "win32" ? path7.join(prefix, "node_modules") : path7.join(prefix, "lib", "node_modules");
32629
+ const env = withNodeRuntimeOnPath(environment);
32630
+ const npm = resolveHarnessExecutable({ id: "npm", command: "npm", installRoots: { posix: [], windows: [] } }, { environment: env });
32631
+ let globalInstall = modules === globalRoot;
32632
+ if (process.platform === "win32") {
32633
+ const project = (await Promise.all(["package.json", "package-lock.json", "npm-shrinkwrap.json"].map((file2) => readFile(path7.join(prefix, file2), "utf8").then(() => true, (error51) => error51.code !== "ENOENT")))).some(Boolean);
32634
+ const bins = typeof metadata.bin === "string" ? { [name.split("/").at(-1) ?? name]: metadata.bin } : metadata.bin ?? {};
32635
+ const launchers = await Promise.all(Object.entries(bins).map(async ([bin, entry]) => {
32636
+ if (path7.basename(bin) !== bin || entry.includes(".."))
32637
+ return false;
32638
+ const target = await realpath(path7.join(directory, entry)).catch(() => "");
32639
+ if (target.toLowerCase() !== selected.toLowerCase())
32640
+ return false;
32641
+ const shim = await readFile(path7.join(prefix, `${bin}.cmd`), "utf8").catch(() => "");
32642
+ return referencesNpmBin(shim, name, entry);
32643
+ }));
32644
+ globalInstall = globalInstall && !project && launchers.some(Boolean);
32645
+ }
32646
+ const canUpdate = globalInstall && !!npm;
32647
+ return {
32648
+ prefix,
32649
+ currentVersion,
32650
+ canUpdate,
32651
+ latest: async () => {
32652
+ const data = JSON.parse(await fetchInstallationText(`https://registry.npmjs.org/${encodeURIComponent(name)}/latest`));
32653
+ return installationVersion(data.version);
32654
+ },
32655
+ update: async (version2) => {
32656
+ if (!canUpdate || !npm)
32657
+ throw new Error("Use the original package manager to update this installation");
32658
+ await runInstallationCommand(npm.executable, ["install", "--global", "--prefix", prefix, `${name}@${installationVersion(version2)}`], env, 3e5);
32659
+ }
32660
+ };
32661
+ }
32662
+ const parent = path7.dirname(directory);
32663
+ if (parent === directory)
32664
+ break;
32665
+ directory = parent;
32666
+ }
32667
+ return null;
32668
+ }
32669
+
32670
+ // dist/installation.js
32671
+ function createDeepSeekInstallation(environment, command) {
32672
+ let update;
32673
+ return createInstallationManager({
32674
+ async check() {
32675
+ const invocation = resolveDeepSeekCommand(command, environment);
32676
+ if (!invocation)
32677
+ throw new Error("DeepSeek Harness is not installed");
32678
+ const currentVersion = versionFromOutput(await runInstallationCommand(invocation.command, [...invocation.arguments, "--version"], environment));
32679
+ const npm = invocation.kind === "npx" ? null : await npmInstallation(invocation.command, ["@deepseek-ai/dsh"], environment);
32680
+ update = npm?.update;
32681
+ const latestVersion = npm ? await npm.latest() : "Unknown";
32682
+ const canUpdate = npm?.canUpdate ?? false;
32683
+ return {
32684
+ currentVersion,
32685
+ latestVersion,
32686
+ updateAvailable: !!npm && newerInstallationVersion(currentVersion, latestVersion),
32687
+ canUpdate,
32688
+ ...!canUpdate ? {
32689
+ message: "Update with the original installer. Offline npx, Python, desktop, and project-local installations are not upgraded through global npm."
32690
+ } : {}
32691
+ };
32692
+ },
32693
+ async update(state) {
32694
+ if (!update)
32695
+ throw new Error("This DeepSeek installation requires a manual update");
32696
+ await update(state.latestVersion);
32697
+ }
32698
+ });
32699
+ }
32700
+
31654
32701
  // dist/plugin.js
31655
32702
  var DEEPSEEK_HARNESS_COMMAND_ENV = "CODEXHOST_DEEPSEEK_HARNESS_COMMAND";
31656
32703
  var DEEPSEEK_HARNESS_ENDPOINT_ENV = "CODEXHOST_DEEPSEEK_HARNESS_ENDPOINT";
31657
32704
  function createHarnessAdapter(context) {
31658
32705
  const environment = { ...context.environment };
31659
32706
  const openLocalUrl = context.openLocalUrl;
31660
- return new DeepSeekHarnessAdapter({
32707
+ return Object.assign(new DeepSeekHarnessAdapter({
31661
32708
  ...environment[DEEPSEEK_HARNESS_COMMAND_ENV] ? { command: environment[DEEPSEEK_HARNESS_COMMAND_ENV] } : {},
31662
32709
  ...environment[DEEPSEEK_HARNESS_ENDPOINT_ENV] ? { endpoint: environment[DEEPSEEK_HARNESS_ENDPOINT_ENV] } : {},
31663
32710
  environment,
31664
32711
  ...!context.managedRemoteHost && openLocalUrl ? { openWebUi: (url2) => openLocalUrl(url2.href) } : {}
32712
+ }), {
32713
+ installation: createDeepSeekInstallation(environment, environment[DEEPSEEK_HARNESS_COMMAND_ENV])
31665
32714
  });
31666
32715
  }
31667
32716
  export {