dsh-charter 0.2.0 → 0.2.1

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.
@@ -1,4 +1,4 @@
1
- import { A as compactionProjectionDigest, B as clientRefsOf, Bt as sha256Text, C as buildRecordArchive, D as validateArchiveEnvelope, E as recordDigestOf, Ft as compareOrderedItems, H as normalizeEditRequest, Ht as bootstrapFromEvents, K as charterBootstrapApplyRequestSchema, M as verifySourceProjection, N as applyOps, Qt as recordMaintenanceAvailable, Rt as isStandingItem, S as assertRestorableArchive, Vt as assertEditAuthorized, Wt as DEFAULT_CHARTER_LIMITS, X as charterIdentitySchema, Xt as clampCharterLimits, Z as charterInitializeRequestSchema, _ as migrateRecordV1ToV2, a as appendMaintenanceReceipt, b as assertArchiveAdmission, c as assertRecoveryRecordAdmission, ct as charterRestoreRequestSchema, d as createEmptyRecord, g as maintenanceRequestDigestOf, h as legacyValidityFor, i as RevisionConflict, j as messageProjectionDigest, k as agentProjectionDigest, m as isRecordOverBudget, nn as charterError, ot as charterRecordSchema, r as MutationReplay, s as assertRecordConsistency, st as charterRecordV1Schema, t as forkRecord, tn as CharterError, u as commitRecord, v as requestDigestOf, x as assertRecoveryRequestAdmission, y as restoredRecord, z as dependencyProjection, zt as sha256Json } from "./fork-D5HVDV1i.js";
1
+ import { A as compactionProjectionDigest, B as clientRefsOf, Bt as sha256Text, C as buildRecordArchive, D as validateArchiveEnvelope, E as recordDigestOf, Ft as compareOrderedItems, H as normalizeEditRequest, Ht as bootstrapFromEvents, K as charterBootstrapApplyRequestSchema, M as verifySourceProjection, N as applyOps, Qt as recordMaintenanceAvailable, Rt as isStandingItem, S as assertRestorableArchive, Vt as assertEditAuthorized, Wt as DEFAULT_CHARTER_LIMITS, X as charterIdentitySchema, Xt as clampCharterLimits, Z as charterInitializeRequestSchema, _ as migrateRecordV1ToV2, a as appendMaintenanceReceipt, b as assertArchiveAdmission, c as assertRecoveryRecordAdmission, ct as charterRestoreRequestSchema, d as createEmptyRecord, g as maintenanceRequestDigestOf, h as legacyValidityFor, i as RevisionConflict, it as charterRecordArchiveSchema, j as messageProjectionDigest, k as agentProjectionDigest, m as isRecordOverBudget, nn as charterError, ot as charterRecordSchema, r as MutationReplay, s as assertRecordConsistency, st as charterRecordV1Schema, t as forkRecord, tn as CharterError, u as commitRecord, v as requestDigestOf, x as assertRecoveryRequestAdmission, y as restoredRecord, z as dependencyProjection, zt as sha256Json } from "./fork-D5HVDV1i.js";
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import { Service } from "@deepseek-ai/cordis";
4
4
  import Schema from "@deepseek-ai/schemastery";
@@ -477,6 +477,23 @@ const charterDomainSpec = defineDomain({
477
477
  layout: "per-record",
478
478
  tables: { sessions: domainTable(z.unknown()) }
479
479
  });
480
+ const CHARTER_ARCHIVES_DOMAIN_NAME = "dsh_charter_archives_v1";
481
+ const CHARTER_ARCHIVES_TABLE = "archives";
482
+ const charterArchivesDomainSpec = defineDomain({
483
+ name: CHARTER_ARCHIVES_DOMAIN_NAME,
484
+ version: 1,
485
+ layout: "per-record",
486
+ tables: { archives: domainTable(z.object({
487
+ key: z.string().min(1),
488
+ sessionId: z.string().min(1).max(256),
489
+ revision: z.number().int().nonnegative(),
490
+ archivedAt: z.number().int().nonnegative(),
491
+ archive: charterRecordArchiveSchema
492
+ }).strict()) }
493
+ });
494
+ function archiveCacheKey(sessionId, revision) {
495
+ return `${sessionId}--r${revision}`;
496
+ }
480
497
  //#endregion
481
498
  //#region .build-ts/host/tool.js
