@llblab/pi-kit 0.15.0 → 0.16.0

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.
Files changed (106) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +2 -2
  3. package/node_modules/@llblab/pi-state-flow/AGENTS.md +9 -9
  4. package/node_modules/@llblab/pi-state-flow/BACKLOG.md +0 -13
  5. package/node_modules/@llblab/pi-state-flow/CHANGELOG.md +15 -0
  6. package/node_modules/@llblab/pi-state-flow/README.md +7 -6
  7. package/node_modules/@llblab/pi-state-flow/dist/lib/config.d.ts +5 -2
  8. package/node_modules/@llblab/pi-state-flow/dist/lib/config.js +17 -16
  9. package/node_modules/@llblab/pi-state-flow/dist/lib/context.d.ts +8 -0
  10. package/node_modules/@llblab/pi-state-flow/dist/lib/context.js +24 -0
  11. package/node_modules/@llblab/pi-state-flow/dist/lib/continuation.js +4 -3
  12. package/node_modules/@llblab/pi-state-flow/dist/lib/durable.d.ts +1 -0
  13. package/node_modules/@llblab/pi-state-flow/dist/lib/durable.js +8 -3
  14. package/node_modules/@llblab/pi-state-flow/dist/lib/episode.d.ts +2 -0
  15. package/node_modules/@llblab/pi-state-flow/dist/lib/episode.js +4 -0
  16. package/node_modules/@llblab/pi-state-flow/dist/lib/extension.d.ts +5 -0
  17. package/node_modules/@llblab/pi-state-flow/dist/lib/extension.js +93 -35
  18. package/node_modules/@llblab/pi-state-flow/dist/lib/git.js +20 -23
  19. package/node_modules/@llblab/pi-state-flow/dist/lib/history.js +8 -4
  20. package/node_modules/@llblab/pi-state-flow/dist/lib/json.js +29 -3
  21. package/node_modules/@llblab/pi-state-flow/dist/lib/migration.js +34 -18
  22. package/node_modules/@llblab/pi-state-flow/dist/lib/protocol.js +14 -16
  23. package/node_modules/@llblab/pi-state-flow/dist/lib/query.d.ts +27 -1
  24. package/node_modules/@llblab/pi-state-flow/dist/lib/query.js +182 -10
  25. package/node_modules/@llblab/pi-state-flow/dist/lib/runtime.d.ts +2 -0
  26. package/node_modules/@llblab/pi-state-flow/dist/lib/runtime.js +34 -5
  27. package/node_modules/@llblab/pi-state-flow/dist/lib/snapshot.d.ts +5 -5
  28. package/node_modules/@llblab/pi-state-flow/dist/lib/snapshot.js +20 -24
  29. package/node_modules/@llblab/pi-state-flow/dist/lib/state.d.ts +6 -3
  30. package/node_modules/@llblab/pi-state-flow/dist/lib/state.js +5 -3
  31. package/node_modules/@llblab/pi-state-flow/dist/lib/status.js +1 -1
  32. package/node_modules/@llblab/pi-state-flow/dist/lib/storage.d.ts +2 -0
  33. package/node_modules/@llblab/pi-state-flow/dist/lib/storage.js +55 -20
  34. package/node_modules/@llblab/pi-state-flow/dist/lib/telegram.d.ts +8 -6
  35. package/node_modules/@llblab/pi-state-flow/dist/lib/telegram.js +10 -3
  36. package/node_modules/@llblab/pi-state-flow/dist/lib/transition.js +7 -3
  37. package/node_modules/@llblab/pi-state-flow/dist/package.json +1 -1
  38. package/node_modules/@llblab/pi-state-flow/dist/skills/state-flow-memory/SKILL.md +11 -3
  39. package/node_modules/@llblab/pi-state-flow/docs/README.md +1 -0
  40. package/node_modules/@llblab/pi-state-flow/docs/architecture.md +5 -3
  41. package/node_modules/@llblab/pi-state-flow/docs/filesystem-recovery.md +3 -2
  42. package/node_modules/@llblab/pi-state-flow/docs/lazy-state.md +504 -0
  43. package/node_modules/@llblab/pi-state-flow/docs/usage.md +11 -8
  44. package/node_modules/@llblab/pi-state-flow/lib/config.ts +18 -15
  45. package/node_modules/@llblab/pi-state-flow/lib/context.ts +24 -0
  46. package/node_modules/@llblab/pi-state-flow/lib/continuation.ts +4 -3
  47. package/node_modules/@llblab/pi-state-flow/lib/durable.ts +8 -4
  48. package/node_modules/@llblab/pi-state-flow/lib/episode.ts +5 -0
  49. package/node_modules/@llblab/pi-state-flow/lib/extension.ts +86 -34
  50. package/node_modules/@llblab/pi-state-flow/lib/git.ts +23 -22
  51. package/node_modules/@llblab/pi-state-flow/lib/history.ts +8 -4
  52. package/node_modules/@llblab/pi-state-flow/lib/json.ts +31 -3
  53. package/node_modules/@llblab/pi-state-flow/lib/migration.ts +33 -16
  54. package/node_modules/@llblab/pi-state-flow/lib/protocol.ts +14 -16
  55. package/node_modules/@llblab/pi-state-flow/lib/query.ts +173 -9
  56. package/node_modules/@llblab/pi-state-flow/lib/runtime.ts +32 -4
  57. package/node_modules/@llblab/pi-state-flow/lib/snapshot.ts +22 -25
  58. package/node_modules/@llblab/pi-state-flow/lib/state.ts +11 -6
  59. package/node_modules/@llblab/pi-state-flow/lib/status.ts +1 -1
  60. package/node_modules/@llblab/pi-state-flow/lib/storage.ts +46 -18
  61. package/node_modules/@llblab/pi-state-flow/lib/telegram.ts +19 -6
  62. package/node_modules/@llblab/pi-state-flow/lib/transition.ts +7 -3
  63. package/node_modules/@llblab/pi-state-flow/package.json +1 -1
  64. package/node_modules/@llblab/pi-state-flow/skills/state-flow-memory/SKILL.md +11 -3
  65. package/node_modules/@llblab/pi-telegram/AGENTS.md +1 -1
  66. package/node_modules/@llblab/pi-telegram/BACKLOG.md +1 -0
  67. package/node_modules/@llblab/pi-telegram/CHANGELOG.md +7 -0
  68. package/node_modules/@llblab/pi-telegram/README.md +1 -0
  69. package/node_modules/@llblab/pi-telegram/dist/lib/bindings.d.ts +2 -1
  70. package/node_modules/@llblab/pi-telegram/dist/lib/bindings.js +2 -1
  71. package/node_modules/@llblab/pi-telegram/dist/lib/commands.d.ts +134 -2
  72. package/node_modules/@llblab/pi-telegram/dist/lib/commands.js +297 -16
  73. package/node_modules/@llblab/pi-telegram/dist/lib/delivery.d.ts +2 -0
  74. package/node_modules/@llblab/pi-telegram/dist/lib/delivery.js +11 -0
  75. package/node_modules/@llblab/pi-telegram/dist/lib/extension.js +68 -8
  76. package/node_modules/@llblab/pi-telegram/dist/lib/menu-settings.d.ts +4 -3
  77. package/node_modules/@llblab/pi-telegram/dist/lib/menu-settings.js +17 -13
  78. package/node_modules/@llblab/pi-telegram/dist/lib/pi.d.ts +2 -1
  79. package/node_modules/@llblab/pi-telegram/dist/lib/pi.js +1 -0
  80. package/node_modules/@llblab/pi-telegram/dist/lib/routing.d.ts +1 -0
  81. package/node_modules/@llblab/pi-telegram/dist/lib/routing.js +55 -5
  82. package/node_modules/@llblab/pi-telegram/dist/lib/thread-display.d.ts +23 -0
  83. package/node_modules/@llblab/pi-telegram/dist/lib/thread-display.js +20 -0
  84. package/node_modules/@llblab/pi-telegram/dist/lib/threads.d.ts +18 -0
  85. package/node_modules/@llblab/pi-telegram/dist/lib/threads.js +152 -6
  86. package/node_modules/@llblab/pi-telegram/dist/lib/updates.d.ts +1 -0
  87. package/node_modules/@llblab/pi-telegram/dist/lib/updates.js +5 -3
  88. package/node_modules/@llblab/pi-telegram/dist/package.json +1 -1
  89. package/node_modules/@llblab/pi-telegram/docs/architecture.md +3 -3
  90. package/node_modules/@llblab/pi-telegram/docs/callback-namespaces.md +1 -1
  91. package/node_modules/@llblab/pi-telegram/docs/public-api.md +4 -3
  92. package/node_modules/@llblab/pi-telegram/docs/sections.md +2 -2
  93. package/node_modules/@llblab/pi-telegram/docs/ui-style.md +2 -1
  94. package/node_modules/@llblab/pi-telegram/docs/updates.md +1 -1
  95. package/node_modules/@llblab/pi-telegram/lib/bindings.ts +3 -0
  96. package/node_modules/@llblab/pi-telegram/lib/commands.ts +466 -21
  97. package/node_modules/@llblab/pi-telegram/lib/delivery.ts +15 -0
  98. package/node_modules/@llblab/pi-telegram/lib/extension.ts +77 -9
  99. package/node_modules/@llblab/pi-telegram/lib/menu-settings.ts +25 -10
  100. package/node_modules/@llblab/pi-telegram/lib/pi.ts +3 -0
  101. package/node_modules/@llblab/pi-telegram/lib/routing.ts +84 -17
  102. package/node_modules/@llblab/pi-telegram/lib/thread-display.ts +30 -0
  103. package/node_modules/@llblab/pi-telegram/lib/threads.ts +199 -6
  104. package/node_modules/@llblab/pi-telegram/lib/updates.ts +5 -2
  105. package/node_modules/@llblab/pi-telegram/package.json +1 -1
  106. package/package.json +3 -3
