@unieai/rabi-plan-mode 0.2.1-rc.3 → 0.2.2-rc.5

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/lib/index.js CHANGED
@@ -19,18 +19,16 @@ import { UserQuestionError } from "@unieai/rabi-user-questions";
19
19
  * assembly, then appends `plan/mode` from `agent/pre-step` only when the step
20
20
  * is accepted. Same-step request retries reuse their assembly.
21
21
  *
22
- * The exit tool remains registered while plan mode is inactive, so entering
23
- * or leaving plan mode changes only the prompt section, not the request tool
24
- * catalog.
22
+ * The exit tool is disclosed progressively: it is admitted from the first step
23
+ * whose selected state is active and stays admitted for the rest of the
24
+ * Session, so leaving plan mode changes only the guidance section. Native
25
+ * declarations, PTC bindings, and execution share that admission.
25
26
  *
26
27
  * See packages/plan/plan-mode/README.md.
27
28
  *
28
29
  * @module @unieai/rabi-plan-mode
29
30
  */
30
- /**
31
- * The model-facing exit tool's name. It stays registered while plan mode is
32
- * inactive so the request tool catalog is stable across transitions.
33
- */
31
+ /** The model-facing exit tool's name, admitted once the Session enters plan mode. */
34
32
  const EXIT_PLAN_MODE = "exit_plan_mode";
35
33
  /** The review question's id, echoed in the answer this tool reads. */
36
34
  const REVIEW_ID = "plan-review";
