@llblab/pi-kit 0.25.0 → 0.27.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.
- package/BACKLOG.md +5 -1
- package/CHANGELOG.md +11 -0
- package/README.md +10 -8
- package/node_modules/@llblab/pi-actors/AGENTS.md +2 -0
- package/node_modules/@llblab/pi-actors/CHANGELOG.md +4 -1
- package/node_modules/@llblab/pi-actors/LICENSE +21 -0
- package/node_modules/@llblab/pi-actors/README.md +1 -1
- package/node_modules/@llblab/pi-actors/docs/coordinator-delivery.md +1 -1
- package/node_modules/@llblab/pi-actors/package.json +4 -3
- package/node_modules/@llblab/pi-claude-usage/AGENTS.md +6 -3
- package/node_modules/@llblab/pi-claude-usage/BACKLOG.md +2 -1
- package/node_modules/@llblab/pi-claude-usage/CHANGELOG.md +8 -0
- package/node_modules/@llblab/pi-claude-usage/README.md +48 -3
- package/node_modules/@llblab/pi-claude-usage/index.ts +8 -1159
- package/node_modules/@llblab/pi-claude-usage/lib/extension.ts +30 -0
- package/node_modules/@llblab/pi-claude-usage/lib/fast.ts +24 -0
- package/node_modules/@llblab/pi-claude-usage/lib/query.ts +146 -0
- package/node_modules/@llblab/pi-claude-usage/lib/status-format.ts +297 -0
- package/node_modules/@llblab/pi-claude-usage/lib/status.ts +366 -0
- package/node_modules/@llblab/pi-claude-usage/lib/telegram.ts +44 -0
- package/node_modules/@llblab/pi-claude-usage/lib/usage-store.ts +221 -0
- package/node_modules/@llblab/pi-claude-usage/lib/usage.ts +128 -0
- package/node_modules/@llblab/pi-claude-usage/package.json +9 -5
- package/node_modules/@llblab/pi-clean-room/AGENTS.md +1 -0
- package/node_modules/@llblab/pi-clean-room/CHANGELOG.md +5 -0
- package/node_modules/@llblab/pi-clean-room/LICENSE +21 -0
- package/node_modules/@llblab/pi-clean-room/README.md +1 -1
- package/node_modules/@llblab/pi-clean-room/package.json +3 -2
- package/node_modules/@llblab/pi-codex-usage/AGENTS.md +9 -6
- package/node_modules/@llblab/pi-codex-usage/BACKLOG.md +2 -1
- package/node_modules/@llblab/pi-codex-usage/CHANGELOG.md +17 -0
- package/node_modules/@llblab/pi-codex-usage/README.md +75 -17
- package/node_modules/@llblab/pi-codex-usage/index.ts +8 -1602
- package/node_modules/@llblab/pi-codex-usage/lib/extension.ts +25 -0
- package/node_modules/@llblab/pi-codex-usage/lib/fast.ts +23 -0
- package/node_modules/@llblab/pi-codex-usage/lib/query.ts +368 -0
- package/node_modules/@llblab/pi-codex-usage/lib/status-format.ts +347 -0
- package/node_modules/@llblab/pi-codex-usage/lib/status.ts +435 -0
- package/node_modules/@llblab/pi-codex-usage/lib/telegram.ts +45 -0
- package/node_modules/@llblab/pi-codex-usage/lib/usage-store.ts +229 -0
- package/node_modules/@llblab/pi-codex-usage/lib/usage.ts +425 -0
- package/node_modules/@llblab/pi-codex-usage/package.json +11 -6
- package/node_modules/@llblab/pi-command-fast/AGENTS.md +7 -0
- package/node_modules/@llblab/pi-command-fast/BACKLOG.md +9 -0
- package/node_modules/@llblab/pi-command-fast/CHANGELOG.md +7 -0
- package/node_modules/@llblab/pi-command-fast/LICENSE +21 -0
- package/node_modules/@llblab/pi-command-fast/README.md +42 -0
- package/node_modules/@llblab/pi-command-fast/dist/command.d.ts +8 -0
- package/node_modules/@llblab/pi-command-fast/dist/command.js +52 -0
- package/node_modules/@llblab/pi-command-fast/dist/index.d.ts +3 -0
- package/node_modules/@llblab/pi-command-fast/dist/index.js +3 -0
- package/node_modules/@llblab/pi-command-fast/dist/models-json.d.ts +10 -0
- package/node_modules/@llblab/pi-command-fast/dist/models-json.js +81 -0
- package/node_modules/@llblab/pi-command-fast/package.json +49 -0
- package/node_modules/@llblab/pi-grow-loop/AGENTS.md +1 -0
- package/node_modules/@llblab/pi-grow-loop/CHANGELOG.md +4 -1
- package/node_modules/@llblab/pi-grow-loop/LICENSE +21 -0
- package/node_modules/@llblab/pi-grow-loop/README.md +1 -1
- package/node_modules/@llblab/pi-grow-loop/package.json +3 -2
- package/node_modules/@llblab/pi-state-flow/AGENTS.md +7 -6
- package/node_modules/@llblab/pi-state-flow/BACKLOG.md +13 -5
- package/node_modules/@llblab/pi-state-flow/CHANGELOG.md +16 -1
- package/node_modules/@llblab/pi-state-flow/LICENSE +21 -0
- package/node_modules/@llblab/pi-state-flow/README.md +117 -35
- package/node_modules/@llblab/pi-state-flow/dist/lib/acquisition.d.ts +24 -1
- package/node_modules/@llblab/pi-state-flow/dist/lib/acquisition.js +80 -1
- package/node_modules/@llblab/pi-state-flow/dist/lib/compaction.d.ts +18 -1
- package/node_modules/@llblab/pi-state-flow/dist/lib/compaction.js +41 -1
- package/node_modules/@llblab/pi-state-flow/dist/lib/extension.js +346 -303
- package/node_modules/@llblab/pi-state-flow/dist/lib/git.d.ts +31 -2
- package/node_modules/@llblab/pi-state-flow/dist/lib/git.js +74 -5
- package/node_modules/@llblab/pi-state-flow/dist/lib/operation.d.ts +37 -0
- package/node_modules/@llblab/pi-state-flow/dist/lib/operation.js +59 -0
- package/node_modules/@llblab/pi-state-flow/dist/lib/ownership.d.ts +31 -0
- package/node_modules/@llblab/pi-state-flow/dist/lib/ownership.js +117 -0
- package/node_modules/@llblab/pi-state-flow/dist/lib/protocol.js +7 -7
- package/node_modules/@llblab/pi-state-flow/dist/lib/query.js +1 -1
- package/node_modules/@llblab/pi-state-flow/dist/lib/session.d.ts +10 -1
- package/node_modules/@llblab/pi-state-flow/dist/lib/session.js +60 -1
- package/node_modules/@llblab/pi-state-flow/dist/lib/snapshot.d.ts +6 -0
- package/node_modules/@llblab/pi-state-flow/dist/lib/snapshot.js +8 -5
- package/node_modules/@llblab/pi-state-flow/dist/lib/status.d.ts +2 -0
- package/node_modules/@llblab/pi-state-flow/dist/lib/status.js +28 -0
- package/node_modules/@llblab/pi-state-flow/dist/lib/transition.js +6 -1
- package/node_modules/@llblab/pi-state-flow/dist/package.json +10 -9
- package/node_modules/@llblab/pi-state-flow/dist/skills/state-flow-guide/SKILL.md +14 -6
- package/node_modules/@llblab/pi-state-flow/dist/skills/state-flow-memory/SKILL.md +2 -2
- package/node_modules/@llblab/pi-state-flow/docs/README.md +19 -9
- package/node_modules/@llblab/pi-state-flow/docs/agent-contract-relocation.md +4 -4
- package/node_modules/@llblab/pi-state-flow/docs/architecture.md +646 -89
- package/node_modules/@llblab/pi-state-flow/docs/compatibility.md +116 -37
- package/node_modules/@llblab/pi-state-flow/docs/filesystem-recovery.md +118 -21
- package/node_modules/@llblab/pi-state-flow/docs/fork-contract.md +70 -8
- package/node_modules/@llblab/pi-state-flow/docs/lazy-state.md +88 -14
- package/node_modules/@llblab/pi-state-flow/docs/performance.md +83 -66
- package/node_modules/@llblab/pi-state-flow/docs/temporal-acceptance.md +391 -62
- package/node_modules/@llblab/pi-state-flow/docs/usage.md +317 -61
- package/node_modules/@llblab/pi-state-flow/lib/acquisition.ts +85 -1
- package/node_modules/@llblab/pi-state-flow/lib/compaction.ts +49 -2
- package/node_modules/@llblab/pi-state-flow/lib/extension.ts +342 -301
- package/node_modules/@llblab/pi-state-flow/lib/git.ts +77 -5
- package/node_modules/@llblab/pi-state-flow/lib/operation.ts +75 -0
- package/node_modules/@llblab/pi-state-flow/lib/ownership.ts +120 -0
- package/node_modules/@llblab/pi-state-flow/lib/protocol.ts +7 -8
- package/node_modules/@llblab/pi-state-flow/lib/query.ts +1 -1
- package/node_modules/@llblab/pi-state-flow/lib/runtime.ts +1 -1
- package/node_modules/@llblab/pi-state-flow/lib/session.ts +52 -1
- package/node_modules/@llblab/pi-state-flow/lib/snapshot.ts +8 -7
- package/node_modules/@llblab/pi-state-flow/lib/status.ts +29 -0
- package/node_modules/@llblab/pi-state-flow/lib/transition.ts +5 -1
- package/node_modules/@llblab/pi-state-flow/package.json +10 -9
- package/node_modules/@llblab/pi-state-flow/skills/state-flow-guide/SKILL.md +14 -6
- package/node_modules/@llblab/pi-state-flow/skills/state-flow-memory/SKILL.md +2 -2
- package/node_modules/@llblab/pi-telegram/BACKLOG.md +1 -0
- package/node_modules/@llblab/pi-telegram/CHANGELOG.md +10 -0
- package/node_modules/@llblab/pi-telegram/README.md +1 -1
- package/node_modules/@llblab/pi-telegram/dist/lib/bindings.d.ts +4 -1
- package/node_modules/@llblab/pi-telegram/dist/lib/bindings.js +16 -12
- package/node_modules/@llblab/pi-telegram/dist/lib/bus-follower.d.ts +1 -1
- package/node_modules/@llblab/pi-telegram/dist/lib/bus-follower.js +7 -1
- package/node_modules/@llblab/pi-telegram/dist/lib/commands.d.ts +12 -3
- package/node_modules/@llblab/pi-telegram/dist/lib/commands.js +137 -83
- package/node_modules/@llblab/pi-telegram/dist/lib/extension.js +26 -0
- package/node_modules/@llblab/pi-telegram/dist/lib/lifecycle.d.ts +57 -2
- package/node_modules/@llblab/pi-telegram/dist/lib/lifecycle.js +109 -4
- package/node_modules/@llblab/pi-telegram/dist/lib/model.js +2 -4
- package/node_modules/@llblab/pi-telegram/dist/lib/status.d.ts +3 -1
- package/node_modules/@llblab/pi-telegram/dist/lib/status.js +31 -1
- package/node_modules/@llblab/pi-telegram/dist/lib/sync.js +4 -4
- package/node_modules/@llblab/pi-telegram/dist/lib/threads.d.ts +1 -0
- package/node_modules/@llblab/pi-telegram/dist/lib/threads.js +17 -4
- package/node_modules/@llblab/pi-telegram/dist/lib/workspace-retirement.d.ts +2 -2
- package/node_modules/@llblab/pi-telegram/dist/lib/workspace-retirement.js +48 -12
- package/node_modules/@llblab/pi-telegram/dist/package.json +1 -1
- package/node_modules/@llblab/pi-telegram/docs/architecture.md +6 -5
- package/node_modules/@llblab/pi-telegram/docs/multi-instance-bus.md +2 -0
- package/node_modules/@llblab/pi-telegram/docs/public-api.md +2 -2
- package/node_modules/@llblab/pi-telegram/docs/ui-style.md +4 -0
- package/node_modules/@llblab/pi-telegram/lib/bindings.ts +17 -10
- package/node_modules/@llblab/pi-telegram/lib/bus-follower.ts +8 -2
- package/node_modules/@llblab/pi-telegram/lib/commands.ts +135 -97
- package/node_modules/@llblab/pi-telegram/lib/extension.ts +25 -0
- package/node_modules/@llblab/pi-telegram/lib/lifecycle.ts +140 -4
- package/node_modules/@llblab/pi-telegram/lib/model.ts +2 -4
- package/node_modules/@llblab/pi-telegram/lib/status.ts +30 -1
- package/node_modules/@llblab/pi-telegram/lib/sync.ts +4 -4
- package/node_modules/@llblab/pi-telegram/lib/threads.ts +21 -3
- package/node_modules/@llblab/pi-telegram/lib/workspace-retirement.ts +46 -13
- package/node_modules/@llblab/pi-telegram/package.json +1 -1
- package/node_modules/jsonc-parser/CHANGELOG.md +76 -0
- package/node_modules/jsonc-parser/LICENSE.md +21 -0
- package/node_modules/jsonc-parser/README.md +364 -0
- package/node_modules/jsonc-parser/SECURITY.md +41 -0
- package/node_modules/jsonc-parser/lib/esm/impl/edit.js +185 -0
- package/node_modules/jsonc-parser/lib/esm/impl/format.js +261 -0
- package/node_modules/jsonc-parser/lib/esm/impl/parser.js +659 -0
- package/node_modules/jsonc-parser/lib/esm/impl/scanner.js +443 -0
- package/node_modules/jsonc-parser/lib/esm/impl/string-intern.js +29 -0
- package/node_modules/jsonc-parser/lib/esm/main.d.ts +351 -0
- package/node_modules/jsonc-parser/lib/esm/main.js +178 -0
- package/node_modules/jsonc-parser/lib/umd/impl/edit.js +201 -0
- package/node_modules/jsonc-parser/lib/umd/impl/format.js +275 -0
- package/node_modules/jsonc-parser/lib/umd/impl/parser.js +682 -0
- package/node_modules/jsonc-parser/lib/umd/impl/scanner.js +456 -0
- package/node_modules/jsonc-parser/lib/umd/impl/string-intern.js +42 -0
- package/node_modules/jsonc-parser/lib/umd/main.d.ts +351 -0
- package/node_modules/jsonc-parser/lib/umd/main.js +194 -0
- package/node_modules/jsonc-parser/package.json +37 -0
- package/package.json +8 -8
|
@@ -21,9 +21,9 @@ Operator commands: `/state-flow-status` inspects; `/state-flow-active` selects s
|
|
|
21
21
|
|
|
22
22
|
| Field | Purpose |
|
|
23
23
|
| --- | --- |
|
|
24
|
-
| `intents` |
|
|
25
|
-
| `contract` | Requirements, decisions, constraints, interfaces |
|
|
26
|
-
| `working` |
|
|
24
|
+
| `intents` | Queue of chosen actions, not possibilities; may own `working`/`lazy` keys |
|
|
25
|
+
| `contract` | Requirements, decisions, rejections, constraints, interfaces |
|
|
26
|
+
| `working` | Temporary context of intents: observations, results, open questions |
|
|
27
27
|
| `artifacts` | Exact source paths, descriptions, compilations |
|
|
28
28
|
| `response` | Previous completed answer; runtime-owned |
|
|
29
29
|
| `lazy` | Durable detail omitted from ordinary context |
|
|
@@ -46,7 +46,7 @@ Example arguments:
|
|
|
46
46
|
{"paths":["cwd.working","session.working"]}
|
|
47
47
|
```
|
|
48
48
|
|
|
49
|
-
Unscoped paths use effective state. `cwd[1].working` reads the preceding causal boundary. Materialized-history and scope patch-history paths such as `cwd.patches[1]` share the configured `historyLimit` bound (default 7) and require actually retained history. Lowering the limit folds excess tails without erasing current state; increasing it does not reconstruct discarded history. Array ranges such as `cwd.lazy.checks[0..3]` exclude the endpoint and require existing elements. Missing paths are unavailable; inspect parent keys only when needed for the task. Missing history is not empty history. Read `lazy` explicitly. Treat structured `$ref` values and `$`-prefixed `read_state` paths inside ordinary strings, such as `$effective.lazy.memory[7]`, as semantic-state references. Other resources retain their native locators. Resolve any reference through the appropriate read/tool only when needed. Neither form proves authority or existence, hydrates, or executes anything. Never scan or resolve references merely to test them. A missing single value path with exact durable sources returns `{value:null, hint:[{type:"dangling-reference", message, paths}]}`. Treat `hint` as top-level diagnostic metadata, never as the requested state: its message is descriptive and conditional; its paths are runtime-verified current reference owners, not verified new locations of the target. The hint proves provenance rather than staleness and is absent when no current durable source matches; keys, patch, and batch reads keep all-or-error behavior. Only then inspect ownership as needed and patch a proven stale owning value while preserving its surrounding meaning. Effective absence, inaccessible external resources, and transient failures are not proof.
|
|
49
|
+
Unscoped paths use effective state. `cwd[1].working` reads the preceding causal boundary. Materialized-history and scope patch-history paths such as `cwd.patches[1]` share the configured `historyLimit` bound (default 7) and require actually retained history. Lowering the limit folds excess tails without erasing current state; increasing it does not reconstruct discarded history. Array ranges such as `cwd.lazy.checks[0..3]` exclude the endpoint and require existing elements. Missing paths are unavailable; inspect parent keys only when needed for the task. Missing history is not empty history. Read `lazy` explicitly. Treat structured `$ref` values and `$`-prefixed `read_state` paths inside ordinary strings, such as `$effective.lazy.memory[7]`, as semantic-state references. Other resources retain their native locators. Resolve any reference through the appropriate read/tool only when needed. Neither form proves authority or existence, hydrates, or executes anything; only intent ownership (see Write) has a deletion consequence. Never scan or resolve references merely to test them. A missing single value path with exact durable sources returns `{value:null, hint:[{type:"dangling-reference", message, paths}]}`. Treat `hint` as top-level diagnostic metadata, never as the requested state: its message is descriptive and conditional; its paths are runtime-verified current reference owners, not verified new locations of the target. The hint proves provenance rather than staleness and is absent when no current durable source matches; keys, patch, and batch reads keep all-or-error behavior. Only then inspect ownership as needed and patch a proven stale owning value while preserving its surrounding meaning. Effective absence, inaccessible external resources, and transient failures are not proof.
|
|
50
50
|
|
|
51
51
|
Missing paths or runtime hints alone do not require historical search. The agent may choose a targeted historical read when a previous value is useful to the current task, without separate user permission. Otherwise continue without searching. Use found values as historical evidence, not automatically as current state; never automatically restore deleted memory. Do not scan all offsets, hydrate automatically or request repair inference. A hint does not prove prior existence, retained history or relocation. A proven stale reference may be repaired within touched work without resurrecting its target. Automatic state and recent-transition projections omit lazy bodies; bounded `lazy_navigation` preserves structure, and explicit current/historical reads still return requested lazy values or patches.
|
|
52
52
|
|
|
@@ -58,12 +58,20 @@ The runtime waits cancelably for publication ownership, then applies authored Gl
|
|
|
58
58
|
|
|
59
59
|
When present, semantic planes `intents`, `contract`, `working`, `artifacts`, and `lazy` are objects; nested lazy values may contain ordinary JSON without stored nulls. Stored checkpoints and patches may omit any documented plane. Current and historical views assemble only known fields present in the selected scopes. Absent fields and empty responses are omitted from views. Checkpoint/tail readers ignore unknown top-level fields, and writers emit only known fields. Nested data within known planes remains intact. Explicit value reads of an absent documented top-level field return `null`. Authored `patch_state` keeps its documented field grammar. Objects merge, arrays/scalars replace, omitted fields persist. Nested `null` removes an owned object key; inherited content may reappear. Canonical `"[N]"` keys patch array elements; indexed deletion is forbidden.
|
|
60
60
|
|
|
61
|
-
|
|
61
|
+
Work from intents. A structured `{"$ref"}` anywhere inside an intent owns ("delete with me") an existing object key under `working` or `lazy` in the same scope; a textual `$path` mention only uses it. Opening a task:
|
|
62
62
|
|
|
63
63
|
```json
|
|
64
|
-
{"session":{"intents":{"check_api":
|
|
64
|
+
{"session":{"intents":{"check_api":{"action":"Verify the API","notes":{"$ref":"session.working.api"},"plan":{"$ref":"session.lazy.api_plan"}}},"working":{"api":"draft findings"},"lazy":{"api_plan":["probe","compare"]}}}
|
|
65
65
|
```
|
|
66
66
|
|
|
67
|
+
Deleting the intent deletes the owned keys after the authored operations, in the same atomic patch, unless another remaining same-scope intent references the target, an ancestor or a descendant. Before closing, move what must survive to an unowned path: results to `working`, `contract` or a broader scope; reasons for abandoned work to `contract` as rejected approaches. Supersede in one patch by deleting the old intent and referencing the same targets from its replacement. Writing to an owned target in the same patch that deletes its intent does not save it: the write is deleted too. Only keys matching `[A-Za-z_$][A-Za-z0-9_$-]*` can be owned. Cross-scope, plane-root, array-element and non-`working`/`lazy` targets are never deleted, nothing is rejected or warned about, and unowned entries remain legal. Illustrative closing, only for an actually completed intent and after satisfying pending acquisitions:
|
|
68
|
+
|
|
69
|
+
```json
|
|
70
|
+
{"session":{"intents":{"check_api":null},"contract":{"api":"verified: v2 only"}}}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Name object keys in ASCII matching `[A-Za-z_$][A-Za-z0-9_$-]*` (for example `api_plan`, not a Cyrillic or spaced key): other keys cannot be addressed by `read_state` paths or `$` references, and cannot be owned by intents. Values may use any language.
|
|
74
|
+
|
|
67
75
|
Never edit backing files, `response`, configuration, provenance, or runtime metadata. Verify changed owner paths when needed; check effective state after override deletion.
|
|
68
76
|
|
|
69
77
|
## Acquire and finish
|
|
@@ -20,9 +20,9 @@ Follow the installed runtime contract. This registered Skill follows its Pi sour
|
|
|
20
20
|
## Reconcile one bounded set
|
|
21
21
|
|
|
22
22
|
1. **Limit the review.** Address the requested scope. A completed phase may motivate recommending cleanup, not starting it without a request. For a whole-state cleanup, inspect global, CWD, and session ownership explicitly; for a narrower request, inspect only affected owners. Use targeted reads for gaps, contradictions, ownership, or verification; do not rerun the project.
|
|
23
|
-
2. **Classify.** Put user requirements and binding confirmed decisions in `contract`, observations, assistant conclusions,
|
|
23
|
+
2. **Classify.** Put user requirements and binding confirmed decisions in `contract`, the queue of chosen actions in `intents`, their temporary context (observations, assistant conclusions, results in progress) in `working`, and inactive reusable detail in `lazy`. Never give an assistant conclusion user authority. Possibilities are not commitments. Name keys in ASCII (`[A-Za-z_$][A-Za-z0-9_$-]*`) so paths, references and ownership resolve; values may use any language. Work from intents: a structured `{"$ref"}` inside an intent owns ("delete with me") a same-scope `working`/`lazy` key; a textual `$path` mention only uses it. Deleting a fulfilled, abandoned, superseded, or impossible intent deletes owned keys no remaining same-scope intent references, so first move what must survive to an unowned path (a write to an owned key in the deleting patch is deleted too): results to `working`, `contract`, or a broader scope; reasons for abandoned work to `contract` as rejected approaches. Supersede in one patch by referencing the same targets from the replacement. Unowned entries remain legal.
|
|
24
24
|
3. **Keep evidence boundaries.** Preserve corrections, prerequisites, bounded negative results, and useful uncertainty. Separate requirements, decisions, observations, conclusions, and hypotheses. Silence is not acceptance; repetition is not verification. One implementation's failure does not reject an approach. Neither freeze provisional methods nor reopen confirmed decisions without grounds.
|
|
25
|
-
4. **Compact for continuation.** Remove duplicates, obsolete progress, unsupported claims, and secrets. Keep sufficient results, real retrieval pointers, pending interaction, and known next checks. Observations are not live external facts. Keep `lazy` shallow and priority-ordered. Recognize optional structured `$ref` values and `$`-prefixed `read_state` paths inside ordinary strings as semantic-state references; other resources retain native locators. No reference form proves authority or existence, authorizes execution, or implies completion. Never scan or resolve references merely to find broken ones. When the bounded review independently needs a reference, a missing single value path with exact durable sources returns `{value:null, hint:[{type:"dangling-reference", message, paths}]}`. Treat the top-level hint as conditional navigation and provenance, never as requested state or proof of staleness; its paths are runtime-verified current reference owners, not verified new locations of the target, while no hint does not prove invention. Inspect ownership only as needed, then patch a proven stale owning value while preserving surrounding meaning. Effective absence or external inaccessibility is insufficient.
|
|
25
|
+
4. **Compact for continuation.** Remove duplicates, obsolete progress, unsupported claims, and secrets. Keep sufficient results, real retrieval pointers, pending interaction, and known next checks. Observations are not live external facts. Keep `lazy` shallow and priority-ordered. Recognize optional structured `$ref` values and `$`-prefixed `read_state` paths inside ordinary strings as semantic-state references; other resources retain native locators. No reference form proves authority or existence, authorizes execution, or implies completion; only intent ownership has a deletion consequence. Never scan or resolve references merely to find broken ones. When the bounded review independently needs a reference, a missing single value path with exact durable sources returns `{value:null, hint:[{type:"dangling-reference", message, paths}]}`. Treat the top-level hint as conditional navigation and provenance, never as requested state or proof of staleness; its paths are runtime-verified current reference owners, not verified new locations of the target, while no hint does not prove invention. Inspect ownership only as needed, then patch a proven stale owning value while preserving surrounding meaning. Effective absence or external inaccessibility is insufficient.
|
|
26
26
|
5. **Check ownership.** Prefer `session` for branch/run continuation, `cwd` for project knowledge, and `global` for established cross-project knowledge. Effective values do not prove ownership; inspect owners before moves. Broader applicability requires evidence.
|
|
27
27
|
|
|
28
28
|
Missing paths or runtime hints alone do not require historical search. The agent may choose a targeted historical read when a previous value is useful to the current task, without separate user permission. Otherwise continue without searching. Use found values as historical evidence, not automatically as current state; never automatically restore deleted memory. Do not scan all offsets, hydrate automatically or request repair inference. A hint does not prove prior existence, retained history or relocation. A proven stale reference may be repaired within touched work without resurrecting its target. Lazy bodies require explicit reads; automatic state/history projections retain navigation without hydrating those bodies.
|
|
@@ -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
|
+
- [ ] `Connect intent across resume` (`post-release acceptance`): The operator approved 0.51.6 release on the successful smoke and green Linux/macOS/Windows CI; this expanded live matrix is not a release blocker. Run live acceptance after rebuilding/reloading: start bare Pi, invoke `/telegram-connect` (default and named profile), immediately `/resume` a session with/without a binding. Check both leader and follower; confirm one connected destination, its correct retained/new slot, no source-target transplant, stale-context error or duplicate notice. Repeat a switch during startup and confirm disconnect cancels it. Native composition, destination-binding, cancellation, and late-completion regressions pass locally. The operator observed one immediate-resume connection complete after a short wait without error; the full profile/role/binding and cancellation matrix remains unverified live.
|
|
5
6
|
- [ ] [`Workspace Thread recovery`](./docs/multi-instance-bus.md) (`environment-gated`): Complete native-Windows coverage for follower restore, inaccessible callbacks, stale targets, and Singleton↔Threaded transitions while preserving accepted work and current ownership.
|
|
6
7
|
- [ ] Select an approved exact-absence observation before implementing ambiguous `deletion-issued` recovery. Never replay an unknown deletion or infer absence from cache, heartbeat silence, empty `editForumTopic`, or `sendChatAction` success.
|
|
7
8
|
- [ ] [`Automatic pairing and follower input custody`](./docs/architecture.md#automatic-pairing-confirmation-design) (`activation-gated`): Keep production custody disabled until historical sources and physical references are reconciled, all legacy writers/consumers are retired or excluded under operator authority, migration is complete, and every participating peer supports the final protocol. Preserve outcome-unknown running work, exact receipt/group authority, authenticated handoff, and rollback/downgrade safety. Then compose the prepared v3 lifecycle/bus ports, add bounded operator disposition for retained legacy retry state, and run real-process plus native-Windows acceptance.
|
|
@@ -4,6 +4,16 @@
|
|
|
4
4
|
|
|
5
5
|
## Unreleased
|
|
6
6
|
|
|
7
|
+
## 0.51.6: Connection resume and Workspace recovery hotfix
|
|
8
|
+
|
|
9
|
+
- `Workspace slot recovery`: Confirmed pressure-retirement deletion invalidates the exact stale active-target record before binding removal. Same-process and successor retries finish a retained `commit-ready` fence without repeating Telegram deletion, preventing exhausted A–Z slots from deadlocking on `protection-changed`. Includes [#305](https://github.com/llblab/pi-telegram/pull/305).
|
|
10
|
+
- `Connect lifecycle`: `/telegram-connect` checks plain session generation before reading Pi context getters after awaited work. Replaced commands cannot publish stale connection notices or retry startup against the old session; config, startup, recovery and takeover confirmation discard obsolete results.
|
|
11
|
+
- `Resume connection`: In-flight `/telegram-connect` or an already connected bridge carries bounded same-process intent into the resumed session, retaining the selected profile but not the source Thread. Startup restores the destination's exact binding or provisions its own slot; cancellation, expiry and late completion cannot revive obsolete work.
|
|
12
|
+
- `Thread binding isolation`: Session-aware startup no longer reuses another session's active target or legacy instance binding. Pending Thread creation records its Workspace binding key; unproven or foreign-session recovery is blocked without consuming evidence or repeating creation.
|
|
13
|
+
- `Connection feedback`: Manual/resumed connection failures use compact cause-and-action notices rather than raw exception guidance. Detailed errors remain in redacted diagnostics; recovery success produces one short notice, and failed disconnect keeps Pi open without a duplicate exception banner. Delayed disconnect completion cannot touch a replaced Pi context.
|
|
14
|
+
- `Model continuation`: In-flight model switching injects one compact line with the resume instruction, selected model and optional thinking level, preserving the control lane and exact reply target.
|
|
15
|
+
- `Lifecycle ownership`: Connect intent and resume scheduling belong to the existing session lifecycle domain; compact failure formatting belongs to status. Transport authority, durable bindings and queue custody keep their existing owners, without introducing a separate connection domain.
|
|
16
|
+
|
|
7
17
|
## 0.51.5: Follower Thread new-session hotfix
|
|
8
18
|
|
|
9
19
|
- `Follower Thread /new`: Telegram `/new` now starts a new session in a follower's Pi process and preserves its Thread binding. The leader publishes and later claims the durable replacement intent through capability-gated, generation-fenced bus requests, validating its own live registration and Workspace binding before accepting the follower's request. Incompatible or stale leaders fail closed rather than silently switching sessions.
|
|
@@ -57,7 +57,7 @@ Paste the bot token. If `~/.pi/agent/telegram.json` already contains a saved tok
|
|
|
57
57
|
/telegram-connect
|
|
58
58
|
```
|
|
59
59
|
|
|
60
|
-
The connected Pi instance owns Telegram polling. Use `/telegram-connect <profile>` to activate a named profile. Each profile is a parallel bot runtime with isolated polling, diagnostics, Threaded Mode state, and local bus transport; the `default` profile keeps unsuffixed runtime paths. In classic mode each profile uses a singleton lock. When Telegram private-chat Threaded Mode is available, one live instance becomes the profile's leader and later visible Pi instances register as followers. Reopening or resuming the same Pi session restores its remembered Thread at session startup
|
|
60
|
+
The connected Pi instance owns Telegram polling. Use `/telegram-connect <profile>` to activate a named profile. Each profile is a parallel bot runtime with isolated polling, diagnostics, Threaded Mode state, and local bus transport; the `default` profile keeps unsuffixed runtime paths. In classic mode each profile uses a singleton lock. When Telegram private-chat Threaded Mode is available, one live instance becomes the profile's leader and later visible Pi instances register as followers. Reopening or resuming the same Pi session restores its remembered Thread at session startup. If `/resume` immediately follows `/telegram-connect`, or the bridge is already connected, connection intent follows the switch: the destination restores its own Thread/slot or receives a new binding, never the source session's Thread. Otherwise, a distinct unbound session still requires explicit `/telegram-connect`.
|
|
61
61
|
|
|
62
62
|
After an unclean computer shutdown, `/telegram-connect` detects truncated or structurally invalid temporary ownership/routing files, quarantines only the damaged files under `tmp/telegram/recovery/`, and retries once. A journal snapshot removed by older broad temp cleanup is rebuilt when its complete segment history proves an empty result, while a revisionless snapshot is repaired from the first surviving segment's exact predecessor when the reconstructed tail validates. Otherwise the snapshot and segments are quarantined as recovery evidence, a fresh journal is published, and startup continues with an informational diagnostic instead of requiring manual JSON repair. Unsupported journal versions block recovery without rewriting or quarantining the retained files; use a compatible runtime rather than deleting journals. Saved `telegram.json` configuration and runtime diagnostics remain intact. Recovery never replaces a verifiable live owner; if safe automatic recovery cannot complete, the command gives one explicit Pi-restart instruction instead of requiring deletion of the whole `tmp/` directory.
|
|
63
63
|
|
|
@@ -194,9 +194,12 @@ interface TelegramCommandsAndToolsBindingDeps {
|
|
|
194
194
|
canSendDirect: () => boolean;
|
|
195
195
|
setGenerativeAppLiveSurfaceRuntime?: (runtime: GenerativeApps.GenerativeAppLiveSurfaceRuntime<GenerativeApps.TelegramBindLiveHandle> | undefined) => void;
|
|
196
196
|
updateStatus: TelegramBridgeStatusUpdater;
|
|
197
|
+
isContextCurrent: (ctx: Pi.ExtensionContext) => boolean;
|
|
198
|
+
getSessionGeneration: () => number;
|
|
199
|
+
connectionIntent: NonNullable<Commands.TelegramBridgeCommandRegistrationDeps["connectionIntent"]>;
|
|
197
200
|
recordRuntimeEvent: TelegramRuntimeEventRecorder;
|
|
198
201
|
}
|
|
199
|
-
export declare function registerTelegramCommandsAndTools({ pi, agentDir, configStore, persistConfig, setup, activeTurnRuntime, lockedPollingRuntime, stopPolling, recoverPollingStart, getDisconnectThreadName, onTransportChanged, getStatusLines, buttonActionStore, sendMarkdownReply, sendChannelMarkdownMessage, sendChannelMediaMessage, listChannelPosts, mutateChannelPost, callMultipart, getDefaultChatId, getDefaultTarget, resolveAgentTarget, routeAgentMessage, canSendDirect, setGenerativeAppLiveSurfaceRuntime, recordRuntimeEvent, updateStatus, }: TelegramCommandsAndToolsBindingDeps): void;
|
|
202
|
+
export declare function registerTelegramCommandsAndTools({ pi, agentDir, configStore, persistConfig, setup, activeTurnRuntime, lockedPollingRuntime, stopPolling, recoverPollingStart, getDisconnectThreadName, onTransportChanged, getStatusLines, buttonActionStore, sendMarkdownReply, sendChannelMarkdownMessage, sendChannelMediaMessage, listChannelPosts, mutateChannelPost, callMultipart, getDefaultChatId, getDefaultTarget, resolveAgentTarget, routeAgentMessage, canSendDirect, setGenerativeAppLiveSurfaceRuntime, recordRuntimeEvent, updateStatus, isContextCurrent, getSessionGeneration, connectionIntent, }: TelegramCommandsAndToolsBindingDeps): void;
|
|
200
203
|
interface TelegramLifecycleBindingDeps {
|
|
201
204
|
pi: Pi.ExtensionAPI;
|
|
202
205
|
publicationRuntime: TelegramBridgePublicationRuntime;
|
|
@@ -323,7 +323,7 @@ export function createTelegramActivityBindingRuntime(deps) {
|
|
|
323
323
|
},
|
|
324
324
|
};
|
|
325
325
|
}
|
|
326
|
-
export function registerTelegramCommandsAndTools({ pi, agentDir, configStore, persistConfig, setup, activeTurnRuntime, lockedPollingRuntime, stopPolling, recoverPollingStart, getDisconnectThreadName, onTransportChanged, getStatusLines, buttonActionStore, sendMarkdownReply, sendChannelMarkdownMessage, sendChannelMediaMessage, listChannelPosts, mutateChannelPost, callMultipart, getDefaultChatId, getDefaultTarget, resolveAgentTarget, routeAgentMessage, canSendDirect, setGenerativeAppLiveSurfaceRuntime, recordRuntimeEvent, updateStatus, }) {
|
|
326
|
+
export function registerTelegramCommandsAndTools({ pi, agentDir, configStore, persistConfig, setup, activeTurnRuntime, lockedPollingRuntime, stopPolling, recoverPollingStart, getDisconnectThreadName, onTransportChanged, getStatusLines, buttonActionStore, sendMarkdownReply, sendChannelMarkdownMessage, sendChannelMediaMessage, listChannelPosts, mutateChannelPost, callMultipart, getDefaultChatId, getDefaultTarget, resolveAgentTarget, routeAgentMessage, canSendDirect, setGenerativeAppLiveSurfaceRuntime, recordRuntimeEvent, updateStatus, isContextCurrent, getSessionGeneration, connectionIntent, }) {
|
|
327
327
|
GenerativeApps.registerTelegramBindTool(pi, {
|
|
328
328
|
agentDir,
|
|
329
329
|
getActiveProfileName: configStore.getActiveProfileName,
|
|
@@ -452,33 +452,35 @@ export function registerTelegramCommandsAndTools({ pi, agentDir, configStore, pe
|
|
|
452
452
|
reloadConfig: configStore.load,
|
|
453
453
|
hasBotToken: configStore.hasBotToken,
|
|
454
454
|
getBotTokenDiagnostic: configStore.getBotTokenDiagnostic,
|
|
455
|
-
startPolling:
|
|
456
|
-
|
|
457
|
-
return await lockedPollingRuntime.start(ctx, options);
|
|
458
|
-
}
|
|
459
|
-
catch (error) {
|
|
460
|
-
recordRuntimeEvent("recovery", error, { phase: "polling-start" });
|
|
461
|
-
throw error;
|
|
462
|
-
}
|
|
463
|
-
},
|
|
455
|
+
startPolling: lockedPollingRuntime.start,
|
|
456
|
+
recordConnectionEvent: (error, phase) => recordRuntimeEvent("connection", error, { phase }),
|
|
464
457
|
stopPolling: stopPolling ?? lockedPollingRuntime.stop,
|
|
465
458
|
recoverPollingStart,
|
|
466
459
|
getDisconnectThreadName,
|
|
467
460
|
queueAgentConnectionContext,
|
|
468
461
|
updateStatus,
|
|
462
|
+
isContextCurrent,
|
|
463
|
+
getSessionGeneration,
|
|
464
|
+
connectionIntent,
|
|
469
465
|
getProfileNames: () => Config.getTelegramProfileNames(configStore.getStoredConfig()),
|
|
470
|
-
activateDefaultProfileConfig: async () => {
|
|
466
|
+
activateDefaultProfileConfig: async (_ctx, isCurrent) => {
|
|
471
467
|
const previousProfileName = configStore.getActiveProfileName();
|
|
472
468
|
await configStore.load();
|
|
469
|
+
if (!isCurrent())
|
|
470
|
+
return;
|
|
473
471
|
if (previousProfileName) {
|
|
474
472
|
await (stopPolling ?? lockedPollingRuntime.stop)();
|
|
473
|
+
if (!isCurrent())
|
|
474
|
+
return;
|
|
475
475
|
}
|
|
476
476
|
configStore.activateProfile(undefined);
|
|
477
477
|
await onTransportChanged?.();
|
|
478
478
|
},
|
|
479
|
-
activateProfileConfig: async (_ctx, profileName) => {
|
|
479
|
+
activateProfileConfig: async (_ctx, profileName, isCurrent) => {
|
|
480
480
|
const previousProfileName = configStore.getActiveProfileName();
|
|
481
481
|
await configStore.load();
|
|
482
|
+
if (!isCurrent())
|
|
483
|
+
return false;
|
|
482
484
|
if (!Config.isValidTelegramProfileName(profileName))
|
|
483
485
|
return false;
|
|
484
486
|
const storedConfig = configStore.getStoredConfig();
|
|
@@ -486,6 +488,8 @@ export function registerTelegramCommandsAndTools({ pi, agentDir, configStore, pe
|
|
|
486
488
|
return false;
|
|
487
489
|
if (previousProfileName !== profileName) {
|
|
488
490
|
await (stopPolling ?? lockedPollingRuntime.stop)();
|
|
491
|
+
if (!isCurrent())
|
|
492
|
+
return false;
|
|
489
493
|
}
|
|
490
494
|
if (!configStore.activateProfile(profileName))
|
|
491
495
|
return false;
|
|
@@ -371,7 +371,7 @@ export declare function createTelegramBusAgentMessageClient(deps: TelegramBusFol
|
|
|
371
371
|
routeMessage: (message: TelegramBusAgentMessage) => Promise<void>;
|
|
372
372
|
};
|
|
373
373
|
export declare function createTelegramBusFollowerApiCaller(deps: TelegramBusFollowerApiCallerDeps): (method: string, args: unknown[]) => Promise<unknown>;
|
|
374
|
-
export declare function createTelegramBusFollowerSessionReplacementSuspender(deps: TelegramBusFollowerSessionReplacementSuspenderDeps): () => Promise<void>;
|
|
374
|
+
export declare function createTelegramBusFollowerSessionReplacementSuspender(deps: TelegramBusFollowerSessionReplacementSuspenderDeps): (preserveTarget?: boolean) => Promise<void>;
|
|
375
375
|
export declare function createTelegramBusFollowerSessionRefreshHook<TContext>(deps: TelegramBusFollowerSessionRefreshHookDeps<TContext>): (_event: unknown, ctx: TContext) => Promise<void>;
|
|
376
376
|
export declare function createTelegramBusFollowerControlState(): TelegramBusFollowerControlState;
|
|
377
377
|
export declare function createTelegramBusFollowerRegistrationState(options?: {
|
|
@@ -519,7 +519,13 @@ function isTelegramStaleContextError(error) {
|
|
|
519
519
|
export function createTelegramBusFollowerSessionReplacementSuspender(deps) {
|
|
520
520
|
const getNowMs = deps.getNowMs ?? Date.now;
|
|
521
521
|
const getPid = deps.getPid ?? (() => process.pid);
|
|
522
|
-
return async () => {
|
|
522
|
+
return async (preserveTarget = true) => {
|
|
523
|
+
if (!preserveTarget) {
|
|
524
|
+
setTelegramFollowerSessionHandoff(undefined);
|
|
525
|
+
Threads.setTelegramLeaderSessionHandoff(undefined);
|
|
526
|
+
await deps.suspendPolling();
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
523
529
|
const target = deps.registrationState.getTarget();
|
|
524
530
|
if (deps.registrationState.isRegistered() && target) {
|
|
525
531
|
setTelegramFollowerSessionHandoff({
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
import { type TelegramConfigStore } from "./config.ts";
|
|
7
7
|
import type * as Pi from "./pi.ts";
|
|
8
8
|
import type { ExtensionAPI, ExtensionCommandContext } from "./pi.ts";
|
|
9
|
-
import type
|
|
9
|
+
import { type TelegramBridgeStatusLineOptions } from "./status.ts";
|
|
10
10
|
import type { TelegramSessionReplacementIntent } from "./threads.ts";
|
|
11
11
|
import { type PendingTelegramControlItem, type TelegramQueueAdmissionReceipt } from "./queue.ts";
|
|
12
12
|
export interface ParsedTelegramCommand {
|
|
@@ -112,12 +112,21 @@ export interface TelegramBridgeCommandRegistrationDeps {
|
|
|
112
112
|
startPolling: (ctx: ExtensionCommandContext, options?: TelegramBridgeCommandStartPollingOptions) => void | Promise<void | TelegramBridgeCommandStartPollingResult> | TelegramBridgeCommandStartPollingResult;
|
|
113
113
|
stopPolling: () => Promise<void | string>;
|
|
114
114
|
recoverPollingStart?: (error: unknown) => Promise<TelegramPollingStartRecoveryResult>;
|
|
115
|
+
recordConnectionEvent?: (error: unknown, phase: string) => void;
|
|
115
116
|
getDisconnectThreadName?: () => string | undefined;
|
|
116
117
|
queueAgentConnectionContext?: (connected: boolean) => void;
|
|
117
118
|
updateStatus: (ctx: ExtensionCommandContext) => void;
|
|
119
|
+
isContextCurrent?: (ctx: ExtensionCommandContext) => boolean;
|
|
120
|
+
getSessionGeneration?: () => number;
|
|
121
|
+
connectionIntent?: {
|
|
122
|
+
begin(cwd: string, profileName?: string): string;
|
|
123
|
+
finish(id: string): void;
|
|
124
|
+
isActive(id: string): boolean;
|
|
125
|
+
cancel(): void;
|
|
126
|
+
};
|
|
118
127
|
getProfileNames?: () => string[];
|
|
119
|
-
activateDefaultProfileConfig?: (ctx: ExtensionCommandContext) => Promise<void>;
|
|
120
|
-
activateProfileConfig?: (ctx: ExtensionCommandContext, profileName: string) => Promise<boolean>;
|
|
128
|
+
activateDefaultProfileConfig?: (ctx: ExtensionCommandContext, isCurrent: () => boolean) => Promise<void>;
|
|
129
|
+
activateProfileConfig?: (ctx: ExtensionCommandContext, profileName: string, isCurrent: () => boolean) => Promise<boolean>;
|
|
121
130
|
}
|
|
122
131
|
export type TelegramThreadDisplayNameRenamePort = (target: {
|
|
123
132
|
chatId: number;
|
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
import { randomUUID } from "node:crypto";
|
|
7
7
|
import { pairTelegramUserIfNeeded, TELEGRAM_DEFAULT_PROFILE_NAME, } from "./config.js";
|
|
8
8
|
import { escapeHtml } from "./rendering.js";
|
|
9
|
+
import { formatTelegramConnectionFailure } from "./status.js";
|
|
9
10
|
import { createTelegramControlItemBuilder, createTelegramControlQueueController, createTelegramQueueAdmissionReceipt, } from "./queue.js";
|
|
10
11
|
const TELEGRAM_EXTENSION_COMMAND_REGISTRY_KEY = "__piTelegramCommandRegistry__";
|
|
11
12
|
const TELEGRAM_BOT_COMMAND_NAME_PATTERN = /^[a-z0-9_]{1,32}$/;
|
|
@@ -270,121 +271,174 @@ export function registerTelegramBridgeCommands(pi, deps) {
|
|
|
270
271
|
pi.registerCommand("telegram-connect", {
|
|
271
272
|
description: "<profile> — Start Telegram bridge",
|
|
272
273
|
handler: async (args, ctx) => {
|
|
274
|
+
const sessionGeneration = deps.getSessionGeneration?.();
|
|
275
|
+
let intentId;
|
|
276
|
+
// Pi context getters throw after replacement; check plain intent/generation first.
|
|
277
|
+
const isCurrent = () => (!intentId || deps.connectionIntent?.isActive(intentId) !== false) &&
|
|
278
|
+
(sessionGeneration === undefined || deps.getSessionGeneration?.() === sessionGeneration) &&
|
|
279
|
+
deps.isContextCurrent?.(ctx) !== false;
|
|
280
|
+
if (!isCurrent())
|
|
281
|
+
return;
|
|
273
282
|
if (args.trim().split(/\s+/).some((word) => /^as=/i.test(word))) {
|
|
274
283
|
ctx.ui.notify("Thread names are configured from Telegram, not from Pi commands.", "warning");
|
|
275
284
|
deps.updateStatus(ctx);
|
|
276
285
|
return;
|
|
277
286
|
}
|
|
278
287
|
const profileName = parseTelegramProfileArg(args);
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
if (
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
if (!deps.hasBotToken()) {
|
|
292
|
-
const botTokenDiagnostic = deps.getBotTokenDiagnostic?.();
|
|
293
|
-
if (botTokenDiagnostic)
|
|
294
|
-
ctx.ui.notify(botTokenDiagnostic, "error");
|
|
295
|
-
const profileNames = deps.getProfileNames?.() ?? [];
|
|
296
|
-
if (!profileName && profileNames.length > 0) {
|
|
297
|
-
ctx.ui.notify(`No default Telegram profile configured. Available profiles: ${profileNames.join(", ")}. Use /telegram-connect <profileName> or /telegram-setup to create a default profile.`, "info");
|
|
298
|
-
deps.updateStatus(ctx);
|
|
299
|
-
return;
|
|
288
|
+
intentId = deps.connectionIntent?.begin(ctx.cwd, profileName);
|
|
289
|
+
try {
|
|
290
|
+
if (profileName && deps.activateProfileConfig) {
|
|
291
|
+
const ok = await deps.activateProfileConfig(ctx, profileName, isCurrent);
|
|
292
|
+
if (!isCurrent())
|
|
293
|
+
return;
|
|
294
|
+
if (!ok) {
|
|
295
|
+
ctx.ui.notify(`Profile "${profileName}" not found.`, "error");
|
|
296
|
+
deps.updateStatus(ctx);
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
299
|
+
ctx.ui.notify(`Activated profile "${profileName}".`, "info");
|
|
300
300
|
}
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
const startWithRecovery = async (options) => {
|
|
306
|
-
try {
|
|
307
|
-
return await deps.startPolling(ctx, options);
|
|
301
|
+
else {
|
|
302
|
+
await (deps.activateDefaultProfileConfig?.(ctx, isCurrent) ?? deps.reloadConfig());
|
|
303
|
+
if (!isCurrent())
|
|
304
|
+
return;
|
|
308
305
|
}
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
306
|
+
if (!deps.hasBotToken()) {
|
|
307
|
+
const botTokenDiagnostic = deps.getBotTokenDiagnostic?.();
|
|
308
|
+
if (botTokenDiagnostic)
|
|
309
|
+
ctx.ui.notify(botTokenDiagnostic, "error");
|
|
310
|
+
const profileNames = deps.getProfileNames?.() ?? [];
|
|
311
|
+
if (!profileName && profileNames.length > 0) {
|
|
312
|
+
ctx.ui.notify(`No default Telegram profile configured. Available profiles: ${profileNames.join(", ")}. Use /telegram-connect <profileName> or /telegram-setup to create a default profile.`, "info");
|
|
313
|
+
deps.updateStatus(ctx);
|
|
314
|
+
return;
|
|
317
315
|
}
|
|
318
|
-
|
|
316
|
+
await deps.promptForConfig(ctx, profileName);
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
let recoveryUsed = false;
|
|
320
|
+
const startWithRecovery = async (options) => {
|
|
319
321
|
try {
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
322
|
+
return await deps.startPolling(ctx, options);
|
|
323
|
+
}
|
|
324
|
+
catch (error) {
|
|
325
|
+
if (!isCurrent())
|
|
326
|
+
return;
|
|
327
|
+
if (!deps.recoverPollingStart || recoveryUsed)
|
|
328
|
+
throw error;
|
|
329
|
+
deps.recordConnectionEvent?.(error, "polling-start");
|
|
330
|
+
const recovery = await deps.recoverPollingStart(error);
|
|
331
|
+
if (!isCurrent())
|
|
332
|
+
return;
|
|
333
|
+
if (recovery.kind === "unhandled")
|
|
334
|
+
throw error;
|
|
335
|
+
if (recovery.kind === "blocked") {
|
|
336
|
+
return { ok: false, message: recovery.message,
|
|
337
|
+
notice: "Telegram recovery blocked. Check /telegram-status --debug." };
|
|
338
|
+
}
|
|
339
|
+
recoveryUsed = true;
|
|
340
|
+
deps.recordConnectionEvent?.(recovery.message, "recovery");
|
|
341
|
+
try {
|
|
342
|
+
const retry = await deps.startPolling(ctx, options);
|
|
343
|
+
if (!isCurrent())
|
|
344
|
+
return;
|
|
345
|
+
if (!retry)
|
|
346
|
+
return { ok: true, message: "Telegram bridge connected; temporary state recovered." };
|
|
347
|
+
return {
|
|
348
|
+
...retry,
|
|
349
|
+
message: retry.ok
|
|
350
|
+
? "Telegram bridge connected; temporary state recovered."
|
|
351
|
+
: retry.message,
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
catch (error) {
|
|
355
|
+
if (!isCurrent())
|
|
356
|
+
return;
|
|
357
|
+
deps.recordConnectionEvent?.(error, "recovery-retry");
|
|
358
|
+
return {
|
|
359
|
+
ok: false,
|
|
360
|
+
notice: "Telegram recovery failed. Restart this Pi instance.",
|
|
361
|
+
};
|
|
323
362
|
}
|
|
324
|
-
return {
|
|
325
|
-
...retry,
|
|
326
|
-
message: retry.ok
|
|
327
|
-
? `${recovery.message} ${retry.message ?? "Telegram bridge connected."}`
|
|
328
|
-
: retry.message,
|
|
329
|
-
};
|
|
330
363
|
}
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
364
|
+
};
|
|
365
|
+
let result = await startWithRecovery({ forceFreshLeaderThread: true });
|
|
366
|
+
if (!isCurrent())
|
|
367
|
+
return;
|
|
368
|
+
if (result && !result.ok && result.canTakeover) {
|
|
369
|
+
const confirmed = await ctx.ui.confirm(formatTelegramTakeoverTitle(ctx), formatTelegramTakeoverPrompt(ctx, result.owner));
|
|
370
|
+
if (!isCurrent())
|
|
371
|
+
return;
|
|
372
|
+
if (!confirmed) {
|
|
373
|
+
ctx.ui.notify("Telegram bridge takeover cancelled.", "info");
|
|
374
|
+
deps.updateStatus(ctx);
|
|
375
|
+
return;
|
|
336
376
|
}
|
|
377
|
+
result = await startWithRecovery({ force: true, forceFreshLeaderThread: true });
|
|
378
|
+
if (!isCurrent())
|
|
379
|
+
return;
|
|
337
380
|
}
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
if (result && !result.ok && result.canTakeover) {
|
|
343
|
-
const confirmed = await ctx.ui.confirm(formatTelegramTakeoverTitle(ctx), formatTelegramTakeoverPrompt(ctx, result.owner));
|
|
344
|
-
if (!confirmed) {
|
|
345
|
-
ctx.ui.notify("Telegram bridge takeover cancelled.", "info");
|
|
346
|
-
deps.updateStatus(ctx);
|
|
347
|
-
return;
|
|
381
|
+
if (result && !result.ok) {
|
|
382
|
+
if (result.message)
|
|
383
|
+
deps.recordConnectionEvent?.(result.message, "connect-refused");
|
|
384
|
+
ctx.ui.notify(result.notice ?? formatTelegramConnectionFailure(result.message), "warning");
|
|
348
385
|
}
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
386
|
+
else if (result?.message) {
|
|
387
|
+
ctx.ui.notify(result.message, "info");
|
|
388
|
+
}
|
|
389
|
+
if (!result || result.ok)
|
|
390
|
+
deps.queueAgentConnectionContext?.(true);
|
|
391
|
+
deps.updateStatus(ctx);
|
|
353
392
|
}
|
|
354
|
-
|
|
355
|
-
|
|
393
|
+
catch (error) {
|
|
394
|
+
if (!isCurrent())
|
|
395
|
+
return;
|
|
396
|
+
deps.recordConnectionEvent?.(error, "connect");
|
|
397
|
+
ctx.ui.notify(formatTelegramConnectionFailure(error), "warning");
|
|
398
|
+
deps.updateStatus(ctx);
|
|
356
399
|
}
|
|
357
|
-
|
|
358
|
-
|
|
400
|
+
finally {
|
|
401
|
+
if (intentId)
|
|
402
|
+
deps.connectionIntent?.finish(intentId);
|
|
359
403
|
}
|
|
360
|
-
deps.updateStatus(ctx);
|
|
361
404
|
},
|
|
362
405
|
});
|
|
363
406
|
pi.registerCommand("telegram-disconnect", {
|
|
364
407
|
description: "Stop Telegram and delete current thread in Threaded Mode",
|
|
365
408
|
handler: async (_args, ctx) => {
|
|
366
|
-
const
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
return;
|
|
373
|
-
}
|
|
374
|
-
}
|
|
409
|
+
const generation = deps.getSessionGeneration?.();
|
|
410
|
+
const isCurrent = () => (generation === undefined || deps.getSessionGeneration?.() === generation) &&
|
|
411
|
+
deps.isContextCurrent?.(ctx) !== false;
|
|
412
|
+
if (!isCurrent())
|
|
413
|
+
return;
|
|
414
|
+
deps.connectionIntent?.cancel();
|
|
375
415
|
try {
|
|
416
|
+
const threadName = deps.getDisconnectThreadName?.();
|
|
417
|
+
if (threadName) {
|
|
418
|
+
const confirmed = await ctx.ui.confirm(ctx.ui.theme.fg("accent", "pi-telegram"), `Delete Telegram thread ${ctx.ui.theme.fg("warning", threadName)} and disconnect this Pi session?`);
|
|
419
|
+
if (!isCurrent())
|
|
420
|
+
return;
|
|
421
|
+
if (!confirmed) {
|
|
422
|
+
ctx.ui.notify("Telegram disconnect cancelled.", "info");
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
}
|
|
376
426
|
const message = await deps.stopPolling();
|
|
427
|
+
if (!isCurrent())
|
|
428
|
+
return;
|
|
377
429
|
if (message)
|
|
378
430
|
ctx.ui.notify(message, "info");
|
|
379
431
|
deps.queueAgentConnectionContext?.(false);
|
|
380
432
|
}
|
|
381
433
|
catch (error) {
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
434
|
+
deps.recordConnectionEvent?.(error, "disconnect");
|
|
435
|
+
if (!isCurrent())
|
|
436
|
+
return;
|
|
437
|
+
ctx.ui.notify("Telegram disconnect incomplete; keep Pi open. Check /telegram-status --debug.", "warning");
|
|
385
438
|
}
|
|
386
439
|
finally {
|
|
387
|
-
|
|
440
|
+
if (isCurrent())
|
|
441
|
+
deps.updateStatus(ctx);
|
|
388
442
|
}
|
|
389
443
|
},
|
|
390
444
|
});
|
|
@@ -1361,6 +1361,28 @@ export default function (pi) {
|
|
|
1361
1361
|
resolveAutomaticThreadCleanupEnabled: configControls.resolveAutomaticThreadCleanupEnabled,
|
|
1362
1362
|
runWorkspaceOperation: telegramWorkspaceOperationRuntime.run,
|
|
1363
1363
|
});
|
|
1364
|
+
const connectionIntent = Lifecycle.createTelegramConnectionIntentRuntime();
|
|
1365
|
+
const connectionLifecycle = Lifecycle.createTelegramConnectionLifecycle({
|
|
1366
|
+
intent: connectionIntent,
|
|
1367
|
+
getGeneration: telegramSessionContextStore.getGeneration,
|
|
1368
|
+
isCurrent: telegramSessionContextStore.isCurrent,
|
|
1369
|
+
getProfileName: configStore.getActiveProfileName,
|
|
1370
|
+
isConnected() {
|
|
1371
|
+
return lockRuntime.owns() || telegramBusFollowerRegistrationState.isRegistered();
|
|
1372
|
+
},
|
|
1373
|
+
async activateProfile(profileName, isCurrent) {
|
|
1374
|
+
await configStore.load();
|
|
1375
|
+
if (!isCurrent())
|
|
1376
|
+
return false;
|
|
1377
|
+
return configStore.activateProfile(profileName) && configStore.hasBotToken();
|
|
1378
|
+
},
|
|
1379
|
+
start(ctx) {
|
|
1380
|
+
return lockedPollingRuntime.start(ctx);
|
|
1381
|
+
},
|
|
1382
|
+
recordError(error) {
|
|
1383
|
+
recordRuntimeEvent("connection", error, { phase: "resume-connect" });
|
|
1384
|
+
},
|
|
1385
|
+
});
|
|
1364
1386
|
const telegramBridgeSessionLifecycleDeps = Lifecycle.createTelegramBridgeSessionLifecycleDeps({
|
|
1365
1387
|
contextStore: telegramSessionContextStore,
|
|
1366
1388
|
queue: {
|
|
@@ -1408,6 +1430,7 @@ export default function (pi) {
|
|
|
1408
1430
|
},
|
|
1409
1431
|
delivery: deliveryLifecycleRuntime,
|
|
1410
1432
|
polling: lockedPollingRuntime,
|
|
1433
|
+
connection: connectionLifecycle,
|
|
1411
1434
|
inboundWorker: {
|
|
1412
1435
|
onSessionShutdown: updateAdmissionRuntimeBinding.onSessionShutdown,
|
|
1413
1436
|
},
|
|
@@ -1536,6 +1559,9 @@ export default function (pi) {
|
|
|
1536
1559
|
modelContextAvailabilityRuntime.reconcile();
|
|
1537
1560
|
},
|
|
1538
1561
|
getStatusLines,
|
|
1562
|
+
isContextCurrent: telegramSessionContextStore.isCurrent,
|
|
1563
|
+
getSessionGeneration: telegramSessionContextStore.getGeneration,
|
|
1564
|
+
connectionIntent,
|
|
1539
1565
|
buttonActionStore,
|
|
1540
1566
|
sendMarkdownReply,
|
|
1541
1567
|
async sendChannelMarkdownMessage(channel, markdown, options) {
|