dsh-compact-pi 0.2.3-b4 → 0.2.3-b6

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.
@@ -2,7 +2,7 @@
2
2
 
3
3
  // src/dsh/convert.ts
4
4
  import { promises as fs2 } from "node:fs";
5
- import * as path2 from "node:path";
5
+ import * as path3 from "node:path";
6
6
 
7
7
  // vendor/dsh-runtime.mjs
8
8
  import { createRequire } from "node:module";
@@ -629,8 +629,8 @@ var ValidationError = class _ValidationError extends TypeError {
629
629
  * @param path — the standard-schema issue path; segments may be `{ key }` objects.
630
630
  * @returns the property keys, or an empty array when the issue has no path.
631
631
  */
632
- static normalizePath(path5 = []) {
633
- return path5.map((segment) => typeof segment === "object" ? segment.key : segment);
632
+ static normalizePath(path9 = []) {
633
+ return path9.map((segment) => typeof segment === "object" ? segment.key : segment);
634
634
  }
635
635
  /**
636
636
  * Format an issue path as a dotted string.
@@ -638,8 +638,8 @@ var ValidationError = class _ValidationError extends TypeError {
638
638
  * @param path — the standard-schema issue path.
639
639
  * @returns the keys joined with `.`.
640
640
  */
641
- static formatPath(path5) {
642
- return _ValidationError.normalizePath(path5).map(String).join(".");
641
+ static formatPath(path9) {
642
+ return _ValidationError.normalizePath(path9).map(String).join(".");
643
643
  }
644
644
  };
645
645
  Object.defineProperty(ValidationError.prototype, kValidationError, {
@@ -3328,10 +3328,10 @@ var EXCEEDS_MODEL_CONTEXT = new RegExp(
3328
3328
  "i"
3329
3329
  );
3330
3330
  function errorChain(value) {
3331
- const path5 = /* @__PURE__ */ new Set();
3331
+ const path9 = /* @__PURE__ */ new Set();
3332
3332
  const render = (current) => {
3333
- if (path5.has(current)) return "<circular cause>";
3334
- path5.add(current);
3333
+ if (path9.has(current)) return "<circular cause>";
3334
+ path9.add(current);
3335
3335
  try {
3336
3336
  if (!(current instanceof Error)) {
3337
3337
  if (typeof current === "object" && current !== null) {
@@ -3350,7 +3350,7 @@ function errorChain(value) {
3350
3350
  } catch {
3351
3351
  return "<unrenderable value>";
3352
3352
  } finally {
3353
- path5.delete(current);
3353
+ path9.delete(current);
3354
3354
  }
3355
3355
  };
3356
3356
  return render(value);
@@ -3656,25 +3656,25 @@ Schema.prototype.volatile = function volatile() {
3656
3656
  };
3657
3657
  var resolvers = {};
3658
3658
  var checkedVolatile = /* @__PURE__ */ Symbol("checked-volatile-schema");
3659
- function validateVolatileSchema(schema, path5 = [], blocked = false, seen = /* @__PURE__ */ new Map()) {
3659
+ function validateVolatileSchema(schema, path9 = [], blocked = false, seen = /* @__PURE__ */ new Map()) {
3660
3660
  const states = seen.get(schema) ?? /* @__PURE__ */ new Set();
3661
3661
  if (states.has(blocked)) return;
3662
3662
  states.add(blocked);
3663
3663
  seen.set(schema, states);
3664
3664
  if (schema.meta?.volatile && blocked) {
3665
- throw new ValidationError2("volatile fields require a fixed object path without an enclosing volatile field", { path: path5 });
3665
+ throw new ValidationError2("volatile fields require a fixed object path without an enclosing volatile field", { path: path9 });
3666
3666
  }
3667
3667
  const nested = blocked || !!schema.meta?.volatile;
3668
3668
  if (schema.dict) {
3669
- for (const [key, child] of Object.entries(schema.dict)) validateVolatileSchema(child, [...path5, key], nested, seen);
3669
+ for (const [key, child] of Object.entries(schema.dict)) validateVolatileSchema(child, [...path9, key], nested, seen);
3670
3670
  }
3671
- if (schema.sKey) validateVolatileSchema(schema.sKey, [...path5, "<key>"], true, seen);
3671
+ if (schema.sKey) validateVolatileSchema(schema.sKey, [...path9, "<key>"], true, seen);
3672
3672
  if (schema.inner && (schema.type !== "lazy" || schema.inner[kSchema])) {
3673
- validateVolatileSchema(schema.inner, [...path5, "*"], true, seen);
3673
+ validateVolatileSchema(schema.inner, [...path9, "*"], true, seen);
3674
3674
  }
3675
3675
  if (schema.list) {
3676
3676
  for (let index = 0; index < schema.list.length; index++) {
3677
- validateVolatileSchema(schema.list[index], [...path5, String(index)], true, seen);
3677
+ validateVolatileSchema(schema.list[index], [...path9, String(index)], true, seen);
3678
3678
  }
3679
3679
  }
3680
3680
  }
@@ -4137,71 +4137,71 @@ var ALWAYS_POLICY_KEYS = /* @__PURE__ */ new Set([
4137
4137
  "backoff"
4138
4138
  ]);
4139
4139
  var BACKOFF_KEYS = /* @__PURE__ */ new Set(["initialDelayMs", "maxDelayMs", "jitterRatio"]);
4140
- function validateKeys(value, allowed, path5) {
4140
+ function validateKeys(value, allowed, path9) {
4141
4141
  for (const key of Object.keys(value)) {
4142
- if (!allowed.has(key)) throw new Error(`${path5}: unknown key "${key}"`);
4142
+ if (!allowed.has(key)) throw new Error(`${path9}: unknown key "${key}"`);
4143
4143
  }
4144
4144
  }
4145
- function resolveBackoff(config2, path5) {
4146
- if (config2 !== void 0) validateKeys(config2, BACKOFF_KEYS, path5);
4145
+ function resolveBackoff(config2, path9) {
4146
+ if (config2 !== void 0) validateKeys(config2, BACKOFF_KEYS, path9);
4147
4147
  const initialDelayMs = config2?.initialDelayMs ?? DEFAULT_INITIAL_DELAY_MS;
4148
4148
  const maxDelayMs = config2?.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;
4149
4149
  const jitterRatio = config2?.jitterRatio ?? DEFAULT_JITTER_RATIO;
4150
4150
  if (!Number.isFinite(initialDelayMs) || initialDelayMs <= 0 || initialDelayMs > MAX_TIMER_DELAY_MS) {
4151
- throw new Error(`${path5}.initialDelayMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);
4151
+ throw new Error(`${path9}.initialDelayMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);
4152
4152
  }
4153
4153
  if (!Number.isFinite(maxDelayMs) || maxDelayMs <= 0 || maxDelayMs > MAX_TIMER_DELAY_MS) {
4154
- throw new Error(`${path5}.maxDelayMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);
4154
+ throw new Error(`${path9}.maxDelayMs must be a positive finite number no greater than ${MAX_TIMER_DELAY_MS}`);
4155
4155
  }
4156
4156
  if (initialDelayMs > maxDelayMs) {
4157
- throw new Error(`${path5}.initialDelayMs must be less than or equal to maxDelayMs`);
4157
+ throw new Error(`${path9}.initialDelayMs must be less than or equal to maxDelayMs`);
4158
4158
  }
4159
4159
  if (!Number.isFinite(jitterRatio) || jitterRatio < 0 || jitterRatio > 1) {
4160
- throw new Error(`${path5}.jitterRatio must be between 0 and 1`);
4160
+ throw new Error(`${path9}.jitterRatio must be between 0 and 1`);
4161
4161
  }
4162
4162
  return Object.freeze({ initialDelayMs, maxDelayMs, jitterRatio });
4163
4163
  }
4164
- function resolveRetryPolicy(config2, path5) {
4164
+ function resolveRetryPolicy(config2, path9) {
4165
4165
  if (config2 === void 0) {
4166
4166
  return Object.freeze({
4167
4167
  mode: "normal",
4168
4168
  maxRetries: DEFAULT_MAX_RETRIES,
4169
4169
  retryableCodes: DEFAULT_RETRYABLE_CODES,
4170
- ...resolveBackoff(void 0, `${path5}.backoff`)
4170
+ ...resolveBackoff(void 0, `${path9}.backoff`)
4171
4171
  });
4172
4172
  }
4173
4173
  switch (config2.mode) {
4174
4174
  case "normal": {
4175
- validateKeys(config2, NORMAL_POLICY_KEYS, path5);
4175
+ validateKeys(config2, NORMAL_POLICY_KEYS, path9);
4176
4176
  const maxRetries = config2.maxRetries ?? DEFAULT_MAX_RETRIES;
4177
4177
  const retryableCodes = config2.retryableCodes ?? [...DEFAULT_RETRYABLE_CODES];
4178
4178
  if (!Number.isSafeInteger(maxRetries) || maxRetries < 0) {
4179
- throw new Error(`${path5}.maxRetries must be a non-negative safe integer`);
4179
+ throw new Error(`${path9}.maxRetries must be a non-negative safe integer`);
4180
4180
  }
4181
4181
  if (retryableCodes.length === 0) {
4182
- throw new Error(`${path5}.retryableCodes must not be empty`);
4182
+ throw new Error(`${path9}.retryableCodes must not be empty`);
4183
4183
  }
4184
4184
  if (retryableCodes.some((code) => typeof code !== "string" || code.length === 0)) {
4185
- throw new Error(`${path5}.retryableCodes must contain only non-empty strings`);
4185
+ throw new Error(`${path9}.retryableCodes must contain only non-empty strings`);
4186
4186
  }
4187
4187
  if (new Set(retryableCodes).size !== retryableCodes.length) {
4188
- throw new Error(`${path5}.retryableCodes must not contain duplicates`);
4188
+ throw new Error(`${path9}.retryableCodes must not contain duplicates`);
4189
4189
  }
4190
4190
  return Object.freeze({
4191
4191
  mode: "normal",
4192
4192
  maxRetries,
4193
4193
  retryableCodes: Object.freeze([...retryableCodes]),
4194
- ...resolveBackoff(config2.backoff, `${path5}.backoff`)
4194
+ ...resolveBackoff(config2.backoff, `${path9}.backoff`)
4195
4195
  });
4196
4196
  }
4197
4197
  case "always":
4198
- validateKeys(config2, ALWAYS_POLICY_KEYS, path5);
4198
+ validateKeys(config2, ALWAYS_POLICY_KEYS, path9);
4199
4199
  return Object.freeze({
4200
4200
  mode: "always",
4201
- ...resolveBackoff(config2.backoff, `${path5}.backoff`)
4201
+ ...resolveBackoff(config2.backoff, `${path9}.backoff`)
4202
4202
  });
4203
4203
  default:
4204
- throw new Error(`${path5}.mode must be "normal" or "always"`);
4204
+ throw new Error(`${path9}.mode must be "normal" or "always"`);
4205
4205
  }
4206
4206
  }
4207
4207
  function callConfigEquals(a, b) {
@@ -5245,8 +5245,8 @@ var LlmRuntime = class extends (_a = TypertRemoteService, _listProviders_dec = [
5245
5245
  return void 0;
5246
5246
  }
5247
5247
  if (hostPath === void 0) return void 0;
5248
- const fs7 = this.ctx.get("fs");
5249
- return fs7?.processPathFromHostPath(hostPath);
5248
+ const fs10 = this.ctx.get("fs");
5249
+ return fs10?.processPathFromHostPath(hostPath);
5250
5250
  }
5251
5251
  /**
5252
5252
  * Final adapter boundary. Adapter selection, dispatch, iterator construction,
@@ -5649,10 +5649,10 @@ var DEFAULT_AGENTS_HOME_DISPLAY = `~/${AGENTS_HOME_DIR_NAME}`;
5649
5649
  function defaultDshHome() {
5650
5650
  return join(homedir(), DSH_HOME_DIR_NAME);
5651
5651
  }
5652
- function expandHomePath(path5) {
5653
- if (path5 === "~") return homedir();
5654
- if (path5.startsWith("~/") || path5.startsWith("~\\")) return join(homedir(), path5.slice(2));
5655
- return path5;
5652
+ function expandHomePath(path9) {
5653
+ if (path9 === "~") return homedir();
5654
+ if (path9.startsWith("~/") || path9.startsWith("~\\")) return join(homedir(), path9.slice(2));
5655
+ return path9;
5656
5656
  }
5657
5657
  function resolveRoot(configured, env, envName, fallback) {
5658
5658
  const fromEnv = env[envName];
@@ -5910,17 +5910,17 @@ async function prepareImageFile(input2, limits, policy) {
5910
5910
  }
5911
5911
  };
5912
5912
  }
5913
- async function syncDirectory(path5) {
5913
+ async function syncDirectory(path9) {
5914
5914
  if (process.platform === "win32") return;
5915
- const handle = await open(path5, constants.O_RDONLY);
5915
+ const handle = await open(path9, constants.O_RDONLY);
5916
5916
  try {
5917
5917
  await handle.sync();
5918
5918
  } finally {
5919
5919
  await handle.close();
5920
5920
  }
5921
5921
  }
5922
- async function ensureDurableDirectory(path5, boundary) {
5923
- const target = resolve3(path5);
5922
+ async function ensureDurableDirectory(path9, boundary) {
5923
+ const target = resolve3(path9);
5924
5924
  const stop = resolve3(boundary);
5925
5925
  await mkdir(target, { recursive: true, mode: 448 });
5926
5926
  await chmod(target, 448);
@@ -5932,8 +5932,8 @@ async function ensureDurableDirectory(path5, boundary) {
5932
5932
  level = parent;
5933
5933
  }
5934
5934
  }
5935
- async function ensureDurableHome(path5) {
5936
- const home = resolve3(path5);
5935
+ async function ensureDurableHome(path9) {
5936
+ const home = resolve3(path9);
5937
5937
  if (!durableHomes.has(home)) {
5938
5938
  await ensureDurableDirectory(home, parse(home).root);
5939
5939
  durableHomes.add(home);
@@ -6053,13 +6053,13 @@ async function publishStagedObject(root, target, staged) {
6053
6053
  throw new AttachmentError("Unable to persist attachment.", "ATTACHMENT_WRITE_FAILED", { cause: error62 });
6054
6054
  }
6055
6055
  }
6056
- async function digestFile(path5) {
6056
+ async function digestFile(path9) {
6057
6057
  const hash2 = createHash("sha256");
6058
- for await (const chunk of createReadStream(path5)) hash2.update(chunk);
6058
+ for await (const chunk of createReadStream(path9)) hash2.update(chunk);
6059
6059
  return hash2.digest("hex");
6060
6060
  }
6061
- async function removeTemporary(path5) {
6062
- await unlink(path5).catch(
6061
+ async function removeTemporary(path9) {
6062
+ await unlink(path9).catch(
6063
6063
  /* v8 ignore next -- Cleanup can observe a staging name already removed after successful linking. */
6064
6064
  (cleanupError) => {
6065
6065
  if (!(cleanupError instanceof Error && "code" in cleanupError && cleanupError.code === "ENOENT")) throw cleanupError;
@@ -6278,9 +6278,9 @@ async function createRequestImage(attachment, target, hasAlpha, policy, signal)
6278
6278
  function cachePath(root, hash2) {
6279
6279
  return join4(root, "request-images", hash2.slice(0, 2), hash2);
6280
6280
  }
6281
- async function readCached(path5, target, expectedAlpha, signal) {
6281
+ async function readCached(path9, target, expectedAlpha, signal) {
6282
6282
  try {
6283
- const data = new Uint8Array(await readFile2(path5, { signal }));
6283
+ const data = new Uint8Array(await readFile2(path9, { signal }));
6284
6284
  if (data.byteLength > target.maxImageBytes) return void 0;
6285
6285
  const detected = await probeImage(data);
6286
6286
  if (detected.depth !== "uchar" || detected.space !== "srgb" || detected.width > target.width || detected.height > target.height || !encodedAlphaIsCompatible(expectedAlpha, detected)) return void 0;
@@ -6301,12 +6301,12 @@ async function verifyRequestImage(image, expectedAlpha) {
6301
6301
  }
6302
6302
  return { ...image, hasAlpha: detected.hasAlpha };
6303
6303
  }
6304
- async function writeCached(path5, data) {
6305
- await mkdir2(dirname3(path5), { recursive: true, mode: 448 });
6306
- const temporary = `${path5}.${randomUUID3()}.tmp`;
6304
+ async function writeCached(path9, data) {
6305
+ await mkdir2(dirname3(path9), { recursive: true, mode: 448 });
6306
+ const temporary = `${path9}.${randomUUID3()}.tmp`;
6307
6307
  try {
6308
6308
  await writeFile(temporary, data, { mode: 384, flag: "wx" });
6309
- await rename(temporary, path5);
6309
+ await rename(temporary, path9);
6310
6310
  } finally {
6311
6311
  await rm(temporary, { force: true });
6312
6312
  }
@@ -6317,12 +6317,12 @@ async function readRequestImageFile(root, attachment, target, policy, signal) {
6317
6317
  const source = await probeImage(attachment.data);
6318
6318
  const variantId = requestImageVariantId(attachment.ref, target, policy);
6319
6319
  const hash2 = String(variantId).slice("sha256:".length);
6320
- const path5 = cachePath(root, hash2);
6321
- const cached2 = await readCached(path5, target, source.hasAlpha, signal);
6320
+ const path9 = cachePath(root, hash2);
6321
+ const cached2 = await readCached(path9, target, source.hasAlpha, signal);
6322
6322
  const created = cached2 ?? await createRequestImage(attachment, target, source.hasAlpha, policy, signal);
6323
6323
  const version3 = cached2 ?? (created.data === attachment.data ? { ...created, hasAlpha: source.hasAlpha } : await verifyRequestImage(created, source.hasAlpha));
6324
6324
  signal?.throwIfAborted();
6325
- if (cached2 === void 0 && version3.data !== attachment.data) await writeCached(path5, version3.data);
6325
+ if (cached2 === void 0 && version3.data !== attachment.data) await writeCached(path9, version3.data);
6326
6326
  return {
6327
6327
  variantId,
6328
6328
  attachment: attachment.ref,
@@ -7547,10 +7547,10 @@ function mergeDefs(...defs) {
7547
7547
  function cloneDef(schema) {
7548
7548
  return mergeDefs(schema._zod.def);
7549
7549
  }
7550
- function getElementAtPath(obj, path5) {
7551
- if (!path5)
7550
+ function getElementAtPath(obj, path9) {
7551
+ if (!path9)
7552
7552
  return obj;
7553
- return path5.reduce((acc, key) => acc?.[key], obj);
7553
+ return path9.reduce((acc, key) => acc?.[key], obj);
7554
7554
  }
7555
7555
  function promiseAllObject(promisesObj) {
7556
7556
  const keys = Object.keys(promisesObj);
@@ -7890,11 +7890,11 @@ function explicitlyAborted(x, startIndex = 0) {
7890
7890
  }
7891
7891
  return false;
7892
7892
  }
7893
- function prefixIssues(path5, issues) {
7893
+ function prefixIssues(path9, issues) {
7894
7894
  return issues.map((iss) => {
7895
7895
  var _a4;
7896
7896
  (_a4 = iss).path ?? (_a4.path = []);
7897
- iss.path.unshift(path5);
7897
+ iss.path.unshift(path9);
7898
7898
  return iss;
7899
7899
  });
7900
7900
  }
@@ -8352,16 +8352,16 @@ function flattenError(error62, mapper = (issue2) => issue2.message) {
8352
8352
  }
8353
8353
  function formatError(error62, mapper = (issue2) => issue2.message) {
8354
8354
  const fieldErrors = { _errors: [] };
8355
- const processError = (error63, path5 = []) => {
8355
+ const processError = (error63, path9 = []) => {
8356
8356
  for (const issue2 of error63.issues) {
8357
8357
  if (issue2.code === "invalid_union" && issue2.errors.length) {
8358
- issue2.errors.map((issues) => processError({ issues }, [...path5, ...issue2.path]));
8358
+ issue2.errors.map((issues) => processError({ issues }, [...path9, ...issue2.path]));
8359
8359
  } else if (issue2.code === "invalid_key") {
8360
- processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
8360
+ processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
8361
8361
  } else if (issue2.code === "invalid_element") {
8362
- processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
8362
+ processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
8363
8363
  } else {
8364
- const fullpath = [...path5, ...issue2.path];
8364
+ const fullpath = [...path9, ...issue2.path];
8365
8365
  if (fullpath.length === 0) {
8366
8366
  fieldErrors._errors.push(mapper(issue2));
8367
8367
  } else {
@@ -8400,17 +8400,17 @@ function formatError(error62, mapper = (issue2) => issue2.message) {
8400
8400
  }
8401
8401
  function treeifyError(error62, mapper = (issue2) => issue2.message) {
8402
8402
  const result = { errors: [] };
8403
- const processError = (error63, path5 = []) => {
8403
+ const processError = (error63, path9 = []) => {
8404
8404
  var _a4;
8405
8405
  for (const issue2 of error63.issues) {
8406
8406
  if (issue2.code === "invalid_union" && issue2.errors.length) {
8407
- issue2.errors.map((issues) => processError({ issues }, [...path5, ...issue2.path]));
8407
+ issue2.errors.map((issues) => processError({ issues }, [...path9, ...issue2.path]));
8408
8408
  } else if (issue2.code === "invalid_key") {
8409
- processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
8409
+ processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
8410
8410
  } else if (issue2.code === "invalid_element") {
8411
- processError({ issues: issue2.issues }, [...path5, ...issue2.path]);
8411
+ processError({ issues: issue2.issues }, [...path9, ...issue2.path]);
8412
8412
  } else {
8413
- const fullpath = [...path5, ...issue2.path];
8413
+ const fullpath = [...path9, ...issue2.path];
8414
8414
  if (fullpath.length === 0) {
8415
8415
  result.errors.push(mapper(issue2));
8416
8416
  continue;
@@ -8449,8 +8449,8 @@ function treeifyError(error62, mapper = (issue2) => issue2.message) {
8449
8449
  }
8450
8450
  function toDotPath(_path) {
8451
8451
  const segs = [];
8452
- const path5 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
8453
- for (const seg of path5) {
8452
+ const path9 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
8453
+ for (const seg of path9) {
8454
8454
  if (typeof seg === "number")
8455
8455
  segs.push(`[${seg}]`);
8456
8456
  else if (typeof seg === "symbol")
@@ -25416,13 +25416,13 @@ function resolveRef(ref, ctx) {
25416
25416
  if (!ref.startsWith("#")) {
25417
25417
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
25418
25418
  }
25419
- const path5 = ref.slice(1).split("/").filter(Boolean);
25420
- if (path5.length === 0) {
25419
+ const path9 = ref.slice(1).split("/").filter(Boolean);
25420
+ if (path9.length === 0) {
25421
25421
  return ctx.rootSchema;
25422
25422
  }
25423
25423
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
25424
- if (path5[0] === defsKey) {
25425
- const key = path5[1] === void 0 ? void 0 : decodeJSONPointerSegment(path5[1]);
25424
+ if (path9[0] === defsKey) {
25425
+ const key = path9[1] === void 0 ? void 0 : decodeJSONPointerSegment(path9[1]);
25426
25426
  if (!key || !ctx.defs[key]) {
25427
25427
  throw new Error(`Reference not found: ${ref}`);
25428
25428
  }
@@ -30123,19 +30123,23 @@ function projectSurface(session, imageToPi) {
30123
30123
  }
30124
30124
 
30125
30125
  // src/dsh/store.ts
30126
- import { execFileSync } from "node:child_process";
30127
30126
  import { promises as fs } from "node:fs";
30127
+ import { promisify } from "node:util";
30128
+ import { zstdDecompress } from "node:zlib";
30129
+ var decompress = promisify(zstdDecompress);
30128
30130
  async function readDshFile(file2) {
30129
- let text;
30131
+ let bytes;
30130
30132
  try {
30131
- text = file2.endsWith(".zstd") ? execFileSync("zstd", ["-dc", file2], {
30132
- encoding: "utf8",
30133
- maxBuffer: 512 * 1024 * 1024
30134
- }) : await fs.readFile(file2, "utf8");
30133
+ bytes = await fs.readFile(file2);
30135
30134
  } catch (error62) {
30136
30135
  if (error62?.code === "ENOENT") return void 0;
30137
30136
  throw error62;
30138
30137
  }
30138
+ return parseDshFile(file2, bytes);
30139
+ }
30140
+ async function parseDshFile(file2, bytes) {
30141
+ const decoded = file2.endsWith(".zstd") ? await decompress(bytes, { maxOutputLength: 512 * 1024 * 1024 }) : bytes;
30142
+ const text = decoded.toString("utf8");
30139
30143
  const rows = text.split("\n").filter((line) => line.trim().length > 0);
30140
30144
  if (rows.length === 0) return void 0;
30141
30145
  const headerRow = JSON.parse(rows[0]);
@@ -30168,7 +30172,7 @@ import {
30168
30172
  mkdirSync,
30169
30173
  appendFileSync
30170
30174
  } from "node:fs";
30171
- import path from "node:path";
30175
+ import path2 from "node:path";
30172
30176
 
30173
30177
  // vendor/pi-messages.mjs
30174
30178
  var COMPACTION_SUMMARY_PREFIX = `The conversation history before this point was compacted into the following summary:
@@ -30301,19 +30305,19 @@ function buildSessionPath(entries, leafId, byId) {
30301
30305
  if (!leaf) {
30302
30306
  return [];
30303
30307
  }
30304
- const path5 = [];
30308
+ const path9 = [];
30305
30309
  let current = leaf;
30306
30310
  while (current) {
30307
- path5.push(current);
30311
+ path9.push(current);
30308
30312
  current = current.parentId ? index.get(current.parentId) : void 0;
30309
30313
  }
30310
- path5.reverse();
30311
- return path5;
30314
+ path9.reverse();
30315
+ return path9;
30312
30316
  }
30313
- function getSessionContextSettings(path5) {
30317
+ function getSessionContextSettings(path9) {
30314
30318
  let thinkingLevel = "off";
30315
30319
  let model = null;
30316
- for (const entry of path5) {
30320
+ for (const entry of path9) {
30317
30321
  if (entry.type === "thinking_level_change") {
30318
30322
  thinkingLevel = entry.thinkingLevel;
30319
30323
  } else if (entry.type === "model_change") {
@@ -30349,24 +30353,24 @@ function sessionEntryToContextMessages(entry) {
30349
30353
  return [];
30350
30354
  }
30351
30355
  function buildContextEntries(entries, leafId, byId) {
30352
- const path5 = buildSessionPath(entries, leafId, byId);
30356
+ const path9 = buildSessionPath(entries, leafId, byId);
30353
30357
  let compaction = null;
30354
- for (const entry of path5) {
30358
+ for (const entry of path9) {
30355
30359
  if (entry.type === "compaction") {
30356
30360
  compaction = entry;
30357
30361
  }
30358
30362
  }
30359
30363
  if (!compaction) {
30360
- return path5;
30364
+ return path9;
30361
30365
  }
30362
- const compactionIdx = path5.findIndex((entry) => entry.id === compaction.id);
30366
+ const compactionIdx = path9.findIndex((entry) => entry.id === compaction.id);
30363
30367
  if (compactionIdx < 0) {
30364
- return path5;
30368
+ return path9;
30365
30369
  }
30366
30370
  const contextEntries = [compaction];
30367
30371
  let foundFirstKept = false;
30368
30372
  for (let i = 0; i < compactionIdx; i++) {
30369
- const entry = path5[i];
30373
+ const entry = path9[i];
30370
30374
  if (entry.id === compaction.firstKeptEntryId) {
30371
30375
  foundFirstKept = true;
30372
30376
  }
@@ -30374,7 +30378,7 @@ function buildContextEntries(entries, leafId, byId) {
30374
30378
  contextEntries.push(entry);
30375
30379
  }
30376
30380
  }
30377
- contextEntries.push(...path5.slice(compactionIdx + 1));
30381
+ contextEntries.push(...path9.slice(compactionIdx + 1));
30378
30382
  return contextEntries;
30379
30383
  }
30380
30384
  function projectContextEntry(entry, edit) {
@@ -30393,8 +30397,8 @@ function projectContextEntry(entry, edit) {
30393
30397
  });
30394
30398
  }
30395
30399
  function buildSessionProjection(entries, leafId, byId) {
30396
- const path5 = buildSessionPath(entries, leafId, byId);
30397
- const { thinkingLevel, model } = getSessionContextSettings(path5);
30400
+ const path9 = buildSessionPath(entries, leafId, byId);
30401
+ const { thinkingLevel, model } = getSessionContextSettings(path9);
30398
30402
  const contextEntries = buildContextEntries(entries, leafId, byId);
30399
30403
  const edits = /* @__PURE__ */ new Map();
30400
30404
  for (const entry of contextEntries) {
@@ -30418,6 +30422,78 @@ function buildSessionProjection(entries, leafId, byId) {
30418
30422
 
30419
30423
  // src/bridge.ts
30420
30424
  import { createHash as createHash5 } from "node:crypto";
30425
+
30426
+ // src/config.ts
30427
+ import { mkdir as mkdir3, readFile as readFile3, rename as rename2, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
30428
+ import path from "node:path";
30429
+ async function readConfig(cwd) {
30430
+ for (const file2 of ["dcp.json", "zcp.json"]) {
30431
+ try {
30432
+ return JSON.parse(await readFile3(path.join(cwd, ".pi", file2), "utf8"));
30433
+ } catch (error62) {
30434
+ if (error62.code !== "ENOENT") throw error62;
30435
+ }
30436
+ }
30437
+ return {};
30438
+ }
30439
+ function validateConfig(value) {
30440
+ if (!value || typeof value !== "object" || Array.isArray(value))
30441
+ throw new Error("dcp.json must be an object");
30442
+ const record2 = value;
30443
+ for (const key of Object.keys(record2))
30444
+ if (!["policy", "audit", "summaryPrompt", "dshBackends"].includes(key))
30445
+ throw new Error(`dcp.json: unknown setting ${key}`);
30446
+ if (record2.audit !== void 0 && typeof record2.audit !== "boolean")
30447
+ throw new Error("dcp.json: audit must be boolean");
30448
+ if (record2.policy !== void 0 && (!record2.policy || typeof record2.policy !== "object" || Array.isArray(record2.policy)))
30449
+ throw new Error("dcp.json: policy must be an object");
30450
+ const policy = record2.policy ?? {};
30451
+ resolveConfig2(policy);
30452
+ if (record2.summaryPrompt !== void 0) {
30453
+ const value2 = record2.summaryPrompt;
30454
+ if (!value2 || typeof value2 !== "object" || Array.isArray(value2))
30455
+ throw new Error("dcp.json: summaryPrompt must be an object");
30456
+ const prompt = value2;
30457
+ for (const key of Object.keys(prompt))
30458
+ if (!["mode", "text"].includes(key))
30459
+ throw new Error(`dcp.json: unknown summaryPrompt setting ${key}`);
30460
+ if (prompt.mode === "native") {
30461
+ if (prompt.text !== void 0)
30462
+ throw new Error("dcp.json: summaryPrompt.text is only used with override or append");
30463
+ } else {
30464
+ if (prompt.mode !== "override" && prompt.mode !== "append")
30465
+ throw new Error("dcp.json: summaryPrompt.mode must be native, override, or append");
30466
+ if (typeof prompt.text !== "string" || !prompt.text.trim())
30467
+ throw new Error("dcp.json: summaryPrompt.text must be a non-empty string");
30468
+ }
30469
+ }
30470
+ if (record2.dshBackends !== void 0) {
30471
+ const backends = record2.dshBackends;
30472
+ if (!backends || typeof backends !== "object" || Array.isArray(backends))
30473
+ throw new Error("dcp.json: dshBackends must be an object of named local backends");
30474
+ for (const [name2, backend] of Object.entries(backends)) {
30475
+ if (!name2.trim() || !backend || typeof backend !== "object" || Array.isArray(backend) || Object.keys(backend).some((key) => key !== "home" && key !== "sessionRoot") || typeof backend.home !== "string" || !path.isAbsolute(backend.home) || backend.sessionRoot !== void 0 && (typeof backend.sessionRoot !== "string" || !path.isAbsolute(backend.sessionRoot)))
30476
+ throw new Error(`dcp.json: dshBackends.${name2} requires an absolute local home and optional absolute sessionRoot`);
30477
+ }
30478
+ }
30479
+ return record2;
30480
+ }
30481
+ async function loadConfig(cwd, agentDir) {
30482
+ const config2 = { policy: {}, audit: true, ...validateConfig(await readConfig(cwd)) };
30483
+ if (agentDir && !config2.summaryPrompt) {
30484
+ const file2 = path.join(agentDir, "dcp.json");
30485
+ try {
30486
+ const userConfig = validateConfig(JSON.parse(await readFile3(file2, "utf8")));
30487
+ if (userConfig.summaryPrompt) config2.summaryPrompt = userConfig.summaryPrompt;
30488
+ } catch (error62) {
30489
+ if (error62.code !== "ENOENT")
30490
+ throw new Error(`${file2}: ${error62.message}`, { cause: error62 });
30491
+ }
30492
+ }
30493
+ return config2;
30494
+ }
30495
+
30496
+ // src/bridge.ts
30421
30497
  var JOURNAL = "dcp/transaction-v1";
30422
30498
  function canonical(value) {
30423
30499
  if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
@@ -30558,7 +30634,7 @@ function dshRowsFromPi(pi, entries, _file2, imageToDsh, projected = projectPiFor
30558
30634
  ].join("\n") + "\n";
30559
30635
  }
30560
30636
  function writeDshFromPi(file2, header, entries, imageToDsh, projected, destination) {
30561
- mkdirSync(path.dirname(file2), { recursive: true });
30637
+ mkdirSync(path2.dirname(file2), { recursive: true });
30562
30638
  const body = dshRowsFromPi(header, entries, file2, imageToDsh, projected, destination);
30563
30639
  const tmp = `${file2}.${process.pid}.tmp`;
30564
30640
  writeFileSync(tmp, body);
@@ -30577,13 +30653,13 @@ async function readPiSession(file2) {
30577
30653
  return { header, entries: rows };
30578
30654
  }
30579
30655
  async function writePiSession(file2, header, entries) {
30580
- const dir = path2.dirname(file2);
30656
+ const dir = path3.dirname(file2);
30581
30657
  await fs2.mkdir(dir, { recursive: true });
30582
30658
  const body = [
30583
30659
  JSON.stringify(header),
30584
30660
  ...entries.map((entry) => JSON.stringify(entry))
30585
30661
  ].join("\n") + "\n";
30586
- const tmp = path2.join(dir, `.${path2.basename(file2)}.${process.pid}.tmp`);
30662
+ const tmp = path3.join(dir, `.${path3.basename(file2)}.${process.pid}.tmp`);
30587
30663
  await fs2.writeFile(tmp, body, "utf8");
30588
30664
  await fs2.rename(tmp, file2);
30589
30665
  }
@@ -30621,7 +30697,7 @@ function messageEntry(id, parentId, time3, message) {
30621
30697
  return { ...base, message: { ...message, timestamp: time3 } };
30622
30698
  }
30623
30699
  async function piToDsh(input2, output2) {
30624
- if (path2.resolve(input2) === path2.resolve(output2))
30700
+ if (path3.resolve(input2) === path3.resolve(output2))
30625
30701
  throw new Error("Choose a separate output file for session conversion");
30626
30702
  const pi = await readPiSession(input2);
30627
30703
  return { input: input2, output: output2, ...await exportPiSession(pi, output2) };
@@ -30644,22 +30720,24 @@ async function exportPiSession(pi, output2, options = {}) {
30644
30720
  };
30645
30721
  }
30646
30722
  async function dshToPi(input2, output2) {
30647
- if (path2.resolve(input2) === path2.resolve(output2))
30723
+ if (path3.resolve(input2) === path3.resolve(output2))
30648
30724
  throw new Error("Choose a separate output file for session conversion");
30649
30725
  const dsh = await readDshFile(input2);
30650
30726
  if (!dsh) throw new Error(`${input2}: not a DSH session file`);
30727
+ const { header, entries } = await convertDshSession(dsh);
30728
+ await writePiSession(output2, header, entries);
30729
+ return {
30730
+ input: input2,
30731
+ output: output2,
30732
+ messages: entries.filter((entry) => entry.type === "message").length,
30733
+ events: dsh.events.length
30734
+ };
30735
+ }
30736
+ async function convertDshSession(dsh, dshHome) {
30651
30737
  const archived = archivedPi(dsh.header, dsh.events);
30652
- if (archived) {
30653
- await writePiSession(output2, archived.header, archived.entries);
30654
- return {
30655
- input: input2,
30656
- output: output2,
30657
- messages: archived.entries.filter((entry) => entry.type === "message").length,
30658
- events: dsh.events.length
30659
- };
30660
- }
30738
+ if (archived) return archived;
30661
30739
  const session = restoreSession(dsh.header, dsh.events);
30662
- const carrier = await openImageBridge();
30740
+ const carrier = await openImageBridge(dshHome);
30663
30741
  let messages;
30664
30742
  try {
30665
30743
  await carrier.images.hydrate(
@@ -30685,17 +30763,16 @@ async function dshToPi(input2, output2) {
30685
30763
  );
30686
30764
  parentId = id;
30687
30765
  }
30688
- await writePiSession(output2, header, entries);
30689
- return { input: input2, output: output2, messages: messages.length, events: dsh.events.length };
30766
+ return { header, entries };
30690
30767
  }
30691
30768
 
30692
30769
  // src/dsh/import.ts
30693
30770
  import { promises as fs3 } from "node:fs";
30694
30771
  import { homedir as homedir2, tmpdir } from "node:os";
30695
- import * as path3 from "node:path";
30696
- import { promisify } from "node:util";
30772
+ import * as path4 from "node:path";
30773
+ import { promisify as promisify2 } from "node:util";
30697
30774
  import { constants as constants2, zstdCompress } from "node:zlib";
30698
- var compress = promisify(zstdCompress);
30775
+ var compress = promisify2(zstdCompress);
30699
30776
  var zstdOptions = { params: { [constants2.ZSTD_c_checksumFlag]: 1 } };
30700
30777
  function escapeSegment(value) {
30701
30778
  return value.replace(
@@ -30712,16 +30789,16 @@ async function nativeDestination(root, sessionId, cwd, plaintext) {
30712
30789
  if (error62.code !== "ENOENT") throw error62;
30713
30790
  }
30714
30791
  const id = sessionId === "." || sessionId === ".." ? sessionId.replaceAll(".", "~002E") : escapeSegment(sessionId);
30715
- const project = path3.join(root, projectKey(cwd));
30716
- const destination = path3.join(project, id);
30717
- const output2 = path3.join(destination, `session.v${DSH_FORMAT_VERSION}.jsonl${plaintext ? "" : ".zstd"}`);
30792
+ const project = path4.join(root, projectKey(cwd));
30793
+ const destination = path4.join(project, id);
30794
+ const output2 = path4.join(destination, `session.v${DSH_FORMAT_VERSION}.jsonl${plaintext ? "" : ".zstd"}`);
30718
30795
  let conflict;
30719
30796
  for await (const existing of fs3.glob("*/*/session{,.v*}.jsonl{,.zstd}", { cwd: root })) {
30720
- const filename = path3.basename(existing);
30797
+ const filename = path4.basename(existing);
30721
30798
  if (!/^session(?:\.v[1-9]\d*)?\.jsonl(?:\.zstd)?$/.test(filename)) continue;
30722
30799
  if (filename.endsWith(".zstd") === plaintext)
30723
30800
  throw new Error(`DSH session root uses a different encoding: ${root}`);
30724
- if (path3.basename(path3.dirname(existing)) === id) conflict = path3.join(root, existing);
30801
+ if (path4.basename(path4.dirname(existing)) === id) conflict = path4.join(root, existing);
30725
30802
  }
30726
30803
  try {
30727
30804
  await fs3.lstat(destination);
@@ -30737,18 +30814,18 @@ function projectKey(cwd) {
30737
30814
  const readable = escapeSegment(cwd.replace(/[/\\:]+/g, "-")).replace(/^-+/, "");
30738
30815
  return `--${(readable || "root").slice(0, 251)}--`;
30739
30816
  }
30740
- async function importPiToDsh(input2, root = path3.join(process.env.DSH_HOME || path3.join(homedir2(), ".dsh"), "sessions"), plaintext = false, options = {}) {
30741
- root = path3.resolve(root);
30817
+ async function importPiToDsh(input2, root = path4.join(process.env.DSH_HOME || path4.join(homedir2(), ".dsh"), "sessions"), plaintext = false, options = {}) {
30818
+ root = path4.resolve(root);
30742
30819
  const pi = options.pi ?? await readPiSession(input2);
30743
30820
  const sessionId = options.sessionId ?? pi.header.id;
30744
30821
  const cwd = options.cwd ?? pi.header.cwd;
30745
- if (!sessionId || !cwd || !path3.isAbsolute(cwd))
30822
+ if (!sessionId || !cwd || !path4.isAbsolute(cwd))
30746
30823
  throw new Error("Import requires a native pi session with an ID and an absolute local project path");
30747
30824
  const output2 = await nativeDestination(root, sessionId, cwd, plaintext);
30748
- const destination = path3.dirname(output2);
30749
- const stage = await fs3.mkdtemp(path3.join(tmpdir(), "dcp-import-"));
30825
+ const destination = path4.dirname(output2);
30826
+ const stage = await fs3.mkdtemp(path4.join(tmpdir(), "dcp-import-"));
30750
30827
  try {
30751
- const raw = path3.join(stage, "session.jsonl");
30828
+ const raw = path4.join(stage, "session.jsonl");
30752
30829
  const report = await exportPiSession(pi, raw, {
30753
30830
  dshHome: options.dshHome,
30754
30831
  destination: options.sessionId !== void 0 || options.cwd !== void 0 ? { id: sessionId, cwd } : void 0
@@ -30759,7 +30836,7 @@ async function importPiToDsh(input2, root = path3.join(process.env.DSH_HOME || p
30759
30836
  compress(bytes.subarray(0, headerEnd), zstdOptions),
30760
30837
  compress(bytes.subarray(headerEnd), zstdOptions)
30761
30838
  ]));
30762
- await fs3.mkdir(path3.dirname(destination), { recursive: true, mode: 448 });
30839
+ await fs3.mkdir(path4.dirname(destination), { recursive: true, mode: 448 });
30763
30840
  try {
30764
30841
  await fs3.mkdir(destination, { mode: 448 });
30765
30842
  } catch (error62) {
@@ -30767,7 +30844,7 @@ async function importPiToDsh(input2, root = path3.join(process.env.DSH_HOME || p
30767
30844
  throw new DestinationConflict(`DSH session already exists: ${sessionId} (${destination})`);
30768
30845
  throw error62;
30769
30846
  }
30770
- const pending = path3.join(destination, ".dcp-import.tmp");
30847
+ const pending = path4.join(destination, ".dcp-import.tmp");
30771
30848
  try {
30772
30849
  await fs3.writeFile(pending, stored, { flag: "wx", mode: 384 });
30773
30850
  await fs3.rename(pending, output2);
@@ -30785,19 +30862,20 @@ async function importPiToDsh(input2, root = path3.join(process.env.DSH_HOME || p
30785
30862
  // src/dsh/migration-cli.ts
30786
30863
  import { promises as fs6 } from "node:fs";
30787
30864
  import { createInterface } from "node:readline/promises";
30865
+ import path6 from "node:path";
30788
30866
  import { parseArgs } from "node:util";
30789
30867
 
30790
30868
  // src/dsh/migration.ts
30791
30869
  import { createHash as createHash6, randomUUID as randomUUID5 } from "node:crypto";
30792
30870
  import { promises as fs4 } from "node:fs";
30793
30871
  import { homedir as homedir3, hostname as hostname3 } from "node:os";
30794
- import path4 from "node:path";
30872
+ import path5 from "node:path";
30795
30873
  var migrationTargets = ["portable", "windows-desktop", "linux-desktop", "web", "tui"];
30796
30874
  var dshVersions = ["0.2.2-rc.1", "0.2.2-rc.5", "0.2.3-alpha.2"];
30797
30875
  function migrationEnvironment() {
30798
- const piHome = path4.resolve(process.env.PI_CODING_AGENT_DIR ?? path4.join(homedir3(), ".pi", "agent"));
30799
- const dshHome = path4.resolve(process.env.DSH_HOME ?? path4.join(homedir3(), ".dsh"));
30800
- return { host: hostname3(), platform: process.platform, piHome, suggestedDshHome: dshHome, suggestedSessionRoot: path4.join(dshHome, "sessions") };
30876
+ const piHome = path5.resolve(process.env.PI_CODING_AGENT_DIR ?? path5.join(homedir3(), ".pi", "agent"));
30877
+ const dshHome = path5.resolve(process.env.DSH_HOME ?? path5.join(homedir3(), ".dsh"));
30878
+ return { host: hostname3(), platform: process.platform, piHome, suggestedDshHome: dshHome, suggestedSessionRoot: path5.join(dshHome, "sessions") };
30801
30879
  }
30802
30880
  var MixedSession = class extends Error {
30803
30881
  };
@@ -30814,8 +30892,8 @@ var piEntryTypes = /* @__PURE__ */ new Set([
30814
30892
  "label"
30815
30893
  ]);
30816
30894
  function absolute(value, label) {
30817
- if (!value || !path4.isAbsolute(value)) throw new Error(`${label} must be an absolute path on this host`);
30818
- return path4.resolve(value);
30895
+ if (!value || !path5.isAbsolute(value)) throw new Error(`${label} must be an absolute path on this host`);
30896
+ return path5.resolve(value);
30819
30897
  }
30820
30898
  async function directory(value, label) {
30821
30899
  const dir = absolute(value, label);
@@ -30825,12 +30903,12 @@ async function directory(value, label) {
30825
30903
  async function targetRoot(value) {
30826
30904
  const root = absolute(value, "Target session root");
30827
30905
  const remaining = [];
30828
- for (let current = root; ; current = path4.dirname(current)) {
30906
+ for (let current = root; ; current = path5.dirname(current)) {
30829
30907
  try {
30830
- return path4.join(await directory(current, "Target session root"), ...remaining);
30908
+ return path5.join(await directory(current, "Target session root"), ...remaining);
30831
30909
  } catch (error62) {
30832
- if (error62.code !== "ENOENT" || current === path4.dirname(current)) throw error62;
30833
- remaining.unshift(path4.basename(current));
30910
+ if (error62.code !== "ENOENT" || current === path5.dirname(current)) throw error62;
30911
+ remaining.unshift(path5.basename(current));
30834
30912
  }
30835
30913
  }
30836
30914
  }
@@ -30839,10 +30917,10 @@ function digest3(value) {
30839
30917
  }
30840
30918
  async function findPiSources({ piHome, cwd, id }) {
30841
30919
  if (!cwd && !id) throw new Error("Pass --cwd or --id to select Pi sessions");
30842
- const root = path4.join(absolute(piHome ?? process.env.PI_CODING_AGENT_DIR ?? path4.join(homedir3(), ".pi", "agent"), "Pi agent directory"), "sessions");
30920
+ const root = path5.join(absolute(piHome ?? process.env.PI_CODING_AGENT_DIR ?? path5.join(homedir3(), ".pi", "agent"), "Pi agent directory"), "sessions");
30843
30921
  const matches = [];
30844
30922
  for await (const file2 of fs4.glob("*/*.jsonl", { cwd: root })) {
30845
- const input2 = path4.join(root, file2);
30923
+ const input2 = path5.join(root, file2);
30846
30924
  const handle = await fs4.open(input2, "r");
30847
30925
  try {
30848
30926
  const buffer = Buffer.alloc(65536);
@@ -30892,14 +30970,14 @@ async function loadSource(input2, recover) {
30892
30970
  return { pi, sha256: digest3(bytes), mirrorRows: mirrors.length };
30893
30971
  }
30894
30972
  async function portableOutput(dir, sessionId) {
30895
- const folder = path4.join(dir, "dcp-" + escapeSegment(sessionId));
30973
+ const folder = path5.join(dir, "dcp-" + escapeSegment(sessionId));
30896
30974
  try {
30897
30975
  await fs4.lstat(folder);
30898
30976
  throw new DestinationConflict(`Export directory already exists: ${folder}`);
30899
30977
  } catch (error62) {
30900
30978
  if (error62.code !== "ENOENT") throw error62;
30901
30979
  }
30902
- return path4.join(folder, "session.dsh.jsonl");
30980
+ return path5.join(folder, "session.dsh.jsonl");
30903
30981
  }
30904
30982
  async function prepare(options, copyId) {
30905
30983
  const { target, dshVersion, profile, encoding } = options;
@@ -30957,7 +31035,7 @@ async function prepare(options, copyId) {
30957
31035
  cwd,
30958
31036
  output: output2,
30959
31037
  conflict,
30960
- attachmentHome: dshHome ?? path4.dirname(output2)
31038
+ attachmentHome: dshHome ?? path5.dirname(output2)
30961
31039
  };
30962
31040
  return { pi, plan };
30963
31041
  }
@@ -30977,7 +31055,7 @@ async function applyMigration(saved, confirmation) {
30977
31055
  const report = await importPiToDsh(source, sessionRoot, encoding === "plain", { pi, sessionId, cwd, dshHome });
30978
31056
  return { ...report, target: plan.target, attachmentHome: plan.attachmentHome, status: "written", verification: "open-and-check-target-history" };
30979
31057
  }
30980
- const folder = path4.dirname(output2);
31058
+ const folder = path5.dirname(output2);
30981
31059
  await fs4.mkdir(folder, { mode: 448 });
30982
31060
  try {
30983
31061
  const report = await exportPiSession(pi, output2, { dshHome: folder, destination });
@@ -31084,8 +31162,15 @@ async function interactive(source) {
31084
31162
  } else throw error62;
31085
31163
  }
31086
31164
  }
31087
- print(plan);
31088
- const code = await ask("Review the destination above and type the confirmation code to write:");
31165
+ console.log(`Session ${plan.sourceSessionId} \u2192 ${plan.target} on ${plan.host}`);
31166
+ console.log(`Output: ${plan.output}`);
31167
+ if (plan.attachmentHome !== path6.dirname(plan.output))
31168
+ console.log(`Attachments: ${plan.attachmentHome}`);
31169
+ if (plan.sessionId !== plan.sourceSessionId)
31170
+ console.log(`New session ID: ${plan.sessionId}`);
31171
+ if (plan.mirrorRows)
31172
+ console.log(`Recover Pi entries only, leaving ${plan.mirrorRows} DSH rows in the source.`);
31173
+ const code = await ask(`Write to this location? Enter ${plan.confirmation} to confirm, or press Enter to cancel.`);
31089
31174
  if (!code) return;
31090
31175
  print(await applyMigration(plan, code));
31091
31176
  } finally {
@@ -31171,9 +31256,385 @@ async function runMigration(args) {
31171
31256
  }
31172
31257
  }
31173
31258
 
31174
- // bin/dcp-session.ts
31259
+ // src/dsh/reverse-migration-cli.ts
31260
+ import { promises as fs9 } from "node:fs";
31261
+ import { parseArgs as parseArgs2 } from "node:util";
31262
+
31263
+ // src/dsh/pi-destination.ts
31264
+ import { promises as fs7 } from "node:fs";
31265
+ import { homedir as homedir4 } from "node:os";
31266
+ import path7 from "node:path";
31267
+ import { pathToFileURL } from "node:url";
31268
+ var piPackage = "@earendil-works/pi-coding-agent";
31269
+ async function installedPi() {
31270
+ for (const folder of (process.env.PATH ?? "").split(path7.delimiter).filter(Boolean)) {
31271
+ const command = path7.resolve(folder, "pi");
31272
+ const entrypoints = [path7.join(folder, "node_modules", piPackage, "dist", "index.js")];
31273
+ try {
31274
+ const real = await fs7.realpath(command);
31275
+ const dist = path7.dirname(real);
31276
+ if (real.endsWith(".js")) entrypoints.push(path7.join(dist, "index.js"), path7.join(dist, "..", "index.js"));
31277
+ else {
31278
+ const handle = await fs7.open(real, "r");
31279
+ try {
31280
+ const buffer = Buffer.alloc(16384);
31281
+ const { bytesRead } = await handle.read(buffer);
31282
+ const target = /^# cmd-shim-target=(.+)$/m.exec(buffer.subarray(0, bytesRead).toString())?.[1]?.trim();
31283
+ if (target && path7.isAbsolute(target))
31284
+ entrypoints.unshift(path7.join(path7.dirname(target), "..", "index.js"), path7.join(path7.dirname(target), "index.js"));
31285
+ } finally {
31286
+ await handle.close();
31287
+ }
31288
+ }
31289
+ } catch (error62) {
31290
+ if (error62.code !== "ENOENT") throw error62;
31291
+ }
31292
+ for (const file2 of entrypoints) {
31293
+ try {
31294
+ if (!(await fs7.stat(file2)).isFile()) continue;
31295
+ } catch (error62) {
31296
+ if (error62.code === "ENOENT") continue;
31297
+ throw error62;
31298
+ }
31299
+ const sdk2 = await import(pathToFileURL(file2).href);
31300
+ if (sdk2.SessionManager && sdk2.SettingsManager) return sdk2;
31301
+ }
31302
+ }
31303
+ const sdk = await import(piPackage).catch(() => void 0);
31304
+ if (sdk) return sdk;
31305
+ throw new Error("Cannot load the local Pi session manager. Run with Pi installed on this host and on PATH.");
31306
+ }
31307
+ async function resolvePiDestination(options) {
31308
+ const workspace = await directory(options.workspace, "Pi workspace");
31309
+ const sdk = await installedPi();
31310
+ const piHome = absolute(options.piHome ?? sdk.getAgentDir(), "Pi agent home");
31311
+ const sessionDirectory = options.sessionDir ?? (process.env.PI_CODING_AGENT_SESSION_DIR || sdk.SettingsManager.create(workspace, piHome).getSessionDir());
31312
+ const key = `--${workspace.replace(/^[/\\]/, "").replace(/[/\\:]/g, "-")}--`;
31313
+ const configuredDir = sessionDirectory && !options.sessionDir ? path7.resolve(workspace, sessionDirectory.replace(/^~(?=[/\\]|$)/, homedir4())) : sessionDirectory;
31314
+ const sessionDir = await targetRoot(configuredDir ?? path7.join(piHome, "sessions", key));
31315
+ let parent = sessionDir;
31316
+ for (; ; ) {
31317
+ try {
31318
+ await fs7.access(parent, fs7.constants.W_OK | fs7.constants.X_OK);
31319
+ break;
31320
+ } catch (error62) {
31321
+ if (error62.code !== "ENOENT" || parent === path7.dirname(parent)) throw error62;
31322
+ parent = path7.dirname(parent);
31323
+ }
31324
+ }
31325
+ const launchArgs = options.sessionDir ? ["--session-dir", sessionDir] : [];
31326
+ return { workspace, piHome, sessionDir, sessionDirSource: options.sessionDir ? "explicit" : configuredDir ? "configured" : "project", launchArgs, sdk };
31327
+ }
31328
+
31329
+ // src/dsh/reverse-migration.ts
31330
+ import { randomUUID as randomUUID7 } from "node:crypto";
31331
+ import { createReadStream as createReadStream3, promises as fs8 } from "node:fs";
31332
+ import { homedir as homedir5, hostname as hostname4 } from "node:os";
31333
+ import path8 from "node:path";
31334
+ import { createZstdDecompress } from "node:zlib";
31335
+ async function checkBackend(name2, backend, origin) {
31336
+ const sessionRoot = backend.sessionRoot ?? path8.join(backend.home, "sessions");
31337
+ const details = { name: name2, origin, home: backend.home, sessionRoot };
31338
+ try {
31339
+ const home = await directory(backend.home, "DSH home");
31340
+ const root = await directory(sessionRoot, "DSH session root");
31341
+ await fs8.access(home, fs8.constants.R_OK | fs8.constants.X_OK);
31342
+ await fs8.access(root, fs8.constants.R_OK | fs8.constants.X_OK);
31343
+ return { ...details, home, sessionRoot: root, available: true };
31344
+ } catch (error62) {
31345
+ return { ...details, available: false, reason: error62.message };
31346
+ }
31347
+ }
31348
+ async function probeDshBackends(project) {
31349
+ const { dshBackends = {} } = await loadConfig(await directory(project, "Current project"));
31350
+ const recorded = await Promise.all(Object.entries(dshBackends).map(([name2, backend]) => checkBackend(name2, backend, "config")));
31351
+ const defaultHome = path8.join(homedir5(), ".dsh");
31352
+ const suggestions = [
31353
+ ...process.env.DSH_HOME ? [await checkBackend("environment", { home: path8.resolve(process.env.DSH_HOME) }, "environment")] : [],
31354
+ await checkBackend("default", { home: defaultHome }, "default")
31355
+ ];
31356
+ const backendKey = (backend) => JSON.stringify([backend.home, backend.sessionRoot]);
31357
+ const seen = new Set(recorded.filter((backend) => backend.available).map(backendKey));
31358
+ return {
31359
+ host: hostname4(),
31360
+ platform: process.platform,
31361
+ status: recorded.length ? "configured" : "no-configured-backend",
31362
+ recorded,
31363
+ suggestions: suggestions.filter((backend) => {
31364
+ const key = backendKey(backend);
31365
+ if (seen.has(key) || Object.hasOwn(dshBackends, backend.name)) return false;
31366
+ seen.add(key);
31367
+ return true;
31368
+ })
31369
+ };
31370
+ }
31371
+ async function selectBackend(options) {
31372
+ const { backend: name2, dshHome, sessionRoot } = options;
31373
+ let backend;
31374
+ if (dshHome) {
31375
+ if (name2) throw new Error("Choose a named backend or pass a custom DSH home");
31376
+ backend = await checkBackend("custom", {
31377
+ home: absolute(dshHome, "DSH home"),
31378
+ sessionRoot: sessionRoot && absolute(sessionRoot, "DSH session root")
31379
+ }, "custom");
31380
+ } else {
31381
+ if (!name2 || sessionRoot) throw new Error("Select --backend or pass --dsh-home with an optional --session-root");
31382
+ const { recorded, suggestions } = await probeDshBackends(options.project);
31383
+ backend = [...recorded, ...suggestions].find((value) => value.name === name2);
31384
+ if (!backend) throw new Error(`Unknown DSH backend: ${name2}. Run probe and confirm a backend.`);
31385
+ }
31386
+ if (!backend.available) throw new Error(`DSH backend ${backend.name} is unavailable: ${backend.reason}`);
31387
+ return backend;
31388
+ }
31389
+ async function readHeader(file2) {
31390
+ const input2 = createReadStream3(file2);
31391
+ const decoder = file2.endsWith(".zstd") ? createZstdDecompress() : void 0;
31392
+ if (decoder) input2.on("error", (error62) => decoder.destroy(error62));
31393
+ const stream = decoder ? input2.pipe(decoder) : input2;
31394
+ try {
31395
+ let header = Buffer.alloc(0);
31396
+ for await (const chunk of stream) {
31397
+ const bytes = Buffer.from(chunk);
31398
+ const newline = bytes.indexOf(10);
31399
+ const prefix = newline === -1 ? bytes : bytes.subarray(0, newline);
31400
+ if (header.length + prefix.length > 65536) throw new Error("DSH session header is too large");
31401
+ header = Buffer.concat([header, prefix]);
31402
+ if (newline !== -1) return JSON.parse(header.toString("utf8"));
31403
+ }
31404
+ throw new Error("Missing DSH session header");
31405
+ } finally {
31406
+ stream.destroy();
31407
+ input2.destroy();
31408
+ }
31409
+ }
31410
+ var logFilename = /^session(?:\.v([1-9]\d*))?\.jsonl(\.zstd)?$/;
31411
+ async function scanDshSessions(root) {
31412
+ const generations = /* @__PURE__ */ new Map();
31413
+ for await (const file2 of fs8.glob("*/*/session*.jsonl{,.zstd}", { cwd: root })) {
31414
+ const match = logFilename.exec(path8.basename(file2));
31415
+ if (!match) continue;
31416
+ const generation = Number(match[1] ?? 1);
31417
+ const folder = path8.dirname(file2);
31418
+ const latest = generations.get(folder);
31419
+ const encodings = latest?.encodings ?? /* @__PURE__ */ new Set();
31420
+ encodings.add(Boolean(match[2]));
31421
+ if (!latest || generation > latest.version) generations.set(folder, { version: generation, file: file2, encodings });
31422
+ }
31423
+ const sessions = [];
31424
+ const skipped = [];
31425
+ for (const { file: relative, version: version3, encodings } of generations.values()) {
31426
+ const file2 = path8.join(root, relative);
31427
+ if (encodings.size > 1 || version3 !== DSH_FORMAT_VERSION) {
31428
+ skipped.push({ file: file2, reason: encodings.size > 1 ? "ambiguous encoding" : `unsupported generation v${version3}` });
31429
+ continue;
31430
+ }
31431
+ try {
31432
+ const realFile = await fs8.realpath(file2);
31433
+ if (realFile !== file2) throw new Error("session log is a symlink");
31434
+ const header = await readHeader(file2);
31435
+ if (header?.type !== "session" || header.version !== DSH_FORMAT_VERSION || typeof header.id !== "string" || !header.id || !Number.isFinite(header.createdAt))
31436
+ throw new Error("invalid DSH v4 session header");
31437
+ const updated = (await fs8.stat(file2)).mtimeMs;
31438
+ sessions.push({ id: header.id, cwd: header.cwd, createdAt: header.createdAt, updated, file: file2 });
31439
+ } catch (error62) {
31440
+ skipped.push({ file: file2, reason: error62.message });
31441
+ }
31442
+ }
31443
+ sessions.sort((a, b) => b.updated - a.updated || a.id.localeCompare(b.id));
31444
+ const counts = /* @__PURE__ */ new Map();
31445
+ for (const session of sessions) counts.set(session.id, (counts.get(session.id) ?? 0) + 1);
31446
+ return {
31447
+ sessions: sessions.filter((session) => counts.get(session.id) === 1),
31448
+ skipped: [...skipped, ...sessions.filter((session) => counts.get(session.id) > 1).map(({ file: file2 }) => ({ file: file2, reason: "duplicate DSH session ID" }))]
31449
+ };
31450
+ }
31451
+ async function listDshSessions(options) {
31452
+ const backend = await selectBackend(options);
31453
+ const { sessions, skipped } = await scanDshSessions(backend.sessionRoot);
31454
+ const selected = options.cwd ? sessions.filter((session) => session.cwd === options.cwd) : sessions;
31455
+ const offset = options.offset ?? 0;
31456
+ const limit = options.limit ?? 20;
31457
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > 100)
31458
+ throw new Error("Use a non-negative offset and a limit between 1 and 100");
31459
+ return { backend, total: selected.length, skipped: skipped.length, offset, sessions: selected.slice(offset, offset + limit) };
31460
+ }
31461
+ async function prepare2(options, copyId) {
31462
+ if (!options.id) throw new Error("Confirm the DSH session ID");
31463
+ if (options.onConflict && options.onConflict !== "copy") throw new Error("Use --on-conflict copy or choose another session");
31464
+ const backend = await selectBackend(options);
31465
+ const { sessions } = await scanDshSessions(backend.sessionRoot);
31466
+ const selected = sessions.find((session) => session.id === options.id);
31467
+ if (!selected) throw new Error("The selected DSH session is no longer uniquely available. Refresh the list.");
31468
+ const raw = await fs8.readFile(selected.file);
31469
+ const { sdk, ...destination } = await resolvePiDestination(options);
31470
+ const timestamp = new Date(selected.createdAt).toISOString().replace(/[:.]/g, "-");
31471
+ const outputFor = (id) => path8.join(destination.sessionDir, `${timestamp}_${id}.jsonl`);
31472
+ const available = async (id) => {
31473
+ if (sdk.SessionManager.findById(destination.workspace, id, destination.sessionDir)) return false;
31474
+ try {
31475
+ await fs8.lstat(outputFor(id));
31476
+ return false;
31477
+ } catch (error62) {
31478
+ if (error62.code === "ENOENT") return true;
31479
+ throw error62;
31480
+ }
31481
+ };
31482
+ let sessionId = selected.id;
31483
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(sessionId))
31484
+ throw new Error("Unsupported DSH session ID for Pi import");
31485
+ const conflict = !await available(sessionId);
31486
+ if (conflict) {
31487
+ if (options.onConflict !== "copy") throw new DestinationConflict(`Pi already has session ${sessionId} at the selected destination; ask whether to import a copy with a new ID.`);
31488
+ sessionId = copyId ?? randomUUID7();
31489
+ if (!/^[0-9a-f-]{36}$/i.test(sessionId) || sessionId === selected.id || !await available(sessionId))
31490
+ throw new DestinationConflict("The copy ID is unavailable. Generate and approve a new plan.");
31491
+ }
31492
+ const plan = {
31493
+ host: hostname4(),
31494
+ platform: process.platform,
31495
+ backend,
31496
+ source: selected.file,
31497
+ sourceSessionId: selected.id,
31498
+ sourceCwd: selected.cwd,
31499
+ sha256: digest3(raw),
31500
+ ...destination,
31501
+ output: outputFor(sessionId),
31502
+ sessionId,
31503
+ conflict
31504
+ };
31505
+ return { sdk, raw, plan };
31506
+ }
31507
+ async function planReverseMigration(options) {
31508
+ const { plan } = await prepare2(options);
31509
+ return { schema: 1, options, ...plan, confirmation: digest3(JSON.stringify(plan)).slice(0, 12) };
31510
+ }
31511
+ async function applyReverseMigration(saved, confirmation) {
31512
+ if (saved.schema !== 1 || !confirmation || confirmation !== saved.confirmation)
31513
+ throw new Error("Apply requires the confirmation code from the approved plan");
31514
+ const { plan, sdk, raw } = await prepare2(saved.options, saved.sessionId);
31515
+ if (digest3(JSON.stringify(plan)).slice(0, 12) !== confirmation)
31516
+ throw new Error("The source or destination changed. Generate and confirm a new plan.");
31517
+ const dsh = await parseDshFile(plan.source, raw);
31518
+ if (!dsh || dsh.header.id !== plan.sourceSessionId) throw new Error("The selected DSH session changed");
31519
+ const { header, entries } = await convertDshSession(dsh, plan.backend.home);
31520
+ await fs8.mkdir(plan.sessionDir, { recursive: true, mode: 448 });
31521
+ if (await fs8.realpath(plan.sessionDir) !== plan.sessionDir)
31522
+ throw new Error("Pi session directory changed. Generate and confirm a new plan.");
31523
+ const stage = await fs8.mkdtemp(path8.join(plan.sessionDir, ".dcp-import-"));
31524
+ try {
31525
+ const staged = path8.join(stage, "session.jsonl");
31526
+ await writePiSession(staged, { ...header, id: plan.sessionId, cwd: plan.workspace }, entries);
31527
+ if (process.platform !== "win32") await fs8.chmod(staged, 384);
31528
+ const pi = await readPiSession(staged);
31529
+ const messages = sdk.SessionManager.open(staged, stage, plan.workspace).buildSessionProjection().messages.length;
31530
+ if (pi.header.id !== plan.sessionId || pi.header.cwd !== plan.workspace || !messages)
31531
+ throw new Error("Converted history could not be opened by Pi");
31532
+ if (sdk.SessionManager.findById(plan.workspace, plan.sessionId, plan.sessionDir))
31533
+ throw new DestinationConflict("The destination session ID was taken after approval");
31534
+ await fs8.link(staged, plan.output);
31535
+ const row = (await sdk.SessionManager.list(plan.workspace, plan.sessionDir)).find((item) => item.id === plan.sessionId && path8.resolve(item.path) === plan.output);
31536
+ if (!row?.messageCount)
31537
+ throw new Error(`Written to ${plan.output}, but Pi could not list the imported history`);
31538
+ return {
31539
+ status: "verified",
31540
+ checks: ["pi-history", "pi-session-list"],
31541
+ output: plan.output,
31542
+ workspace: plan.workspace,
31543
+ piHome: plan.piHome,
31544
+ sessionDir: plan.sessionDir,
31545
+ sessionId: plan.sessionId,
31546
+ messages: row.messageCount,
31547
+ resumeArgs: [...plan.launchArgs, "--session", plan.output]
31548
+ };
31549
+ } finally {
31550
+ await fs8.rm(stage, { force: true, recursive: true });
31551
+ }
31552
+ }
31553
+
31554
+ // src/dsh/reverse-migration-cli.ts
31175
31555
  var help2 = `Usage:
31556
+ dcp-session import-dsh probe [--project <dir>]
31557
+ dcp-session import-dsh sessions [--project <dir>] <backend> [--cwd <source-project>] [--limit <n>] [--offset <n>]
31558
+ dcp-session import-dsh destination [--workspace <dir>] [--pi-home <dir>] [--session-dir <dir>]
31559
+ dcp-session import-dsh plan [--project <dir>] <backend> --id <session-id> --workspace <dir> --plan-file <file>
31560
+ [--pi-home <dir>] [--session-dir <dir>] [--on-conflict copy]
31561
+ dcp-session import-dsh apply --plan-file <file> --confirm <code>
31562
+
31563
+ Backend: --backend <name> from probe, or --dsh-home <dir> [--session-root <dir>].
31564
+ Use native paths on the host that runs Pi. Only apply writes a Pi session.
31565
+ Confirm the selected workspace, session directory and exact output before apply.`;
31566
+ var string4 = { type: "string" };
31567
+ var backendOptions = { project: string4, backend: string4, "dsh-home": string4, "session-root": string4 };
31568
+ var destinationOptions = { workspace: string4, "pi-home": string4, "session-dir": string4 };
31569
+ var print2 = (value) => console.log(JSON.stringify(value, null, 2));
31570
+ async function runReverseMigration([command, ...args]) {
31571
+ if (!command || command === "--help" || command === "-h") {
31572
+ console.log(help2);
31573
+ return;
31574
+ }
31575
+ if (command === "probe") {
31576
+ const { values } = parseArgs2({ args, options: { project: string4 } });
31577
+ print2(await probeDshBackends(values.project ?? process.cwd()));
31578
+ } else if (command === "sessions") {
31579
+ const { values } = parseArgs2({ args, options: {
31580
+ ...backendOptions,
31581
+ cwd: string4,
31582
+ limit: string4,
31583
+ offset: string4
31584
+ } });
31585
+ print2(await listDshSessions({
31586
+ project: values.project ?? process.cwd(),
31587
+ backend: values.backend,
31588
+ dshHome: values["dsh-home"],
31589
+ sessionRoot: values["session-root"],
31590
+ cwd: values.cwd,
31591
+ limit: values.limit === void 0 ? void 0 : Number(values.limit),
31592
+ offset: values.offset === void 0 ? void 0 : Number(values.offset)
31593
+ }));
31594
+ } else if (command === "destination") {
31595
+ const { values } = parseArgs2({ args, options: destinationOptions });
31596
+ const { workspace, piHome, sessionDir, sessionDirSource } = await resolvePiDestination({
31597
+ workspace: values.workspace ?? process.cwd(),
31598
+ piHome: values["pi-home"],
31599
+ sessionDir: values["session-dir"]
31600
+ });
31601
+ print2({ workspace, piHome, sessionDir, sessionDirSource });
31602
+ } else if (command === "plan") {
31603
+ const { values } = parseArgs2({ args, options: {
31604
+ ...backendOptions,
31605
+ ...destinationOptions,
31606
+ id: string4,
31607
+ "plan-file": string4,
31608
+ "on-conflict": string4
31609
+ } });
31610
+ if (!values.id || !values.workspace || !values["plan-file"])
31611
+ throw new Error("Pass the selected --id, --workspace and a fresh --plan-file");
31612
+ const plan = await planReverseMigration({
31613
+ project: values.project ?? process.cwd(),
31614
+ backend: values.backend,
31615
+ dshHome: values["dsh-home"],
31616
+ sessionRoot: values["session-root"],
31617
+ id: values.id,
31618
+ workspace: values.workspace,
31619
+ piHome: values["pi-home"],
31620
+ sessionDir: values["session-dir"],
31621
+ onConflict: values["on-conflict"]
31622
+ });
31623
+ await fs9.writeFile(values["plan-file"], JSON.stringify(plan, null, 2) + "\n", { mode: 384, flag: "wx" });
31624
+ print2(plan);
31625
+ } else if (command === "apply") {
31626
+ const { values } = parseArgs2({ args, options: { "plan-file": string4, confirm: string4 } });
31627
+ if (!values["plan-file"] || !values.confirm) throw new Error("Pass --plan-file and the approved --confirm code");
31628
+ print2(await applyReverseMigration(JSON.parse(await fs9.readFile(values["plan-file"], "utf8")), values.confirm));
31629
+ } else {
31630
+ throw new Error(help2);
31631
+ }
31632
+ }
31633
+
31634
+ // bin/dcp-session.ts
31635
+ var help3 = `Usage:
31176
31636
  dcp-session migrate --help
31637
+ dcp-session import-dsh --help
31177
31638
  dcp-session pi2dsh <pi-session.jsonl> <out.dsh.jsonl>
31178
31639
  dcp-session pi2dsh-import <pi-session.jsonl> [dsh-session-root] [--plain]
31179
31640
  dcp-session dsh2pi <dsh-session.jsonl> <out.pi.jsonl>
@@ -31186,21 +31647,22 @@ configured with plaintext session storage.
31186
31647
  dsh2pi restores those entries from an unchanged export. For a native or
31187
31648
  continued DSH session it imports the active DSH context.
31188
31649
 
31189
- Use a separate output path. DSH input may be .jsonl or .zstd (requires zstd).
31650
+ Use a separate output path. DSH input may be .jsonl or .zstd.
31190
31651
  Image references are resolved under DSH_HOME (default ~/.dsh).`;
31191
31652
  async function main([command, input2, ...args]) {
31192
31653
  if (command === "--help" || command === "-h") {
31193
- console.log(help2);
31654
+ console.log(help3);
31194
31655
  return;
31195
31656
  }
31196
31657
  if (command === "migrate") return runMigration(input2 === void 0 ? [] : [input2, ...args]);
31658
+ if (command === "import-dsh") return runReverseMigration(input2 === void 0 ? [] : [input2, ...args]);
31197
31659
  const importing = command === "pi2dsh-import";
31198
31660
  const plain = importing && args.at(-1) === "--plain";
31199
31661
  if (plain) args.pop();
31200
31662
  const [output2, ...extra2] = args;
31201
31663
  const valid = importing ? !output2?.startsWith("--") : (command === "pi2dsh" || command === "dsh2pi") && output2;
31202
31664
  if (!input2 || !valid || extra2.length) {
31203
- console.error(help2);
31665
+ console.error(help3);
31204
31666
  process.exitCode = 2;
31205
31667
  return;
31206
31668
  }