my-durable 0.0.38 → 0.0.39

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.
@@ -13,6 +13,8 @@ import type {
13
13
  ModelInfo,
14
14
  Page,
15
15
  SendResult,
16
+ DeviceUsageReport,
17
+ ProjectPatchBody,
16
18
  SessionSearchMatch,
17
19
  SessionSearchResult,
18
20
  SessionSummary,
@@ -30,12 +32,20 @@ import {
30
32
  THINKING_LEVELS,
31
33
  type CompactionSettings,
32
34
  } from "../../dpi-sdk/src/api.js";
33
- import { lastAssistantText, messageText, toMarkdown, toTranscript } from "../../dpi-sdk/src/transcript.js";
35
+ import {
36
+ lastAssistantText,
37
+ messageText,
38
+ sumUsage,
39
+ toMarkdown,
40
+ toTranscript,
41
+ type UsageSummary,
42
+ } from "../../dpi-sdk/src/transcript.js";
34
43
  import { ApiFault, invalid, notFound } from "./errors.js";
35
- import { git, gitDirtyMarks, onGitDirty } from "./git.js";
44
+ import { git, gitDirtyMarks, gitStatus, onGitDirty } from "./git.js";
36
45
  import { DatabaseSync } from "node:sqlite";
37
46
  import { mkdir, readdir, realpath, rename as renamePath, stat } from "node:fs/promises";
38
47
  import { deviceVitals, type DeviceVitals } from "./vitals.js";
48
+ import { ProjectRegistry, type ProjectRecord } from "./projects.js";
39
49
  import { zipSync, type ZipEntry } from "./zip.js";
40
50
  import { mkdirSync, writeFileSync, readFileSync, unlinkSync } from "node:fs";
41
51
  import { ensurePrivateDir } from "../../dpi-sdk/src/node/private-dir.js";
@@ -117,6 +127,20 @@ const CODE_DIR = resolve(import.meta.dirname, "../../..");
117
127
  /** Session search result cap: one screen of matches, not a transcript dump. */
118
128
  const SEARCH_LIMIT = 50;
119
129
 
130
+ /** Starting point for a per-model usage accumulator. */
131
+ const ZERO_USAGE: UsageSummary = {
132
+ tokens: 0,
133
+ cost: 0,
134
+ input: 0,
135
+ output: 0,
136
+ cacheRead: 0,
137
+ cacheWrite: 0,
138
+ inputCost: 0,
139
+ outputCost: 0,
140
+ cacheReadCost: 0,
141
+ cacheWriteCost: 0,
142
+ };
143
+
120
144
  /** A bundle for a session whose store is closed (archived or restarting) still exports its record. */
121
145
  const NOT_OPENED_README = [
122
146
  "This bundle was exported while the session's store was closed.",
@@ -200,6 +224,9 @@ export class Store {
200
224
  readonly catalog: DatabaseSync;
201
225
  readonly startedAt = Date.now();
202
226
  shared!: SharedState;
227
+ /** Projects (Wave 2): a registry of roots with labels, grouped by the cwd a
228
+ * session starts in. Opened with the store so routes never see a half state. */
229
+ projects!: ProjectRegistry;
203
230
  uid!: string;
204
231
  modelList: ModelInfo[] = [];
205
232
  private unlockCatalog: () => void;
@@ -222,6 +249,9 @@ export class Store {
222
249
  get archiveDir() {
223
250
  return join(this.options.dataDir, "archive");
224
251
  }
252
+ get projectsPath() {
253
+ return join(this.options.dataDir, "projects.json");
254
+ }
225
255
  get name() {
226
256
  return this.options.name;
227
257
  }
@@ -270,6 +300,17 @@ export class Store {
270
300
  // Start dirs are where new sessions begin; create any that do not exist yet.
271
301
  await Promise.all(options.startDirs.map((dir) => mkdir(dir, { recursive: true }).catch(() => {})));
272
302
  try {
303
+ store.projects = await ProjectRegistry.open(store.projectsPath, {
304
+ warn: (m) => process.emitWarning(`projects: ${m}`),
305
+ });
306
+ // Seed the registry from history: a device that predates projects still
307
+ // shows every root its sessions already live in (idempotent by rootPath).
308
+ for (const row of store.list()) {
309
+ const status = await gitStatus(row.cwd).catch(() => undefined);
310
+ await store.projects
311
+ .ensure({ rootPath: status?.repo ? (status.root ?? row.cwd) : row.cwd, kind: status?.repo ? "git" : "plain" })
312
+ .catch(() => undefined);
313
+ }
273
314
  store.unlockShared = lockFile(`${store.sharedStatePath}.lock`);
274
315
  store.shared = await SharedState.open(store.sharedStatePath);
275
316
  store.shared.harness.subscribeCommits(() => store.notify());
@@ -583,6 +624,12 @@ export class Store {
583
624
  } catch {
584
625
  throw invalid(`cwd must be an existing folder on ${this.name}`);
585
626
  }
627
+ // Every session roots a project: the registry is the tree's group-by-cwd,
628
+ // promoted to an entity you can name, label and archive (paseo model).
629
+ const status = await gitStatus(cwd).catch(() => undefined);
630
+ await this.projects
631
+ .ensure({ rootPath: status?.repo ? (status.root ?? cwd) : cwd, kind: status?.repo ? "git" : "plain" })
632
+ .catch(() => undefined);
586
633
  const model = this.validateModel(body.model);
587
634
  if (body.thinkingLevel !== undefined && !THINKING_LEVELS.includes(body.thinkingLevel))
588
635
  throw invalid("Invalid thinking level");
@@ -1551,6 +1598,110 @@ export class Store {
1551
1598
  };
1552
1599
  }
1553
1600
 
1601
+ // ------------------------------------------------- projects (Wave 2)
1602
+
1603
+ /** Projects, newest activity first: the tree's group-by-cwd as an entity. */
1604
+ projectList(includeArchived = false): ProjectRecord[] {
1605
+ return this.projects.list({ includeArchived });
1606
+ }
1607
+
1608
+ /**
1609
+ * Rename/label a project. `customName` wins over the derived basename, and
1610
+ * labels are what humans filter by — paseo's rule that reconciliation never
1611
+ * touches either.
1612
+ */
1613
+ async updateProject(id: string, patch: ProjectPatchBody): Promise<ProjectRecord> {
1614
+ // Only the keys the caller actually sent: passing `customName: undefined`
1615
+ // must not read as "clear the name" (that is `customName: ""`).
1616
+ const next: { customName?: string; labels?: string[] } = {};
1617
+ if (patch.customName !== undefined) next.customName = patch.customName;
1618
+ if (patch.labels !== undefined) next.labels = patch.labels;
1619
+ return this.projects.update(id, next);
1620
+ }
1621
+
1622
+ async archiveProject(id: string): Promise<ProjectRecord> {
1623
+ this.notify();
1624
+ return this.projects.archive(id);
1625
+ }
1626
+
1627
+ async unarchiveProject(id: string): Promise<ProjectRecord> {
1628
+ this.notify();
1629
+ return this.projects.unarchive(id);
1630
+ }
1631
+
1632
+ /**
1633
+ * Usage rollup (orca `usage/`, our data): every live session's harness usage,
1634
+ * summed per session, per model and per project. Archived sessions are closed
1635
+ * stores, so they are not counted — this is "what this device is spending on
1636
+ * the work it still holds", not a lifetime invoice.
1637
+ */
1638
+ async usageReport(): Promise<DeviceUsageReport> {
1639
+ const models = new Map<string, UsageSummary>();
1640
+ const projects = new Map<string, DeviceUsageReport["projects"][number]>();
1641
+ const sessions: DeviceUsageReport["sessions"] = [];
1642
+ let tokens = 0;
1643
+ let cost = 0;
1644
+
1645
+ for (const row of this.list()) {
1646
+ const opened = this.opened.get(row.id);
1647
+ if (!opened) continue;
1648
+ const raw = await this.usage(opened.harness);
1649
+ const usage = sumUsage(raw);
1650
+ for (const [key, u] of Object.entries(raw.models ?? {})) {
1651
+ const prev = models.get(key) ?? ZERO_USAGE;
1652
+ models.set(key, {
1653
+ tokens: prev.tokens + (u.totalTokens ?? 0),
1654
+ cost: prev.cost + (u.cost?.total ?? 0),
1655
+ input: prev.input + (u.input ?? 0),
1656
+ output: prev.output + (u.output ?? 0),
1657
+ cacheRead: prev.cacheRead + (u.cacheRead ?? 0),
1658
+ cacheWrite: prev.cacheWrite + (u.cacheWrite ?? 0),
1659
+ inputCost: prev.inputCost + (u.cost?.input ?? 0),
1660
+ outputCost: prev.outputCost + (u.cost?.output ?? 0),
1661
+ cacheReadCost: prev.cacheReadCost + (u.cost?.cacheRead ?? 0),
1662
+ cacheWriteCost: prev.cacheWriteCost + (u.cost?.cacheWrite ?? 0),
1663
+ });
1664
+ }
1665
+ const project = this.projects.findByPath(row.cwd) ?? this.projects.findByPath(dirname(row.cwd));
1666
+ sessions.push({
1667
+ id: row.id,
1668
+ name: row.name,
1669
+ cwd: row.cwd,
1670
+ project: project ? (project.customName ?? project.name) : undefined,
1671
+ tokens: usage.tokens,
1672
+ cost: usage.cost,
1673
+ agents: (await this.agents(row)).length,
1674
+ });
1675
+ tokens += usage.tokens;
1676
+ cost += usage.cost;
1677
+ if (project) {
1678
+ const prev = projects.get(project.id) ?? {
1679
+ rootPath: project.rootPath,
1680
+ name: project.customName ?? project.name,
1681
+ tokens: 0,
1682
+ cost: 0,
1683
+ sessions: 0,
1684
+ };
1685
+ projects.set(project.id, {
1686
+ ...prev,
1687
+ tokens: prev.tokens + usage.tokens,
1688
+ cost: prev.cost + usage.cost,
1689
+ sessions: prev.sessions + 1,
1690
+ });
1691
+ }
1692
+ }
1693
+
1694
+ return {
1695
+ at: Date.now(),
1696
+ totals: { tokens, cost },
1697
+ models: [...models.entries()]
1698
+ .map(([key, value]) => ({ key, ...value }))
1699
+ .sort((a, b) => b.cost - a.cost || b.tokens - a.tokens),
1700
+ sessions: sessions.sort((a, b) => b.cost - a.cost || b.tokens - a.tokens),
1701
+ projects: [...projects.values()].sort((a, b) => b.cost - a.cost || b.tokens - a.tokens),
1702
+ };
1703
+ }
1704
+
1554
1705
  // ------------------------------------------------------------ demo extension
1555
1706
 
1556
1707
  async demoState(c: Conversation, body: Record<string, unknown>) {