@llblab/pi-state-flow 0.8.0 โ 0.9.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/AGENTS.md +4 -4
- package/BACKLOG.md +7 -0
- package/CHANGELOG.md +10 -0
- package/README.md +4 -2
- package/docs/architecture.md +5 -3
- package/docs/temporal-acceptance.md +2 -2
- package/index.ts +22 -1
- package/lib/context.ts +1 -1
- package/lib/extension.ts +248 -144
- package/lib/telegram.ts +267 -0
- package/lib/terminal.ts +1 -1
- package/package.json +1 -1
package/AGENTS.md
CHANGED
|
@@ -24,15 +24,15 @@
|
|
|
24
24
|
- Bind every loaded scope and active Pi branch/checkpoint to the corresponding State Flow Git revision. Resume and tree restoration must recover branch-correct runtime config and semantic layers from that revision without blindly importing Git `HEAD`; reading an older revision must use object-level Git reads and never reset or check out the shared repository worktree.
|
|
25
25
|
- Every accepted semantic change, including session-only and response-only changes, atomically updates affected checkpoint/tail pairs and temporal metadata and creates one immediate local Git commit when Git is available; each commit stages the complete non-ignored worktree delta (`git add -A` semantics, including manual deletions) before overlaying exact prepared State Flow outputs, respects `.gitignore`, keeps State Flow-owned active files under compare-and-swap protection, and synchronizes the caller-visible index to the committed tree. `remotePublication` is branch runtime policy: `turn-end` queues only the newest accepted target for asynchronous non-interactive push, `off` remains local-only, and `transition` preserves synchronous legacy behavior. Queue state is operational metadata beneath the Git common directory, not semantic history; use exact targets, destination identity, symlink-safe atomic CAS, descendant-only coalescing, cross-process worker leases, restart recovery, and truthful failure diagnostics. Remote failure never rolls back accepted state or regenerates an answer. A repository with no remote is intentionally local-only; only Git executable `ENOENT` authorizes file-only mode.
|
|
26
26
|
- Register `patch_state` as the sole model-authored semantic mutation protocol. It accepts optional fixed `global`, `cwd`, and `session` semantic patches plus optional `final:true`; require at least one scope or `final:true`, reject unknown fields, `final:false`, empty supplied scopes, material no-ops, and the retired `{scope, patch}` / `unchanged` grammar. Validate every supplied scope against one causal basis and publish it all-or-nothing with one identity, temporal boundary, and durable cohort. Never accept model-authored `response`.
|
|
27
|
-
- Treat every semantic `patch_state` as a strict inference barrier. Give it sequential execution mode, inspect Pi's synchronized current assistant message during tool preflight, require exactly one `patch_state` call in that response, and block every sibling tool call before execution. Every enabled iteration begins terminal-ineligible; only a successful call containing `final:true` latches eligibility for the next accepted `turn_end`, without stopping later reasoning, tools, or patches. If
|
|
28
|
-
- Reconcile `response` only from the actually accepted ordinary assistant answer at `turn_end`; it remains runtime-owned. State Flow has no terminal HTML-comment mutation protocol and does not parse generic service comments.
|
|
27
|
+
- Treat every semantic `patch_state` as a strict inference barrier. Give it sequential execution mode, inspect Pi's synchronized current assistant message during tool preflight, require exactly one `patch_state` call in that response, and block every sibling tool call before execution. Every enabled iteration begins terminal-ineligible; only a successful call containing `final:true` latches eligibility for the next accepted `turn_end`, without stopping later reasoning, tools, or patches. If a terminal draft ends before eligibility, preserve it as the runtime-owned response at that `turn_end` and start at most two same-run fallback turns whose only purpose is the `final:true` patch; an eligible draft whose final validation fails after a later acquisition follows the same path. Fallback turns never enter `response`, and their only instruction is to apply `patch_state` with any durable changes and `final:true`, or `{final:true}` alone. A successful fallback closes resolution with the preserved answer intact; two failed fallbacks close the iteration with the preserved answer and current state plus one bounded warning and a finalization diagnostic. Failed patch calls do not consume fallback turns. A subsequent legal patch remains possible, and only an accepted ordinary answer is reconciled.
|
|
28
|
+
- Reconcile `response` only from the actually accepted ordinary assistant answer at `turn_end`; it remains runtime-owned. State Flow has no terminal HTML-comment mutation protocol and does not parse generic service comments. The first terminal draft that cannot be reconciled is preserved as the iteration response rather than discarded; fallback turns during pending resolution never reach `response`. Other extensions retain ownership of their own comments and output handling.
|
|
29
29
|
- Treat terminal state as a decision-relevant handoff, not narration: retain source-addressed reusable operational knowledge in `artifacts`; compile stable requirements, confirmed decisions, rejected approaches, and interface commitments into `contract`; retain observations, validation, failures, current domain state, unresolved work, interaction consequences, and exact continuation in `working`. Preserve relevant completed prerequisites and verified outcomes while removing obsolete progress narration; reconcile only information affected by the run and relevant existing commitments, not every scope or repository surface.
|
|
30
30
|
- Preserve active constraints, unresolved questions, consequential negative results, and the next discriminating check before compression. Distinguish observations, user requirements, assistant decisions, and hypotheses; do not promote assistant conclusions to user requirements. Retain useful source locators and validity conditions for consequential facts without mandatory per-value metadata. Keep rejection reasons and reconsideration conditions. Reconcile contradictions through evidence or user clarification instead of silently overwriting established constraints or observations; retain unresolved conflicts and decision-relevant hypotheses as uncertain. These are protocol obligations, not deterministic semantic validation gates.
|
|
31
31
|
- Treat `working` as last observations, not a live workspace. Revalidate volatile facts before consequential actions; after interruption or branch navigation inspect relevant external effects before repeating operations. Failed state commits and restored memory do not undo tool effects. Missing evidence proves neither success nor absence of effects: retain uncertainty and the next check. Keep revalidation targeted, without action ledgers or runtime freshness/rollback guarantees.
|
|
32
32
|
- Treat each successful `SKILL.md` read as CWD artifact acquisition using the finalized tool-execution arguments after mutable interception: require a non-empty compiler output in the next `patch_state` call under `cwd.artifacts[exactReadPath]` with `description`, `kind: "skill"`, and a flexible non-empty `compilation` object; hash the executed source bytes and record runtime-owned `sourceHash` plus `skill-artifact-v1` `compilerRevision` in the CWD provenance registry; reject missing, unhashable, malformed, or forged freshness data; replace the complete prior Skill artifact and its provenance entry on refresh so obsolete evidence cannot survive. `contract.compiled_skills` is retired and rejected; migrate useful legacy entries into artifacts while preserving behavior and marking fallback hashes unverified when the source is unavailable.
|
|
33
33
|
- Make the model audit and optimize complete state at every handoff: reorganize inefficient structure, merge fragmented facts, compress history into conclusions, and delete stale, completed, redundant, or low-value keys while preserving active commitments and evidence.
|
|
34
34
|
- Accept omitted semantic fields inside each supplied scope patch, but reject empty supplied scopes; when no state change is needed require explicit `{final:true}` without inventing bookkeeping. This final-only call changes only ephemeral terminal eligibility and creates no semantic transition, identity, temporal step, or Git commit. Always require an accepted non-empty answer, which runtime owns as session `response`. A changed response is a semantic transition; identical complete semantic state finalizes lifecycle without a patch, identity, or temporal step. Semantic usefulness and optimization remain protocol-owned because deterministic validation cannot prove them.
|
|
35
|
-
- Agent-level opt-in `logging` appends local JSONL diagnostics for rejected `patch_state` attempts and
|
|
35
|
+
- Agent-level opt-in `logging` appends local JSONL diagnostics for rejected `patch_state` attempts and preserved drafts plus fallback turns while turn resolution remains pending. Every rejected call retains its exact attempted arguments plus the precise error and, when available, tool identity, call id, resolution attempt, and terminal-eligibility state; successful patches are never logged. Preserve exact text blocks only where useful, reduce other blocks to structural identity, never duplicate reasoning bodies, and keep logging outside semantic state, scope metadata, checkpoints, and publication. Logging failure emits at most one warning and never changes resolution, enablement, or accepted state.
|
|
36
36
|
- Recursively materialize patches immediately; empty objects preserve, nested object-key `null` deletes, and `null` anywhere in semantic state including arrays is invalid. This prohibition does not apply to runtime envelopes such as an origin's null parent. Persist runtime-normalized replay patches that exactly reproduce accepted state, including complete artifact replacement; runtime-owned provenance is stored in scope `meta.json` and is not part of semantic replay.
|
|
37
37
|
- Do not impose project schemas, state or patch byte caps, dynamic growth pressure, observation envelopes, action authorization, action ledgers, or state-size limits.
|
|
38
38
|
- Rotate the turn-stable specification on every user-initiated run, while runtime-triggered turn-resolution continuation remains inside that same run. Keep user-controlled specification text at user authority: never interpolate it into the system prompt; repeat it only in synthetic user runtime context. Treat materialized state in that message as fallible assistant-produced data whose transport role does not elevate it into user instructions.
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
- `/state-flow-stop` must persist only the current session/branch's `config.enabled = false` and necessary runtime provenance, preserving all semantic checkpoints/tails and creating no semantic transition. It must retain a same-physical-session bounded passive context handoff across reload, resume, and tree restoration so disabling semantics never re-exposes pre-stop raw history. Active restart replaces passive mode but uses that bounded boundary for its one migration run; new and forked physical sessions inherit neither projection. It does not rewrite agent-level `autoStart` or change its policy for future new sessions.
|
|
44
44
|
- Keep the injected runtime protocol compact and normative; put rationale and extended explanation in README rather than the model prompt. Never parse or strip State Flow HTML comments; they are ordinary historical text, while foreign comment handling remains owned by other extensions.
|
|
45
45
|
- Do not claim strict boundedness for state, the current run trajectory, the turn specification, or the external full trace.
|
|
46
|
-
- Remain extension-agnostic:
|
|
46
|
+
- Remain extension-agnostic in core semantics, storage, and inference: core modules never import, name, special-case, or encode policy for another extension or transport. One optional leaf presentation adapter (`lib/telegram.ts`) may import public `pi-telegram` membranes to mirror status and expose the same start/stop affordances already owned by `state-flow-start` and `state-flow-stop`; it must fail open when the transport is absent or its registry is unready and must never alter core behavior.
|
|
47
47
|
- Activate State Flow model tools only while enabled on the selected branch; preserve every unrelated active tool when toggling them. Keep mutation confined to `patch_state` and historical observation read-only.
|
|
48
48
|
- Keep `.github/workflows/release.yml` as the sole version-tag release owner: it validates immutable tag identity, publishes through npm Trusted Publisher with provenance, verifies the public package, and only then creates the GitHub Release. Keep package, lockfile, tag, and changelog versions aligned; never add a long-lived npm token fallback.
|
|
49
49
|
- Run `npm run validate` after retained code changes.
|
package/BACKLOG.md
CHANGED
|
@@ -2,6 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
Completed release work belongs in [CHANGELOG.md](CHANGELOG.md). No implementation item remains open for 0.8.0.
|
|
4
4
|
|
|
5
|
+
## Candidate evolution
|
|
6
|
+
|
|
7
|
+
- [ ] **Read-only global bootstrap layer:** Project the existing global materialization into enabled and non-enabled sessions by default, so even one-shot work starts carrying established cross-project facts, preferences, routing, and conventions. The global scope is the highest-value, lowest-cost half of the memory, while writing carries the protocol and curation tax; making the read side unconditional gives continuity without enabling mutation.
|
|
8
|
+
- Boundary: project the existing durable global materialization only. No writes, transitions, patches, barriers, session/CWD initialization, or temporal-history changes. Model tools and the full protocol remain opt-in behind explicit start, and the bootstrap adds no second semantic mode.
|
|
9
|
+
- Open questions: whether deferred Markdown freshness discovery must run ahead of the first inference, token cost of a stable global prefix, behavior under untrusted project contexts, and naming distinct from the existing bootstrap-run concept.
|
|
10
|
+
- Status: candidate, not scheduled. Do not start without a dedicated release contract.
|
|
11
|
+
|
|
5
12
|
## Deferred host integration
|
|
6
13
|
|
|
7
14
|
- [ ] **Native default session continuation:** Integrate the existing read-only recommendation, exact-selection, and rehydration contracts before Pi creates `SessionManager`, while preserving explicit new/resume and native-picker precedence, truthful notices, and cross-process session ownership. Pi 0.84.4 exposes no suitable pre-session resolver hook, so this requires upstream support or an SDK/launcher integration. Reverify the host API before taking the item; it is not a release dependency.
|
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,16 @@
|
|
|
2
2
|
|
|
3
3
|
> Each release keeps at most 8 outcome records of at most 512 characters.
|
|
4
4
|
|
|
5
|
+
## 0.9.0: Telegram status surface
|
|
6
|
+
|
|
7
|
+
- `Interop`: Added an optional fail-open `pi-telegram` presentation adapter. With the transport installed, the status screen shows `State Flow: on ยท step #N` while enabled, and the inline main menu places a `๐ State Flow: #N` or `โซ๏ธ State Flow: off` section button directly before Settings.
|
|
8
|
+
- `Control`: The section submenu exposes the branch lifecycle already owned by the commands: Start, Stop, Refresh, and Cancel start while a start deferred behind an active run is pending. A busy start waits for the current run to settle, Stop applies immediately, and the adapter calls the same start/stop functions as `/state-flow-start` and `/state-flow-stop`.
|
|
9
|
+
- `Compatibility`: Registration fails open when pi-telegram is absent or its section registry is not ready, retries on session start, and disposes on session shutdown. Core semantics, storage, inference, and hosts without pi-telegram are unchanged.
|
|
10
|
+
|
|
11
|
+
## 0.8.1: Preserved answers and bounded fallback resolution
|
|
12
|
+
|
|
13
|
+
- `Resolution`: A terminal draft is never discarded. A draft ending before eligibility โ or an eligible draft whose final validation fails for a later acquisition โ is preserved as the runtime-owned response at `turn_end`, then at most two same-run fallback turns exist only to obtain the `final:true` patch. Fallback turns never enter `response`; success commits their patches with the preserved answer intact, and exhaustion closes the iteration with the preserved answer, current state, one bounded warning, and a finalization diagnostic.
|
|
14
|
+
|
|
5
15
|
## 0.8.0: Atomic cohorts and final eligibility
|
|
6
16
|
|
|
7
17
|
- `Protocol`: Replaced the single-scope PATCH and UNCHANGED forms with one canonical `patch_state({global?, cwd?, session?, final?})` call. Supplied scopes validate against one causal basis and publish as one atomic transition with a single identity, temporal boundary, durable cohort, and inference barrier; unknown fields, `final:false`, empty scopes, and material no-ops fail closed.
|
package/README.md
CHANGED
|
@@ -66,6 +66,8 @@ Stopping changes the current session/branch configuration, preserves semantic ch
|
|
|
66
66
|
|
|
67
67
|
The compact status is an accent `state-flow` and dim `#<step>`. Detailed status distinguishes runtime config/meta from semantic materialization, reports scope keys, the selected temporal head and runtime revision, available hot offsets, per-scope retained patch tails, artifact counts, stale Markdown reasons, and pending publication. Retained tails may include inherited pre-origin records, so their counts are not active history depth. It labels global/CWD/session/effective state without dumping source bodies. Failed inspection means unavailable evidence, never a falsely clean count.
|
|
68
68
|
|
|
69
|
+
When the optional `pi-telegram` extension is installed, State Flow mirrors the same identity there: the Status screen shows `State Flow: on ยท step #N` while enabled, and the inline main menu places a `๐ State Flow: #N` or `โซ๏ธ State Flow: off` section button directly before Settings. The button opens a compact control submenu for the current session branch: `Start` or `Stop`, `Refresh`, and `Cancel start` while a start deferred behind an active run is pending. Starting while a run is active waits for that run to settle; stopping applies immediately. Registration fails open when the transport is absent, retries when the section registry becomes ready, and disposes on session shutdown; the `/state-flow-*` commands remain the authority and nothing changes for hosts without `pi-telegram`.
|
|
70
|
+
|
|
69
71
|
## State, scope, and time
|
|
70
72
|
|
|
71
73
|
Every scope has exactly the same semantic shape:
|
|
@@ -219,7 +221,7 @@ patch_state({...?, final:true}) โ atomic accepted state + terminal eligibility
|
|
|
219
221
|
patch_state({final:true}) โ terminal eligibility only, with no semantic transition
|
|
220
222
|
```
|
|
221
223
|
|
|
222
|
-
Every enabled iteration begins terminal-ineligible. `final:true` latches eligibility for the next accepted `turn_end`; it does not terminate the turn, stop tools or reasoning, freeze state, or prevent later `patch_state` calls.
|
|
224
|
+
Every enabled iteration begins terminal-ineligible. `final:true` latches eligibility for the next accepted `turn_end`; it does not terminate the turn, stop tools or reasoning, freeze state, or prevent later `patch_state` calls. A terminal draft that ends before eligibility, or an eligible draft whose final validation fails after a later acquisition, is preserved: it is reconciled as the runtime-owned `response` at that `turn_end` instead of being discarded, and State Flow starts at most two same-run fallback turns whose only purpose is to obtain the `final:true` patch. Fallback turns are never the response. A successful `final:true` during a fallback commits its patches and closes resolution with the preserved answer intact; when both fallbacks pass without it, the iteration closes with the preserved answer and current state, plus one bounded warning and a finalization diagnostic. Failed patch calls do not consume fallback turns. Only an accepted answer reaches `response`; aborted, length-limited, and provider-error endings never do.
|
|
223
225
|
|
|
224
226
|
A semantic patch remains an inference barrier. The complete scope cohort is validated, durably accepted, and rematerialized before further reasoning. Empty supplied scopes and materially no-op scope cohorts are rejected; omit unchanged scopes and use `{final:true}` alone when no semantic update is needed. `response` is never accepted from the model. The final answer is ordinary assistant output, not a state transport. State Flow has no terminal `state_flow` HTML-comment protocol and does not parse generic service comments. Historical `state_flow` text is ordinary text. Other extensions retain ownership of their own comments such as `telegram_button`. Never put secrets in state.
|
|
225
227
|
|
|
@@ -294,7 +296,7 @@ npm install
|
|
|
294
296
|
npm run validate
|
|
295
297
|
```
|
|
296
298
|
|
|
297
|
-
Validation runs TypeScript checks, automated tests, and an import smoke check. Temporal algebra tests compare all available offsets with independently retained test snapshots through dense/sparse repeated folding, shared transitions, deletion overlays, no-ops, and forks. Temporary-repository tests also cover explicit migration, ten committed sparse transitions with folding and all hot offsets, cold Git scope recovery, and historical symlink rejection. Storage-level tests also prove atomic runtime/semantic publication, config-only stop without semantic history, runtime identity and lineage validation, self-reference resolution across unrelated commits, and exact accepted-commit retry. Real Pi tests also exercise configured automatic activation, deferred source discovery, strict draft โ resolution โ accepted-answer continuation, temporal barriers and next-inference state, lazy runtime offset-one reads, unchanged shared-stream inheritance, old-branch stop/resume, and bounded passive stop/restart projection. The complete twenty-case temporal acceptance audit is documented in the property map; the canonical backlog identifies any subsequent open work.
|
|
299
|
+
Validation runs TypeScript checks, automated tests, and an import smoke check. Temporal algebra tests compare all available offsets with independently retained test snapshots through dense/sparse repeated folding, shared transitions, deletion overlays, no-ops, and forks. Temporary-repository tests also cover explicit migration, ten committed sparse transitions with folding and all hot offsets, cold Git scope recovery, and historical symlink rejection. Storage-level tests also prove atomic runtime/semantic publication, config-only stop without semantic history, runtime identity and lineage validation, self-reference resolution across unrelated commits, and exact accepted-commit retry. Real Pi tests also exercise configured automatic activation, deferred source discovery, strict draft โ preserved answer and fallback resolution โ accepted-answer continuation, temporal barriers and next-inference state, lazy runtime offset-one reads, unchanged shared-stream inheritance, old-branch stop/resume, and bounded passive stop/restart projection. The complete twenty-case temporal acceptance audit is documented in the property map; the canonical backlog identifies any subsequent open work.
|
|
298
300
|
|
|
299
301
|
- [Canonical open work](BACKLOG.md)
|
|
300
302
|
- [Delivery history](CHANGELOG.md)
|
package/docs/architecture.md
CHANGED
|
@@ -19,7 +19,7 @@ The extension owns durable memory while enabled. Global semantic memory is alway
|
|
|
19
19
|
- `memory`: external promotion records and memory diagnostics.
|
|
20
20
|
- `continuation`: native-header discovery, runtime-provenance inspection, deterministic recommendation, and host startup precedence.
|
|
21
21
|
- `publication`: remote policy, durable CAS queue/store, cross-process leases, and asynchronous worker lifecycle.
|
|
22
|
-
- `status`, `extension`: operator projection and Pi adapter wiring.
|
|
22
|
+
- `status`, `telegram`, `extension`: operator projection, the optional fail-open pi-telegram presentation adapter, and Pi adapter wiring.
|
|
23
23
|
|
|
24
24
|
## Semantic state
|
|
25
25
|
|
|
@@ -71,7 +71,7 @@ A final-only `patch_state({"final":true})` call changes only ephemeral terminal
|
|
|
71
71
|
|
|
72
72
|
`read_state` reads one cached effective or scoped projection at offsets zero through seven. It never publishes or advances history.
|
|
73
73
|
|
|
74
|
-
Every enabled assistant iteration starts terminal-ineligible. Only a successful `patch_state` call containing `final:true` latches eligibility for the next accepted `turn_end`; the call may atomically include global, CWD, and session patches. Eligibility does not stop later reasoning, tools, or patches. If terminal prose arrives before eligibility, State Flow
|
|
74
|
+
Every enabled assistant iteration starts terminal-ineligible. Only a successful `patch_state` call containing `final:true` latches eligibility for the next accepted `turn_end`; the call may atomically include global, CWD, and session patches. Eligibility does not stop later reasoning, tools, or patches. If terminal prose arrives before eligibility, State Flow preserves that draft and reconciles it into runtime-owned `response` at `turn_end`, then starts at most two same-run fallback turns whose only purpose is the `final:true` patch. The same path covers an eligible draft whose final validation fails after a later acquisition. Fallback turns never become the response: a successful `final:true` commits its patches and closes resolution with the preserved answer intact, while two failed fallbacks close the iteration with the preserved answer and current state plus one bounded warning and a finalization diagnostic. Failed patch calls do not consume the budget. A following legal patch remains possible, and only an accepted ordinary answer is reconciled into runtime-owned `response` at `turn_end`. State Flow no longer parses `state_flow` or generic HTML comments; historical comments are ordinary text and other extensions retain their own comment handling.
|
|
75
75
|
|
|
76
76
|
## Lifecycle planes
|
|
77
77
|
|
|
@@ -199,7 +199,9 @@ Unknown keys fail loading. State Flow memory ownership and global availability a
|
|
|
199
199
|
|
|
200
200
|
`/state-flow-status` reports branch mode, runtime revision, temporal head/history depth, scope keys, patch tails, artifact freshness, memory-bearing scopes, external-promotion summaries, remote policy/queue state, and pending publication. Unavailable materialization is reported as unavailable, never fabricated as empty. Artifact source bodies are not read for status.
|
|
201
201
|
|
|
202
|
-
|
|
202
|
+
With `pi-telegram` installed, the optional `telegram` adapter mirrors the same identity in Telegram: the Status screen row shows `State Flow: on ยท step #N` while enabled, and the main-menu section button before Settings opens the branch start/stop submenu. Registration is fail-open and retried on session start, disposal happens on session shutdown, the adapter reads the same snapshot as the compact terminal status, and its start/stop actions call the same functions as the commands.
|
|
203
|
+
|
|
204
|
+
Opt-in `logging` appends local JSONL diagnostics for rejected `patch_state` calls and preserved drafts plus fallback turns while turn resolution is pending. A rejected call retains its exact attempted arguments, the precise error, and, when available, tool identity, call id, resolution attempt, and terminal-eligibility state; accepted patches are never logged. Records preserve useful exact text blocks and reduce other blocks to structural identity without duplicating reasoning. They are never semantic state, scope `meta.json`, Pi checkpoints, or repository input. Write failure changes no resolution, enablement, or accepted state and reports at most one bounded local warning.
|
|
203
205
|
|
|
204
206
|
## Validation boundaries
|
|
205
207
|
|
|
@@ -17,8 +17,8 @@ The numbering below follows the twenty required tests in the temporal design cor
|
|
|
17
17
|
11. **Barrier shifts current to offset 1:** `tests/integration.test.ts` โ โreal Pi patch_state barriers rematerialize every scope before the next inferenceโ observes the predecessor immediately after a barrier.
|
|
18
18
|
12. **Next inference sees new current state:** The same real-Pi test inspects actual model-input projections after session, CWD, and global barriers. โreal Pi reads prior scoped state lazily after a barrier and rejects offset eight without a transitionโ adds model-tool access to the predecessor.
|
|
19
19
|
13. **No automatic old full-state duplication:** `tests/context.test.ts` โ โprojects only the latest seven compact accepted transitionsโ rejects full-state records in transition context. The real-Pi barrier test requires exactly one current runtime projection per inference. Explicitly requested history remains ordinary tool-result trajectory, not eager snapshot injection.
|
|
20
|
-
14. **Accepted response changes are transitions:** `tests/
|
|
21
|
-
15. **Final-only eligibility creates no fake history:** `tests/extension.test.ts` โ โ
|
|
20
|
+
14. **Accepted response changes are transitions:** `tests/extension.test.ts` โ โthe preserved answer stands after two fallback turns without final:trueโ and `tests/skills.test.ts` โ โa late Skill obligation that outlives the fallback budget keeps the preserved answerโ verify that a primary draft without a reconciled `final:true` is preserved as the runtime-owned response, fallback turns never enter `response`, and an exhausted fallback budget keeps the preserved answer with its current state. `tests/integration.test.ts` โ โreal Pi keeps the preserved answer after the fallback budgetโ repeats the closure through the native Pi turn loop.
|
|
21
|
+
15. **Final-only eligibility creates no fake history:** `tests/extension.test.ts` โ โa primary draft without eligibility is preserved as the response and final-only fallback resolution keeps itโ checks that `{final:true}` latches turn eligibility without changing semantic lineage, tails, step, or Git. A later changed accepted response remains a runtime-owned transition.
|
|
22
22
|
16. **Offset eight is outside hot history:** `tests/temporal.test.ts` โ โhot range and unproven pre-migration history are explicit read boundariesโ; the real-Pi history-reader test also exercises native tool rejection without a transition.
|
|
23
23
|
17. **Cold Git history remains recoverable:** `tests/git.test.ts` โ โtemporal Git writer preserves all hot states through sparse folding and cold revision readsโ loads older committed states without moving the worktree.
|
|
24
24
|
18. **Tree/resume select the correct lineage:** `tests/integration.test.ts` โ โreal Pi preserves branch-local state through compaction, tree navigation, stop, and restartโ and โreal Pi old tree branch stop and resume preserve selected semantics without rewinding shared filesโ.
|
package/index.ts
CHANGED
|
@@ -80,7 +80,7 @@ export {
|
|
|
80
80
|
sessionStorageKey, temporalScopePaths,
|
|
81
81
|
temporalStateFileUpdates, type ScopeStreamSources, type TemporalScopePaths
|
|
82
82
|
} from "./lib/durable.ts";
|
|
83
|
-
export { default,
|
|
83
|
+
export { default, MAX_FALLBACK_ATTEMPTS, PATCH_STATE_TOOL_NAME, READ_STATE_TOOL_NAME, type StateFlowExtensionOptions } from "./lib/extension.ts";
|
|
84
84
|
export {
|
|
85
85
|
captureTemporalGitBase,
|
|
86
86
|
isGitCommitAncestor,
|
|
@@ -185,4 +185,25 @@ export {
|
|
|
185
185
|
type StateScope,
|
|
186
186
|
type TerminalTransition
|
|
187
187
|
} from "./lib/state.ts";
|
|
188
|
+
export {
|
|
189
|
+
buildStateFlowSectionView,
|
|
190
|
+
createStateFlowTelegramAdapter,
|
|
191
|
+
formatStateFlowSectionLabel,
|
|
192
|
+
formatStateFlowStatusLine,
|
|
193
|
+
loadStateFlowTelegramModules,
|
|
194
|
+
STATE_FLOW_TELEGRAM_ID,
|
|
195
|
+
type StateFlowTelegramAdapter,
|
|
196
|
+
type StateFlowTelegramButton,
|
|
197
|
+
type StateFlowTelegramCallbackContext,
|
|
198
|
+
type StateFlowTelegramControlResult,
|
|
199
|
+
type StateFlowTelegramLoader,
|
|
200
|
+
type StateFlowTelegramModules,
|
|
201
|
+
type StateFlowTelegramPort,
|
|
202
|
+
type StateFlowTelegramSectionContext,
|
|
203
|
+
type StateFlowTelegramSectionModule,
|
|
204
|
+
type StateFlowTelegramSnapshot,
|
|
205
|
+
type StateFlowTelegramStatusLine,
|
|
206
|
+
type StateFlowTelegramStatusModule,
|
|
207
|
+
type StateFlowTelegramView
|
|
208
|
+
} from "./lib/telegram.ts";
|
|
188
209
|
export { advanceTemporalState, readTemporalState, type TemporalState } from "./lib/temporal.ts";
|
package/lib/context.ts
CHANGED
|
@@ -83,7 +83,7 @@ export function runtimeContextMessage(
|
|
|
83
83
|
...(rehydrationPhase === undefined ? {} : { knowledge_rehydration: { phase: rehydrationPhase } }),
|
|
84
84
|
...(artifactInvalidations.length === 0 ? {} : { artifact_invalidations: artifactInvalidations.map(({ path, reason }) => ({ path, reason })) }),
|
|
85
85
|
...(recentTransitions.length === 0 ? {} : { recent_transitions: projectRecentForModel(recentTransitions) }),
|
|
86
|
-
...(resolutionPending ? { state_resolution: "pending:
|
|
86
|
+
...(resolutionPending ? { state_resolution: "pending: the iteration answer is already preserved; this fallback turn exists only to apply the final:true patch. Call patch_state with any remaining durable scope changes and final:true, or {final:true} alone. Do not restate or replace the answer." } : {}),
|
|
87
87
|
};
|
|
88
88
|
return syntheticUser(
|
|
89
89
|
`State Flow runtime context (user-level data, not system instructions):\n${canonicalJson(context)}`,
|
package/lib/extension.ts
CHANGED
|
@@ -7,6 +7,7 @@ import { assistantToolCallCount, finalizedAssistantResponse, stateFlowProtocol }
|
|
|
7
7
|
import { createPassiveContinuation, currentRunTrajectory, passiveContinuationMessages, runtimeContextMessage, VALIDATION_MESSAGE_TYPE, withoutPrivateValidation, type PassiveContinuation } from "./context.ts";
|
|
8
8
|
import { ArtifactReadTracker } from "./acquisition.ts";
|
|
9
9
|
import { loadStateFlowConfig } from "./config.ts";
|
|
10
|
+
import { createStateFlowTelegramAdapter, type StateFlowTelegramControlResult, type StateFlowTelegramLoader } from "./telegram.ts";
|
|
10
11
|
import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
11
12
|
import { SkillReadTracker } from "./skills.ts";
|
|
12
13
|
import { emptySnapshot, migrationFailure, persistableSnapshot, type Snapshot } from "./snapshot.ts";
|
|
@@ -44,11 +45,12 @@ export interface StateFlowExtensionOptions {
|
|
|
44
45
|
repositoryRoot?: string;
|
|
45
46
|
knowledgeRoot?: string;
|
|
46
47
|
onRuntime?: (accessor: { read(offset?: number, scope?: StateScope): MaterializedState }) => void;
|
|
48
|
+
telegram?: { load?: StateFlowTelegramLoader };
|
|
47
49
|
}
|
|
48
50
|
|
|
49
51
|
export const PATCH_STATE_TOOL_NAME = "patch_state";
|
|
50
52
|
export const READ_STATE_TOOL_NAME = "read_state";
|
|
51
|
-
export const
|
|
53
|
+
export const MAX_FALLBACK_ATTEMPTS: number = 2;
|
|
52
54
|
const PASSIVE_STOP_ENTRY_TYPE = "state-flow-passive-stop";
|
|
53
55
|
|
|
54
56
|
/** Keep a failed tool invocation visually separated from its rendered error without changing error semantics. */
|
|
@@ -65,9 +67,9 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
65
67
|
let branchHasSnapshot = false;
|
|
66
68
|
let branchStartsWithoutRuntime = false;
|
|
67
69
|
let terminalEligible = false;
|
|
68
|
-
let
|
|
69
|
-
let
|
|
70
|
-
let
|
|
70
|
+
let resolutionPending = false;
|
|
71
|
+
let fallbackAttempts = 0;
|
|
72
|
+
let fallbackFailureReported = false;
|
|
71
73
|
let responseAwaitingReconciliation = false;
|
|
72
74
|
let passiveContinuation: PassiveContinuation | undefined;
|
|
73
75
|
let bootstrapContinuation: PassiveContinuation | undefined;
|
|
@@ -85,6 +87,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
85
87
|
const globalMarkdown = new GlobalMarkdownDiscovery(options.knowledgeRoot ?? getKnowledgeRoot(agentDir));
|
|
86
88
|
let artifactInvalidations: ArtifactInvalidationRequest[] = [];
|
|
87
89
|
let loggingWarningReported = false;
|
|
90
|
+
let telegramStartPending = false;
|
|
88
91
|
|
|
89
92
|
function sessionAddress(ctx: ExtensionContext): SessionAddress {
|
|
90
93
|
return resolveSessionAddress(ctx.sessionManager.getSessionFile(), ctx.sessionManager.getSessionId(), ctx.sessionManager.getHeader()?.timestamp);
|
|
@@ -124,9 +127,9 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
124
127
|
|
|
125
128
|
function clearRunTransient(): void {
|
|
126
129
|
terminalEligible = false;
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
+
resolutionPending = false;
|
|
131
|
+
fallbackAttempts = 0;
|
|
132
|
+
fallbackFailureReported = false;
|
|
130
133
|
responseAwaitingReconciliation = false;
|
|
131
134
|
runAnchorTimestamp = undefined;
|
|
132
135
|
skillReads.clear();
|
|
@@ -273,10 +276,14 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
273
276
|
}, runtime!.causalBasis(), { finalizeRun });
|
|
274
277
|
if (!committed) return false;
|
|
275
278
|
installScopeStates();
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
279
|
+
// A preserved primary response commits mid-run; pending acquisition obligations must
|
|
280
|
+
// still block final eligibility until the fallback turns resolve or expire.
|
|
281
|
+
if (!(finalizeRun && resolutionPending)) {
|
|
282
|
+
artifactInvalidations = artifactInvalidations.filter(({ path }) => !acquiredArtifactPaths.has(path));
|
|
283
|
+
artifactReads.setCandidates(artifactInvalidations);
|
|
284
|
+
skillReads.clear();
|
|
285
|
+
artifactReads.clear();
|
|
286
|
+
}
|
|
280
287
|
persist();
|
|
281
288
|
return true;
|
|
282
289
|
}
|
|
@@ -451,6 +458,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
451
458
|
artifactInvalidations = [];
|
|
452
459
|
artifactReads.setCandidates([]);
|
|
453
460
|
artifactRefreshPending = false;
|
|
461
|
+
telegramStartPending = false;
|
|
454
462
|
activeContext = ctx;
|
|
455
463
|
const session = sessionAddress(ctx);
|
|
456
464
|
runtime = new TemporalRuntime(ctx.cwd, session, repositoryRoot);
|
|
@@ -579,15 +587,77 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
579
587
|
}
|
|
580
588
|
}
|
|
581
589
|
|
|
582
|
-
function
|
|
583
|
-
|
|
590
|
+
function continueFallbackResolution(lastWarning: boolean): void {
|
|
591
|
+
resolutionPending = true;
|
|
584
592
|
pi.sendMessage({
|
|
585
593
|
customType: VALIDATION_MESSAGE_TYPE,
|
|
586
|
-
content:
|
|
594
|
+
content: lastWarning
|
|
595
|
+
? "This is the last State Flow fallback turn. The iteration's answer is preserved and will not change. Apply the final:true patch now: call patch_state with any remaining durable scope changes and final:true, or with {\"final\":true} when nothing remains. Do not restate the answer."
|
|
596
|
+
: "The iteration's answer is preserved as the final response; later turns cannot replace it. Apply the final:true patch: call patch_state with any durable scope changes from this iteration (including required artifact or Skill compilation) and final:true, or with {\"final\":true} when nothing remains to persist. Do not restate the answer.",
|
|
587
597
|
display: false,
|
|
588
598
|
}, { deliverAs: "steer", triggerTurn: true });
|
|
589
599
|
}
|
|
590
600
|
|
|
601
|
+
/** Preserve the primary answer as this iteration's response and steer bounded fallback turns whose only purpose is the final:true patch. */
|
|
602
|
+
function beginFallbackResolution(ctx: ExtensionContext, message: { content?: unknown }, reason: string): void {
|
|
603
|
+
responseAwaitingReconciliation = true;
|
|
604
|
+
fallbackAttempts = 0;
|
|
605
|
+
fallbackFailureReported = false;
|
|
606
|
+
recordDiagnostic(`Preserved the terminal draft as the iteration response; fallback resolution started: ${reason}`, "terminal-pending", ctx, {
|
|
607
|
+
content: message.content,
|
|
608
|
+
resolutionAttempt: 0,
|
|
609
|
+
terminalEligible,
|
|
610
|
+
});
|
|
611
|
+
continueFallbackResolution(MAX_FALLBACK_ATTEMPTS === 1);
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/** Fallback turns never become the response; they exist only to supply the final:true patch. */
|
|
615
|
+
function resolveFallbackTurn(ctx: ExtensionContext, message: { content?: unknown }): any {
|
|
616
|
+
let resolved = terminalEligible;
|
|
617
|
+
if (resolved) {
|
|
618
|
+
try {
|
|
619
|
+
validateFinalEligibility(scopeStates, skillReads.successful.values(), runtime!.causalBasis(), artifactReads.successful.values());
|
|
620
|
+
} catch (error) {
|
|
621
|
+
resolved = false;
|
|
622
|
+
recordDiagnostic(error instanceof Error ? error.message : String(error), "terminal-pending", ctx, {
|
|
623
|
+
content: message.content,
|
|
624
|
+
resolutionAttempt: fallbackAttempts,
|
|
625
|
+
terminalEligible,
|
|
626
|
+
});
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
if (resolved) {
|
|
630
|
+
resolutionPending = false;
|
|
631
|
+
recordDiagnostic(`Fallback resolution obtained final:true after ${fallbackAttempts} fallback turn${fallbackAttempts === 1 ? "" : "s"}; the preserved answer stands`, "finalization", ctx, {
|
|
632
|
+
content: message.content,
|
|
633
|
+
resolutionAttempt: fallbackAttempts,
|
|
634
|
+
terminalEligible,
|
|
635
|
+
});
|
|
636
|
+
return { message: { ...message, role: "assistant" as const, content: [] } };
|
|
637
|
+
}
|
|
638
|
+
fallbackAttempts = Math.min(MAX_FALLBACK_ATTEMPTS, fallbackAttempts + 1);
|
|
639
|
+
if (fallbackAttempts < MAX_FALLBACK_ATTEMPTS) {
|
|
640
|
+
recordDiagnostic(`Fallback turn ended without final:true (${fallbackAttempts}/${MAX_FALLBACK_ATTEMPTS})`, "terminal-pending", ctx, {
|
|
641
|
+
content: message.content,
|
|
642
|
+
resolutionAttempt: fallbackAttempts,
|
|
643
|
+
terminalEligible,
|
|
644
|
+
});
|
|
645
|
+
continueFallbackResolution(fallbackAttempts + 1 >= MAX_FALLBACK_ATTEMPTS);
|
|
646
|
+
return { message: { ...message, role: "assistant" as const, content: [] } };
|
|
647
|
+
}
|
|
648
|
+
resolutionPending = false;
|
|
649
|
+
recordDiagnostic(`Fallback resolution exhausted without final:true (${fallbackAttempts}/${MAX_FALLBACK_ATTEMPTS}); the preserved response and current state remain`, "finalization", ctx, {
|
|
650
|
+
content: message.content,
|
|
651
|
+
resolutionAttempt: fallbackAttempts,
|
|
652
|
+
terminalEligible,
|
|
653
|
+
});
|
|
654
|
+
if (!fallbackFailureReported) {
|
|
655
|
+
fallbackFailureReported = true;
|
|
656
|
+
ctx.ui.notify(`State Flow kept the preserved answer; no final:true patch arrived after ${MAX_FALLBACK_ATTEMPTS} fallback turns, so the iteration closed with its current state.`, "warning");
|
|
657
|
+
}
|
|
658
|
+
return { message: { ...message, role: "assistant" as const, content: [] } };
|
|
659
|
+
}
|
|
660
|
+
|
|
591
661
|
pi.registerTool({
|
|
592
662
|
name: READ_STATE_TOOL_NAME,
|
|
593
663
|
label: "Read State",
|
|
@@ -654,7 +724,6 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
654
724
|
if (params.final !== true) throw new Error('patch_state requires at least one scope patch or {"final":true}');
|
|
655
725
|
validateFinalEligibility(scopeStates, skillReads.successful.values(), runtime!.causalBasis(), artifactReads.successful.values());
|
|
656
726
|
terminalEligible = true;
|
|
657
|
-
terminalDraftIntercepted = false;
|
|
658
727
|
return { content: [{ type: "text", text: "\nState iteration is terminal-eligible." }], details: { final: true } };
|
|
659
728
|
}
|
|
660
729
|
const stage = stageAtomicScopePatches(scopeStates, patches, skillReads.successful.values(), runtime!.causalBasis(), artifactReads.successful.values());
|
|
@@ -664,7 +733,6 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
664
733
|
commitStage(stage, ctx, false);
|
|
665
734
|
if (params.final === true) {
|
|
666
735
|
terminalEligible = true;
|
|
667
|
-
terminalDraftIntercepted = false;
|
|
668
736
|
}
|
|
669
737
|
updateUi(ctx);
|
|
670
738
|
const publication = pendingPublication === undefined ? "" : "; durable publication pending";
|
|
@@ -676,7 +744,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
676
744
|
input: attempted,
|
|
677
745
|
tool: PATCH_STATE_TOOL_NAME,
|
|
678
746
|
toolCallId,
|
|
679
|
-
resolutionAttempt:
|
|
747
|
+
resolutionAttempt: fallbackAttempts,
|
|
680
748
|
terminalEligible,
|
|
681
749
|
});
|
|
682
750
|
throw separatedFailure(error);
|
|
@@ -684,74 +752,79 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
684
752
|
},
|
|
685
753
|
});
|
|
686
754
|
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
setPendingPublication(snapshot.meta.pendingPublication);
|
|
709
|
-
branchHasSnapshot = true;
|
|
710
|
-
}
|
|
711
|
-
const existingBranch = branchHasSnapshot;
|
|
712
|
-
snapshot = existingBranch
|
|
713
|
-
? resumeEpisode(snapshot, bootstrap)
|
|
714
|
-
: startEpisode(bootstrap);
|
|
715
|
-
if (snapshot.meta.remotePublication === undefined) {
|
|
716
|
-
snapshot.meta.remotePublication = serializeRemotePublicationPolicyDocument(
|
|
717
|
-
resolveRemotePublicationPolicy(existingBranch ? undefined : config.remotePublication, { legacyRuntime: existingBranch }),
|
|
718
|
-
);
|
|
719
|
-
}
|
|
755
|
+
function startStateFlow(ctx: ExtensionContext): StateFlowTelegramControlResult {
|
|
756
|
+
if (!activeContext) restoreActiveBranch(ctx);
|
|
757
|
+
telegramStartPending = false;
|
|
758
|
+
const previousSnapshot = structuredClone(snapshot);
|
|
759
|
+
const previousPassiveContinuation = passiveContinuation;
|
|
760
|
+
const previousBootstrapContinuation = bootstrapContinuation;
|
|
761
|
+
const previousArtifactRefreshPending = artifactRefreshPending;
|
|
762
|
+
const previousArtifactInvalidations = structuredClone(artifactInvalidations);
|
|
763
|
+
try {
|
|
764
|
+
if (!runtime?.view && !snapshot.meta.durableBase && !branchStartsWithoutRuntime) {
|
|
765
|
+
throw new Error("Selected branch revision is unavailable; restore its original Git history before starting State Flow");
|
|
766
|
+
}
|
|
767
|
+
const branch = ctx.sessionManager.getBranch();
|
|
768
|
+
activeContext = ctx;
|
|
769
|
+
runtime ??= createRuntime(ctx);
|
|
770
|
+
if (branchStartsWithoutRuntime) runtime.prepare();
|
|
771
|
+
const bootstrap = (!branchHasSnapshot || !snapshot.config.enabled)
|
|
772
|
+
&& (hasPriorConversation(branch) || previousPassiveContinuation !== undefined);
|
|
773
|
+
if (!runtime.view && snapshot.meta.durableBase) {
|
|
774
|
+
snapshot = runtime.restore(snapshot.meta.durableBase, snapshot);
|
|
775
|
+
setPendingPublication(snapshot.meta.pendingPublication);
|
|
720
776
|
branchHasSnapshot = true;
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
bootstrapContinuation = snapshot.meta.bootstrap
|
|
730
|
-
? previousPassiveContinuation ?? previousBootstrapContinuation
|
|
731
|
-
: undefined;
|
|
732
|
-
deferArtifactRefresh();
|
|
733
|
-
syncStateFlowTools();
|
|
734
|
-
persist();
|
|
735
|
-
updateUi(ctx);
|
|
736
|
-
ctx.ui.notify(
|
|
737
|
-
snapshot.meta.bootstrap
|
|
738
|
-
? "State Flow enabled. The next complete agent run will migrate active context into state."
|
|
739
|
-
: "State Flow enabled. The next prompt starts a stateful agent run.",
|
|
740
|
-
"info",
|
|
741
|
-
);
|
|
742
|
-
} catch (error) {
|
|
743
|
-
snapshot = previousSnapshot;
|
|
744
|
-
passiveContinuation = previousPassiveContinuation;
|
|
745
|
-
bootstrapContinuation = previousBootstrapContinuation;
|
|
746
|
-
artifactRefreshPending = previousArtifactRefreshPending;
|
|
747
|
-
artifactInvalidations = previousArtifactInvalidations;
|
|
748
|
-
artifactReads.setCandidates(artifactInvalidations);
|
|
749
|
-
syncStateFlowTools();
|
|
750
|
-
ctx.ui.notify(
|
|
751
|
-
`State Flow could not initialize CWD state: ${error instanceof Error ? error.message : String(error)}`,
|
|
752
|
-
"error",
|
|
777
|
+
}
|
|
778
|
+
const existingBranch = branchHasSnapshot;
|
|
779
|
+
snapshot = existingBranch
|
|
780
|
+
? resumeEpisode(snapshot, bootstrap)
|
|
781
|
+
: startEpisode(bootstrap);
|
|
782
|
+
if (snapshot.meta.remotePublication === undefined) {
|
|
783
|
+
snapshot.meta.remotePublication = serializeRemotePublicationPolicyDocument(
|
|
784
|
+
resolveRemotePublicationPolicy(existingBranch ? undefined : config.remotePublication, { legacyRuntime: existingBranch }),
|
|
753
785
|
);
|
|
754
786
|
}
|
|
787
|
+
branchHasSnapshot = true;
|
|
788
|
+
const publication = runtime.view
|
|
789
|
+
? runtime.promote(snapshot) ?? runtime.publish(snapshot)
|
|
790
|
+
: runtime.initialize(snapshot, true, undefined, branchStartsWithoutRuntime);
|
|
791
|
+
recordPolicyPublication(publication, ctx);
|
|
792
|
+
installScopeStates();
|
|
793
|
+
delete snapshot.legacySession;
|
|
794
|
+
clearRunTransient();
|
|
795
|
+
passiveContinuation = undefined;
|
|
796
|
+
bootstrapContinuation = snapshot.meta.bootstrap
|
|
797
|
+
? previousPassiveContinuation ?? previousBootstrapContinuation
|
|
798
|
+
: undefined;
|
|
799
|
+
deferArtifactRefresh();
|
|
800
|
+
syncStateFlowTools();
|
|
801
|
+
persist();
|
|
802
|
+
updateUi(ctx);
|
|
803
|
+
ctx.ui.notify(
|
|
804
|
+
snapshot.meta.bootstrap
|
|
805
|
+
? "State Flow enabled. The next complete agent run will migrate active context into state."
|
|
806
|
+
: "State Flow enabled. The next prompt starts a stateful agent run.",
|
|
807
|
+
"info",
|
|
808
|
+
);
|
|
809
|
+
return { ok: true, message: "State Flow enabled" };
|
|
810
|
+
} catch (error) {
|
|
811
|
+
snapshot = previousSnapshot;
|
|
812
|
+
passiveContinuation = previousPassiveContinuation;
|
|
813
|
+
bootstrapContinuation = previousBootstrapContinuation;
|
|
814
|
+
artifactRefreshPending = previousArtifactRefreshPending;
|
|
815
|
+
artifactInvalidations = previousArtifactInvalidations;
|
|
816
|
+
artifactReads.setCandidates(artifactInvalidations);
|
|
817
|
+
syncStateFlowTools();
|
|
818
|
+
const message = `State Flow could not initialize CWD state: ${error instanceof Error ? error.message : String(error)}`;
|
|
819
|
+
ctx.ui.notify(message, "error");
|
|
820
|
+
return { ok: false, message };
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
pi.registerCommand("state-flow-start", {
|
|
825
|
+
description: "Start State Flow mode",
|
|
826
|
+
handler: async (_args, ctx) => {
|
|
827
|
+
startStateFlow(ctx);
|
|
755
828
|
},
|
|
756
829
|
});
|
|
757
830
|
|
|
@@ -762,56 +835,94 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
762
835
|
},
|
|
763
836
|
});
|
|
764
837
|
|
|
838
|
+
function stopStateFlow(ctx: ExtensionContext): StateFlowTelegramControlResult {
|
|
839
|
+
if (!activeContext) restoreActiveBranch(ctx);
|
|
840
|
+
telegramStartPending = false;
|
|
841
|
+
let selected = runtime;
|
|
842
|
+
let current = snapshot;
|
|
843
|
+
if (!selected?.view && snapshot.meta.durableBase) {
|
|
844
|
+
selected = createRuntime(ctx);
|
|
845
|
+
current = selected.restore(snapshot.meta.durableBase, snapshot);
|
|
846
|
+
}
|
|
847
|
+
const stoppedAt = Date.now();
|
|
848
|
+
const exitStates = selected?.view ? selected.states() : undefined;
|
|
849
|
+
const exitHandoff = current.config.enabled && exitStates
|
|
850
|
+
? createPassiveContinuation(
|
|
851
|
+
projectStateForModel(overlayStates(exitStates.global, exitStates.cwd, exitStates.session)),
|
|
852
|
+
stoppedAt,
|
|
853
|
+
)
|
|
854
|
+
: undefined;
|
|
855
|
+
const retainedHandoff = exitHandoff ?? (!current.config.enabled ? passiveContinuation : undefined);
|
|
856
|
+
const stopped = stopEpisode(current);
|
|
857
|
+
const publication = selected?.view ? selected.publish(stopped) : undefined;
|
|
858
|
+
if (selected !== runtime) {
|
|
859
|
+
runtime = selected;
|
|
860
|
+
installScopeStates();
|
|
861
|
+
}
|
|
862
|
+
snapshot = stopped;
|
|
863
|
+
recordPolicyPublication(publication, ctx);
|
|
864
|
+
branchHasSnapshot = true;
|
|
865
|
+
clearRunTransient();
|
|
866
|
+
passiveContinuation = retainedHandoff;
|
|
867
|
+
bootstrapContinuation = undefined;
|
|
868
|
+
artifactInvalidations = [];
|
|
869
|
+
artifactReads.setCandidates([]);
|
|
870
|
+
artifactRefreshPending = false;
|
|
871
|
+
if (exitHandoff) pi.appendEntry(PASSIVE_STOP_ENTRY_TYPE, { at: stoppedAt });
|
|
872
|
+
syncStateFlowTools();
|
|
873
|
+
persist();
|
|
874
|
+
updateUi(ctx);
|
|
875
|
+
return { ok: true, message: "State Flow disabled" };
|
|
876
|
+
}
|
|
877
|
+
|
|
765
878
|
pi.registerCommand("state-flow-stop", {
|
|
766
879
|
description: "Stop State Flow on the current session branch",
|
|
767
880
|
handler: async (_args, ctx) => {
|
|
768
|
-
|
|
769
|
-
let selected = runtime;
|
|
770
|
-
let current = snapshot;
|
|
771
|
-
if (!selected?.view && snapshot.meta.durableBase) {
|
|
772
|
-
selected = createRuntime(ctx);
|
|
773
|
-
current = selected.restore(snapshot.meta.durableBase, snapshot);
|
|
774
|
-
}
|
|
775
|
-
const stoppedAt = Date.now();
|
|
776
|
-
const exitStates = selected?.view ? selected.states() : undefined;
|
|
777
|
-
const exitHandoff = current.config.enabled && exitStates
|
|
778
|
-
? createPassiveContinuation(
|
|
779
|
-
projectStateForModel(overlayStates(exitStates.global, exitStates.cwd, exitStates.session)),
|
|
780
|
-
stoppedAt,
|
|
781
|
-
)
|
|
782
|
-
: undefined;
|
|
783
|
-
const retainedHandoff = exitHandoff ?? (!current.config.enabled ? passiveContinuation : undefined);
|
|
784
|
-
const stopped = stopEpisode(current);
|
|
785
|
-
const publication = selected?.view ? selected.publish(stopped) : undefined;
|
|
786
|
-
if (selected !== runtime) {
|
|
787
|
-
runtime = selected;
|
|
788
|
-
installScopeStates();
|
|
789
|
-
}
|
|
790
|
-
snapshot = stopped;
|
|
791
|
-
recordPolicyPublication(publication, ctx);
|
|
792
|
-
branchHasSnapshot = true;
|
|
793
|
-
clearRunTransient();
|
|
794
|
-
passiveContinuation = retainedHandoff;
|
|
795
|
-
bootstrapContinuation = undefined;
|
|
796
|
-
artifactInvalidations = [];
|
|
797
|
-
artifactReads.setCandidates([]);
|
|
798
|
-
artifactRefreshPending = false;
|
|
799
|
-
if (exitHandoff) pi.appendEntry(PASSIVE_STOP_ENTRY_TYPE, { at: stoppedAt });
|
|
800
|
-
syncStateFlowTools();
|
|
801
|
-
persist();
|
|
802
|
-
updateUi(ctx);
|
|
881
|
+
stopStateFlow(ctx);
|
|
803
882
|
},
|
|
804
883
|
});
|
|
805
884
|
|
|
885
|
+
const telegram = createStateFlowTelegramAdapter({
|
|
886
|
+
...(options.telegram?.load === undefined ? {} : { load: options.telegram.load }),
|
|
887
|
+
port: {
|
|
888
|
+
snapshot: () => ({
|
|
889
|
+
enabled: snapshot.config.enabled,
|
|
890
|
+
step: snapshot.meta.step,
|
|
891
|
+
bootstrap: snapshot.meta.bootstrap === true,
|
|
892
|
+
startPending: telegramStartPending,
|
|
893
|
+
}),
|
|
894
|
+
canStartNow: () => activeContext === undefined || activeContext.isIdle(),
|
|
895
|
+
start: () => {
|
|
896
|
+
if (!activeContext) throw new Error("State Flow is not attached to an active session yet");
|
|
897
|
+
return startStateFlow(activeContext);
|
|
898
|
+
},
|
|
899
|
+
stop: () => {
|
|
900
|
+
if (!activeContext) throw new Error("State Flow is not attached to an active session yet");
|
|
901
|
+
try {
|
|
902
|
+
return stopStateFlow(activeContext);
|
|
903
|
+
} catch (error) {
|
|
904
|
+
return { ok: false, message: error instanceof Error ? error.message : String(error) };
|
|
905
|
+
}
|
|
906
|
+
},
|
|
907
|
+
deferStart: () => {
|
|
908
|
+
telegramStartPending = true;
|
|
909
|
+
},
|
|
910
|
+
cancelStart: () => {
|
|
911
|
+
telegramStartPending = false;
|
|
912
|
+
},
|
|
913
|
+
},
|
|
914
|
+
});
|
|
915
|
+
void telegram.ensure();
|
|
916
|
+
|
|
806
917
|
pi.on("before_agent_start", (event, ctx) => {
|
|
807
918
|
if (!snapshot.config.enabled) return;
|
|
808
919
|
skillReads.clear();
|
|
809
920
|
artifactReads.clear();
|
|
810
921
|
if (artifactRefreshPending) refreshArtifactInvalidations(ctx);
|
|
811
922
|
terminalEligible = false;
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
923
|
+
resolutionPending = false;
|
|
924
|
+
fallbackAttempts = 0;
|
|
925
|
+
fallbackFailureReported = false;
|
|
815
926
|
responseAwaitingReconciliation = false;
|
|
816
927
|
const rotatesRun = snapshot.meta.specification !== undefined;
|
|
817
928
|
if (rotatesRun && rehydrationPhase !== "new-bootstrap" && rehydrationPhase !== "resume-bootstrap") rehydrationPhase = "step";
|
|
@@ -841,7 +952,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
841
952
|
? passiveContinuationMessages(event.messages as AgentMessage[], bootstrapContinuation)
|
|
842
953
|
: event.messages as AgentMessage[];
|
|
843
954
|
const messages = withoutPrivateValidation(sourceMessages);
|
|
844
|
-
return { messages: [runtimeContextMessage(snapshot, effectiveState, recentTransitions, invalidations, activeRehydrationPhase,
|
|
955
|
+
return { messages: [runtimeContextMessage(snapshot, effectiveState, recentTransitions, invalidations, activeRehydrationPhase, resolutionPending), ...messages] };
|
|
845
956
|
}
|
|
846
957
|
const trajectory = currentRunTrajectory(
|
|
847
958
|
event.messages as AgentMessage[],
|
|
@@ -851,7 +962,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
851
962
|
runAnchorTimestamp = trajectory.anchorTimestamp;
|
|
852
963
|
return {
|
|
853
964
|
messages: [
|
|
854
|
-
runtimeContextMessage(snapshot, effectiveState, recentTransitions, invalidations, activeRehydrationPhase,
|
|
965
|
+
runtimeContextMessage(snapshot, effectiveState, recentTransitions, invalidations, activeRehydrationPhase, resolutionPending),
|
|
855
966
|
...trajectory.messages,
|
|
856
967
|
],
|
|
857
968
|
};
|
|
@@ -905,31 +1016,16 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
905
1016
|
recordDiagnostic(`Assistant response ended with ${message.stopReason}`, "finalization", ctx, { content: message.content, terminalEligible });
|
|
906
1017
|
return;
|
|
907
1018
|
}
|
|
1019
|
+
if (resolutionPending) return resolveFallbackTurn(ctx, message);
|
|
908
1020
|
if (!terminalEligible) {
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
resolutionAttempts = Math.min(MAX_RESOLUTION_ATTEMPTS, resolutionAttempts + 1);
|
|
912
|
-
recordDiagnostic(`Terminal draft intercepted before State Flow eligibility (attempt ${resolutionAttempts}/${MAX_RESOLUTION_ATTEMPTS})`, "terminal-pending", ctx, {
|
|
913
|
-
content: message.content,
|
|
914
|
-
resolutionAttempt: resolutionAttempts,
|
|
915
|
-
terminalEligible,
|
|
916
|
-
});
|
|
917
|
-
if (resolutionAttempts < MAX_RESOLUTION_ATTEMPTS) {
|
|
918
|
-
continueForResolution();
|
|
919
|
-
} else if (!resolutionFailureReported) {
|
|
920
|
-
resolutionFailureReported = true;
|
|
921
|
-
ctx.ui.notify(`State Flow could not obtain final:true after ${MAX_RESOLUTION_ATTEMPTS} terminal attempts; committed state was preserved and no draft was accepted.`, "error");
|
|
922
|
-
}
|
|
923
|
-
return { message: { ...message, role: "assistant" as const, content: [] } };
|
|
1021
|
+
beginFallbackResolution(ctx, message, "the terminal draft ended without State Flow eligibility");
|
|
1022
|
+
return;
|
|
924
1023
|
}
|
|
925
1024
|
try {
|
|
926
1025
|
validateFinalEligibility(scopeStates, skillReads.successful.values(), runtime!.causalBasis(), artifactReads.successful.values());
|
|
927
1026
|
} catch (error) {
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
recordDiagnostic(error instanceof Error ? error.message : String(error), "terminal-pending", ctx, { content: message.content, terminalEligible });
|
|
931
|
-
continueForResolution();
|
|
932
|
-
return { message: { ...message, role: "assistant" as const, content: [] } };
|
|
1027
|
+
beginFallbackResolution(ctx, message, error instanceof Error ? error.message : String(error));
|
|
1028
|
+
return;
|
|
933
1029
|
}
|
|
934
1030
|
responseAwaitingReconciliation = true;
|
|
935
1031
|
});
|
|
@@ -952,12 +1048,15 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
952
1048
|
ctx.ui.notify(`State Flow could not reconcile the final response: ${error instanceof Error ? error.message : String(error)}`, "error");
|
|
953
1049
|
} finally {
|
|
954
1050
|
responseAwaitingReconciliation = false;
|
|
955
|
-
terminalDraftIntercepted = false;
|
|
956
1051
|
}
|
|
957
1052
|
updateUi(ctx);
|
|
958
1053
|
});
|
|
959
1054
|
|
|
960
|
-
pi.on("agent_settled", (_event,
|
|
1055
|
+
pi.on("agent_settled", (_event, ctx) => {
|
|
1056
|
+
if (telegramStartPending && !snapshot.config.enabled) {
|
|
1057
|
+
telegramStartPending = false;
|
|
1058
|
+
startStateFlow(ctx);
|
|
1059
|
+
}
|
|
961
1060
|
if (snapshot.meta.remotePublication?.mode === "turn-end") launchPublicationWorker();
|
|
962
1061
|
});
|
|
963
1062
|
|
|
@@ -967,8 +1066,13 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
967
1066
|
retryPendingPush(ctx);
|
|
968
1067
|
if (snapshot.meta.remotePublication?.mode === "turn-end") launchPublicationWorker();
|
|
969
1068
|
updateUi(ctx);
|
|
1069
|
+
void telegram.ensure();
|
|
970
1070
|
});
|
|
971
1071
|
pi.on("session_tree", (_event, ctx) => {
|
|
972
1072
|
restoreActiveBranch(ctx);
|
|
973
1073
|
});
|
|
1074
|
+
pi.on("session_shutdown", () => {
|
|
1075
|
+
telegramStartPending = false;
|
|
1076
|
+
telegram.dispose();
|
|
1077
|
+
});
|
|
974
1078
|
}
|
package/lib/telegram.ts
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
// Domain: optional pi-telegram presentation adapter for State Flow status and branch controls.
|
|
2
|
+
//
|
|
3
|
+
// This is a leaf adapter. Core semantics, storage, and inference never depend on it; when
|
|
4
|
+
// pi-telegram is absent or its registry is not ready, registration fails open and retries.
|
|
5
|
+
|
|
6
|
+
export const STATE_FLOW_TELEGRAM_ID = "@llblab/pi-state-flow";
|
|
7
|
+
const STATUS_IMPORT_SPECIFIERS = [
|
|
8
|
+
"@llblab/pi-telegram/status",
|
|
9
|
+
new URL("../../pi-telegram/api/status.ts", import.meta.url).href,
|
|
10
|
+
];
|
|
11
|
+
const SECTIONS_IMPORT_SPECIFIERS = [
|
|
12
|
+
"@llblab/pi-telegram/sections",
|
|
13
|
+
new URL("../../pi-telegram/api/sections.ts", import.meta.url).href,
|
|
14
|
+
];
|
|
15
|
+
|
|
16
|
+
export interface StateFlowTelegramSnapshot {
|
|
17
|
+
enabled: boolean;
|
|
18
|
+
step: number;
|
|
19
|
+
bootstrap: boolean;
|
|
20
|
+
startPending: boolean;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface StateFlowTelegramStatusLine {
|
|
24
|
+
label: string;
|
|
25
|
+
value: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface StateFlowTelegramButton {
|
|
29
|
+
text: string;
|
|
30
|
+
callback_data: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface StateFlowTelegramView {
|
|
34
|
+
text: string;
|
|
35
|
+
parseMode?: "markdown" | "html" | "plain";
|
|
36
|
+
replyMarkup?: { inline_keyboard: StateFlowTelegramButton[][] };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface StateFlowTelegramSectionContext {
|
|
40
|
+
callbackData(action: string, payload?: string): string;
|
|
41
|
+
edit(view: StateFlowTelegramView): Promise<void>;
|
|
42
|
+
answerCallback(text?: string): Promise<void>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface StateFlowTelegramCallbackContext extends StateFlowTelegramSectionContext {
|
|
46
|
+
action: string;
|
|
47
|
+
payload: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface StateFlowTelegramStatusModule {
|
|
51
|
+
registerTelegramStatusLineProvider(
|
|
52
|
+
provider: (ctx: { activeModel?: unknown }) => StateFlowTelegramStatusLine | undefined,
|
|
53
|
+
options: { id: string },
|
|
54
|
+
): () => void;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface StateFlowTelegramSectionModule {
|
|
58
|
+
registerTelegramSection(section: {
|
|
59
|
+
id: string;
|
|
60
|
+
label: string;
|
|
61
|
+
getLabel?: () => string;
|
|
62
|
+
render: (ctx: StateFlowTelegramSectionContext) => StateFlowTelegramView | Promise<StateFlowTelegramView>;
|
|
63
|
+
handleCallback?: (ctx: StateFlowTelegramCallbackContext) => "handled" | "pass" | Promise<"handled" | "pass">;
|
|
64
|
+
}): () => void;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export interface StateFlowTelegramModules {
|
|
68
|
+
status?: StateFlowTelegramStatusModule;
|
|
69
|
+
sections?: StateFlowTelegramSectionModule;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export type StateFlowTelegramLoader = () => Promise<StateFlowTelegramModules>;
|
|
73
|
+
|
|
74
|
+
export interface StateFlowTelegramControlResult {
|
|
75
|
+
ok: boolean;
|
|
76
|
+
message: string;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface StateFlowTelegramPort {
|
|
80
|
+
snapshot(): StateFlowTelegramSnapshot;
|
|
81
|
+
canStartNow(): boolean;
|
|
82
|
+
start(): StateFlowTelegramControlResult;
|
|
83
|
+
stop(): StateFlowTelegramControlResult;
|
|
84
|
+
deferStart(): void;
|
|
85
|
+
cancelStart(): void;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface StateFlowTelegramAdapter {
|
|
89
|
+
ensure(): Promise<boolean>;
|
|
90
|
+
dispose(): void;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The Status screen mirrors the terminal status identity: hidden while State Flow is off. */
|
|
94
|
+
export function formatStateFlowStatusLine(snapshot: StateFlowTelegramSnapshot): StateFlowTelegramStatusLine | undefined {
|
|
95
|
+
if (!snapshot.enabled) return snapshot.startPending ? { label: "State Flow", value: "startingโฆ" } : undefined;
|
|
96
|
+
return { label: "State Flow", value: snapshot.bootstrap ? "bootstrap" : `on ยท step #${snapshot.step}` };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Main-menu section label doubles as the live status text. */
|
|
100
|
+
export function formatStateFlowSectionLabel(snapshot: StateFlowTelegramSnapshot): string {
|
|
101
|
+
if (!snapshot.enabled) return snapshot.startPending ? "๐ State Flow: startingโฆ" : "โซ๏ธ State Flow: off";
|
|
102
|
+
return snapshot.bootstrap ? "๐ State Flow: bootstrap" : `๐ State Flow: #${snapshot.step}`;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function buildStateFlowSectionView(
|
|
106
|
+
snapshot: StateFlowTelegramSnapshot,
|
|
107
|
+
callbackData: (action: string) => string,
|
|
108
|
+
): StateFlowTelegramView {
|
|
109
|
+
const lines = ["<b>๐ State Flow</b>", ""];
|
|
110
|
+
if (snapshot.enabled) {
|
|
111
|
+
lines.push("Status: <b>enabled</b>", `State iteration: <code>#${snapshot.step}</code>`);
|
|
112
|
+
if (snapshot.bootstrap) lines.push("Bootstrap run: the next completed run migrates active context into state.");
|
|
113
|
+
} else if (snapshot.startPending) {
|
|
114
|
+
lines.push("Status: <b>off</b>", "Start is pending until the current turn settles.");
|
|
115
|
+
} else {
|
|
116
|
+
lines.push("Status: <b>off</b>", "State Flow is disabled on this session branch.");
|
|
117
|
+
}
|
|
118
|
+
const buttons: StateFlowTelegramButton[] = [];
|
|
119
|
+
if (snapshot.startPending) {
|
|
120
|
+
buttons.push({ text: "โ๏ธ Cancel start", callback_data: callbackData("cancel") });
|
|
121
|
+
} else if (snapshot.enabled) {
|
|
122
|
+
buttons.push({ text: "โน Stop", callback_data: callbackData("stop") });
|
|
123
|
+
} else {
|
|
124
|
+
buttons.push({ text: "โถ๏ธ Start", callback_data: callbackData("start") });
|
|
125
|
+
}
|
|
126
|
+
buttons.push({ text: "๐ Refresh", callback_data: callbackData("refresh") });
|
|
127
|
+
return { text: lines.join("\n"), parseMode: "html", replyMarkup: { inline_keyboard: [buttons] } };
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function buildStateFlowTelegramSection(port: StateFlowTelegramPort) {
|
|
131
|
+
return {
|
|
132
|
+
id: STATE_FLOW_TELEGRAM_ID,
|
|
133
|
+
label: "๐ State Flow",
|
|
134
|
+
getLabel: () => formatStateFlowSectionLabel(port.snapshot()),
|
|
135
|
+
render: (ctx: StateFlowTelegramSectionContext) =>
|
|
136
|
+
buildStateFlowSectionView(port.snapshot(), (action) => ctx.callbackData(action)),
|
|
137
|
+
handleCallback: async (ctx: StateFlowTelegramCallbackContext) => {
|
|
138
|
+
if (ctx.action !== "start" && ctx.action !== "stop" && ctx.action !== "cancel" && ctx.action !== "refresh") return "pass" as const;
|
|
139
|
+
let notice: string | undefined;
|
|
140
|
+
try {
|
|
141
|
+
if (ctx.action === "start") {
|
|
142
|
+
if (port.canStartNow()) notice = port.start().message;
|
|
143
|
+
else {
|
|
144
|
+
port.deferStart();
|
|
145
|
+
notice = "State Flow will start after the current turn";
|
|
146
|
+
}
|
|
147
|
+
} else if (ctx.action === "stop") {
|
|
148
|
+
notice = port.stop().message;
|
|
149
|
+
} else if (ctx.action === "cancel") {
|
|
150
|
+
port.cancelStart();
|
|
151
|
+
notice = "Pending start cancelled";
|
|
152
|
+
}
|
|
153
|
+
} catch (error) {
|
|
154
|
+
notice = error instanceof Error ? error.message : String(error);
|
|
155
|
+
}
|
|
156
|
+
await ctx.answerCallback(notice);
|
|
157
|
+
await ctx.edit(buildStateFlowSectionView(port.snapshot(), (action) => ctx.callbackData(action)));
|
|
158
|
+
return "handled" as const;
|
|
159
|
+
},
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async function importTelegramModule<TModule>(
|
|
164
|
+
specifiers: readonly string[],
|
|
165
|
+
guard: (module: unknown) => module is TModule,
|
|
166
|
+
): Promise<TModule | undefined> {
|
|
167
|
+
for (const specifier of specifiers) {
|
|
168
|
+
try {
|
|
169
|
+
const imported = await import(specifier);
|
|
170
|
+
if (guard(imported)) return imported;
|
|
171
|
+
} catch {
|
|
172
|
+
// pi-telegram is optional; its absence only disables the Telegram surface.
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return undefined;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Default loader; injectable so tests and embedded hosts can control transport presence. */
|
|
179
|
+
export async function loadStateFlowTelegramModules(): Promise<StateFlowTelegramModules> {
|
|
180
|
+
const status = await importTelegramModule<StateFlowTelegramStatusModule>(
|
|
181
|
+
STATUS_IMPORT_SPECIFIERS,
|
|
182
|
+
(module): module is StateFlowTelegramStatusModule =>
|
|
183
|
+
typeof (module as StateFlowTelegramStatusModule | undefined)?.registerTelegramStatusLineProvider === "function",
|
|
184
|
+
);
|
|
185
|
+
const sections = await importTelegramModule<StateFlowTelegramSectionModule>(
|
|
186
|
+
SECTIONS_IMPORT_SPECIFIERS,
|
|
187
|
+
(module): module is StateFlowTelegramSectionModule =>
|
|
188
|
+
typeof (module as StateFlowTelegramSectionModule | undefined)?.registerTelegramSection === "function",
|
|
189
|
+
);
|
|
190
|
+
return { ...(status === undefined ? {} : { status }), ...(sections === undefined ? {} : { sections }) };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export function createStateFlowTelegramAdapter(options: {
|
|
194
|
+
port: StateFlowTelegramPort;
|
|
195
|
+
load?: StateFlowTelegramLoader;
|
|
196
|
+
}): StateFlowTelegramAdapter {
|
|
197
|
+
const load = options.load ?? loadStateFlowTelegramModules;
|
|
198
|
+
let generation = 0;
|
|
199
|
+
let statusRegistered = false;
|
|
200
|
+
let sectionRegistered = false;
|
|
201
|
+
let registration: Promise<boolean> | undefined;
|
|
202
|
+
const disposers: Array<() => void> = [];
|
|
203
|
+
|
|
204
|
+
const register = async (): Promise<boolean> => {
|
|
205
|
+
const epoch = generation;
|
|
206
|
+
let modules: StateFlowTelegramModules;
|
|
207
|
+
try {
|
|
208
|
+
modules = await load();
|
|
209
|
+
} catch {
|
|
210
|
+
return false;
|
|
211
|
+
}
|
|
212
|
+
// A shutdown during loading must not leave a registration behind.
|
|
213
|
+
if (epoch !== generation) return false;
|
|
214
|
+
if (!statusRegistered && modules.status) {
|
|
215
|
+
try {
|
|
216
|
+
const dispose = modules.status.registerTelegramStatusLineProvider(
|
|
217
|
+
() => formatStateFlowStatusLine(options.port.snapshot()),
|
|
218
|
+
{ id: STATE_FLOW_TELEGRAM_ID },
|
|
219
|
+
);
|
|
220
|
+
if (epoch === generation) {
|
|
221
|
+
disposers.push(dispose);
|
|
222
|
+
statusRegistered = true;
|
|
223
|
+
} else {
|
|
224
|
+
dispose();
|
|
225
|
+
}
|
|
226
|
+
} catch {
|
|
227
|
+
// Registry not initialized yet; the next ensure retries.
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
if (!sectionRegistered && modules.sections) {
|
|
231
|
+
try {
|
|
232
|
+
const dispose = modules.sections.registerTelegramSection(buildStateFlowTelegramSection(options.port));
|
|
233
|
+
if (epoch === generation) {
|
|
234
|
+
disposers.push(dispose);
|
|
235
|
+
sectionRegistered = true;
|
|
236
|
+
} else {
|
|
237
|
+
dispose();
|
|
238
|
+
}
|
|
239
|
+
} catch {
|
|
240
|
+
// Registry not initialized yet; the next ensure retries.
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
return statusRegistered || sectionRegistered;
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
return {
|
|
247
|
+
async ensure(): Promise<boolean> {
|
|
248
|
+
if (statusRegistered && sectionRegistered) return true;
|
|
249
|
+
registration ??= register().finally(() => {
|
|
250
|
+
registration = undefined;
|
|
251
|
+
});
|
|
252
|
+
return registration;
|
|
253
|
+
},
|
|
254
|
+
dispose(): void {
|
|
255
|
+
generation += 1;
|
|
256
|
+
for (const dispose of disposers.splice(0)) {
|
|
257
|
+
try {
|
|
258
|
+
dispose();
|
|
259
|
+
} catch {
|
|
260
|
+
// Disposal is best-effort; pi-telegram owns its registry lifetime.
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
statusRegistered = false;
|
|
264
|
+
sectionRegistered = false;
|
|
265
|
+
},
|
|
266
|
+
};
|
|
267
|
+
}
|
package/lib/terminal.ts
CHANGED
|
@@ -23,7 +23,7 @@ Use read_state only for a concrete historical or scope-specific gap. It reads on
|
|
|
23
23
|
|
|
24
24
|
Use patch_state as the sole model-authored semantic mutation mechanism. Supply any combination of global, cwd, and session patches; all supplied scopes are validated and durably accepted as one atomic transition before further reasoning. Call patch_state alone in its assistant response; after its acknowledgement choose the next action from accepted state.
|
|
25
25
|
|
|
26
|
-
Every enabled iteration starts terminal-ineligible. Set final:true in a successful patch_state call when the iteration may finish at a later turn_end. final:true does not stop reasoning, tools, or later patch_state calls, and repeated final:true calls are allowed. Use {"final":true} when no semantic update is needed. If
|
|
26
|
+
Every enabled iteration starts terminal-ineligible. Set final:true in a successful patch_state call when the iteration may finish at a later turn_end. final:true does not stop reasoning, tools, or later patch_state calls, and repeated final:true calls are allowed. Use {"final":true} when no semantic update is needed. If you end a terminal turn without eligibility, runtime preserves that answer as the iteration response and starts bounded fallback turns whose only purpose is the final:true patch: call patch_state with any durable scope changes and final:true, or {"final":true} alone, and never restate or replace the answer. After two fallback turns without final:true the iteration closes with its preserved answer and current state. A final-only call creates no semantic transition. Never write response through patch_state; runtime records what was actually delivered at turn_end.
|
|
27
27
|
|
|
28
28
|
SCOPES: session is branch/run continuation, cwd is project state and Skills, global is cross-project state. Deleting an override affects only its scope and may reveal a parent value.
|
|
29
29
|
|