@llblab/pi-state-flow 0.8.1 โ 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +1 -1
- package/BACKLOG.md +4 -1
- package/CHANGELOG.md +11 -0
- package/README.md +2 -0
- package/docs/architecture.md +3 -1
- package/index.ts +21 -0
- package/lib/extension.ts +157 -101
- package/lib/telegram.ts +266 -0
- package/package.json +1 -1
package/AGENTS.md
CHANGED
|
@@ -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
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# BACKLOG
|
|
2
2
|
|
|
3
|
-
Completed release work belongs in [CHANGELOG.md](CHANGELOG.md). No implementation item remains open for 0.
|
|
3
|
+
Completed release work belongs in [CHANGELOG.md](CHANGELOG.md). No implementation item remains open for 0.9.0.
|
|
4
4
|
|
|
5
5
|
## Candidate evolution
|
|
6
6
|
|
|
@@ -8,6 +8,9 @@ Completed release work belongs in [CHANGELOG.md](CHANGELOG.md). No implementatio
|
|
|
8
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
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
10
|
- Status: candidate, not scheduled. Do not start without a dedicated release contract.
|
|
11
|
+
- [ ] **Telegram submenu state analyzer:** Extend the State Flow Telegram section with a read-only analyzer view over the same diagnostics `/state-flow-status` already reports (branch mode, temporal head and hot depth, scope keys, retained tails, artifact freshness, publication). The operator deliberately deferred this beyond the 0.9.0 control surface.
|
|
12
|
+
- Boundary: presentation only. Reuse existing status diagnostics; no new semantic mode, and never mutate state from the analyzer view.
|
|
13
|
+
- Status: candidate, not scheduled. Do not start without a dedicated release contract.
|
|
11
14
|
|
|
12
15
|
## Deferred host integration
|
|
13
16
|
|
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,17 @@
|
|
|
2
2
|
|
|
3
3
|
> Each release keeps at most 8 outcome records of at most 512 characters.
|
|
4
4
|
|
|
5
|
+
## 0.9.1: Status text mirrors the terminal line
|
|
6
|
+
|
|
7
|
+
- `Interop`: The `pi-telegram` surfaces now copy the compact terminal status instead of decorating it. The Status screen shows the terminal value itself (`State Flow: #N`) and hides entirely while State Flow is off; the main-menu button shows `๐ State Flow: #N` or a plain `โซ๏ธ State Flow` without on/off, starting, bootstrap, or separator text.
|
|
8
|
+
- `Testing`: The shared test harness removes its temporary fixture repositories at process exit; runaway fixtures previously exhausted the `/tmp` inode table and made later runs fail with ENOSPC.
|
|
9
|
+
|
|
10
|
+
## 0.9.0: Telegram status surface
|
|
11
|
+
|
|
12
|
+
- `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.
|
|
13
|
+
- `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`.
|
|
14
|
+
- `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.
|
|
15
|
+
|
|
5
16
|
## 0.8.1: Preserved answers and bounded fallback resolution
|
|
6
17
|
|
|
7
18
|
- `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.
|
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: #N` while enabled and hides the row while off, and the inline main menu places a `๐ State Flow: #N` or `โซ๏ธ State Flow` 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:
|
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
|
|
|
@@ -199,6 +199,8 @@ 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
|
+
With `pi-telegram` installed, the optional `telegram` adapter mirrors the same identity in Telegram: the Status screen row shows `State Flow: #N` while enabled and hides while off, 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
|
+
|
|
202
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
|
package/index.ts
CHANGED
|
@@ -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/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,6 +45,7 @@ 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";
|
|
@@ -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);
|
|
@@ -455,6 +458,7 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
455
458
|
artifactInvalidations = [];
|
|
456
459
|
artifactReads.setCandidates([]);
|
|
457
460
|
artifactRefreshPending = false;
|
|
461
|
+
telegramStartPending = false;
|
|
458
462
|
activeContext = ctx;
|
|
459
463
|
const session = sessionAddress(ctx);
|
|
460
464
|
runtime = new TemporalRuntime(ctx.cwd, session, repositoryRoot);
|
|
@@ -748,74 +752,79 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
748
752
|
},
|
|
749
753
|
});
|
|
750
754
|
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
setPendingPublication(snapshot.meta.pendingPublication);
|
|
773
|
-
branchHasSnapshot = true;
|
|
774
|
-
}
|
|
775
|
-
const existingBranch = branchHasSnapshot;
|
|
776
|
-
snapshot = existingBranch
|
|
777
|
-
? resumeEpisode(snapshot, bootstrap)
|
|
778
|
-
: startEpisode(bootstrap);
|
|
779
|
-
if (snapshot.meta.remotePublication === undefined) {
|
|
780
|
-
snapshot.meta.remotePublication = serializeRemotePublicationPolicyDocument(
|
|
781
|
-
resolveRemotePublicationPolicy(existingBranch ? undefined : config.remotePublication, { legacyRuntime: existingBranch }),
|
|
782
|
-
);
|
|
783
|
-
}
|
|
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);
|
|
784
776
|
branchHasSnapshot = true;
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
bootstrapContinuation = snapshot.meta.bootstrap
|
|
794
|
-
? previousPassiveContinuation ?? previousBootstrapContinuation
|
|
795
|
-
: undefined;
|
|
796
|
-
deferArtifactRefresh();
|
|
797
|
-
syncStateFlowTools();
|
|
798
|
-
persist();
|
|
799
|
-
updateUi(ctx);
|
|
800
|
-
ctx.ui.notify(
|
|
801
|
-
snapshot.meta.bootstrap
|
|
802
|
-
? "State Flow enabled. The next complete agent run will migrate active context into state."
|
|
803
|
-
: "State Flow enabled. The next prompt starts a stateful agent run.",
|
|
804
|
-
"info",
|
|
805
|
-
);
|
|
806
|
-
} catch (error) {
|
|
807
|
-
snapshot = previousSnapshot;
|
|
808
|
-
passiveContinuation = previousPassiveContinuation;
|
|
809
|
-
bootstrapContinuation = previousBootstrapContinuation;
|
|
810
|
-
artifactRefreshPending = previousArtifactRefreshPending;
|
|
811
|
-
artifactInvalidations = previousArtifactInvalidations;
|
|
812
|
-
artifactReads.setCandidates(artifactInvalidations);
|
|
813
|
-
syncStateFlowTools();
|
|
814
|
-
ctx.ui.notify(
|
|
815
|
-
`State Flow could not initialize CWD state: ${error instanceof Error ? error.message : String(error)}`,
|
|
816
|
-
"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 }),
|
|
817
785
|
);
|
|
818
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);
|
|
819
828
|
},
|
|
820
829
|
});
|
|
821
830
|
|
|
@@ -826,47 +835,85 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
826
835
|
},
|
|
827
836
|
});
|
|
828
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
|
+
|
|
829
878
|
pi.registerCommand("state-flow-stop", {
|
|
830
879
|
description: "Stop State Flow on the current session branch",
|
|
831
880
|
handler: async (_args, ctx) => {
|
|
832
|
-
|
|
833
|
-
let selected = runtime;
|
|
834
|
-
let current = snapshot;
|
|
835
|
-
if (!selected?.view && snapshot.meta.durableBase) {
|
|
836
|
-
selected = createRuntime(ctx);
|
|
837
|
-
current = selected.restore(snapshot.meta.durableBase, snapshot);
|
|
838
|
-
}
|
|
839
|
-
const stoppedAt = Date.now();
|
|
840
|
-
const exitStates = selected?.view ? selected.states() : undefined;
|
|
841
|
-
const exitHandoff = current.config.enabled && exitStates
|
|
842
|
-
? createPassiveContinuation(
|
|
843
|
-
projectStateForModel(overlayStates(exitStates.global, exitStates.cwd, exitStates.session)),
|
|
844
|
-
stoppedAt,
|
|
845
|
-
)
|
|
846
|
-
: undefined;
|
|
847
|
-
const retainedHandoff = exitHandoff ?? (!current.config.enabled ? passiveContinuation : undefined);
|
|
848
|
-
const stopped = stopEpisode(current);
|
|
849
|
-
const publication = selected?.view ? selected.publish(stopped) : undefined;
|
|
850
|
-
if (selected !== runtime) {
|
|
851
|
-
runtime = selected;
|
|
852
|
-
installScopeStates();
|
|
853
|
-
}
|
|
854
|
-
snapshot = stopped;
|
|
855
|
-
recordPolicyPublication(publication, ctx);
|
|
856
|
-
branchHasSnapshot = true;
|
|
857
|
-
clearRunTransient();
|
|
858
|
-
passiveContinuation = retainedHandoff;
|
|
859
|
-
bootstrapContinuation = undefined;
|
|
860
|
-
artifactInvalidations = [];
|
|
861
|
-
artifactReads.setCandidates([]);
|
|
862
|
-
artifactRefreshPending = false;
|
|
863
|
-
if (exitHandoff) pi.appendEntry(PASSIVE_STOP_ENTRY_TYPE, { at: stoppedAt });
|
|
864
|
-
syncStateFlowTools();
|
|
865
|
-
persist();
|
|
866
|
-
updateUi(ctx);
|
|
881
|
+
stopStateFlow(ctx);
|
|
867
882
|
},
|
|
868
883
|
});
|
|
869
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
|
+
|
|
870
917
|
pi.on("before_agent_start", (event, ctx) => {
|
|
871
918
|
if (!snapshot.config.enabled) return;
|
|
872
919
|
skillReads.clear();
|
|
@@ -1005,7 +1052,11 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
1005
1052
|
updateUi(ctx);
|
|
1006
1053
|
});
|
|
1007
1054
|
|
|
1008
|
-
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
|
+
}
|
|
1009
1060
|
if (snapshot.meta.remotePublication?.mode === "turn-end") launchPublicationWorker();
|
|
1010
1061
|
});
|
|
1011
1062
|
|
|
@@ -1015,8 +1066,13 @@ export default function stateFlowExtension(pi: ExtensionAPI, options: StateFlowE
|
|
|
1015
1066
|
retryPendingPush(ctx);
|
|
1016
1067
|
if (snapshot.meta.remotePublication?.mode === "turn-end") launchPublicationWorker();
|
|
1017
1068
|
updateUi(ctx);
|
|
1069
|
+
void telegram.ensure();
|
|
1018
1070
|
});
|
|
1019
1071
|
pi.on("session_tree", (_event, ctx) => {
|
|
1020
1072
|
restoreActiveBranch(ctx);
|
|
1021
1073
|
});
|
|
1074
|
+
pi.on("session_shutdown", () => {
|
|
1075
|
+
telegramStartPending = false;
|
|
1076
|
+
telegram.dispose();
|
|
1077
|
+
});
|
|
1022
1078
|
}
|
package/lib/telegram.ts
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
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 line: key plus step value, hidden while State Flow is off. */
|
|
94
|
+
export function formatStateFlowStatusLine(snapshot: StateFlowTelegramSnapshot): StateFlowTelegramStatusLine | undefined {
|
|
95
|
+
if (!snapshot.enabled) return undefined;
|
|
96
|
+
return { label: "State Flow", value: `#${snapshot.step}` };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Main-menu section label doubles as the live status value; the disabled row carries no status text. */
|
|
100
|
+
export function formatStateFlowSectionLabel(snapshot: StateFlowTelegramSnapshot): string {
|
|
101
|
+
return snapshot.enabled ? `๐ State Flow: #${snapshot.step}` : "โซ๏ธ State Flow";
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function buildStateFlowSectionView(
|
|
105
|
+
snapshot: StateFlowTelegramSnapshot,
|
|
106
|
+
callbackData: (action: string) => string,
|
|
107
|
+
): StateFlowTelegramView {
|
|
108
|
+
const lines = ["<b>๐ State Flow</b>", ""];
|
|
109
|
+
if (snapshot.enabled) {
|
|
110
|
+
lines.push("Status: <b>enabled</b>", `State iteration: <code>#${snapshot.step}</code>`);
|
|
111
|
+
if (snapshot.bootstrap) lines.push("Bootstrap run: the next completed run migrates active context into state.");
|
|
112
|
+
} else if (snapshot.startPending) {
|
|
113
|
+
lines.push("Status: <b>off</b>", "Start is pending until the current turn settles.");
|
|
114
|
+
} else {
|
|
115
|
+
lines.push("Status: <b>off</b>", "State Flow is disabled on this session branch.");
|
|
116
|
+
}
|
|
117
|
+
const buttons: StateFlowTelegramButton[] = [];
|
|
118
|
+
if (snapshot.startPending) {
|
|
119
|
+
buttons.push({ text: "โ๏ธ Cancel start", callback_data: callbackData("cancel") });
|
|
120
|
+
} else if (snapshot.enabled) {
|
|
121
|
+
buttons.push({ text: "โน Stop", callback_data: callbackData("stop") });
|
|
122
|
+
} else {
|
|
123
|
+
buttons.push({ text: "โถ๏ธ Start", callback_data: callbackData("start") });
|
|
124
|
+
}
|
|
125
|
+
buttons.push({ text: "๐ Refresh", callback_data: callbackData("refresh") });
|
|
126
|
+
return { text: lines.join("\n"), parseMode: "html", replyMarkup: { inline_keyboard: [buttons] } };
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function buildStateFlowTelegramSection(port: StateFlowTelegramPort) {
|
|
130
|
+
return {
|
|
131
|
+
id: STATE_FLOW_TELEGRAM_ID,
|
|
132
|
+
label: "๐ State Flow",
|
|
133
|
+
getLabel: () => formatStateFlowSectionLabel(port.snapshot()),
|
|
134
|
+
render: (ctx: StateFlowTelegramSectionContext) =>
|
|
135
|
+
buildStateFlowSectionView(port.snapshot(), (action) => ctx.callbackData(action)),
|
|
136
|
+
handleCallback: async (ctx: StateFlowTelegramCallbackContext) => {
|
|
137
|
+
if (ctx.action !== "start" && ctx.action !== "stop" && ctx.action !== "cancel" && ctx.action !== "refresh") return "pass" as const;
|
|
138
|
+
let notice: string | undefined;
|
|
139
|
+
try {
|
|
140
|
+
if (ctx.action === "start") {
|
|
141
|
+
if (port.canStartNow()) notice = port.start().message;
|
|
142
|
+
else {
|
|
143
|
+
port.deferStart();
|
|
144
|
+
notice = "State Flow will start after the current turn";
|
|
145
|
+
}
|
|
146
|
+
} else if (ctx.action === "stop") {
|
|
147
|
+
notice = port.stop().message;
|
|
148
|
+
} else if (ctx.action === "cancel") {
|
|
149
|
+
port.cancelStart();
|
|
150
|
+
notice = "Pending start cancelled";
|
|
151
|
+
}
|
|
152
|
+
} catch (error) {
|
|
153
|
+
notice = error instanceof Error ? error.message : String(error);
|
|
154
|
+
}
|
|
155
|
+
await ctx.answerCallback(notice);
|
|
156
|
+
await ctx.edit(buildStateFlowSectionView(port.snapshot(), (action) => ctx.callbackData(action)));
|
|
157
|
+
return "handled" as const;
|
|
158
|
+
},
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
async function importTelegramModule<TModule>(
|
|
163
|
+
specifiers: readonly string[],
|
|
164
|
+
guard: (module: unknown) => module is TModule,
|
|
165
|
+
): Promise<TModule | undefined> {
|
|
166
|
+
for (const specifier of specifiers) {
|
|
167
|
+
try {
|
|
168
|
+
const imported = await import(specifier);
|
|
169
|
+
if (guard(imported)) return imported;
|
|
170
|
+
} catch {
|
|
171
|
+
// pi-telegram is optional; its absence only disables the Telegram surface.
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return undefined;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Default loader; injectable so tests and embedded hosts can control transport presence. */
|
|
178
|
+
export async function loadStateFlowTelegramModules(): Promise<StateFlowTelegramModules> {
|
|
179
|
+
const status = await importTelegramModule<StateFlowTelegramStatusModule>(
|
|
180
|
+
STATUS_IMPORT_SPECIFIERS,
|
|
181
|
+
(module): module is StateFlowTelegramStatusModule =>
|
|
182
|
+
typeof (module as StateFlowTelegramStatusModule | undefined)?.registerTelegramStatusLineProvider === "function",
|
|
183
|
+
);
|
|
184
|
+
const sections = await importTelegramModule<StateFlowTelegramSectionModule>(
|
|
185
|
+
SECTIONS_IMPORT_SPECIFIERS,
|
|
186
|
+
(module): module is StateFlowTelegramSectionModule =>
|
|
187
|
+
typeof (module as StateFlowTelegramSectionModule | undefined)?.registerTelegramSection === "function",
|
|
188
|
+
);
|
|
189
|
+
return { ...(status === undefined ? {} : { status }), ...(sections === undefined ? {} : { sections }) };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export function createStateFlowTelegramAdapter(options: {
|
|
193
|
+
port: StateFlowTelegramPort;
|
|
194
|
+
load?: StateFlowTelegramLoader;
|
|
195
|
+
}): StateFlowTelegramAdapter {
|
|
196
|
+
const load = options.load ?? loadStateFlowTelegramModules;
|
|
197
|
+
let generation = 0;
|
|
198
|
+
let statusRegistered = false;
|
|
199
|
+
let sectionRegistered = false;
|
|
200
|
+
let registration: Promise<boolean> | undefined;
|
|
201
|
+
const disposers: Array<() => void> = [];
|
|
202
|
+
|
|
203
|
+
const register = async (): Promise<boolean> => {
|
|
204
|
+
const epoch = generation;
|
|
205
|
+
let modules: StateFlowTelegramModules;
|
|
206
|
+
try {
|
|
207
|
+
modules = await load();
|
|
208
|
+
} catch {
|
|
209
|
+
return false;
|
|
210
|
+
}
|
|
211
|
+
// A shutdown during loading must not leave a registration behind.
|
|
212
|
+
if (epoch !== generation) return false;
|
|
213
|
+
if (!statusRegistered && modules.status) {
|
|
214
|
+
try {
|
|
215
|
+
const dispose = modules.status.registerTelegramStatusLineProvider(
|
|
216
|
+
() => formatStateFlowStatusLine(options.port.snapshot()),
|
|
217
|
+
{ id: STATE_FLOW_TELEGRAM_ID },
|
|
218
|
+
);
|
|
219
|
+
if (epoch === generation) {
|
|
220
|
+
disposers.push(dispose);
|
|
221
|
+
statusRegistered = true;
|
|
222
|
+
} else {
|
|
223
|
+
dispose();
|
|
224
|
+
}
|
|
225
|
+
} catch {
|
|
226
|
+
// Registry not initialized yet; the next ensure retries.
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
if (!sectionRegistered && modules.sections) {
|
|
230
|
+
try {
|
|
231
|
+
const dispose = modules.sections.registerTelegramSection(buildStateFlowTelegramSection(options.port));
|
|
232
|
+
if (epoch === generation) {
|
|
233
|
+
disposers.push(dispose);
|
|
234
|
+
sectionRegistered = true;
|
|
235
|
+
} else {
|
|
236
|
+
dispose();
|
|
237
|
+
}
|
|
238
|
+
} catch {
|
|
239
|
+
// Registry not initialized yet; the next ensure retries.
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
return statusRegistered || sectionRegistered;
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
return {
|
|
246
|
+
async ensure(): Promise<boolean> {
|
|
247
|
+
if (statusRegistered && sectionRegistered) return true;
|
|
248
|
+
registration ??= register().finally(() => {
|
|
249
|
+
registration = undefined;
|
|
250
|
+
});
|
|
251
|
+
return registration;
|
|
252
|
+
},
|
|
253
|
+
dispose(): void {
|
|
254
|
+
generation += 1;
|
|
255
|
+
for (const dispose of disposers.splice(0)) {
|
|
256
|
+
try {
|
|
257
|
+
dispose();
|
|
258
|
+
} catch {
|
|
259
|
+
// Disposal is best-effort; pi-telegram owns its registry lifetime.
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
statusRegistered = false;
|
|
263
|
+
sectionRegistered = false;
|
|
264
|
+
},
|
|
265
|
+
};
|
|
266
|
+
}
|