482
499
  function defineCharterReadTool(charter) {
@@ -742,6 +759,10 @@ var CharterService = class extends Service {
742
759
  static Config = Config;
743
760
  config;
744
761
  sessionsTable;
762
+ archivesTable;
763
+ archivesDomain;
764
+ /** Captures awaiting their durable put; visible to list/read immediately. */
765
+ pendingArchives = /* @__PURE__ */ new Map();
745
766
  globalFailure;
746
767
  admissionOpen = true;
747
768
  unavailable = /* @__PURE__ */ new Map();
@@ -1008,6 +1029,13 @@ var CharterService = class extends Service {
1008
1029
  const domain = await this.ctx.storageDomain.open(charterDomainSpec);
1009
1030
  const rawTable = domain.table(CHARTER_SESSIONS_TABLE);
1010
1031
  this.sessionsTable = rawTable;
1032
+ try {
1033
+ const archives = await this.ctx.storageDomain.open(charterArchivesDomainSpec);
1034
+ this.archivesDomain = archives;
1035
+ this.archivesTable = archives.table(CHARTER_ARCHIVES_TABLE);
1036
+ } catch (error) {
1037
+ this.ctx.logger.warn(`charter: archive cache is unavailable: ${describeError(error)}`);
1038
+ }
1011
1039
  for (const [id, stored] of rawTable.entries()) {
1012
1040
  let parsed = charterRecordSchema.safeParse(stored);
1013
1041
  if (!parsed.success) {
@@ -1047,7 +1075,11 @@ var CharterService = class extends Service {
1047
1075
  }
1048
1076
  this.mutationQueues.clear();
1049
1077
  for (const sessionId of [...this.listeners.keys()]) this.closeListeners(sessionId);
1078
+ const archivesDomain = this.archivesDomain;
1079
+ this.archivesTable = void 0;
1080
+ this.archivesDomain = void 0;
1050
1081
  await domain.close();
1082
+ await archivesDomain?.close();
1051
1083
  this.sessionsTable = void 0;
1052
1084
  }, "charter.domain");
1053
1085
  } catch (error) {
@@ -1139,6 +1171,7 @@ var CharterService = class extends Service {
1139
1171
  this.recordStates.set(session.id, inspection.state);
1140
1172
  if (inspection.state.kind === "healthy") this.unavailable.delete(session.id);
1141
1173
  this.publish(session.id);
1174
+ if (inspection.state.kind === "healthy" && inspection.record !== void 0) this.captureArchive(session, inspection.record);
1142
1175
  if (inspection.state.kind !== "healthy") return;
1143
1176
  }
1144
1177
  if (session.header.parentSession !== void 0) {
@@ -1215,6 +1248,7 @@ var CharterService = class extends Service {
1215
1248
  recordDigest: recordDigestOf(record)
1216
1249
  });
1217
1250
  this.publish(session.id);
1251
+ this.captureArchive(session, record);
1218
1252
  });
1219
1253
  } catch (error) {
1220
1254
  if (putMayHaveLanded && !(error instanceof DomainError && (error.code === "closed" || error.code === "missing-key"))) {
@@ -2315,10 +2349,14 @@ var CharterService = class extends Service {
2315
2349
  if (data.source?.kind !== "user") continue;
2316
2350
  const text = (data.content ?? []).filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join("\n").trim();
2317
2351
  if (text.length === 0) continue;
2352
+ const messageProjectionLimit = 8192;
2353
+ const clipped = text.length > messageProjectionLimit;
2318
2354
  messages.push({
2319
2355
  seq: event.seq,
2320
2356
  role: "user",
2321
2357
  excerpt: text.length > 160 ? `${text.slice(0, 157)}...` : text,
2358
+ text: clipped ? text.slice(0, messageProjectionLimit) : text,
2359
+ ...clipped ? { truncated: true } : {},
2322
2360
  length: text.length
2323
2361
  });
2324
2362
  }
@@ -2350,15 +2388,24 @@ var CharterService = class extends Service {
2350
2388
  const start = options.start ?? 0;
2351
2389
  const end = options.end ?? selected.text.length;
2352
2390
  if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start < 0 || end < start || end > selected.text.length) return unavailableResult("INVALID_ARGUMENT", "message selection is outside the selected message");
2353
- const text = selected.text.slice(start, end).trim();
2391
+ const selectedText = selected.text.slice(start, end).trim();
2392
+ const override = options.text === void 0 ? void 0 : options.text.trim();
2393
+ const text = override ?? selectedText;
2354
2394
  if (text.length === 0) return unavailableResult("INVALID_ARGUMENT", "message selection is empty");
2395
+ const edited = override !== void 0 && override !== selectedText;
2355
2396
  const view = this.view(session);
2356
2397
  if (view.status !== "ready") return unavailableResult("UNAVAILABLE", "Charter is not editable in its current state");
2357
2398
  const selection = start === 0 && end === selected.text.length ? void 0 : {
2358
2399
  start: selected.leading + start,
2359
2400
  end: selected.leading + end
2360
2401
  };
2361
- const source = {
2402
+ const manualActor = actor.kind === "owner" ? "owner" : actor.kind === "user" ? "user" : void 0;
2403
+ if (edited && manualActor === void 0) return unavailableResult("FORBIDDEN", "Only the owner or a user may create an edited proposal");
2404
+ const source = edited ? {
2405
+ kind: "manual",
2406
+ actor: manualActor,
2407
+ at: Date.now()
2408
+ } : {
2362
2409
  kind: "message",
2363
2410
  sessionId: session.id,
2364
2411
  sessionCreatedAt: identityOf(session).createdAt,
@@ -2585,6 +2632,7 @@ var CharterService = class extends Service {
2585
2632
  recordDigest: recordDigestOf(table.get(session.id))
2586
2633
  });
2587
2634
  this.publish(session.id);
2635
+ this.captureArchive(session, next);
2588
2636
  return {
2589
2637
  ok: true,
2590
2638
  replayed: false,
@@ -2682,6 +2730,133 @@ var CharterService = class extends Service {
2682
2730
  };
2683
2731
  }
2684
2732
  /** Export the complete raw record for one Session (owner-only). */
2733
+ /**
2734
+ * Bounded cache policy: at most five snapshots per Session and at most
2735
+ * `CHARTER_ARCHIVE_TOTAL_LIMIT` across all Sessions. Oldest snapshots are
2736
+ * evicted first; this is a derivative cache, never the authoritative record.
2737
+ */
2738
+ async pruneArchiveCache() {
2739
+ const table = this.archivesTable;
2740
+ if (table === void 0) return;
2741
+ const ordered = [...new Map([...[...table.entries()], ...[...this.pendingArchives.entries()]]).entries()].sort((left, right) => right[1].archivedAt - left[1].archivedAt || right[1].revision - left[1].revision);
2742
+ const perSession = /* @__PURE__ */ new Map();
2743
+ let total = 0;
2744
+ for (const [key, entry] of ordered) {
2745
+ const count = perSession.get(entry.sessionId) ?? 0;
2746
+ if (count >= 5 || total >= 25) {
2747
+ if (this.pendingArchives.get(key) === entry) this.pendingArchives.delete(key);
2748
+ else await table.delete(key);
2749
+ continue;
2750
+ }
2751
+ perSession.set(entry.sessionId, count + 1);
2752
+ total += 1;
2753
+ }
2754
+ }
2755
+ /**
2756
+ * Best-effort bounded archive cache. It stores the exact record envelope at
2757
+ * each successful revision so recovery does not depend on a downloaded file.
2758
+ */
2759
+ async captureArchive(session, record) {
2760
+ const table = this.archivesTable;
2761
+ if (table === void 0) return;
2762
+ if (!this.recordMaintenanceCapability().recordMaintenance) return;
2763
+ try {
2764
+ const archive = buildRecordArchive({
2765
+ sessionId: session.id,
2766
+ lifecycle: lifecycleFingerprint(identityOf(session)),
2767
+ health: "healthy",
2768
+ revision: record.current.revision,
2769
+ record,
2770
+ exportedAt: Date.now()
2771
+ });
2772
+ assertArchiveAdmission(archive, this.config);
2773
+ const key = archiveCacheKey(session.id, record.current.revision);
2774
+ const entry = {
2775
+ key,
2776
+ sessionId: session.id,
2777
+ revision: record.current.revision,
2778
+ archivedAt: archive.exportedAt,
2779
+ archive
2780
+ };
2781
+ this.pendingArchives.set(key, entry);
2782
+ try {
2783
+ await this.pruneArchiveCache();
2784
+ if (this.pendingArchives.get(key) !== entry) return;
2785
+ await table.put(key, entry);
2786
+ await this.pruneArchiveCache();
2787
+ } finally {
2788
+ this.pendingArchives.delete(key);
2789
+ }
2790
+ } catch (error) {
2791
+ this.ctx.logger.warn(`charter: could not cache archive for ${session.id}: ${describeError(error)}`);
2792
+ }
2793
+ }
2794
+ listArchives(sessionId, actor) {
2795
+ const gate = this.maintenanceGate(actor);
2796
+ if (!gate.ok) return {
2797
+ ok: false,
2798
+ code: gate.code,
2799
+ message: gate.message
2800
+ };
2801
+ if (this.ctx.sessions.get(sessionId) === void 0) return {
2802
+ ok: false,
2803
+ code: "NOT_FOUND",
2804
+ message: "The Session is not live"
2805
+ };
2806
+ const table = this.archivesTable;
2807
+ if (table === void 0) return {
2808
+ ok: false,
2809
+ code: "UNAVAILABLE",
2810
+ message: "The archive cache is unavailable"
2811
+ };
2812
+ const prefix = `${sessionId}--r`;
2813
+ return {
2814
+ ok: true,
2815
+ archives: [...new Map([...[...table.entries()].filter(([key]) => key.startsWith(prefix)), ...[...this.pendingArchives.entries()].filter(([key]) => key.startsWith(prefix))]).values()].map((entry) => ({
2816
+ key: entry.key,
2817
+ revision: entry.revision,
2818
+ archivedAt: entry.archivedAt,
2819
+ payloadDigest: entry.archive.payloadDigest,
2820
+ recordDigest: entry.archive.source.recordDigest,
2821
+ lifecycle: entry.archive.source.lifecycle
2822
+ })).sort((left, right) => right.archivedAt - left.archivedAt || right.revision - left.revision).slice(0, 5),
2823
+ limit: 5
2824
+ };
2825
+ }
2826
+ readArchive(sessionId, key, actor) {
2827
+ const gate = this.maintenanceGate(actor);
2828
+ if (!gate.ok) return {
2829
+ ok: false,
2830
+ code: gate.code,
2831
+ message: gate.message
2832
+ };
2833
+ if (this.ctx.sessions.get(sessionId) === void 0) return {
2834
+ ok: false,
2835
+ code: "NOT_FOUND",
2836
+ message: "The Session is not live"
2837
+ };
2838
+ const table = this.archivesTable;
2839
+ if (table === void 0) return {
2840
+ ok: false,
2841
+ code: "UNAVAILABLE",
2842
+ message: "The archive cache is unavailable"
2843
+ };
2844
+ if (!key.startsWith(`${sessionId}--r`)) return {
2845
+ ok: false,
2846
+ code: "NOT_FOUND",
2847
+ message: "The archive does not belong to this Session"
2848
+ };
2849
+ const entry = table.get(key) ?? this.pendingArchives.get(key);
2850
+ if (entry === void 0) return {
2851
+ ok: false,
2852
+ code: "NOT_FOUND",
2853
+ message: "The archive is no longer cached"
2854
+ };
2855
+ return {
2856
+ ok: true,
2857
+ archive: entry.archive
2858
+ };
2859
+ }
2685
2860
  exportRecord(sessionId, actor = { kind: "owner" }) {
2686
2861
  const gate = this.maintenanceGate(actor);
2687
2862
  if (!gate.ok) return {
@@ -2733,6 +2908,7 @@ var CharterService = class extends Service {
2733
2908
  };
2734
2909
  throw error;
2735
2910
  }
2911
+ if (inspection.state.kind === "healthy" && inspection.record !== void 0) this.captureArchive(session, inspection.record);
2736
2912
  return {
2737
2913
  ok: true,
2738
2914
  filename: `dsh-charter-${String(sessionId).replace(/[^A-Za-z0-9._-]+/gu, "-")}-r${inspection.record?.current.revision ?? 0}-${Date.now()}.json`,
@@ -2844,6 +3020,7 @@ var CharterService = class extends Service {
2844
3020
  recordDigest: recordDigestOf(next)
2845
3021
  });
2846
3022
  this.publish(session.id);
3023
+ await this.captureArchive(session, next);
2847
3024
  return this.maintenanceResult(session, false);
2848
3025
  } catch (error) {
2849
3026
  if (error instanceof CharterError) return {
@@ -3052,6 +3229,7 @@ var CharterService = class extends Service {
3052
3229
  recordDigest: recordDigestOf(next)
3053
3230
  });
3054
3231
  this.publish(session.id);
3232
+ await this.captureArchive(session, next);
3055
3233
  return this.maintenanceResult(session, false);
3056
3234
  } catch (error) {
3057
3235
  if (error instanceof CharterError) return {
package/lib/version.d.ts CHANGED
@@ -3,4 +3,4 @@
3
3
  * bundle carries the value; `tests/version.spec.ts` fails if it drifts from
4
4
  * `package.json`.
5
5
  */
6
- export declare const CHARTER_VERSION = "0.2.0";
6
+ export declare const CHARTER_VERSION = "0.2.1";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-charter",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "A durable, user-owned session charter for DeepSeek Harness, designed to survive context compaction.",
5
5
  "license": "MIT",
6
6
  "type": "module",