@@ -64,7 +62,7 @@ function resolveConfig(config) {
64
62
  /** Projection of logged plan selections and committed mode. */
65
63
  const planProjectionDefinition = {
66
64
  key: "plan",
67
- stateVersion: 3,
65
+ stateVersion: 4,
68
66
  stateSchema: z.object({
69
67
  active: z.boolean(),
70
68
  wanted: z.boolean().nullable(),
@@ -72,13 +70,15 @@ const planProjectionDefinition = {
72
70
  commandId: z.string(),
73
71
  wanted: z.boolean()
74
72
  }).strict().nullable(),
75
- activeAtLastHeader: z.boolean().nullable()
73
+ activeAtLastHeader: z.boolean().nullable(),
74
+ entered: z.boolean()
76
75
  }).strict(),
77
76
  init: () => ({
78
77
  active: false,
79
78
  wanted: null,
80
79
  running: null,
81
- activeAtLastHeader: null
80
+ activeAtLastHeader: null,
81
+ entered: false
82
82
  }),
83
83
  apply: (state, event) => {
84
84
  if (event.type === "command/run" && event.data.name === "plan") {
@@ -103,7 +103,8 @@ const planProjectionDefinition = {
103
103
  if (event.type === "plan/mode") return {
104
104
  ...state,
105
105
  active: event.data.active,
106
- wanted: null
106
+ wanted: null,
107
+ entered: state.entered || event.data.active
107
108
  };
108
109
  if (event.type === "request/header") return {
109
110
  ...state,
@@ -127,17 +128,21 @@ const planProjectionDefinition = {
127
128
  };
128
129
  /**
129
130
  * `ctx.planMode`: owns logged plan state, applies and narrates selected state at step start,
130
- * the `plan:policy` section, the `/plan` command, and the stable exit tool.
131
+ * the `plan:policy` section, the `/plan` command, and the conditional exit tool.
131
132
  * Client carriers expose the projection's cropped `{ active, pending }` view.
133
+ * Agent prompt assembly fails while the projection reader is not ready;
134
+ * callers must await plugin activation before running an agent.
132
135
  */
133
136
  var PlanModeController = class extends Service {
134
137
  static inject = [
135
138
  "tools",
136
139
  "systemPrompt",
137
- "sessionProjections"
140
+ "sessionProjections",
141
+ "agents"
138
142
  ];
139
143
  /** Validated deployment-owned guidance. */
140
144
  section;
145
+ planProjectionHandle;
141
146
  /**
142
147
  * Latest selection per session awaiting the next accepted in-turn pre-step.
143
148
  * `narrate` is true for user selections and false for the exit tool, whose
@@ -147,6 +152,18 @@ var PlanModeController = class extends Service {
147
152
  constructor(ctx, config = { section: "" }) {
148
153
  super(ctx, "planMode");
149
154
  this.section = resolveConfig(config).section;
155
+ }
156
+ async [Service.init]() {
157
+ const ctx = this.ctx;
158
+ ctx.systemPrompt.section({
159
+ name: "plan:policy",
160
+ order: ctx.systemPrompt.getSectionOrder("PLAN_POLICY"),
161
+ text: (context) => {
162
+ if (context.agent === void 0) return "";
163
+ return this.selectedActive(context.agent.session) ? this.section : "";
164
+ }
165
+ });
166
+ this.planProjectionHandle = await ctx.sessionProjections.register(planProjectionDefinition);
150
167
  let disposed = false;
151
168
  ctx.on("agent/pre-step", async ({ agent, signal }, next) => {
152
169
  const decision = await next();
@@ -167,15 +184,6 @@ var PlanModeController = class extends Service {
167
184
  ctx.effect(() => () => {
168
185
  disposed = true;
169
186
  }, "rabi-plan-mode: close service lifetime");
170
- ctx.systemPrompt.section({
171
- name: "plan:policy",
172
- order: ctx.systemPrompt.getSectionOrder("PLAN_POLICY"),
173
- text: (context) => {
174
- if (context.agent === void 0) return "";
175
- return this.pendingIntents.get(context.agent.session)?.active ?? this.loggedActive(context.agent.session) ? this.section : "";
176
- }
177
- });
178
- ctx.sessionProjections.register(planProjectionDefinition);
179
187
  ctx.inject(["commands"], (commandCtx) => {
180
188
  commandCtx.commands.register({
181
189
  definitionId: brandString("@unieai/rabi-plan-mode"),
@@ -251,8 +259,7 @@ var PlanModeController = class extends Service {
251
259
  },
252
260
  execute: async (args, exec) => {
253
261
  const agent = exec.agent;
254
- if (agent === void 0) throw new Error(`${EXIT_PLAN_MODE} requires a calling agent (no session to switch)`);
255
- if (!this.loggedActive(agent.session)) throw new Error(`${EXIT_PLAN_MODE} is only available in plan mode`);
262
+ if (agent === void 0 || !this.loggedActive(agent.session)) throw new Error(`${EXIT_PLAN_MODE} is only available in plan mode`);
256
263
  if (!/^#\s+\S/.test(args.plan.trim())) throw new Error(`${EXIT_PLAN_MODE} requires a non-empty markdown plan starting with a # heading`);
257
264
  const interaction = ctx.get("userQuestions");
258
265
  if (interaction === void 0) throw new Error("no user-questions channel is available to review the plan; ask the user to switch the session mode instead");
@@ -314,24 +321,24 @@ var PlanModeController = class extends Service {
314
321
  title: "Plan review",
315
322
  content: result.content
316
323
  })
317
- }));
324
+ }), { when: ({ agent }) => this.selectedActive(agent.session) || this.planState(agent.session).entered });
318
325
  }
319
326
  loggedActive(session) {
320
327
  return this.planState(session).active;
321
328
  }
329
+ /** The state a proposed step presents: a pending selection, else the logged state. */
330
+ selectedActive(session) {
331
+ return this.pendingIntents.get(session)?.active ?? this.loggedActive(session);
332
+ }
322
333
  hasOpenTurn(session) {
323
- const state = this.ctx.sessionProjections.stateOf(session, "turnBoundary");
324
- if (state === void 0) throw new Error("plan-mode requires the turnBoundary session projection");
325
- return state.openTurnStartSeq !== null;
334
+ return this.ctx.agents.turnBoundaryOf(session).openTurnStartSeq !== null;
326
335
  }
327
336
  loggedActiveAtLastHeader(session) {
328
337
  return this.planState(session).activeAtLastHeader ?? void 0;
329
338
  }
330
- /** Read the required plan projection state or fail at the first service access. */
331
339
  planState(session) {
332
- const state = this.ctx.sessionProjections.stateOf(session, "plan");
333
- if (state === void 0) throw new Error("plan-mode requires the plan session projection");
334
- return state;
340
+ if (this.planProjectionHandle === void 0) throw new Error("plan mode is not ready; await plugin activation before running an agent");
341
+ return this.planProjectionHandle.stateOf(session);
335
342
  }
336
343
  /**
337
344
  * Read the logged plan state and any selected state awaiting the next
@@ -12,9 +12,10 @@
12
12
  * assembly, then appends `plan/mode` from `agent/pre-step` only when the step
13
13
  * is accepted. Same-step request retries reuse their assembly.
14
14
  *
15
- * The exit tool remains registered while plan mode is inactive, so entering
16
- * or leaving plan mode changes only the prompt section, not the request tool
17
- * catalog.
15
+ * The exit tool is disclosed progressively: it is admitted from the first step
16
+ * whose selected state is active and stays admitted for the rest of the
17
+ * Session, so leaving plan mode changes only the guidance section. Native
18
+ * declarations, PTC bindings, and execution share that admission.
18
19
  *
19
20
  * See packages/plan/plan-mode/README.md.
20
21
  *
@@ -50,10 +51,7 @@ declare module '@unieai/cordis' {
50
51
  planMode: PlanModeController;
51
52
  }
52
53
  }
53
- /**
54
- * The model-facing exit tool's name. It stays registered while plan mode is
55
- * inactive so the request tool catalog is stable across transitions.
56
- */
54
+ /** The model-facing exit tool's name, admitted once the Session enters plan mode. */
57
55
  export declare const EXIT_PLAN_MODE = "exit_plan_mode";
58
56
  /** Deployment-owned plan guidance. */
59
57
  export interface PlanModeConfig {
@@ -78,6 +76,7 @@ export declare const planProjectionDefinition: {
78
76
  wanted: null;
79
77
  running: null;
80
78
  activeAtLastHeader: null;
79
+ entered: false;
81
80
  };
82
81
  apply: (state: NoInfer<PlanUnitState>, event: import("@unieai/rabi-session").SessionEvent) => PlanUnitState;
83
82
  wire: {
@@ -90,13 +89,16 @@ export declare const planProjectionDefinition: {
90
89
  };
91
90
  /**
92
91
  * `ctx.planMode`: owns logged plan state, applies and narrates selected state at step start,
93
- * the `plan:policy` section, the `/plan` command, and the stable exit tool.
92
+ * the `plan:policy` section, the `/plan` command, and the conditional exit tool.
94
93
  * Client carriers expose the projection's cropped `{ active, pending }` view.
94
+ * Agent prompt assembly fails while the projection reader is not ready;
95
+ * callers must await plugin activation before running an agent.
95
96
  */
96
97
  export declare class PlanModeController extends Service {
97
98
  static inject: string[];
98
99
  /** Validated deployment-owned guidance. */
99
100
  private readonly section;
101
+ private planProjectionHandle;
100
102
  /**
101
103
  * Latest selection per session awaiting the next accepted in-turn pre-step.
102
104
  * `narrate` is true for user selections and false for the exit tool, whose
@@ -104,10 +106,12 @@ export declare class PlanModeController extends Service {
104
106
  */
105
107
  private readonly pendingIntents;
106
108
  constructor(ctx: Context, config?: PlanModeConfig);
109
+ protected [Service.init](): Promise<void>;
107
110
  private loggedActive;
111
+ /** The state a proposed step presents: a pending selection, else the logged state. */
112
+ private selectedActive;
108
113
  private hasOpenTurn;
109
114
  private loggedActiveAtLastHeader;
110
- /** Read the required plan projection state or fail at the first service access. */
111
115
  private planState;
112
116
  /**
113
117
  * Read the logged plan state and any selected state awaiting the next
@@ -12,9 +12,10 @@
12
12
  * assembly, then appends `plan/mode` from `agent/pre-step` only when the step
13
13
  * is accepted. Same-step request retries reuse their assembly.
14
14
  *
15
- * The exit tool remains registered while plan mode is inactive, so entering
16
- * or leaving plan mode changes only the prompt section, not the request tool
17
- * catalog.
15
+ * The exit tool is disclosed progressively: it is admitted from the first step
16
+ * whose selected state is active and stays admitted for the rest of the
17
+ * Session, so leaving plan mode changes only the guidance section. Native
18
+ * declarations, PTC bindings, and execution share that admission.
18
19
  *
19
20
  * See packages/plan/plan-mode/README.md.
20
21
  *
@@ -26,10 +27,7 @@ import { z as zod } from 'zod';
26
27
  import { createUserMessage } from '@unieai/rabi-llm';
27
28
  import { defineTool } from '@unieai/rabi-tools';
28
29
  import { UserQuestionError } from '@unieai/rabi-user-questions';
29
- /**
30
- * The model-facing exit tool's name. It stays registered while plan mode is
31
- * inactive so the request tool catalog is stable across transitions.
32
- */
30
+ /** The model-facing exit tool's name, admitted once the Session enters plan mode. */
33
31
  export const EXIT_PLAN_MODE = 'exit_plan_mode';
34
32
  /** The review question's id, echoed in the answer this tool reads. */
35
33
  const REVIEW_ID = 'plan-review';
@@ -78,6 +76,7 @@ const planUnitStateSchema = zod.object({
78
76
  wanted: zod.boolean(),
79
77
  }).strict().nullable(),
80
78
  activeAtLastHeader: zod.boolean().nullable(),
79
+ entered: zod.boolean(),
81
80
  }).strict();
82
81
  /** Wire payload schema of the `plan` projection. */
83
82
  const planProjectionSchema = zod.object({
@@ -87,9 +86,9 @@ const planProjectionSchema = zod.object({
87
86
  /** Projection of logged plan selections and committed mode. */
88
87
  export const planProjectionDefinition = {
89
88
  key: 'plan',
90
- stateVersion: 3,
89
+ stateVersion: 4,
91
90
  stateSchema: planUnitStateSchema,
92
- init: () => ({ active: false, wanted: null, running: null, activeAtLastHeader: null }),
91
+ init: () => ({ active: false, wanted: null, running: null, activeAtLastHeader: null, entered: false }),
93
92
  apply: (state, event) => {
94
93
  if (event.type === 'command/run' && event.data.name === 'plan') {
95
94
  if (event.data.args === undefined)
@@ -104,7 +103,7 @@ export const planProjectionDefinition = {
104
103
  return { ...state, wanted, running: null };
105
104
  }
106
105
  if (event.type === 'plan/mode') {
107
- return { ...state, active: event.data.active, wanted: null };
106
+ return { ...state, active: event.data.active, wanted: null, entered: state.entered || event.data.active };
108
107
  }
109
108
  if (event.type === 'request/header') {
110
109
  return { ...state, activeAtLastHeader: state.active };
@@ -121,13 +120,16 @@ export const planProjectionDefinition = {
121
120
  };
122
121
  /**
123
122
  * `ctx.planMode`: owns logged plan state, applies and narrates selected state at step start,
124
- * the `plan:policy` section, the `/plan` command, and the stable exit tool.
123
+ * the `plan:policy` section, the `/plan` command, and the conditional exit tool.
125
124
  * Client carriers expose the projection's cropped `{ active, pending }` view.
125
+ * Agent prompt assembly fails while the projection reader is not ready;
126
+ * callers must await plugin activation before running an agent.
126
127
  */
127
128
  export class PlanModeController extends Service {
128
- static inject = ['tools', 'systemPrompt', 'sessionProjections'];
129
+ static inject = ['tools', 'systemPrompt', 'sessionProjections', 'agents'];
129
130
  /** Validated deployment-owned guidance. */
130
131
  section;
132
+ planProjectionHandle;
131
133
  /**
132
134
  * Latest selection per session awaiting the next accepted in-turn pre-step.
133
135
  * `narrate` is true for user selections and false for the exit tool, whose
@@ -137,6 +139,19 @@ export class PlanModeController extends Service {
137
139
  constructor(ctx, config = { section: '' }) {
138
140
  super(ctx, 'planMode');
139
141
  this.section = resolveConfig(config).section;
142
+ }
143
+ async [Service.init]() {
144
+ const ctx = this.ctx;
145
+ ctx.systemPrompt.section({
146
+ name: 'plan:policy',
147
+ order: ctx.systemPrompt.getSectionOrder('PLAN_POLICY'),
148
+ text: (context) => {
149
+ if (context.agent === undefined)
150
+ return '';
151
+ return this.selectedActive(context.agent.session) ? this.section : '';
152
+ },
153
+ });
154
+ this.planProjectionHandle = await ctx.sessionProjections.register(planProjectionDefinition);
140
155
  let disposed = false;
141
156
  // Pre-step is outside Session.append publication, so it can append the
142
157
  // log-only mode event inside an open turn without re-entering the session.
@@ -160,17 +175,6 @@ export class PlanModeController extends Service {
160
175
  : { ...decision, messages: [...decision.messages, narration] };
161
176
  });
162
177
  ctx.effect(() => () => { disposed = true; }, 'rabi-plan-mode: close service lifetime');
163
- ctx.systemPrompt.section({
164
- name: 'plan:policy',
165
- order: ctx.systemPrompt.getSectionOrder('PLAN_POLICY'),
166
- text: (context) => {
167
- if (context.agent === undefined)
168
- return '';
169
- const pending = this.pendingIntents.get(context.agent.session);
170
- return (pending?.active ?? this.loggedActive(context.agent.session)) ? this.section : '';
171
- },
172
- });
173
- ctx.sessionProjections.register(planProjectionDefinition);
174
178
  // The command child activates only when a command registry is composed.
175
179
  ctx.inject(['commands'], (commandCtx) => {
176
180
  commandCtx.commands.register({
@@ -242,9 +246,8 @@ export class PlanModeController extends Service {
242
246
  },
243
247
  execute: async (args, exec) => {
244
248
  const agent = exec.agent;
245
- if (agent === undefined)
246
- throw new Error(`${EXIT_PLAN_MODE} requires a calling agent (no session to switch)`);
247
- if (!this.loggedActive(agent.session)) {
249
+ // Admission outlives plan mode and follows the selected state, so check the committed state.
250
+ if (agent === undefined || !this.loggedActive(agent.session)) {
248
251
  throw new Error(`${EXIT_PLAN_MODE} is only available in plan mode`);
249
252
  }
250
253
  if (!/^#\s+\S/.test(args.plan.trim())) {
@@ -316,26 +319,26 @@ export class PlanModeController extends Service {
316
319
  title: 'Plan review',
317
320
  content: result.content,
318
321
  }),
319
- }));
322
+ }), { when: ({ agent }) => this.selectedActive(agent.session) || this.planState(agent.session).entered });
320
323
  }
321
324
  loggedActive(session) {
322
325
  return this.planState(session).active;
323
326
  }
327
+ /** The state a proposed step presents: a pending selection, else the logged state. */
328
+ selectedActive(session) {
329
+ return this.pendingIntents.get(session)?.active ?? this.loggedActive(session);
330
+ }
324
331
  hasOpenTurn(session) {
325
- const state = this.ctx.sessionProjections.stateOf(session, 'turnBoundary');
326
- if (state === undefined)
327
- throw new Error('plan-mode requires the turnBoundary session projection');
328
- return state.openTurnStartSeq !== null;
332
+ return this.ctx.agents.turnBoundaryOf(session).openTurnStartSeq !== null;
329
333
  }
330
334
  loggedActiveAtLastHeader(session) {
331
335
  return this.planState(session).activeAtLastHeader ?? undefined;
332
336
  }
333
- /** Read the required plan projection state or fail at the first service access. */
334
337
  planState(session) {
335
- const state = this.ctx.sessionProjections.stateOf(session, 'plan');
336
- if (state === undefined)
337
- throw new Error('plan-mode requires the plan session projection');
338
- return state;
338
+ if (this.planProjectionHandle === undefined) {
339
+ throw new Error('plan mode is not ready; await plugin activation before running an agent');
340
+ }
341
+ return this.planProjectionHandle.stateOf(session);
339
342
  }
340
343
  /**
341
344
  * Read the logged plan state and any selected state awaiting the next
@@ -33,12 +33,10 @@ export interface PlanUnitState {
33
33
  } | null;
34
34
  /** Active state recorded by the latest `request/header`, or null. */
35
35
  activeAtLastHeader: boolean | null;
36
+ /** Whether a logged `plan/mode` has ever activated plan mode in this Session. */
37
+ entered: boolean;
36
38
  }
37
39
  declare module '@unieai/rabi-session-projection/types' {
38
- interface SessionProjectionStateMap {
39
- /** Host plan-mode fold state. */
40
- plan: PlanUnitState;
41
- }
42
40
  interface SessionProjectionMap {
43
41
  /** Plan collaboration state folded from the plan command lifecycle and `plan/mode` events. */
44
42
  plan: PlanProjection;
package/locale/de.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Planungsmodus",
4
+ "description": "Lassen Sie die KI zunächst den Plan erstellen und nach Überprüfung durch den Benutzer mit der Ausführung fortfahren."
5
+ }
6
+ }
package/locale/es.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "modo de planificación",
4
+ "description": "Deje que AI cree el plan primero y pase a ejecución después de la revisión del usuario."
5
+ }
6
+ }
package/locale/fr.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "mode de planification",
4
+ "description": "Laissez l’IA créer le plan en premier et passez à l’exécution après examen par l’utilisateur."
5
+ }
6
+ }
package/locale/ja.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "計画モード",
4
+ "description": "AI が先に計画を作成し、ユーザーがレビューしてから実行に切り替えます。"
5
+ }
6
+ }
package/locale/pt.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "modo de planejamento",
4
+ "description": "Deixe a IA criar o plano primeiro e passar para a execução após a revisão do usuário."
5
+ }
6
+ }
package/locale/ru.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "режим планирования",
4
+ "description": "Пусть ИИ сначала создаст план и перейдет к исполнению после проверки пользователем."
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@unieai/rabi-plan-mode",
3
3
  "description": "Logged per-agent plan mode with deployment guidance, a direct slash command, and a user-reviewed exit",
4
- "version": "0.2.1-rc.3",
4
+ "version": "0.2.2-rc.5",
5
5
  "publishConfig": {
6
6
  "access": "public"
7
7
  },
@@ -30,19 +30,22 @@
30
30
  "lib/index.js",
31
31
  "lib/types/**/*.js",
32
32
  "lib/types/**/*.d.ts",
33
+ "lib/types/**/*.d.ts.map",
34
+ "lib/**/*.js.map",
35
+ "src",
33
36
  "README.md"
34
37
  ],
35
38
  "license": "MIT",
36
39
  "peerDependencies": {
37
- "@unieai/rabi-agent": "0.2.1-rc.3",
38
- "@unieai/rabi-commands": "0.2.1-rc.3",
39
- "@unieai/rabi-llm": "0.2.1-rc.3",
40
- "@unieai/rabi-session": "0.2.1-rc.3",
41
- "@unieai/rabi-session-projection": "0.2.1-rc.3",
42
- "@unieai/rabi-system-prompt": "0.2.1-rc.3",
43
- "@unieai/rabi-tools": "0.2.1-rc.3",
44
- "@unieai/rabi-user-questions": "0.2.1-rc.3",
45
- "@unieai/cordis": "4.0.5"
40
+ "@unieai/rabi-agent": "0.2.2-rc.5",
41
+ "@unieai/rabi-commands": "0.2.2-rc.5",
42
+ "@unieai/rabi-llm": "0.2.2-rc.5",
43
+ "@unieai/rabi-session": "0.2.2-rc.5",
44
+ "@unieai/rabi-session-projection": "0.2.2-rc.5",
45
+ "@unieai/rabi-system-prompt": "0.2.2-rc.5",
46
+ "@unieai/rabi-tools": "0.2.2-rc.5",
47
+ "@unieai/rabi-user-questions": "0.2.2-rc.5",
48
+ "@unieai/cordis": "4.1.0"
46
49
  },
47
50
  "peerDependenciesMeta": {
48
51
  "@unieai/rabi-commands": {
@@ -50,7 +53,7 @@
50
53
  }
51
54
  },
52
55
  "dependencies": {
53
- "@unieai/rabi-brand": "0.2.1-rc.3",
54
- "zod": "4.4.3"
56
+ "@unieai/rabi-brand": "0.2.2-rc.5",
57
+ "zod": "4.6.6"
55
58
  }
56
59
  }
package/src/client.ts ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Client-namespace projection of the plan domain: a pure re-export of the package's
3
+ * types outlet. Client code imports ONLY the client namespace (repo
4
+ * discipline), so `./client` projects the same single-source content
5
+ * `./types` serves to host consumers — zero duplication.
6
+ *
7
+ * @module @unieai/rabi-plan-mode/client
8
+ */
9
+
10
+ export type * from './types.ts'
package/src/index.ts ADDED
@@ -0,0 +1,483 @@
1
+ /**
2
+ * Plan mode is logged per-agent collaboration state: while active, a
3
+ * deployment-owned guidance section is included in each model request, and
4
+ * `exit_plan_mode` presents the completed plan for user review, while the
5
+ * `/plan off` command lets a user leave directly. Sandbox mode and approval
6
+ * policy enforce restrictions independently and do not read or write plan
7
+ * state.
8
+ *
9
+ * The `plan` projection folds the session log, so resume and fork restore the
10
+ * state. User selections remain pending until the next accepted in-turn
11
+ * pre-step. The service includes the selected state in the proposed step
12
+ * assembly, then appends `plan/mode` from `agent/pre-step` only when the step
13
+ * is accepted. Same-step request retries reuse their assembly.
14
+ *
15
+ * The exit tool is disclosed progressively: it is admitted from the first step
16
+ * whose selected state is active and stays admitted for the rest of the
17
+ * Session, so leaving plan mode changes only the guidance section. Native
18
+ * declarations, PTC bindings, and execution share that admission.
19
+ *
20
+ * See packages/plan/plan-mode/README.md.
21
+ *
22
+ * @module @unieai/rabi-plan-mode
23
+ */
24
+
25
+ import { Context, Service } from '@unieai/cordis'
26
+ import { brandString } from '@unieai/rabi-brand'
27
+ import { z as zod } from 'zod'
28
+ import type { ZodType } from 'zod'
29
+ import type { Agent, PreStepDecision } from '@unieai/rabi-agent'
30
+ import { createUserMessage } from '@unieai/rabi-llm'
31
+ import type { ContextFormed } from '@unieai/rabi-llm'
32
+ import type { Session, UserMessage } from '@unieai/rabi-session'
33
+ import { defineTool } from '@unieai/rabi-tools'
34
+ import { UserQuestionError, type AskUserQuestionAnswer } from '@unieai/rabi-user-questions'
35
+ import type { CommandDefinitionId, CommandId } from '@unieai/rabi-commands'
36
+ import type {} from '@unieai/rabi-session-projection'
37
+ import type { ProjectionDefinition, ProjectionHandle } from '@unieai/rabi-session-projection'
38
+ import type { PlanProjection, PlanUnitState } from './types.ts'
39
+ declare module '@unieai/rabi-llm' {
40
+ interface MessageSourceMap {
41
+ 'plan-mode': { kind: 'plan-mode' } & ContextFormed
42
+ }
43
+ }
44
+ export type * from './types.ts'
45
+
46
+ declare module '@unieai/rabi-session/types' {
47
+ interface SessionEventMap {
48
+ /**
49
+ * Whether plan mode is in force from this point on: log-only, non-surface,
50
+ * whole-value replace. The last `plan/mode` wins; a log with none folds to
51
+ * inactive through the projection unit's fold.
52
+ */
53
+ 'plan/mode': { active: boolean }
54
+ }
55
+ }
56
+
57
+ declare module '@unieai/cordis' {
58
+ interface Context {
59
+ planMode: PlanModeController
60
+ }
61
+ }
62
+
63
+ /** The model-facing exit tool's name, admitted once the Session enters plan mode. */
64
+ export const EXIT_PLAN_MODE = 'exit_plan_mode'
65
+
66
+ /** Deployment-owned plan guidance. */
67
+ export interface PlanModeConfig {
68
+ /** Guidance rendered as the `plan:policy` prompt section while plan mode is active. */
69
+ section: string
70
+ }
71
+
72
+ /** The review question's id, echoed in the answer this tool reads. */
73
+ const REVIEW_ID = 'plan-review'
74
+
75
+ /** The review question's approve option label. */
76
+ const APPROVE_LABEL = 'Approve'
77
+
78
+ /** The review question's keep-planning option label. */
79
+ const KEEP_PLANNING_LABEL = 'Keep planning'
80
+
81
+ const EXIT_DESCRIPTION
82
+ = 'Use only in plan mode. Present your plan for the user\'s review and, on approval, leave plan mode. '
83
+ + 'The user may approve (carry out the plan from your next step) or keep '
84
+ + 'planning — their feedback comes back in the tool result; revise and present again.'
85
+
86
+ /** The plan's first markdown heading (any level), or `undefined` when it has none. */
87
+ function firstHeading(plan: string): string | undefined {
88
+ for (const line of plan.split('\n')) {
89
+ const match = /^#{1,6}\s+(.+?)\s*$/.exec(line)
90
+ if (match) return match[1]
91
+ }
92
+ return undefined
93
+ }
94
+
95
+ /**
96
+ * Validate deployment-owned plan guidance. Missing, blank, non-string, or
97
+ * unknown fields fail at plugin load rather than being ignored.
98
+ *
99
+ * @param config Raw plugin config.
100
+ * @returns A detached validated config.
101
+ */
102
+ export function resolveConfig(config: PlanModeConfig): PlanModeConfig {
103
+ const section = (config as Partial<PlanModeConfig>).section
104
+ if (typeof section !== 'string') {
105
+ throw new Error('PlanModeConfig needs a string `section`')
106
+ }
107
+ if (section.trim() === '') {
108
+ throw new Error('PlanModeConfig needs a non-empty `section`')
109
+ }
110
+ const unknown = Object.keys(config).filter(key => key !== 'section')
111
+ if (unknown.length > 0) {
112
+ throw new Error(`PlanModeConfig has unknown key(s) ${unknown.join(', ')} — config is { section }`)
113
+ }
114
+ return { section }
115
+ }
116
+
117
+ const planUnitStateSchema: ZodType<PlanUnitState> = zod.object({
118
+ active: zod.boolean(),
119
+ wanted: zod.boolean().nullable(),
120
+ running: zod.object({
121
+ commandId: zod.string() as unknown as ZodType<CommandId>,
122
+ wanted: zod.boolean(),
123
+ }).strict().nullable(),
124
+ activeAtLastHeader: zod.boolean().nullable(),
125
+ entered: zod.boolean(),
126
+ }).strict()
127
+
128
+ /** Wire payload schema of the `plan` projection. */
129
+ const planProjectionSchema: ZodType<PlanProjection> = zod.object({
130
+ active: zod.boolean(),
131
+ pending: zod.boolean(),
132
+ })
133
+
134
+ /** Projection of logged plan selections and committed mode. */
135
+ export const planProjectionDefinition = {
136
+ key: 'plan',
137
+ stateVersion: 4,
138
+ stateSchema: planUnitStateSchema,
139
+ init: () => ({ active: false, wanted: null, running: null, activeAtLastHeader: null, entered: false }),
140
+ apply: (state, event) => {
141
+ if (event.type === 'command/run' && event.data.name === 'plan') {
142
+ if (event.data.args === undefined) return state
143
+ const wanted = event.data.args.trim() !== 'off'
144
+ return { ...state, running: { commandId: event.data.commandId, wanted } }
145
+ }
146
+ if (event.type === 'command/done' && event.data.commandId === state.running?.commandId) {
147
+ const wanted = event.data.kind === 'success' && state.running.wanted !== state.active
148
+ ? state.running.wanted
149
+ : null
150
+ return { ...state, wanted, running: null }
151
+ }
152
+ if (event.type === 'plan/mode') {
153
+ return { ...state, active: event.data.active, wanted: null, entered: state.entered || event.data.active }
154
+ }
155
+ if (event.type === 'request/header') {
156
+ return { ...state, activeAtLastHeader: state.active }
157
+ }
158
+ return state
159
+ },
160
+ wire: {
161
+ viewSchema: planProjectionSchema,
162
+ view: (state) => {
163
+ const wanted = state.running?.wanted ?? state.wanted
164
+ return { active: state.active, pending: wanted !== null && wanted !== state.active }
165
+ },
166
+ },
167
+ } satisfies ProjectionDefinition<'plan', PlanUnitState>
168
+
169
+ /**
170
+ * `ctx.planMode`: owns logged plan state, applies and narrates selected state at step start,
171
+ * the `plan:policy` section, the `/plan` command, and the conditional exit tool.
172
+ * Client carriers expose the projection's cropped `{ active, pending }` view.
173
+ * Agent prompt assembly fails while the projection reader is not ready;
174
+ * callers must await plugin activation before running an agent.
175
+ */
176
+ export class PlanModeController extends Service {
177
+ static inject = ['tools', 'systemPrompt', 'sessionProjections', 'agents']
178
+
179
+ /** Validated deployment-owned guidance. */
180
+ private readonly section: string
181
+ private planProjectionHandle: ProjectionHandle<PlanUnitState> | undefined
182
+
183
+ /**
184
+ * Latest selection per session awaiting the next accepted in-turn pre-step.
185
+ * `narrate` is true for user selections and false for the exit tool, whose
186
+ * result already narrates the transition.
187
+ */
188
+ private readonly pendingIntents = new WeakMap<Session, { active: boolean; narrate: boolean }>()
189
+
190
+ constructor(ctx: Context, config: PlanModeConfig = { section: '' }) {
191
+ super(ctx, 'planMode')
192
+ this.section = resolveConfig(config).section
193
+ }
194
+
195
+ protected async [Service.init](): Promise<void> {
196
+ const ctx = this.ctx
197
+ ctx.systemPrompt.section({
198
+ name: 'plan:policy',
199
+ order: ctx.systemPrompt.getSectionOrder('PLAN_POLICY'),
200
+ text: (context) => {
201
+ if (context.agent === undefined) return ''
202
+ return this.selectedActive(context.agent.session) ? this.section : ''
203
+ },
204
+ })
205
+ this.planProjectionHandle = await ctx.sessionProjections.register(planProjectionDefinition)
206
+ let disposed = false
207
+ // Pre-step is outside Session.append publication, so it can append the
208
+ // log-only mode event inside an open turn without re-entering the session.
209
+ // A failed append remains pending for a later accepted in-turn pre-step,
210
+ // and policy cannot block the step.
211
+ ctx.on('agent/pre-step', async (
212
+ { agent, signal },
213
+ next,
214
+ ): Promise<PreStepDecision> => {
215
+ const decision = await next()
216
+ const pending = this.pendingIntents.get(agent.session)
217
+ if (decision.kind === 'reject' || signal.aborted || pending === undefined) return decision
218
+ const narration = this.narration(agent.session, pending.active)
219
+ try {
220
+ this.onBoundary(agent.session)
221
+ } catch (error) {
222
+ ctx.logger.warn('rabi-plan-mode: failed to append selected plan mode at step start: %o', error)
223
+ return decision
224
+ }
225
+ return !pending.narrate || narration === undefined
226
+ ? decision
227
+ : { ...decision, messages: [...decision.messages, narration] }
228
+ })
229
+ ctx.effect(() => () => { disposed = true }, 'rabi-plan-mode: close service lifetime')
230
+
231
+ // The command child activates only when a command registry is composed.
232
+ ctx.inject(['commands'], (commandCtx) => {
233
+ commandCtx.commands.register({
234
+ definitionId: brandString<CommandDefinitionId>('@unieai/rabi-plan-mode'),
235
+ name: 'plan',
236
+ description: 'Enter or leave plan mode',
237
+ input: { hint: '[off|message]', attachments: true },
238
+ handler: ({ agent, rawInput, attachments }) => {
239
+ const message = rawInput.trim()
240
+ if (message === 'off' && attachments.length > 0) {
241
+ return { kind: 'error', text: 'Attachments cannot accompany /plan off.' }
242
+ }
243
+ if (message === 'off') {
244
+ switch (this.set(agent, false)) {
245
+ case 'committed':
246
+ return { kind: 'success', text: 'Plan mode off.' }
247
+ case 'queued':
248
+ return { kind: 'success', text: 'Leaving plan mode (applies from the next step).' }
249
+ case 'cancelled':
250
+ return { kind: 'success', text: 'Plan mode entry cancelled.' }
251
+ case 'noop':
252
+ // Repeat the queued wording while an exit still awaits the
253
+ // next accepted pre-step; only a truly inactive session reads
254
+ // idempotent.
255
+ return this.loggedActive(agent.session)
256
+ ? { kind: 'success', text: 'Leaving plan mode (applies from the next step).' }
257
+ : { kind: 'success', text: 'Plan mode is already inactive.' }
258
+ }
259
+ }
260
+ const outcome = this.set(agent, true)
261
+ if (message !== '' || attachments.length > 0) {
262
+ agent.steer(createUserMessage({
263
+ content: [
264
+ ...attachments,
265
+ ...(message === '' ? [] : [{ type: 'text' as const, text: message }]),
266
+ ],
267
+ source: { kind: 'user' },
268
+ }))
269
+ }
270
+ return {
271
+ kind: 'success',
272
+ text: outcome === 'committed'
273
+ ? 'Plan mode on. Use /plan off to leave.'
274
+ : 'Entering plan mode (applies from the next step). Use /plan off to leave.',
275
+ }
276
+ },
277
+ })
278
+ })
279
+
280
+ ctx.tools.register(defineTool({
281
+ name: EXIT_PLAN_MODE,
282
+ description: EXIT_DESCRIPTION,
283
+ parameters: {
284
+ plan: { type: 'string', required: true, description: 'The complete plan, as markdown, starting with a # heading that names it.' },
285
+ },
286
+ output: {
287
+ schema: {
288
+ type: 'object',
289
+ additionalProperties: false,
290
+ properties: {
291
+ approved: { type: 'boolean', required: true },
292
+ },
293
+ },
294
+ render: (_args, { approved }) => [{
295
+ type: 'text',
296
+ text: approved
297
+ ? 'Plan approved — plan mode exited; carry out the plan starting with your next step.'
298
+ : 'The user dismissed the plan review to reply in their own words; plan mode remains active.',
299
+ }],
300
+ },
301
+ execute: async (args, exec) => {
302
+ const agent = exec.agent
303
+ // Admission outlives plan mode and follows the selected state, so check the committed state.
304
+ if (agent === undefined || !this.loggedActive(agent.session)) {
305
+ throw new Error(`${EXIT_PLAN_MODE} is only available in plan mode`)
306
+ }
307
+ if (!/^#\s+\S/.test(args.plan.trim())) {
308
+ throw new Error(`${EXIT_PLAN_MODE} requires a non-empty markdown plan starting with a # heading`)
309
+ }
310
+ const interaction = ctx.get('userQuestions')
311
+ if (interaction === undefined) {
312
+ throw new Error('no user-questions channel is available to review the plan; ask the user to switch the session mode instead')
313
+ }
314
+ let answer: AskUserQuestionAnswer
315
+ try {
316
+ answer = await interaction.ask({
317
+ questions: [{
318
+ id: REVIEW_ID,
319
+ header: 'Plan review',
320
+ question: 'Approve this plan and leave plan mode?',
321
+ detail: args.plan,
322
+ options: [
323
+ { label: APPROVE_LABEL, description: 'Leave plan mode; the plan is carried out from the next step.' },
324
+ { label: KEEP_PLANNING_LABEL, description: 'Stay in plan mode; feedback goes back to the model.' },
325
+ ],
326
+ // Presentation only: a capable UI renders the plan as a review
327
+ // decision instead of a generic question, and answers with one of
328
+ // the labels above either way.
329
+ intent: { kind: 'plan-review', approve: APPROVE_LABEL, callId: exec.callId },
330
+ }],
331
+ agent,
332
+ signal: exec.signal,
333
+ })
334
+ } catch (cause: unknown) {
335
+ // A dismissed review is not a failed one: the user took the turn back
336
+ // to say something the two options do not cover, so the turn ends
337
+ // here instead of spending a model request on waiting. An abort (turn
338
+ // cancel, provider teardown) keeps its own failure.
339
+ if (cause instanceof UserQuestionError && cause.code === 'ASK_CANCELLED') {
340
+ exec.concludeTurn()
341
+ return { approved: false }
342
+ }
343
+ throw cause
344
+ }
345
+ // A review may outlive this plugin fiber. Without its pre-step listener,
346
+ // an approved selection could never be appended, so fail and keep planning.
347
+ if (disposed) {
348
+ throw new Error('the plan-mode service was reloaded while the plan was under review; present the plan again')
349
+ }
350
+ const reviewItems = answer.answers.filter(entry => entry.id === REVIEW_ID)
351
+ const item = reviewItems.length === 1 ? reviewItems[0] : undefined
352
+ if (item?.selected.length !== 1 || item.selected[0] !== APPROVE_LABEL || item.custom !== undefined) {
353
+ const feedback = item?.custom ?? ''
354
+ throw new Error(feedback === ''
355
+ ? 'The user chose to keep planning; revise the plan and present it again.'
356
+ : `The user chose to keep planning; their feedback: ${feedback}`)
357
+ }
358
+ // Keep plan guidance for the rest of this assistant tool batch. The
359
+ // silent selection is appended at the next accepted in-turn pre-step,
360
+ // before its request assembly.
361
+ this.pendingIntents.set(agent.session, { active: false, narrate: false })
362
+ return { approved: true }
363
+ },
364
+ presentCall: args => ({
365
+ card: 'generic',
366
+ title: firstHeading(args.plan) ?? 'Plan',
367
+ kind: 'other',
368
+ content: [{ type: 'text', text: args.plan }],
369
+ }),
370
+ presentResult: (_args, result) => ({
371
+ card: 'generic',
372
+ title: 'Plan review',
373
+ content: result.content,
374
+ }),
375
+ }), { when: ({ agent }) => this.selectedActive(agent.session) || this.planState(agent.session).entered })
376
+ }
377
+
378
+ private loggedActive(session: Session): boolean {
379
+ return this.planState(session).active
380
+ }
381
+
382
+ /** The state a proposed step presents: a pending selection, else the logged state. */
383
+ private selectedActive(session: Session): boolean {
384
+ return this.pendingIntents.get(session)?.active ?? this.loggedActive(session)
385
+ }
386
+
387
+ private hasOpenTurn(session: Session): boolean {
388
+ return this.ctx.agents.turnBoundaryOf(session).openTurnStartSeq !== null
389
+ }
390
+
391
+ private loggedActiveAtLastHeader(session: Session): boolean | undefined {
392
+ return this.planState(session).activeAtLastHeader ?? undefined
393
+ }
394
+
395
+ private planState(session: Session): PlanUnitState {
396
+ if (this.planProjectionHandle === undefined) {
397
+ throw new Error('plan mode is not ready; await plugin activation before running an agent')
398
+ }
399
+ return this.planProjectionHandle.stateOf(session)
400
+ }
401
+
402
+ /**
403
+ * Read the logged plan state and any selected state awaiting the next
404
+ * accepted in-turn pre-step.
405
+ *
406
+ * @param agent The agent to read.
407
+ * @returns Current logged state plus a pending selection, when present.
408
+ */
409
+ get(agent: Agent): { active: boolean; pending?: boolean } {
410
+ const active = this.loggedActive(agent.session)
411
+ const pending = this.pendingIntents.get(agent.session)
412
+ return pending === undefined ? { active } : { active, pending: pending.active }
413
+ }
414
+
415
+ /**
416
+ * Select whether plan mode should be active. Between turns the method
417
+ * appends the change immediately because no in-turn pre-step will run until
418
+ * another prompt starts a turn. The open-turn fold is the idle signal:
419
+ * agent status stays `running` through post-turn checkpointing, when no
420
+ * further in-turn pre-step runs. During an open turn the selection remains
421
+ * pending until the next accepted in-turn pre-step. Repeated selection of
422
+ * the current or already-pending state is a no-op.
423
+ *
424
+ * @param agent The agent to switch.
425
+ * @param active Whether plan mode should be active.
426
+ * @returns what happened: `committed` (logged now), `queued` (awaiting the
427
+ * next accepted in-turn pre-step), `cancelled` (an opposite pending selection
428
+ * was cleared; the logged state already matches), or `noop` (already in that
429
+ * state).
430
+ */
431
+ set(agent: Agent, active: boolean): 'committed' | 'queued' | 'cancelled' | 'noop' {
432
+ const session = agent.session
433
+ const pending = this.pendingIntents.get(session)
434
+ const target = pending?.active ?? this.loggedActive(session)
435
+ if (active === target) return 'noop'
436
+ if (this.hasOpenTurn(session)) {
437
+ this.pendingIntents.set(session, { active, narrate: true })
438
+ return this.loggedActive(session) === active ? 'cancelled' : 'queued'
439
+ }
440
+ // No open turn: commit now. Delete only after append succeeds so a
441
+ // failed durable write leaves the selection retryable, not dropped.
442
+ if (active === this.loggedActive(session)) {
443
+ this.pendingIntents.delete(session)
444
+ return 'cancelled'
445
+ }
446
+ session.append('plan/mode', { active })
447
+ this.pendingIntents.delete(session)
448
+ const narration = this.narration(session, active)
449
+ if (narration !== undefined) agent.inject(narration)
450
+ return 'committed'
451
+ }
452
+
453
+ /** Append one pending selection before the next request assembly. */
454
+ private onBoundary(session: Session): void {
455
+ const pending = this.pendingIntents.get(session)
456
+ if (pending === undefined) return
457
+ const target = pending.active
458
+ if (target === this.loggedActive(session)) {
459
+ this.pendingIntents.delete(session)
460
+ return
461
+ }
462
+ session.append('plan/mode', { active: target })
463
+ // Delete only after append succeeds so a later accepted in-turn pre-step
464
+ // can retry a failed durable write.
465
+ this.pendingIntents.delete(session)
466
+ }
467
+
468
+ /** Build a user-switch notice when the last logged header described the other mode. */
469
+ private narration(session: Session, target: boolean): UserMessage | undefined {
470
+ const told = this.loggedActiveAtLastHeader(session)
471
+ if (told === undefined || told === target) return
472
+ const text = target
473
+ ? 'The user switched this session to plan mode.'
474
+ : 'The user switched this session back to the default mode.'
475
+ return createUserMessage({
476
+ content: [{ type: 'text', text }],
477
+ // The narration is already one sentence, so it is its own summary.
478
+ source: { kind: 'plan-mode', form: 'notice', summary: text },
479
+ })
480
+ }
481
+ }
482
+
483
+ export default PlanModeController
package/src/types.ts ADDED
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Pure types of the plan domain: the ONE home of the `plan` projection-key
3
+ * declaration, free of this package's host-side value imports (cordis,
4
+ * rabi-tools, rabi-agent). Two namespace projections serve it — `./types` for
5
+ * host consumers and `./client` for client aggregates — with zero content
6
+ * duplication.
7
+ *
8
+ * @module @unieai/rabi-plan-mode/types
9
+ */
10
+
11
+ import type { CommandId } from '@unieai/rabi-commands/brand'
12
+
13
+ /**
14
+ * The plan projection's wire value. `active` is the logged state in force
15
+ * (the last `plan/mode`, inactive before the first); `pending` is true while
16
+ * a logged `/plan` selection targets a state other than `active`, has not
17
+ * failed through its paired `command/done`, and no later `plan/mode` event has
18
+ * recorded that state. Capability absence (plan-mode not composed) is the
19
+ * key's absence, never a value.
20
+ */
21
+ export interface PlanProjection {
22
+ active: boolean
23
+ pending: boolean
24
+ }
25
+
26
+ /** Host state used to derive {@link PlanProjection}. */
27
+ export interface PlanUnitState {
28
+ /** Logged plan mode. */
29
+ active: boolean
30
+ /** The selection's target mode; null when no selection is outstanding. */
31
+ wanted: boolean | null
32
+ /** The latest plan command awaiting its paired settlement. */
33
+ running: { commandId: CommandId; wanted: boolean } | null
34
+ /** Active state recorded by the latest `request/header`, or null. */
35
+ activeAtLastHeader: boolean | null
36
+ /** Whether a logged `plan/mode` has ever activated plan mode in this Session. */
37
+ entered: boolean
38
+ }
39
+
40
+ declare module '@unieai/rabi-session-projection/types' {
41
+ interface SessionProjectionMap {
42
+ /** Plan collaboration state folded from the plan command lifecycle and `plan/mode` events. */
43
+ plan: PlanProjection
44
+ }
45
+ }