@@ -2,7 +2,7 @@
2
2
  // Excludes: temporal algebra, Pi lifecycle, Git objects/remotes, and backend fallback policy.
3
3
  import { spawnSync } from "node:child_process";
4
4
  import { createHash } from "node:crypto";
5
- import { closeSync, lstatSync, mkdirSync, openSync, rmSync, writeFileSync } from "node:fs";
5
+ import { closeSync, lstatSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
6
  import { dirname, relative, resolve } from "node:path";
7
7
  import {
8
8
  assertOwnedFileUpdates, captureTemporalFileBases, parseScopeProvenance, parseScopeStream, restoreDurableFileBases,
@@ -44,17 +44,42 @@ export function initializeFileStore(root: string): void {
44
44
  mkdirSync(resolve(root), { recursive: true });
45
45
  }
46
46
 
47
+ const PUBLICATION_LOCK_WAIT_MS = 2_000;
48
+ const PUBLICATION_LOCK_POLL_MS = 25;
49
+ const publicationLockWait = new Int32Array(new SharedArrayBuffer(4));
50
+
51
+ function liveForeignLockOwner(path: string): boolean {
52
+ let owner: string;
53
+ try { owner = readFileSync(path, "utf8").trim(); }
54
+ catch { return true; }
55
+ if (owner.length === 0) return true;
56
+ if (!/^[1-9]\d*$/.test(owner)) return false;
57
+ const pid = Number(owner);
58
+ if (!Number.isSafeInteger(pid) || pid === process.pid) return false;
59
+ try { process.kill(pid, 0); return true; }
60
+ catch (error) { return (error as NodeJS.ErrnoException).code === "EPERM"; }
61
+ }
62
+
63
+ /** Wait only for a cooperating live owner; interrupted or malformed locks remain explicit recovery errors. */
64
+ export function acquirePublicationLock(path: string, unavailable: (cause: unknown) => Error): number {
65
+ const deadline = Date.now() + PUBLICATION_LOCK_WAIT_MS;
66
+ while (true) {
67
+ try { return openSync(path, "wx", 0o600); }
68
+ catch (error) {
69
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST" || !liveForeignLockOwner(path) || Date.now() >= deadline) throw unavailable(error);
70
+ Atomics.wait(publicationLockWait, 0, 0, Math.min(PUBLICATION_LOCK_POLL_MS, deadline - Date.now()));
71
+ }
72
+ }
73
+ }
74
+
47
75
  /** Git writers also acquire this lock before their common-Git-directory lock. */
48
76
  export function withStoragePublicationLock<T>(repositoryRoot: string, action: (root: string) => T): T {
49
77
  const root = resolve(repositoryRoot);
50
78
  assertStorageDirectory(root);
51
79
  const path = resolve(root, ".state-flow-publication.lock");
52
- let descriptor: number;
53
- try {
54
- descriptor = openSync(path, "wx", 0o600);
55
- } catch (error) {
56
- throw new RevisionUnavailableError(`State Flow publication lock is unavailable at ${path}; reconcile the active or interrupted publisher before retrying`, { cause: error });
57
- }
80
+ const descriptor = acquirePublicationLock(path, (cause) => new RevisionUnavailableError(
81
+ `State Flow publication lock is unavailable at ${path}; reconcile the active or interrupted publisher before retrying`, { cause },
82
+ ));
58
83
  try {
59
84
  writeFileSync(descriptor, `${process.pid}\n`);
60
85
  return action(root);
@@ -91,9 +116,9 @@ export function planTemporalPublication(
91
116
  changedScopes.push(scope);
92
117
  }
93
118
  const provenanceUpdates: OwnedFileUpdate[] = [];
94
- // Shared metadata owns provenance, temporal boundaries, and CWD identity beside semantic files.
119
+ // Every scope metadata file owns provenance and temporal boundaries beside semantic files.
95
120
  if (!runtimeOnly) {
96
- for (const scope of ["global", "cwd"] as const) {
121
+ for (const scope of SCOPES) {
97
122
  const paths = temporalScopePaths(cwd, sessionId, scope, root, sessionKey);
98
123
  const registry = provenance?.[scope] ?? parseScopeProvenance(files.get(paths.meta)!.content, paths.meta);
99
124
  const currentFile = files.get(paths.meta)!;
@@ -104,18 +129,21 @@ export function planTemporalPublication(
104
129
  }
105
130
  }
106
131
  const runtimePaths = sessionRuntimePaths(cwd, sessionId, root, sessionKey);
107
- const previousRuntime = parseSessionRuntime(files.get(runtimePaths.config)!.content, files.get(runtimePaths.meta)!.content, cwd, sessionId);
132
+ const previousRuntime = parseSessionRuntime(files.get(runtimePaths.config)!.content, files.get(runtimePaths.runtime)!.content, cwd, sessionId, files.get(runtimePaths.meta)!.content);
108
133
  if (previousRuntime !== undefined && changedScopes.length > 0 && runtime === undefined) throw new Error("Temporal semantic publication requires its session runtime cohort");
109
134
  const runtimeUpdates: OwnedFileUpdate[] = [];
110
135
  if (runtime !== undefined) {
111
- const sources = serializeSessionRuntime(runtime, cwd, sessionId, runtimeOnly ? undefined : view.scopes.session, files.get(runtimePaths.meta)!.content);
136
+ const sources = serializeSessionRuntime(runtime, cwd, sessionId);
112
137
  if (!sameJson(runtime.meta.lineage, view.lineage)) throw new Error("Runtime lineage does not match the temporal cohort");
113
- if (files.get(runtimePaths.config)!.content !== sources.config || files.get(runtimePaths.meta)!.content !== sources.meta) {
114
- runtimeUpdates.push({ path: runtimePaths.config, content: sources.config }, { path: runtimePaths.meta, content: sources.meta });
138
+ if (files.get(runtimePaths.config)!.content !== sources.config || files.get(runtimePaths.runtime)!.content !== sources.runtime) {
139
+ runtimeUpdates.push({ path: runtimePaths.config, content: sources.config }, { path: runtimePaths.runtime, content: sources.runtime });
140
+ }
141
+ if (files.get(runtimePaths.runtime)!.identity === "missing" && files.get(runtimePaths.meta)!.content !== undefined
142
+ && previousRuntime !== undefined && !provenanceUpdates.some(({ path }) => path === runtimePaths.meta)) {
143
+ const registry = provenance?.session ?? parseArtifactProvenanceRegistry(previousRuntime.meta.artifacts, "State Flow session artifact provenance");
144
+ const content = serializeScopeMetadata(registry, view.scopes.session, "session", undefined, files.get(runtimePaths.meta)!.content);
145
+ runtimeUpdates.push({ path: runtimePaths.meta, content });
115
146
  }
116
- } else if (!runtimeOnly && changedScopes.includes("session")) {
117
- const content = serializeScopeMetadata(undefined, view.scopes.session, "session", undefined, files.get(runtimePaths.meta)!.content);
118
- if (files.get(runtimePaths.meta)!.content !== content) runtimeUpdates.push({ path: runtimePaths.meta, content });
119
147
  }
120
148
  const changedPaths = new Set(changedScopes.flatMap((scope) => {
121
149
  const paths = temporalScopePaths(cwd, sessionId, scope, root, sessionKey);
@@ -153,14 +181,14 @@ function decodeFileCohort(cwd: string, sessionId: string, root: string, base: Te
153
181
  scopes[scope] = stream;
154
182
  }
155
183
  const paths = sessionRuntimePaths(cwd, sessionId, root, sessionKey);
156
- const runtime = parseSessionRuntime(files.get(paths.config), files.get(paths.meta), cwd, sessionId);
184
+ const runtime = parseSessionRuntime(files.get(paths.config), files.get(paths.runtime), cwd, sessionId, files.get(paths.meta));
157
185
  if (!runtime || runtime.meta.publication !== "files") throw new Error("File-only recovery requires file publication provenance, not a Git self reference");
158
186
  const view = { scopes, lineage: runtime.meta.lineage };
159
187
  validateTemporalState(view);
160
188
  const provenance: Record<StateScope, ArtifactProvenanceRegistry> = {
161
189
  global: parseScopeProvenance(files.get(temporalScopePaths(cwd, sessionId, "global", root, sessionKey).meta), temporalScopePaths(cwd, sessionId, "global", root, sessionKey).meta),
162
190
  cwd: parseScopeProvenance(files.get(temporalScopePaths(cwd, sessionId, "cwd", root, sessionKey).meta), temporalScopePaths(cwd, sessionId, "cwd", root, sessionKey).meta),
163
- session: parseArtifactProvenanceRegistry(runtime.meta.artifacts, "State Flow session artifact provenance"),
191
+ session: parseScopeProvenance(files.get(paths.meta), paths.meta),
164
192
  };
165
193
  return { runtime, view, provenance };
166
194
  }
@@ -27,12 +27,18 @@ export interface StateFlowTelegramState {
27
27
  contract: Record<string, unknown>;
28
28
  working: Record<string, unknown>;
29
29
  response: string;
30
+ lazy?: unknown;
30
31
  }
31
32
 
33
+ export type StateFlowTelegramRichText =
34
+ | string
35
+ | StateFlowTelegramRichText[]
36
+ | { type: "bold" | "code"; text: StateFlowTelegramRichText };
37
+
32
38
  export type StateFlowTelegramRichBlock =
33
- | { type: "heading"; text: string; size: 3 }
34
- | { type: "pre"; text: string; language?: string }
35
- | { type: "details"; summary: string | { type: "bold" | "code"; text: string }; blocks: StateFlowTelegramRichBlock[]; is_open?: true };
39
+ | { type: "heading"; text: StateFlowTelegramRichText; size: 3 }
40
+ | { type: "pre"; text: StateFlowTelegramRichText; language?: string }
41
+ | { type: "details"; summary: StateFlowTelegramRichText; blocks: StateFlowTelegramRichBlock[]; is_open?: true };
36
42
 
37
43
  export interface StateFlowTelegramRichMessage {
38
44
  blocks: StateFlowTelegramRichBlock[];
@@ -168,6 +174,9 @@ function renderStateFlowTelegramField(value: unknown): string {
168
174
  const length = Math.floor((low + high) / 2);
169
175
  const candidate = JSON.stringify({
170
176
  truncated: true,
177
+ ...(value !== null && typeof value === "object" && !Array.isArray(value)
178
+ ? { keys: Object.keys(value) }
179
+ : {}),
171
180
  preview: json.slice(0, length),
172
181
  omittedChars: json.length - length,
173
182
  }, null, 2);
@@ -182,14 +191,18 @@ function renderStateFlowTelegramField(value: unknown): string {
182
191
  }
183
192
 
184
193
  export function renderStateFlowRichState(scope: StateFlowTelegramScope, step: number, state: StateFlowTelegramState): StateFlowTelegramRichMessage {
185
- const fields = ["artifacts", "contract", "working", "response"] as const;
194
+ const fields = ["artifacts", "contract", "working", "response", "lazy"] as const;
186
195
  return {
187
196
  blocks: [
188
- { type: "heading", text: `${STATE_FLOW_SCOPE_LABELS[scope]}: \`#${step}\``, size: 3 },
197
+ {
198
+ type: "heading",
199
+ text: [`${STATE_FLOW_SCOPE_LABELS[scope]}: `, { type: "code", text: `#${step}` }],
200
+ size: 3,
201
+ },
189
202
  ...fields.map((field) => ({
190
203
  type: "details" as const,
191
204
  summary: { type: "code" as const, text: field },
192
- blocks: [{ type: "pre" as const, language: "json", text: renderStateFlowTelegramField(state[field]) }],
205
+ blocks: [{ type: "pre" as const, language: "json", text: renderStateFlowTelegramField(state[field] ?? {}) }],
193
206
  })),
194
207
  ],
195
208
  skip_entity_detection: true,
@@ -35,7 +35,7 @@ export interface StagedScopedTransition {
35
35
  }
36
36
 
37
37
  const SCOPES = new Set<StateScope>(["global", "cwd", "session"]);
38
- const PATCH_KEYS = new Set(["artifacts", "contract", "working"]);
38
+ const PATCH_KEYS = new Set(["artifacts", "contract", "working", "lazy"]);
39
39
 
40
40
  function compileReadArtifacts(
41
41
  nextState: StateDocument,
@@ -123,14 +123,17 @@ function validateScopePatch(scope: unknown, patch: unknown): asserts patch is Sc
123
123
  validatePatch(patch);
124
124
  for (const key of Object.keys(patch)) {
125
125
  if (!PATCH_KEYS.has(key)) {
126
- throw new Error(`Scoped State Flow patches cannot modify ${key}; only artifacts, contract, and working are model-owned`);
126
+ throw new Error(`Scoped State Flow patches cannot modify ${key}; only artifacts, contract, working, and lazy are model-owned`);
127
127
  }
128
128
  }
129
- for (const key of PATCH_KEYS) {
129
+ for (const key of ["artifacts", "contract", "working"] as const) {
130
130
  if (Object.hasOwn(patch, key) && !isObject(patch[key])) {
131
131
  throw new Error(`Scoped State Flow patch field ${key} must be a JSON object`);
132
132
  }
133
133
  }
134
+ if (Object.hasOwn(patch, "lazy") && patch.lazy === null) {
135
+ throw new Error("Scoped State Flow patch field lazy cannot be null");
136
+ }
134
137
  if (isObject(patch.artifacts)) validateModelArtifactPatch(patch.artifacts);
135
138
  }
136
139
 
@@ -140,6 +143,7 @@ function completePatch(patch: ScopePatch, response: string): StatePatch {
140
143
  contract: patch.contract ?? {},
141
144
  working: patch.working ?? {},
142
145
  response,
146
+ ...(Object.hasOwn(patch, "lazy") ? { lazy: structuredClone(patch.lazy!) } : {}),
143
147
  };
144
148
  }
145
149
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@llblab/pi-state-flow",
3
- "version": "0.13.3",
3
+ "version": "0.14.0",
4
4
  "private": false,
5
5
  "description": "Incremental scoped state/context/memory compiler for Pi, inspired by SKILL.state",
6
6
  "keywords": [
@@ -46,6 +46,8 @@ Separate a binding requirement from the method currently proposed to satisfy it.
46
46
 
47
47
  When it affects continuation, retain what was proposed, accepted, rejected, corrected, explained, or left unresolved, and what the next response or action must address. Preserve enough referents for pending follow-ups to make sense.
48
48
 
49
+ Treat every completed work slice as a possible restart boundary. Its checkpoint should let a fresh executor recover the achieved outcome, surviving evidence, active commitments, decision-relevant uncertainty, and exact continuation without replaying the prior reasoning trajectory. Optimize decomposition for resumability as well as functional completion; if the next safe action depends on transient context that will disappear, the slice is not yet at a sufficient boundary.
50
+
49
51
  Keep consequences, not a transcript or a personality dossier. Do not invent shared history or claim subjective continuity. A fresh run should not unnecessarily reopen a settled exchange or treat an unanswered proposal as approved.
50
52
 
51
53
  ### Preserve learning at its demonstrated boundary
@@ -70,11 +72,17 @@ A locator supports later retrieval; it does not replace content needed for the n
70
72
 
71
73
  Do not rerun the underlying project merely to curate its memory. Leave an exact unresolved check when verification falls outside the requested boundary.
72
74
 
73
- ### Compact without flattening
75
+ ### Preserve priority and keep Lazy shallow
76
+
77
+ Treat array order in Lazy as semantic priority: earlier entries are higher priority. Preserve that order deliberately; do not reorder entries for aesthetics, incidental grouping, or normalization.
78
+
79
+ Minimize Lazy nesting, especially for top-level collections. Keep a top-level collection as a direct array when its members are the domain values. Represent a standalone item directly, normally as a string; use an object only when that item genuinely owns structured or nested fields. Do not add `items`, `owner`, `source`, or similar wrapper objects merely to describe the collection, and do not introduce nested arrays unless the domain itself requires a matrix or grouped sequence.
80
+
81
+ ### Compact without flattening meaning
74
82
 
75
83
  Merge redundant fragments and remove obsolete scaffolding, repeated argumentation, and routine progress. Do not rewrite unchanged state merely to normalize wording.
76
84
 
77
- Do not erase a meaningful correction, uncertainty, commitment, negative result, or continuation dependency to make state shorter. Do not retain the previous chain of reasoning solely to steer the next run toward the same method.
85
+ Do not erase a meaningful correction, uncertainty, commitment, negative result, priority order, or continuation dependency to make state shorter. Do not retain the previous chain of reasoning solely to steer the next run toward the same method.
78
86
 
79
87
  ### Reconcile phase boundaries
80
88
 
@@ -90,7 +98,7 @@ Effective state does not prove which scope owns a value. When ownership matters
90
98
 
91
99
  Before writing, review the proposed changes once within the requested boundary:
92
100
 
93
- - Would a fresh executor know what must still hold, what changed, what remains unresolved, and how to continue?
101
+ - Would a fresh executor know what must still hold, what changed, what remains unresolved, and the exact next action without replaying the prior cognitive trajectory?
94
102
  - Could an omission cause a known failed attempt, an unnecessary repeated explanation, or loss of an active commitment?
95
103
  - Could a retained claim impose an unapproved method, overgeneralize a result, or hide a live alternative?
96
104
 
@@ -121,7 +121,7 @@ The detailed map is canonical in [`docs/architecture.md`](./docs/architecture.md
121
121
  - Command templates remain compact and shell-free. Use string leaves or ordered `template` arrays; shell operators are not an execution contract. Examples use portable executable placeholders, never machine-local paths.
122
122
  - `telegram_attach` is the canonical file path and `telegram_message` the direct Markdown text/buttons path. Both require current direct or registered-follower authority and must not replace the normal active-turn reply.
123
123
  - Inbound handlers transform text/media before queueing; outbound handlers precede programmatic/provider fallbacks. Public contracts and ordering live in `docs/inbound.md`, `docs/outbound.md`, and `docs/public-api.md`.
124
- - Pi integration uses public hooks and APIs. A Telegram `/new` or equivalent session replacement requires a public Pi API that executes the real terminal path.
124
+ - Pi integration uses public hooks and APIs. Telegram `/new` is scheduled against the exact durable update, dispatched only after that update is removed from the journal, and then routed through an internal Pi command via `pi.sendUserMessage(..., { expandPromptTemplates: true })`; the command handler receives the real `ExtensionCommandContext` and calls `ctx.newSession()`. Before replacement, CAS-publish one exact expiring handoff in the profile target snapshot. `workspace-thread` successors re-key the matching Workspace binding; `classic-chat` successors preserve Profile/CWD/session/chat continuity without creating a binding or invoking topic APIs. Both atomically claim the intent before one terminal result, and the old `withSession` path never publishes the same success. Never replace the session while inbound authority is unsettled, store stale command contexts, accept an expired or mismatched handoff, inject terminal input, spawn a shadow Pi process, or mutate session files.
125
125
 
126
126
  ## 7. Engineering Conventions
127
127
 
@@ -2,6 +2,7 @@
2
2
 
3
3
  _This file owns unresolved project work only. Completed behavior belongs in `CHANGELOG.md`; durable contracts belong in `AGENTS.md` and `/docs`._
4
4
 
5
+ - [ ] `Unified Telegram /new continuity` (`local-actionable`, current priority; closes [#81](https://github.com/llblab/pi-telegram/issues/81)): The existing one-shot intent now has strict `workspace-thread | classic-chat` continuity. Classic preparation persists exact Profile/CWD/session/chat identity without requiring or fabricating a Workspace binding; its codec round-trip and claim path leave Workspace bindings untouched. Threaded preparation and successor re-key retain the existing slot/name path. Local implementation and docs are complete. Classic preparation-to-successor settlement passes with one terminal send and no Workspace mutation against both the same store instance and a freshly reopened process store; duplicate settlement sends nothing. Threaded re-key, mismatch, expiry, failed-claim, full-suite, invariants, and Domain DAG regressions pass under the discriminated codec. Final `dist` is rebuilt; Classic Settings also hides both Thread-specific controls rather than exposing only cleanup. Remaining: operator-authorized Classic and Threaded live smoke. Do not close or post to #81 before release authority. Both modes delete confirmation before replacement, CAS-claim before terminal send, and preserve at-most-once cross-process result semantics; do not close or post to #81 before release authority.
5
6
  - [ ] `Prompt enqueue hotfix` (`optional`, `operator-gated`): Optional nonblocking operator-authorized disposable-follower smoke: overlap delayed voice processing with turn completion and confirm one-time ordered consumption and truthful counts against the [queue contract](./docs/architecture.md#queue-and-dispatch-safety). Separately authorized supported recovery investigation remains open: prevention does not repair an already-wedged in-memory queue; establish the exact recovery path and preservation/discard consequences before mutation, otherwise report the blocker. No journal/ownership edits, replay of settled input, implicit queue clearing, or restart; live activation requires separate operator authorization.
6
7
  - [ ] `Channel multimedia posts` (`0.45.1`, live-acceptance-gated): `telegram_message` channel delivery accepts one local `.jpg`/`.jpeg`/`.png`/`.webp` photo or `.mp4` video, uploads it through the multipart transport as `sendPhoto`/`sendVideo` with `text` as the HTML caption, validates kind and size (photo ≤ 10 MiB, video ≤ 50 MiB) plus ≤ 1024 visible caption characters before issuance, and rejects unsupported types and albums instead of downgrading them to links. The channel-post journal binds kind/file name/byte size/SHA-256 and caption, so duplicate requests and lost acknowledgements never re-upload; media-post edits replace the caption through `editMessageCaption`, and Markdown spoilers render as `<tg-spoiler>`. Live image publication passed on `@llb_log`. Regressions cover confirmed publication, duplicate requests, lost ACK, pre-issuance rejection, caption edits, and reconnect replacement. Remaining: operator-authorized disposable-channel acceptance of rejected upload, duplicate request, and caption edit.
7
8
  - [ ] `Manual Thread naming` (`gated-but-preparable`, release priority): Local bot-owned `/name Name` and bare `/name` flows avoid model dispatch. One expiring exact-target input dialog immediately accepts the next valid name, always offers cancel, and offers **Reset to automatic** only while a manual override exists; duplicate/stale callbacks cannot repeat mutation. Durable manual override supersedes every automatic display mode, reset is leader/follower generation- and target-fenced, and Letters remains the default without rewriting recovery identity. Local review findings are remediated, including Bot-API-wait target-replacement regressions for leader/follower rename and reset. Remaining: disposable live acceptance for command-menu ordering, dialog, invalid input, duplicate callbacks, leader/follower rename and reset.
@@ -4,6 +4,13 @@
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ ## 0.49.0: Unified fresh-session continuity
8
+
9
+ - `/new`: Classic and Threaded Mode now share one confirmed fresh-session flow. The settled callback deletes its dialog and publishes an expiring exact-target intent; a same- or cross-process successor preserves the classic chat or re-keys the Thread/slot/name, atomically claims once, then sends one terminal result. Identity mismatches fail closed.
10
+ - `Command menus`: Both Telegram command menus now keep the primary sequence `/start`, `/compact`, `/new`, `/continue`, `/next`; the niche `/name` command remains available but moves out of menus into the Thread display Settings guidance.
11
+ - `Classic Settings`: Hides both Thread display and Thread cleanup controls when Threaded Mode is unavailable, rather than exposing only half of the Thread-specific surface.
12
+ - `Thread display`: A current Thread with a manual `/name` override now appears as `custom` on the Settings row and detail heading; choosing any automatic mode clears the current Thread's override, reapplies that projection, and selects it again. Successful interactive rename/reset now settles its source before asynchronously publishing the result, so immediate `/new` cannot replay the consumed name after replacement; cancellation reports only its completed result.
13
+
7
14
  ## 0.48.3: Assistant publication identity hotfix
8
15
 
9
16
  - `Thread restore display identity`: Restoring or reclaiming a Thread now renames the destination from its current Workspace display title when available, rather than leaking the internal baked slot name such as `Moss` into directory-title mode.
@@ -164,6 +164,7 @@ Use these in the bot DM.
164
164
  | --- | --- |
165
165
  | `/start` | Pair when needed and open the main operator menu |
166
166
  | `/name [Name]` | Set a manual Thread title immediately, or open rename/reset controls when Name is omitted |
167
+ | `/new` | Start a new Pi session in the current classic chat or Thread after confirming the bridge is idle |
167
168
  | `/compact` | Confirm and run session compaction when safe |
168
169
  | `/next` | Dispatch the next queued turn, aborting first if needed |
169
170
  | `/continue` | Enqueue a priority continuation prompt |
@@ -216,6 +216,7 @@ interface TelegramLifecycleBindingDeps {
216
216
  deferredQueueDispatchRuntime: Queue.TelegramDeferredQueueDispatchRuntime<Pi.ExtensionContext>;
217
217
  modelContextAvailabilityRuntime: Prompts.TelegramModelContextAvailabilityRuntime;
218
218
  disconnectOnQuit?: () => Promise<unknown>;
219
+ onSessionStarted?: (event: Pi.SessionStartEvent, ctx: Pi.ExtensionContext) => void;
219
220
  shutdownGenerativeAppLiveSurfaces?: () => void;
220
221
  resolveAutomaticThreadCleanupEnabled?: () => boolean | Promise<boolean>;
221
222
  buttonActionStore: OutboundHandlers.TelegramButtonActionStore;
@@ -246,5 +247,5 @@ interface TelegramLifecycleBindingDeps {
246
247
  updateStatus: TelegramBridgeStatusUpdater;
247
248
  recordRuntimeEvent: TelegramRuntimeEventRecorder;
248
249
  }
249
- export declare function registerTelegramLifecycleRuntimeHooks({ pi, publicationRuntime, activityRuntime, activityVerbosityRuntime, assistantOutputRuntime, sessionLifecycleRuntime, configStore, abort, typing, lifecycle, activeTurnRuntime, telegramQueueStore, modelSwitchController, previewRuntime, promptDispatchRuntime, deferredQueueDispatchRuntime, modelContextAvailabilityRuntime, disconnectOnQuit, shutdownGenerativeAppLiveSurfaces, resolveAutomaticThreadCleanupEnabled, buttonActionStore, callMultipart, sendChatAction, sendRecordVoiceAction, sendMarkdownReply, sendTextReply, dispatchNextQueuedTelegramTurn, onPromptHandedOff, answerGuestQuery, deleteMessage, sendGuestReply, editGuestReply, stopGuestPlaceholder, preparePreviewDelivery, finalizeMarkdownPreview, proactivePushTargetGetter, getAssistantRenderingMode, recordMessageOwnership, canSendAgentActivity, isSessionContextActive, isTurnTransportActive, updateStatus, recordRuntimeEvent, }: TelegramLifecycleBindingDeps): void;
250
+ export declare function registerTelegramLifecycleRuntimeHooks({ pi, publicationRuntime, activityRuntime, activityVerbosityRuntime, assistantOutputRuntime, sessionLifecycleRuntime, configStore, abort, typing, lifecycle, activeTurnRuntime, telegramQueueStore, modelSwitchController, previewRuntime, promptDispatchRuntime, deferredQueueDispatchRuntime, modelContextAvailabilityRuntime, disconnectOnQuit, onSessionStarted, shutdownGenerativeAppLiveSurfaces, resolveAutomaticThreadCleanupEnabled, buttonActionStore, callMultipart, sendChatAction, sendRecordVoiceAction, sendMarkdownReply, sendTextReply, dispatchNextQueuedTelegramTurn, onPromptHandedOff, answerGuestQuery, deleteMessage, sendGuestReply, editGuestReply, stopGuestPlaceholder, preparePreviewDelivery, finalizeMarkdownPreview, proactivePushTargetGetter, getAssistantRenderingMode, recordMessageOwnership, canSendAgentActivity, isSessionContextActive, isTurnTransportActive, updateStatus, recordRuntimeEvent, }: TelegramLifecycleBindingDeps): void;
250
251
  export {};
@@ -499,7 +499,7 @@ export function registerTelegramCommandsAndTools({ pi, agentDir, configStore, pe
499
499
  },
500
500
  });
501
501
  }
502
- export function registerTelegramLifecycleRuntimeHooks({ pi, publicationRuntime, activityRuntime, activityVerbosityRuntime, assistantOutputRuntime, sessionLifecycleRuntime, configStore, abort, typing, lifecycle, activeTurnRuntime, telegramQueueStore, modelSwitchController, previewRuntime, promptDispatchRuntime, deferredQueueDispatchRuntime, modelContextAvailabilityRuntime, disconnectOnQuit, shutdownGenerativeAppLiveSurfaces, resolveAutomaticThreadCleanupEnabled, buttonActionStore, callMultipart, sendChatAction, sendRecordVoiceAction, sendMarkdownReply, sendTextReply, dispatchNextQueuedTelegramTurn, onPromptHandedOff, answerGuestQuery, deleteMessage, sendGuestReply, editGuestReply, stopGuestPlaceholder, preparePreviewDelivery, finalizeMarkdownPreview, proactivePushTargetGetter, getAssistantRenderingMode, recordMessageOwnership, canSendAgentActivity, isSessionContextActive = () => true, isTurnTransportActive, updateStatus, recordRuntimeEvent, }) {
502
+ export function registerTelegramLifecycleRuntimeHooks({ pi, publicationRuntime, activityRuntime, activityVerbosityRuntime, assistantOutputRuntime, sessionLifecycleRuntime, configStore, abort, typing, lifecycle, activeTurnRuntime, telegramQueueStore, modelSwitchController, previewRuntime, promptDispatchRuntime, deferredQueueDispatchRuntime, modelContextAvailabilityRuntime, disconnectOnQuit, onSessionStarted, shutdownGenerativeAppLiveSurfaces, resolveAutomaticThreadCleanupEnabled, buttonActionStore, callMultipart, sendChatAction, sendRecordVoiceAction, sendMarkdownReply, sendTextReply, dispatchNextQueuedTelegramTurn, onPromptHandedOff, answerGuestQuery, deleteMessage, sendGuestReply, editGuestReply, stopGuestPlaceholder, preparePreviewDelivery, finalizeMarkdownPreview, proactivePushTargetGetter, getAssistantRenderingMode, recordMessageOwnership, canSendAgentActivity, isSessionContextActive = () => true, isTurnTransportActive, updateStatus, recordRuntimeEvent, }) {
503
503
  const agentEndResetter = Runtime.createTelegramAgentEndResetter({
504
504
  abort,
505
505
  typing,
@@ -755,6 +755,7 @@ export function registerTelegramLifecycleRuntimeHooks({ pi, publicationRuntime,
755
755
  activityVerbosityRuntime?.reset();
756
756
  modelContextAvailabilityRuntime.reconcile();
757
757
  await sessionLifecycleRuntime.onSessionStart(event, ctx);
758
+ onSessionStarted?.(event, ctx);
758
759
  },
759
760
  async onSessionShutdown(event, ctx) {
760
761
  if (!isSessionContextActive(ctx))
@@ -1,11 +1,13 @@
1
1
  /**
2
2
  * Telegram command routing helpers
3
3
  * Zones: telegram controls, pi agent commands, queue controls
4
- * Owns Telegram slash-command normalization, bot command metadata, and pi-side command registration behind runtime ports
4
+ * Owns Telegram slash-command normalization, bot command metadata, pi-side command registration, and command-initiated session replacement orchestration behind runtime ports
5
5
  */
6
6
  import { type TelegramConfigStore } from "./config.ts";
7
+ import type * as Pi from "./pi.ts";
7
8
  import type { ExtensionAPI, ExtensionCommandContext } from "./pi.ts";
8
9
  import type { TelegramBridgeStatusLineOptions } from "./status.ts";
10
+ import type { TelegramSessionReplacementIntent } from "./threads.ts";
9
11
  import { type PendingTelegramControlItem, type TelegramQueueAdmissionReceipt } from "./queue.ts";
10
12
  export interface ParsedTelegramCommand {
11
13
  name: string;
@@ -60,6 +62,7 @@ export declare const TELEGRAM_COMMAND_EMOJI: {
60
62
  readonly abort: "⏹️";
61
63
  readonly stop: "🟥";
62
64
  readonly name: "🏷️";
65
+ readonly new: "🆕";
63
66
  };
64
67
  export type TelegramCommandEmojiName = keyof typeof TELEGRAM_COMMAND_EMOJI;
65
68
  export declare function getTelegramCommandEmoji(command: TelegramCommandEmojiName): string;
@@ -144,7 +147,7 @@ export declare function createTelegramThreadDisplayNameRenameBinding(): {
144
147
  };
145
148
  export declare function parseTelegramRequestedThreadName(args: string): string | undefined;
146
149
  export declare function registerTelegramBridgeCommands(pi: ExtensionAPI, deps: TelegramBridgeCommandRegistrationDeps): void;
147
- export declare const TELEGRAM_RESERVED_COMMAND_NAMES: readonly ["stop", "name", "abort", "next", "continue", "status", "queue", "compact", "model", "thinking", "settings", "help", "start"];
150
+ export declare const TELEGRAM_RESERVED_COMMAND_NAMES: readonly ["stop", "name", "new", "abort", "next", "continue", "status", "queue", "compact", "model", "thinking", "settings", "help", "start"];
148
151
  export type TelegramReservedCommandName = (typeof TELEGRAM_RESERVED_COMMAND_NAMES)[number];
149
152
  export declare function isTelegramReservedCommandName(commandName: string | undefined): commandName is TelegramReservedCommandName;
150
153
  export type TelegramCommandAction = {
@@ -156,6 +159,9 @@ export type TelegramCommandAction = {
156
159
  } | {
157
160
  kind: "name";
158
161
  executionMode: "immediate";
162
+ } | {
163
+ kind: "new";
164
+ executionMode: "immediate";
159
165
  } | {
160
166
  kind: "abort";
161
167
  executionMode: "immediate";
@@ -192,6 +198,7 @@ export type TelegramCommandExecutionMode = "ignored" | "immediate";
192
198
  export interface TelegramCommandActionDeps<TMessage, TContext> {
193
199
  handleStop: (message: TMessage, ctx: TContext) => Promise<void>;
194
200
  handleName: (message: TMessage, ctx: TContext, name: string) => Promise<void>;
201
+ handleNew: (message: TMessage, ctx: TContext) => Promise<void>;
195
202
  handleAbort: (message: TMessage, ctx: TContext) => Promise<void>;
196
203
  handleNext: (message: TMessage, ctx: TContext) => Promise<void>;
197
204
  handleContinue: (message: TMessage, ctx: TContext) => Promise<void>;
@@ -264,6 +271,13 @@ export interface TelegramCompactConfirmationCallbackQuery {
264
271
  message_thread_id?: number;
265
272
  };
266
273
  }
274
+ export interface TelegramNewConfirmationCallbackDeps<TContext> {
275
+ ctx: TContext;
276
+ answerCallbackQuery: (callbackQueryId: string, text?: string) => Promise<void>;
277
+ editInteractiveMessage: (chatId: number, messageId: number, text: string, mode: "markdown" | "html" | "plain", replyMarkup: TelegramCompactConfirmationReplyMarkup) => Promise<void>;
278
+ deleteMessage: (chatId: number, messageId: number) => Promise<void>;
279
+ runNew: (ctx: TContext) => Promise<void>;
280
+ }
267
281
  export interface TelegramCompactConfirmationCallbackDeps<TContext> {
268
282
  ctx: TContext;
269
283
  answerCallbackQuery: (callbackQueryId: string, text?: string) => Promise<void>;
@@ -390,6 +404,7 @@ export interface TelegramCommandRuntimeDeps<TMessage extends TelegramCommandRunt
390
404
  }) => void;
391
405
  stopTypingLoop?: () => void;
392
406
  enqueueContinueTurn: (message: TMessage, ctx: TContext) => Promise<void>;
407
+ requestNewSession?: (message: TMessage) => void;
393
408
  compact: (ctx: TContext, callbacks: {
394
409
  onComplete: () => void;
395
410
  onError: (error: unknown) => void;
@@ -434,6 +449,10 @@ export declare const TELEGRAM_COMMAND_ACTIONS: {
434
449
  readonly kind: "name";
435
450
  readonly executionMode: "immediate";
436
451
  };
452
+ readonly new: {
453
+ readonly kind: "new";
454
+ readonly executionMode: "immediate";
455
+ };
437
456
  readonly abort: {
438
457
  readonly kind: "abort";
439
458
  readonly executionMode: "immediate";
@@ -515,10 +534,27 @@ export declare function handleTelegramNextCommand(deps: {
515
534
  export declare function handleTelegramContinueCommand<TMessage, TContext>(message: TMessage, ctx: TContext, deps: {
516
535
  enqueueContinueTurn: (message: TMessage, ctx: TContext) => Promise<void>;
517
536
  }): Promise<void>;
537
+ export declare function buildTelegramNewConfirmationReplyMarkup(): TelegramCompactConfirmationReplyMarkup;
538
+ export declare function getTelegramNewConfirmationHtml(): string;
539
+ export declare function openTelegramNewConfirmation(target: TelegramCommandMessageTarget, deps: TelegramCompactConfirmationDeps): Promise<void>;
540
+ export declare function handleTelegramNewConfirmationCallback<TContext>(query: TelegramCompactConfirmationCallbackQuery, deps: TelegramNewConfirmationCallbackDeps<TContext>): Promise<boolean>;
518
541
  export declare function buildTelegramCompactConfirmationReplyMarkup(): TelegramCompactConfirmationReplyMarkup;
519
542
  export declare function getTelegramCompactConfirmationHtml(): string;
520
543
  export declare function openTelegramCompactConfirmation(target: TelegramCommandMessageTarget, deps: TelegramCompactConfirmationDeps): Promise<void>;
521
544
  export declare function handleTelegramCompactConfirmationCallback<TContext>(query: TelegramCompactConfirmationCallbackQuery, deps: TelegramCompactConfirmationCallbackDeps<TContext>): Promise<boolean>;
545
+ export interface TelegramNewCommandDeps extends TelegramRuntimeEventRecorderPort {
546
+ isIdle: () => boolean;
547
+ hasPendingMessages: () => boolean;
548
+ hasActiveTelegramTurn: () => boolean;
549
+ hasDispatchPending: () => boolean;
550
+ hasQueuedTelegramItems: () => boolean;
551
+ isCompactionInProgress: () => boolean;
552
+ requestNewSession?: () => void;
553
+ sendTextReply: (text: string, options?: {
554
+ parseMode?: "HTML";
555
+ }) => Promise<void>;
556
+ }
557
+ export declare function handleTelegramNewCommand(deps: TelegramNewCommandDeps): Promise<void>;
522
558
  export declare function handleTelegramCompactCommand(deps: TelegramCompactCommandDeps): Promise<void>;
523
559
  export declare function handleTelegramStatusCommand<TContext>(deps: {
524
560
  ctx: TContext;
@@ -538,4 +574,100 @@ export declare function createTelegramCommandHandler<TMessage extends TelegramCo
538
574
  export declare function createTelegramCommandOrPromptRuntime<TMessage, TContext>(deps: TelegramCommandOrPromptRuntimeDeps<TMessage, TContext>): {
539
575
  dispatchMessages: (messages: TMessage[], ctx: TContext) => Promise<void>;
540
576
  };
577
+ export declare const TELEGRAM_SESSION_ACTION_COMMAND_NAME = "telegram-session-action";
578
+ export declare const TELEGRAM_SESSION_ACTION_COMMAND_DESCRIPTION = "(internal) replace the current Pi session after Telegram settlement";
579
+ export declare function delayTelegramSessionAction(delayMs: number): Promise<void>;
580
+ export interface TelegramSessionActionRuntimeDeps {
581
+ registerCommand: Pi.ExtensionAPI["registerCommand"];
582
+ sendUserMessage: Pi.ExtensionAPI["sendUserMessage"];
583
+ notifyResult: (target: {
584
+ chatId: number;
585
+ threadId?: number;
586
+ messageId: number;
587
+ }, result: "success" | "cancelled" | "failure") => Promise<void>;
588
+ prepareReplacement?: (ctx: Pi.ExtensionCommandContext, updateId: number, target: {
589
+ chatId: number;
590
+ threadId?: number;
591
+ messageId: number;
592
+ }) => Promise<void>;
593
+ recordRuntimeEvent?: (category: string, error: unknown) => void;
594
+ }
595
+ export interface TelegramSessionReplacementSettlementDeps {
596
+ getIntent: () => Promise<TelegramSessionReplacementIntent | undefined>;
597
+ hasSuccessorContinuity: (intent: TelegramSessionReplacementIntent) => boolean;
598
+ editSuccess: (intent: TelegramSessionReplacementIntent) => Promise<{
599
+ ok: boolean;
600
+ retryable?: boolean;
601
+ message?: string;
602
+ }>;
603
+ clearIntent: (intent: TelegramSessionReplacementIntent) => Promise<boolean>;
604
+ profileName: string | undefined;
605
+ cwd: string;
606
+ sessionId: string;
607
+ now?: () => number;
608
+ sleep?: (delayMs: number) => Promise<void>;
609
+ isCurrent?: () => boolean;
610
+ }
611
+ export declare function settleTelegramSessionReplacement(deps: TelegramSessionReplacementSettlementDeps): Promise<"none" | "settled" | "expired" | "failed" | "stale">;
612
+ export declare function createTelegramSessionReplacementSettlementRuntime<TContext>(deps: {
613
+ resolve: (ctx: TContext) => TelegramSessionReplacementSettlementDeps | undefined;
614
+ onResult?: (result: "none" | "settled" | "expired" | "failed" | "stale") => void;
615
+ onError?: (error: unknown) => void;
616
+ }): {
617
+ onSessionStart: (ctx: TContext) => void;
618
+ };
619
+ export interface TelegramSessionActionAssemblyDeps {
620
+ registerCommand: Pi.ExtensionAPI["registerCommand"];
621
+ sendUserMessage: Pi.ExtensionAPI["sendUserMessage"];
622
+ store: {
623
+ load: () => Promise<void>;
624
+ refresh?: () => Promise<void>;
625
+ getWorkspaceBindingByTarget: (target: {
626
+ chatId: number;
627
+ threadId?: number;
628
+ }, sessionId?: string) => {
629
+ cwd: string;
630
+ sessionId?: string;
631
+ slot?: string;
632
+ threadName?: string;
633
+ manualThreadName?: string;
634
+ target: {
635
+ chatId: number;
636
+ threadId: number;
637
+ };
638
+ } | undefined;
639
+ getSessionReplacementIntent: () => TelegramSessionReplacementIntent | undefined;
640
+ commitSessionReplacementIntent: (intent: TelegramSessionReplacementIntent, isCurrent: () => boolean) => Promise<boolean>;
641
+ removeSessionReplacementIntent: (intent: TelegramSessionReplacementIntent, isCurrent: () => boolean) => Promise<boolean>;
642
+ };
643
+ getProfileName: () => string | undefined;
644
+ ownsPersistence: () => boolean;
645
+ sendResult: (target: {
646
+ chatId: number;
647
+ threadId?: number;
648
+ }, html: string) => Promise<{
649
+ ok: boolean;
650
+ retryable?: boolean;
651
+ }>;
652
+ handoffTtlMs: number;
653
+ now?: () => number;
654
+ recordRuntimeEvent?: (category: string, error: unknown) => void;
655
+ }
656
+ export declare function createTelegramSessionActionAssembly(deps: TelegramSessionActionAssemblyDeps): {
657
+ action: TelegramSessionActionRuntime;
658
+ settlement: {
659
+ onSessionStart: (ctx: Pi.ExtensionContext) => void;
660
+ };
661
+ };
662
+ export interface TelegramSessionActionRuntime {
663
+ register: () => void;
664
+ scheduleAfterUpdate: (updateId: number, target: {
665
+ chatId: number;
666
+ threadId?: number;
667
+ messageId: number;
668
+ }) => boolean;
669
+ onUpdateCompleted: (updateId: number) => void;
670
+ hasPending: () => boolean;
671
+ }
672
+ export declare function createTelegramSessionActionRuntime(deps: TelegramSessionActionRuntimeDeps): TelegramSessionActionRuntime;
541
673
  export {};