@llblab/pi-state-flow 0.27.4 → 0.27.6
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 +3 -2
- package/BACKLOG.md +1 -1
- package/CHANGELOG.md +10 -0
- package/README.md +6 -4
- package/dist/lib/config.d.ts +1 -1
- package/dist/lib/extension.d.ts +2 -2
- package/dist/lib/extension.js +265 -249
- package/dist/lib/ownership.d.ts +1 -1
- package/dist/lib/ownership.js +2 -2
- package/dist/lib/protocol.d.ts +1 -1
- package/dist/lib/protocol.js +6 -6
- package/dist/lib/query.js +1 -1
- package/dist/lib/telegram.js +0 -2
- package/dist/package.json +1 -1
- package/dist/skills/state-flow-guide/SKILL.md +8 -6
- package/dist/skills/state-flow-memory/SKILL.md +8 -6
- package/docs/README.md +1 -1
- package/docs/architecture.md +16 -14
- package/docs/compatibility.md +10 -0
- package/docs/filesystem-recovery.md +1 -1
- package/docs/lazy-state.md +17 -17
- package/docs/public-module-contract.md +1 -1
- package/docs/scope-selection-contract.md +2 -0
- package/docs/semantic-module-contract.md +1 -1
- package/docs/single-scope-interface-contract.md +1 -1
- package/docs/usage.md +18 -16
- package/lib/config.ts +1 -1
- package/lib/extension.ts +39 -23
- package/lib/ownership.ts +2 -2
- package/lib/protocol.ts +6 -6
- package/lib/query.ts +1 -1
- package/lib/telegram.ts +0 -2
- package/package.json +1 -1
- package/skills/state-flow-guide/SKILL.md +8 -6
- package/skills/state-flow-memory/SKILL.md +8 -6
package/dist/lib/extension.js
CHANGED
|
@@ -34,8 +34,12 @@ import { createStateFlowTelegramAdapter } from "./telegram.js";
|
|
|
34
34
|
import { readTemporalScopes, temporalScopeRevisions } from "./temporal.js";
|
|
35
35
|
import { commitSelectedTransition, stageSelectedScopePatches, stageSelectedScopedTransition } from "./transition.js";
|
|
36
36
|
export { formatPatchStateArguments };
|
|
37
|
-
export const PATCH_STATE_TOOL_NAME = "
|
|
38
|
-
export const READ_STATE_TOOL_NAME = "
|
|
37
|
+
export const PATCH_STATE_TOOL_NAME = "state_flow_patch";
|
|
38
|
+
export const READ_STATE_TOOL_NAME = "state_flow_read";
|
|
39
|
+
const LEGACY_PATCH_STATE_TOOL_NAME = "patch_state";
|
|
40
|
+
const LEGACY_READ_STATE_TOOL_NAME = "read_state";
|
|
41
|
+
const STATE_FLOW_TOOL_NAMES = [PATCH_STATE_TOOL_NAME, READ_STATE_TOOL_NAME, LEGACY_PATCH_STATE_TOOL_NAME, LEGACY_READ_STATE_TOOL_NAME];
|
|
42
|
+
const isPatchStateTool = (name) => name === PATCH_STATE_TOOL_NAME || name === LEGACY_PATCH_STATE_TOOL_NAME;
|
|
39
43
|
const PASSIVE_STOP_ENTRY_TYPE = "state-flow-passive-stop";
|
|
40
44
|
const flatPatchParameters = Type.Object({
|
|
41
45
|
intents: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
|
|
@@ -317,13 +321,14 @@ export default function stateFlowExtension(pi, options = {}) {
|
|
|
317
321
|
// Every SDK registration is a fresh copy, preserving old response-wrapper declarations.
|
|
318
322
|
if (force || patchStateTool.parameters !== parameters) {
|
|
319
323
|
patchStateTool.parameters = parameters;
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
324
|
+
for (const tool of [patchStateTool, legacyPatchStateTool])
|
|
325
|
+
pi.registerTool({ ...tool, parameters, ...(external.length && tool === patchStateTool ? {
|
|
326
|
+
promptGuidelines: [...(patchStateTool.promptGuidelines ?? []), `Registered mutable object planes: ${external.join(", ")}. Availability and matching retained schema/policy are revalidated at acceptance.`],
|
|
327
|
+
} : {}) });
|
|
323
328
|
}
|
|
324
329
|
}
|
|
325
330
|
const active = pi.getActiveTools();
|
|
326
|
-
const owned =
|
|
331
|
+
const owned = STATE_FLOW_TOOL_NAMES;
|
|
327
332
|
if (owned.every((name) => active.includes(name) === available))
|
|
328
333
|
return;
|
|
329
334
|
pi.setActiveTools(available
|
|
@@ -952,261 +957,272 @@ export default function stateFlowExtension(pi, options = {}) {
|
|
|
952
957
|
return false;
|
|
953
958
|
}
|
|
954
959
|
}
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
const check = () => {
|
|
982
|
-
receipt.revalidate();
|
|
983
|
-
signal?.throwIfAborted();
|
|
984
|
-
if (!ctx || runtime !== selected || selected.sessionId !== receipt.policy.owner || receipt.policy.owner !== ctx.sessionManager.getSessionId() || receipt.policy.cwd !== ctx.cwd
|
|
985
|
-
|| selected.cwd !== ctx.cwd || selected.sessionKey !== sessionAddress(ctx).key)
|
|
986
|
-
throw new Error("State Flow read selection owner changed");
|
|
987
|
-
};
|
|
988
|
-
check();
|
|
989
|
-
const wanted = captureScopeSelection(receipt.policy.scopes);
|
|
990
|
-
params = structuredClone(params);
|
|
991
|
-
check();
|
|
992
|
-
if (params.path === undefined && params.paths === undefined)
|
|
993
|
-
throw new Error("read_state requires path or paths");
|
|
994
|
-
if (params.path !== undefined && params.paths !== undefined)
|
|
995
|
-
throw new Error("read_state accepts path or paths, not both");
|
|
996
|
-
{
|
|
997
|
-
const requestedPaths = [...(params.paths ?? [params.path])];
|
|
998
|
-
const paths = requestedPaths.map(path => normalizeModelReadPath(path, wanted, config.historyLimit));
|
|
999
|
-
check();
|
|
1000
|
-
const view = readableView(selected);
|
|
1001
|
-
// Wanted policy was checked by normalization; an observational subset is not an exclusion.
|
|
1002
|
-
for (const path of paths) {
|
|
1003
|
-
const owner = /^(global|cwd|session)(?=\.|\[|$)/.exec(path)?.[1];
|
|
1004
|
-
if (owner && !view?.selection.includes(owner))
|
|
1005
|
-
throw new Error(`State Flow ${owner}: selected, unavailable`);
|
|
1006
|
-
}
|
|
1007
|
-
if (!view)
|
|
960
|
+
function readStateDefinition(name) {
|
|
961
|
+
return defineTool({
|
|
962
|
+
name,
|
|
963
|
+
...(name === LEGACY_READ_STATE_TOOL_NAME ? { prepareLoadout: () => ({ hiddenDeclarations: [name] }) } : {}),
|
|
964
|
+
label: "Read State",
|
|
965
|
+
description: "Read exact State Flow values or historical semantic patches with one path or an ordered path list. With one participating owner, semantic paths and structured references are scope-free, effective[N] selects that owner's historical boundary, and patches[N] selects its retained owner patch. With multiple owners, unscoped paths use the effective overlay and owner patch history requires an explicit owner. Optional global/cwd/session roots may address only participating available owners. Array selectors are zero-based indices or half-open [start..end] ranges, never temporal offsets inside a semantic value. Projection value returns data; keys returns minimal structure; patch intersects the selected path at its boundary. Path object keys must be ASCII identifiers ([A-Za-z_$][A-Za-z0-9_$-]*); non-ASCII keys cannot be addressed.",
|
|
966
|
+
promptSnippet: "Read exact state values, structures, or historical semantic patches",
|
|
967
|
+
promptGuidelines: [SCOPE_PARTICIPATION_GUIDELINE],
|
|
968
|
+
parameters: Type.Object({
|
|
969
|
+
path: Type.Optional(Type.String({ description: "One semantic path. One owner: flat planes, effective[N] history or retained patches[N]. Multiple owners: effective overlay or explicit participating owner; patch history needs owner.patches[N]. Nested array selectors stay ordinary indices/ranges." })),
|
|
970
|
+
paths: Type.Optional(Type.Array(Type.String(), { minItems: 1, description: "Ordered query paths evaluated as one all-or-error read" })),
|
|
971
|
+
projection: Type.Optional(StringEnum(["value", "keys", "patch"], { description: "Value snapshot by default, structural keys with minimal meta, or the selected historical semantic patch" })),
|
|
972
|
+
}, { additionalProperties: false }),
|
|
973
|
+
async execute(toolCallId, params, signal, _onUpdate, ctx) {
|
|
974
|
+
try {
|
|
975
|
+
const admission = nativeToolAdmission(toolCallId, name, ctx);
|
|
976
|
+
admission?.revalidate();
|
|
977
|
+
if (admission)
|
|
978
|
+
signal = signal ? AbortSignal.any([signal, admission.signal]) : admission.signal;
|
|
979
|
+
if (!memoryToolsAvailable())
|
|
980
|
+
throw new Error("State Flow tools are off for this session");
|
|
981
|
+
if (signal?.aborted)
|
|
982
|
+
throw new Error("State Flow read was aborted");
|
|
983
|
+
assertSelectedBranchAvailable();
|
|
984
|
+
const selected = runtime;
|
|
985
|
+
if (!selected)
|
|
1008
986
|
throw new Error("State Flow temporal runtime is unavailable");
|
|
987
|
+
const receipt = admission ?? requestPolicy.capture();
|
|
988
|
+
const check = () => {
|
|
989
|
+
receipt.revalidate();
|
|
990
|
+
signal?.throwIfAborted();
|
|
991
|
+
if (!ctx || runtime !== selected || selected.sessionId !== receipt.policy.owner || receipt.policy.owner !== ctx.sessionManager.getSessionId() || receipt.policy.cwd !== ctx.cwd
|
|
992
|
+
|| selected.cwd !== ctx.cwd || selected.sessionKey !== sessionAddress(ctx).key)
|
|
993
|
+
throw new Error("State Flow read selection owner changed");
|
|
994
|
+
};
|
|
1009
995
|
check();
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
const
|
|
996
|
+
const wanted = captureScopeSelection(receipt.policy.scopes);
|
|
997
|
+
params = structuredClone(params);
|
|
998
|
+
check();
|
|
999
|
+
if (params.path === undefined && params.paths === undefined)
|
|
1000
|
+
throw new Error("state_flow_read requires path or paths");
|
|
1001
|
+
if (params.path !== undefined && params.paths !== undefined)
|
|
1002
|
+
throw new Error("state_flow_read accepts path or paths, not both");
|
|
1003
|
+
{
|
|
1004
|
+
const requestedPaths = [...(params.paths ?? [params.path])];
|
|
1005
|
+
const paths = requestedPaths.map(path => normalizeModelReadPath(path, wanted, config.historyLimit));
|
|
1006
|
+
check();
|
|
1007
|
+
const view = readableView(selected);
|
|
1008
|
+
// Wanted policy was checked by normalization; an observational subset is not an exclusion.
|
|
1009
|
+
for (const path of paths) {
|
|
1010
|
+
const owner = /^(global|cwd|session)(?=\.|\[|$)/.exec(path)?.[1];
|
|
1011
|
+
if (owner && !view?.selection.includes(owner))
|
|
1012
|
+
throw new Error(`State Flow ${owner}: selected, unavailable`);
|
|
1013
|
+
}
|
|
1014
|
+
if (!view)
|
|
1015
|
+
throw new Error("State Flow temporal runtime is unavailable");
|
|
1016
|
+
check();
|
|
1017
|
+
if (paths.some((path) => /^session(?:\.|\[|$)/.test(path)))
|
|
1018
|
+
assertSelectedBranchAvailable();
|
|
1019
|
+
if (paths.length === 1 && /^(?:global|cwd|session)\.patches(?:\[\d+\])?$/.test(paths[0])) {
|
|
1020
|
+
if (params.projection !== undefined && params.projection !== "value")
|
|
1021
|
+
throw new Error("Scope patch paths support only the value projection");
|
|
1022
|
+
const result = readStatePath(view, paths[0], config.historyLimit);
|
|
1023
|
+
if (!("patch" in result))
|
|
1024
|
+
throw new Error("Expected a scope patch path");
|
|
1025
|
+
const output = wanted.length === 1 ? projectModelReferences({ patch: result.patch }, wanted, wanted.flatMap(scope => Object.keys(view.scopes[scope]?.modules ?? {}))) : { patch: result.patch };
|
|
1026
|
+
check();
|
|
1027
|
+
return {
|
|
1028
|
+
content: [{ type: "text", text: `\n${JSON.stringify(output)}` }],
|
|
1029
|
+
details: { path: requestedPaths[0], transitionId: result.boundary.id },
|
|
1030
|
+
};
|
|
1031
|
+
}
|
|
1032
|
+
const result = readProjectedState(view, paths, params.projection, config.historyLimit);
|
|
1033
|
+
const output = wanted.length === 1 ? projectModelReferences(result, wanted, wanted.flatMap(scope => Object.keys(view.scopes[scope]?.modules ?? {}))) : result;
|
|
1019
1034
|
check();
|
|
1020
1035
|
return {
|
|
1021
1036
|
content: [{ type: "text", text: `\n${JSON.stringify(output)}` }],
|
|
1022
|
-
details: { path: requestedPaths[0],
|
|
1037
|
+
details: { ...(params.path === undefined ? { paths: requestedPaths } : { path: requestedPaths[0] }), projection: params.projection ?? "value" },
|
|
1023
1038
|
};
|
|
1024
1039
|
}
|
|
1025
|
-
const result = readProjectedState(view, paths, params.projection, config.historyLimit);
|
|
1026
|
-
const output = wanted.length === 1 ? projectModelReferences(result, wanted, wanted.flatMap(scope => Object.keys(view.scopes[scope]?.modules ?? {}))) : result;
|
|
1027
|
-
check();
|
|
1028
|
-
return {
|
|
1029
|
-
content: [{ type: "text", text: `\n${JSON.stringify(output)}` }],
|
|
1030
|
-
details: { ...(params.path === undefined ? { paths: requestedPaths } : { path: requestedPaths[0] }), projection: params.projection ?? "value" },
|
|
1031
|
-
};
|
|
1032
1040
|
}
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
}
|
|
1037
|
-
}
|
|
1038
|
-
}
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
"
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
throw new Error("State Flow patch was aborted before materialization");
|
|
1076
|
-
if (!ctx)
|
|
1077
|
-
throw new Error("State Flow patch selection owner changed");
|
|
1078
|
-
const selected = runtime ??= createRuntime(ctx);
|
|
1079
|
-
const sameSession = sessionIdentity(ctx);
|
|
1080
|
-
const receipt = admission ?? requestPolicy.capture();
|
|
1081
|
-
const wanted = captureScopeSelection(receipt.policy.scopes);
|
|
1082
|
-
const catalog = moduleHost.captureIfBound();
|
|
1083
|
-
signal = AbortSignal.any([signal, receipt.signal, ...(catalog ? [catalog.signal] : [])]);
|
|
1084
|
-
const check = () => {
|
|
1085
|
-
receipt.revalidate();
|
|
1086
|
-
if (runtime !== selected || !sameSession() || selected.sessionId !== receipt.policy.owner || receipt.policy.owner !== ctx.sessionManager.getSessionId()
|
|
1087
|
-
|| receipt.policy.cwd !== ctx.cwd || selected.cwd !== ctx.cwd || selected.sessionKey !== sessionAddress(ctx).key)
|
|
1088
|
-
throw new Error("State Flow patch selection owner changed");
|
|
1089
|
-
assertPublicationAvailable();
|
|
1090
|
-
catalog?.assertCurrent();
|
|
1091
|
-
};
|
|
1092
|
-
// Rehash and normalize only after caller admission, still before canonical exclusion.
|
|
1093
|
-
check();
|
|
1094
|
-
const excluded = isObject(params) && Object.keys(params).find(key => DEFAULT_SCOPE_SELECTION.includes(key) && !wanted.includes(key));
|
|
1095
|
-
if (excluded)
|
|
1096
|
-
throw new Error(`State Flow ${excluded} patch scope is excluded`);
|
|
1097
|
-
params = structuredClone(params);
|
|
1098
|
-
check();
|
|
1099
|
-
admitted = true;
|
|
1100
|
-
const knownModules = [...new Set([...(catalog?.modules.map(module => module.id) ?? []),
|
|
1101
|
-
...wanted.flatMap(scope => Object.keys(readableView(selected)?.scopes[scope]?.modules ?? {}))])];
|
|
1102
|
-
const patches = normalizeModelPatches(params, wanted, knownModules);
|
|
1103
|
-
check();
|
|
1104
|
-
const scopes = Object.keys(patches);
|
|
1105
|
-
const firstAuthoring = selected.selectedView() === undefined;
|
|
1106
|
-
const acquiredArtifacts = structuredClone([...artifactReads.successful.values()]);
|
|
1107
|
-
const acquiredSkills = structuredClone([...skillReads.successful.values()]);
|
|
1108
|
-
const previousEffective = effectiveState;
|
|
1109
|
-
skillReads.validateCompilations(patches);
|
|
1110
|
-
const author = (transaction) => {
|
|
1111
|
-
check();
|
|
1112
|
-
if (runtime !== selected)
|
|
1113
|
-
throw new Error("State Flow session selection changed while awaiting publication");
|
|
1041
|
+
catch (error) {
|
|
1042
|
+
throw separatedFailure(error);
|
|
1043
|
+
}
|
|
1044
|
+
},
|
|
1045
|
+
});
|
|
1046
|
+
}
|
|
1047
|
+
pi.registerTool(readStateDefinition(READ_STATE_TOOL_NAME));
|
|
1048
|
+
pi.registerTool({ ...readStateDefinition(LEGACY_READ_STATE_TOOL_NAME), promptSnippet: "", promptGuidelines: [] });
|
|
1049
|
+
function patchStateDefinition(name) {
|
|
1050
|
+
return defineTool({
|
|
1051
|
+
name,
|
|
1052
|
+
...(name === LEGACY_PATCH_STATE_TOOL_NAME ? { prepareLoadout: () => ({ hiddenDeclarations: [name] }) } : {}),
|
|
1053
|
+
label: "Patch State",
|
|
1054
|
+
description: "The sole State Flow semantic mutation protocol. With one participating owner, supply intents/strategy/tactics/artifacts/lazy planes directly, without an owner wrapper. With multiple owners, supply one or more global, cwd, or session patches for participating owners; all supplied owners commit atomically. This call must be the only State Flow barrier in its assistant response. Intent updates run first, then clear owned same-scope strategy/tactics/lazy keys unless a remaining or new intent refs them, then other fields apply. Later writes can recreate cleared paths without old fields. Name keys in ASCII ([A-Za-z_$][A-Za-z0-9_$-]*) so read paths and refs resolve; values may use any language.",
|
|
1055
|
+
promptSnippet: "Atomically patch participating semantic memory in its declared flat or multi-owner form",
|
|
1056
|
+
promptGuidelines: [
|
|
1057
|
+
RESPONSE_PATCH_GUIDELINE,
|
|
1058
|
+
SCOPE_PARTICIPATION_GUIDELINE,
|
|
1059
|
+
"Use state_flow_patch only for material durable semantic changes; ordinary answers need no finalization call.",
|
|
1060
|
+
"Use state_flow_patch as reconciliation, not append-only notes: place new knowledge at the narrowest valid scope and remove superseded or completed state from touched branches.",
|
|
1061
|
+
"Call state_flow_patch alone in an assistant response; after its acknowledgement, further reasoning, tools, and later state_flow_patch calls remain allowed.",
|
|
1062
|
+
],
|
|
1063
|
+
executionMode: "sequential",
|
|
1064
|
+
parameters: config.scopes.length === 1 ? flatPatchParameters : scopedPatchParameters,
|
|
1065
|
+
renderCall(args, theme, context) {
|
|
1066
|
+
const title = theme.fg("toolTitle", theme.bold(name));
|
|
1067
|
+
if (!config.showSuccessfulPatches && !context.isError)
|
|
1068
|
+
return new Text(title, 0, 0);
|
|
1069
|
+
return new Text(`${title}\n${separatedOutput(theme.fg("dim", formatPatchStateArguments(args)))}`, 0, 0);
|
|
1070
|
+
},
|
|
1071
|
+
renderResult(result) {
|
|
1072
|
+
const text = result.content.find((block) => block.type === "text")?.text ?? "";
|
|
1073
|
+
return new Text(separatedOutput(text), 0, 0);
|
|
1074
|
+
},
|
|
1075
|
+
async execute(toolCallId, params, signal, _onUpdate, ctx) {
|
|
1076
|
+
signal = signal ? AbortSignal.any([signal, memoryToolLifetime.signal]) : memoryToolLifetime.signal;
|
|
1077
|
+
let admitted = false;
|
|
1078
|
+
try {
|
|
1079
|
+
const admission = nativeToolAdmission(toolCallId, name, ctx);
|
|
1080
|
+
admission?.revalidate();
|
|
1081
|
+
if (admission)
|
|
1082
|
+
signal = AbortSignal.any([signal, admission.signal]);
|
|
1114
1083
|
if (!memoryToolsAvailable())
|
|
1115
1084
|
throw new Error("State Flow tools are off for this session");
|
|
1116
1085
|
assertPublicationAvailable();
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
const
|
|
1125
|
-
const
|
|
1126
|
-
|
|
1127
|
-
const
|
|
1128
|
-
|
|
1129
|
-
|
|
1086
|
+
if (signal?.aborted)
|
|
1087
|
+
throw new Error("State Flow patch was aborted before materialization");
|
|
1088
|
+
if (!ctx)
|
|
1089
|
+
throw new Error("State Flow patch selection owner changed");
|
|
1090
|
+
const selected = runtime ??= createRuntime(ctx);
|
|
1091
|
+
const sameSession = sessionIdentity(ctx);
|
|
1092
|
+
const receipt = admission ?? requestPolicy.capture();
|
|
1093
|
+
const wanted = captureScopeSelection(receipt.policy.scopes);
|
|
1094
|
+
const catalog = moduleHost.captureIfBound();
|
|
1095
|
+
signal = AbortSignal.any([signal, receipt.signal, ...(catalog ? [catalog.signal] : [])]);
|
|
1096
|
+
const check = () => {
|
|
1097
|
+
receipt.revalidate();
|
|
1098
|
+
if (runtime !== selected || !sameSession() || selected.sessionId !== receipt.policy.owner || receipt.policy.owner !== ctx.sessionManager.getSessionId()
|
|
1099
|
+
|| receipt.policy.cwd !== ctx.cwd || selected.cwd !== ctx.cwd || selected.sessionKey !== sessionAddress(ctx).key)
|
|
1100
|
+
throw new Error("State Flow patch selection owner changed");
|
|
1101
|
+
assertPublicationAvailable();
|
|
1130
1102
|
catalog?.assertCurrent();
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
if (
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
const
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
return await selected.withSelectedPatchTransaction(author, check, signal);
|
|
1152
|
-
check();
|
|
1153
|
-
const disposition = await selected.inspectSelectedLifecycle(wanted, check, signal);
|
|
1154
|
-
if (disposition && !wanted.includes("session")) {
|
|
1155
|
-
return await selected.withSelectedCurrentTransaction(wanted, (_current, _publish, transaction) => author(Object.freeze({
|
|
1156
|
-
...transaction, snapshot: { ...transaction.snapshot, config: { mode: receipt.policy.mode } },
|
|
1157
|
-
})), check, signal);
|
|
1158
|
-
}
|
|
1159
|
-
if (disposition) {
|
|
1160
|
-
const acquire = () => {
|
|
1103
|
+
};
|
|
1104
|
+
// Rehash and normalize only after caller admission, still before canonical exclusion.
|
|
1105
|
+
check();
|
|
1106
|
+
const excluded = isObject(params) && Object.keys(params).find(key => DEFAULT_SCOPE_SELECTION.includes(key) && !wanted.includes(key));
|
|
1107
|
+
if (excluded)
|
|
1108
|
+
throw new Error(`State Flow ${excluded} patch scope is excluded`);
|
|
1109
|
+
params = structuredClone(params);
|
|
1110
|
+
check();
|
|
1111
|
+
admitted = true;
|
|
1112
|
+
const knownModules = [...new Set([...(catalog?.modules.map(module => module.id) ?? []),
|
|
1113
|
+
...wanted.flatMap(scope => Object.keys(readableView(selected)?.scopes[scope]?.modules ?? {}))])];
|
|
1114
|
+
const patches = normalizeModelPatches(params, wanted, knownModules);
|
|
1115
|
+
check();
|
|
1116
|
+
const scopes = Object.keys(patches);
|
|
1117
|
+
const firstAuthoring = selected.selectedView() === undefined;
|
|
1118
|
+
const acquiredArtifacts = structuredClone([...artifactReads.successful.values()]);
|
|
1119
|
+
const acquiredSkills = structuredClone([...skillReads.successful.values()]);
|
|
1120
|
+
const previousEffective = effectiveState;
|
|
1121
|
+
skillReads.validateCompilations(patches);
|
|
1122
|
+
const author = (transaction) => {
|
|
1161
1123
|
check();
|
|
1162
|
-
if (
|
|
1163
|
-
|
|
1164
|
-
|
|
1124
|
+
if (runtime !== selected)
|
|
1125
|
+
throw new Error("State Flow session selection changed while awaiting publication");
|
|
1126
|
+
if (!memoryToolsAvailable())
|
|
1127
|
+
throw new Error("State Flow tools are off for this session");
|
|
1128
|
+
assertPublicationAvailable();
|
|
1129
|
+
for (const acquired of acquiredArtifacts) {
|
|
1130
|
+
const observation = inspectRegisteredArtifactPaths([acquired.path])[0];
|
|
1131
|
+
if (acquired.sourceFingerprint === undefined || observation?.kind !== "present"
|
|
1132
|
+
|| !sameArtifactSourceFingerprint(acquired.sourceFingerprint, observation.fingerprint)) {
|
|
1133
|
+
throw new Error(`Artifact source changed after acquisition: ${acquired.path}`);
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
const stage = stageSelectedScopePatches(transaction, patches, acquiredSkills, transaction.causalBasis, acquiredArtifacts, catalog?.modules);
|
|
1137
|
+
const changed = transaction.selection.some((scope) => !sameJson(transaction.states[scope], stage.nextStates[scope])
|
|
1138
|
+
|| Object.entries(stage.provenanceUpdates[scope] ?? {}).some(([path, evidence]) => !Object.hasOwn(transaction.provenance[scope] ?? {}, path) || !sameJson(transaction.provenance[scope]?.[path], evidence)));
|
|
1139
|
+
const nextSnapshot = structuredClone(firstAuthoring ? transaction.snapshot : snapshot);
|
|
1140
|
+
let publication;
|
|
1141
|
+
commitSelectedTransition(nextSnapshot, transaction, stage, (accepted, next) => {
|
|
1142
|
+
catalog?.assertCurrent();
|
|
1143
|
+
publication = transaction.publish(next, accepted, stage.provenanceUpdates, stage.moduleAdditions);
|
|
1144
|
+
}, transaction.causalBasis, { finalizeRun: false });
|
|
1145
|
+
snapshot = nextSnapshot;
|
|
1146
|
+
installScopeStates();
|
|
1147
|
+
if (publication?.changed) {
|
|
1148
|
+
recordPublication();
|
|
1149
|
+
appendCheckpoint();
|
|
1150
|
+
}
|
|
1151
|
+
clearAcceptedAcquisitions(new Set(acquiredArtifacts.map(({ path }) => path)));
|
|
1152
|
+
updateUi(ctx);
|
|
1153
|
+
const updates = contextProjection.acceptPatch(previousEffective, effectiveState, patches, acquisition.hints, stage.cascades, isActive(), wanted);
|
|
1154
|
+
const acknowledgement = changed
|
|
1155
|
+
? `\nState materialized atomically at ${scopes.join("+")} scope${scopes.length === 1 ? "" : "s"}.`
|
|
1156
|
+
: "\nState already current.";
|
|
1157
|
+
return { content: [
|
|
1158
|
+
{ type: "text", text: acknowledgement + stage.missingDeletions.map(deletion => projectModelMissingDeletion(deletion, wanted)).map(({ path, unavailablePath }) => `\n\nHint: deletion skipped at ${path}; target absent. First unavailable component: ${unavailablePath}. Check the path if you expected an existing value.`).join("") },
|
|
1159
|
+
...(updates ? [{ type: "text", text: `\n${presentationJson({ state_updates: updates })}` }] : []),
|
|
1160
|
+
], details: { scopes, step: snapshot.meta.step, changed, missingDeletions: stage.missingDeletions } };
|
|
1165
1161
|
};
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
acquire();
|
|
1169
|
-
if (!base)
|
|
1170
|
-
throw new Error("Unacquired State Flow first mutation source disappeared");
|
|
1171
|
-
let result;
|
|
1172
|
-
return await selected.withSelectedSessionAcquisitionTransaction({ kind: "unacquired", base, selection: wanted,
|
|
1173
|
-
snapshot: { ...disposition.snapshot, config: { mode: receipt.policy.mode } }, historyLimit: config.historyLimit,
|
|
1174
|
-
author: (basis, publish) => {
|
|
1175
|
-
acquire();
|
|
1176
|
-
result = author(Object.freeze({ selection: wanted,
|
|
1177
|
-
states: readTemporalScopes(basis.view, 0, config.historyLimit), snapshot: basis.snapshot,
|
|
1178
|
-
modules: Object.fromEntries(wanted.filter(scope => basis.view.scopes[scope]?.modules !== undefined).map(scope => [scope, structuredClone(basis.view.scopes[scope].modules)])),
|
|
1179
|
-
causalBasis: basis.view.lineage.at(-1).id, provenance: basis.provenance,
|
|
1180
|
-
publish: (next, transition, provenance, additions) => { acquire(); return publish(next, transition, provenance, additions); } }));
|
|
1181
|
-
} }, publish => { acquire(); publish(); return result; }, signal, true);
|
|
1182
|
-
}
|
|
1183
|
-
if (!branchStartsWithoutRuntime || forkInitialization || branchPolicy(ctx).forkPending)
|
|
1184
|
-
throw new Error("State Flow first authoring requires native independent origin authority");
|
|
1185
|
-
return await selected.withSelectedFirstPatchTransaction(wanted, snapshot, author, () => {
|
|
1162
|
+
if (!firstAuthoring)
|
|
1163
|
+
return await selected.withSelectedPatchTransaction(author, check, signal);
|
|
1186
1164
|
check();
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
if (admitted && !signal.aborted && memoryToolsAvailable()) {
|
|
1193
|
-
let attempted;
|
|
1194
|
-
try {
|
|
1195
|
-
attempted = structuredClone(params);
|
|
1165
|
+
const disposition = await selected.inspectSelectedLifecycle(wanted, check, signal);
|
|
1166
|
+
if (disposition && !wanted.includes("session")) {
|
|
1167
|
+
return await selected.withSelectedCurrentTransaction(wanted, (_current, _publish, transaction) => author(Object.freeze({
|
|
1168
|
+
...transaction, snapshot: { ...transaction.snapshot, config: { mode: receipt.policy.mode } },
|
|
1169
|
+
})), check, signal);
|
|
1196
1170
|
}
|
|
1197
|
-
|
|
1198
|
-
|
|
1171
|
+
if (disposition) {
|
|
1172
|
+
const acquire = () => {
|
|
1173
|
+
check();
|
|
1174
|
+
if (receipt.policy.mode === "off" || !wanted.includes("session") || disposition.privateAcquisition !== "unacquired"
|
|
1175
|
+
|| forkInitialization || branchPolicy(ctx).forkPending)
|
|
1176
|
+
throw new Error("State Flow first mutation requires independent unacquired Session participation");
|
|
1177
|
+
};
|
|
1178
|
+
acquire();
|
|
1179
|
+
const base = await loadSelectedFileCohort(ctx.cwd, selected.sessionId, disposition.selection, selected.root, selected.sessionKey, signal);
|
|
1180
|
+
acquire();
|
|
1181
|
+
if (!base)
|
|
1182
|
+
throw new Error("Unacquired State Flow first mutation source disappeared");
|
|
1183
|
+
let result;
|
|
1184
|
+
return await selected.withSelectedSessionAcquisitionTransaction({ kind: "unacquired", base, selection: wanted,
|
|
1185
|
+
snapshot: { ...disposition.snapshot, config: { mode: receipt.policy.mode } }, historyLimit: config.historyLimit,
|
|
1186
|
+
author: (basis, publish) => {
|
|
1187
|
+
acquire();
|
|
1188
|
+
result = author(Object.freeze({ selection: wanted,
|
|
1189
|
+
states: readTemporalScopes(basis.view, 0, config.historyLimit), snapshot: basis.snapshot,
|
|
1190
|
+
modules: Object.fromEntries(wanted.filter(scope => basis.view.scopes[scope]?.modules !== undefined).map(scope => [scope, structuredClone(basis.view.scopes[scope].modules)])),
|
|
1191
|
+
causalBasis: basis.view.lineage.at(-1).id, provenance: basis.provenance,
|
|
1192
|
+
publish: (next, transition, provenance, additions) => { acquire(); return publish(next, transition, provenance, additions); } }));
|
|
1193
|
+
} }, publish => { acquire(); publish(); return result; }, signal, true);
|
|
1199
1194
|
}
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1195
|
+
if (!branchStartsWithoutRuntime || forkInitialization || branchPolicy(ctx).forkPending)
|
|
1196
|
+
throw new Error("State Flow first authoring requires native independent origin authority");
|
|
1197
|
+
return await selected.withSelectedFirstPatchTransaction(wanted, snapshot, author, () => {
|
|
1198
|
+
check();
|
|
1199
|
+
if (!branchStartsWithoutRuntime || forkInitialization || branchPolicy(ctx).forkPending)
|
|
1200
|
+
throw new Error("State Flow origin authority changed");
|
|
1201
|
+
}, signal, true);
|
|
1204
1202
|
}
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1203
|
+
catch (error) {
|
|
1204
|
+
if (admitted && !signal.aborted && memoryToolsAvailable()) {
|
|
1205
|
+
let attempted;
|
|
1206
|
+
try {
|
|
1207
|
+
attempted = structuredClone(params);
|
|
1208
|
+
}
|
|
1209
|
+
catch {
|
|
1210
|
+
attempted = undefined;
|
|
1211
|
+
}
|
|
1212
|
+
const cause = diagnosticText(error);
|
|
1213
|
+
recordDiagnostic(cause, /concurrently|advanced/.test(cause) ? "publication-conflict" : "invalid-patch", ctx, {
|
|
1214
|
+
input: attempted, tool: name, toolCallId,
|
|
1215
|
+
});
|
|
1216
|
+
}
|
|
1217
|
+
throw separatedFailure(error);
|
|
1218
|
+
}
|
|
1219
|
+
},
|
|
1220
|
+
});
|
|
1221
|
+
}
|
|
1222
|
+
const patchStateTool = patchStateDefinition(PATCH_STATE_TOOL_NAME);
|
|
1223
|
+
const legacyPatchStateTool = { ...patchStateDefinition(LEGACY_PATCH_STATE_TOOL_NAME), promptSnippet: "", promptGuidelines: [] };
|
|
1209
1224
|
pi.registerTool({ ...patchStateTool });
|
|
1225
|
+
pi.registerTool({ ...legacyPatchStateTool });
|
|
1210
1226
|
function startStateFlow(ctx, reselect = false) {
|
|
1211
1227
|
if (shuttingDown)
|
|
1212
1228
|
return Promise.resolve({ ok: false, message: "State Flow is shutting down" });
|
|
@@ -2050,10 +2066,10 @@ export default function stateFlowExtension(pi, options = {}) {
|
|
|
2050
2066
|
artifactReads.recordStart(event.toolCallId, event.toolName, event.args);
|
|
2051
2067
|
});
|
|
2052
2068
|
pi.on("tool_call", (event, ctx) => {
|
|
2053
|
-
const owned =
|
|
2069
|
+
const owned = STATE_FLOW_TOOL_NAMES.includes(event.toolName);
|
|
2054
2070
|
if (event.parentToolCallId) {
|
|
2055
|
-
if (event.toolName
|
|
2056
|
-
return { block: true, reason: "
|
|
2071
|
+
if (isPatchStateTool(event.toolName) && isActive())
|
|
2072
|
+
return { block: true, reason: "state_flow_patch requires a direct native assistant barrier, not a nested call" };
|
|
2057
2073
|
try {
|
|
2058
2074
|
nativeRequests.nested(event.toolCallId, event.toolName, event.parentToolCallId);
|
|
2059
2075
|
}
|
|
@@ -2073,15 +2089,15 @@ export default function stateFlowExtension(pi, options = {}) {
|
|
|
2073
2089
|
if (!isActive() || !currentNativeTool(event.toolCallId, event.toolName, ctx))
|
|
2074
2090
|
return;
|
|
2075
2091
|
const batch = findAssistantToolBatch(ctx.sessionManager, event.toolCallId);
|
|
2076
|
-
const patchCalls = batch?.filter(
|
|
2092
|
+
const patchCalls = batch?.filter(isPatchStateTool).length ?? 0;
|
|
2077
2093
|
if (patchCalls > 0) {
|
|
2078
2094
|
if (patchCalls !== 1) {
|
|
2079
|
-
const reason = "A State Flow barrier response must contain exactly one
|
|
2095
|
+
const reason = "A State Flow barrier response must contain exactly one state_flow_patch call";
|
|
2080
2096
|
recordDiagnostic(reason, "barrier-block", ctx, { tool: event.toolName, toolCallId: event.toolCallId, batchToolNames: batch });
|
|
2081
2097
|
return { block: true, reason };
|
|
2082
2098
|
}
|
|
2083
|
-
if (event.toolName
|
|
2084
|
-
const reason = "Blocked by the
|
|
2099
|
+
if (!isPatchStateTool(event.toolName)) {
|
|
2100
|
+
const reason = "Blocked by the state_flow_patch barrier; reconsider this action after State Flow rematerializes context";
|
|
2085
2101
|
recordDiagnostic(reason, "barrier-block", ctx, { tool: event.toolName, toolCallId: event.toolCallId, batchToolNames: batch });
|
|
2086
2102
|
return { block: true, reason };
|
|
2087
2103
|
}
|
package/dist/lib/ownership.d.ts
CHANGED
|
@@ -25,7 +25,7 @@ export declare function extractOwnedPaths(scope: StateScope, value: JsonValue):
|
|
|
25
25
|
export declare function computeIntentCascade(scope: StateScope, before: SemanticState, after: SemanticState): OwnedPath[];
|
|
26
26
|
/** Express cascade targets as explicit nested object-key deletions. */
|
|
27
27
|
export declare function cascadeDeletionPatch(paths: readonly OwnedPath[]): JsonObject;
|
|
28
|
-
/** Render an ownership target as its scoped `
|
|
28
|
+
/** Render an ownership target as its scoped `state_flow_read` path. */
|
|
29
29
|
export declare function formatOwnedPath(scope: StateScope, path: OwnedPath): string;
|
|
30
30
|
/** Top-level ownership-eligible keys referenced by current intents of `scope`. */
|
|
31
31
|
export declare function ownedTopLevelKeys(scope: StateScope, state: SemanticState): Record<OwnedPlane, Set<string>>;
|