@unieai/rabi-tool-goal 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DeepSeek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,8 @@
1
- # Temporary Holding Version
1
+ # @unieai/rabi-tool-goal
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Model-facing same-session goal tools with execution-time authority checks
4
+
5
+ Part of Rabi, the agent harness UnieAI Code runs on. Installed as a dependency of `@unieai/rabi`;
6
+ not meant to be used on its own.
7
+
8
+ See LICENSE for the license and copyright of this package.
package/lib/index.js ADDED
@@ -0,0 +1,373 @@
1
+ import z from "@unieai/schemastery";
2
+ import { GoalId } from "@unieai/rabi-goal";
3
+ import { HarnessError, boundContextSummary, createUserMessage } from "@unieai/rabi-llm";
4
+ import { defineTool } from "@unieai/rabi-tools";
5
+ //#region lib/types/authority.js
6
+ /** Execution-time authority checks for the model-facing goal tools. */
7
+ /** Throw one structured tool-policy failure. */
8
+ function reject(message, code = "GOAL_TOOL_AUTHORITY_REQUIRED") {
9
+ throw new HarnessError(message, code);
10
+ }
11
+ /** Resolve the immutable event cut and open-turn boundary without copying the turn suffix. */
12
+ function openTurnEvents(ctx, agent) {
13
+ const events = agent.session.snapshotEvents();
14
+ const boundary = ctx.agents.turnBoundaryOf(agent.session);
15
+ if (boundary.openTurnStartSeq === null) reject("goal tools require an open model turn", "GOAL_TOOL_DRIVER_REQUIRED");
16
+ return {
17
+ events,
18
+ openTurnStartSeq: boundary.openTurnStartSeq
19
+ };
20
+ }
21
+ /**
22
+ * Resolve and authenticate the calling agent and its driver boundary.
23
+ * @param ctx - Context carrying the live agent registry.
24
+ * @param exec - Tool execution metadata supplied by the registry.
25
+ * @returns The authenticated agent, immutable event cut, and open-turn boundary.
26
+ */
27
+ function goalToolExecution(ctx, exec) {
28
+ const agent = exec.agent;
29
+ if (agent === void 0) return reject("goal tools require a calling agent", "GOAL_TOOL_AGENT_REQUIRED");
30
+ if (ctx.agents.get(agent.id) !== agent || agent.status !== "running" || ctx.agents.currentInitiator() !== agent) return reject("goal tools require the exact live calling agent inside its active driver", "GOAL_TOOL_DRIVER_REQUIRED");
31
+ return {
32
+ agent,
33
+ ...openTurnEvents(ctx, agent)
34
+ };
35
+ }
36
+ /** Whether the captured open turn contains an event accepted by `predicate`. */
37
+ function someOpenTurnEvent(execution, predicate) {
38
+ for (let seq = execution.openTurnStartSeq + 1; seq < execution.events.length; seq += 1) {
39
+ const event = execution.events[seq];
40
+ if (event !== void 0 && predicate(event)) return true;
41
+ }
42
+ return false;
43
+ }
44
+ /**
45
+ * Whether host-attested human input appears in the current root-agent turn.
46
+ * An omitted `Agent.followup()` / `steer()` source resolves to `user`, so non-human
47
+ * producers must supply their own source rather than inheriting this authority.
48
+ */
49
+ function hasDirectHumanInput(ctx, execution) {
50
+ if (ctx.agents.get(execution.agent.id) !== execution.agent || execution.agent.session.header.origin === "subagent") return false;
51
+ return someOpenTurnEvent(execution, (event) => event.type === "user/message" && event.data.source.kind === "user");
52
+ }
53
+ /** Whether this turn is the current goal's exact admitted round. */
54
+ function isMatchingGoalRound(execution, goal) {
55
+ return someOpenTurnEvent(execution, (event) => event.type === "user/message" && event.data.source.kind === "goal" && event.data.source.goalId === goal.id && event.data.source.revision === goal.revision && event.data.source.round === goal.roundsStarted);
56
+ }
57
+ /**
58
+ * Require authority originating in a human message accepted by a runtime root.
59
+ * @param ctx - Context carrying the live agent graph.
60
+ * @param execution - Authenticated current tool execution.
61
+ */
62
+ function requireDirectHuman(ctx, execution) {
63
+ if (hasDirectHumanInput(ctx, execution)) return;
64
+ reject("this goal operation requires a direct human turn on a top-level agent");
65
+ }
66
+ /**
67
+ * Resolve completion authority from either direct human input or the exact goal round.
68
+ * @param ctx - Context carrying live agents and goal state.
69
+ * @param execution - Authenticated current tool execution.
70
+ * @returns The direct-human or exact-goal-round authority grant.
71
+ */
72
+ function completionAuthority(ctx, execution) {
73
+ if (hasDirectHumanInput(ctx, execution)) return { kind: "direct-human" };
74
+ const goal = ctx.goals.get(execution.agent);
75
+ if (goal !== void 0 && isMatchingGoalRound(execution, goal)) return {
76
+ kind: "goal-round",
77
+ goal
78
+ };
79
+ return reject("complete and blocked require a direct human turn or the current goal round");
80
+ }
81
+ //#endregion
82
+ //#region lib/types/wrapup.js
83
+ /**
84
+ * Render the closing-message instruction injected after an autonomous goal
85
+ * round reports `complete` or `blocked`, replacing the former hard turn stop
86
+ * so the model still addresses the user once before the turn ends.
87
+ * @param objective - the terminal goal's objective, echoed for grounding.
88
+ * @param blockedReason - the validated report for `blocked`; omitted for `complete`.
89
+ * @returns a fresh one-block context for `ToolRunContext.deferContext()`.
90
+ */
91
+ function renderWrapupContext(objective, blockedReason) {
92
+ const heading = `Objective: ${JSON.stringify(objective)}\n`;
93
+ return [{
94
+ type: "text",
95
+ text: blockedReason === void 0 ? "<goal_complete>\n" + heading + "The goal is marked complete and this autonomous run is ending. Write the closing message to the user now: state the outcome, summarize what was done and how it was verified, and point to the concrete results (files, commits, or other artifacts). Report only what earlier rounds and tool results in this session actually establish; when a detail is not in the session, say so instead of inventing it. Note anything the user should review or do next. Address the user directly. Do not call any more tools in this run; further work waits for the user's next instruction.\n</goal_complete>" : "<goal_blocked>\n" + heading + `Blocked: ${JSON.stringify(blockedReason)}\nThe goal is marked blocked and this autonomous run is ending. Write the closing message to the user now: state what has been completed so far, describe the concrete blocking condition and what you tried, and say exactly what you need from the user to continue. Report only what earlier rounds and tool results in this session actually establish; when a detail is not in the session, say so instead of inventing it. Address the user directly. Do not call any more tools in this run; further work waits for the user's next instruction.
96
+ </goal_blocked>`
97
+ }];
98
+ }
99
+ //#endregion
100
+ //#region lib/types/index.js
101
+ /**
102
+ * Model-facing `get_goal`, `create_goal`, and `update_goal` tools over the
103
+ * persisted same-session goal domain.
104
+ * @module @unieai/rabi-tool-goal
105
+ */
106
+ const name = "tool-goal";
107
+ const inject = [
108
+ "agents",
109
+ "goals",
110
+ "tools",
111
+ "systemPrompt"
112
+ ];
113
+ /** Schemastery config for the goal-tool policy. */
114
+ const Config = z.object({ blockedAfterConsecutiveRounds: z.number().step(1).min(1).default(3) });
115
+ const UPDATE_ACTIONS = [
116
+ "edit",
117
+ "pause",
118
+ "resume",
119
+ "complete",
120
+ "blocked"
121
+ ];
122
+ const CREATE_DESCRIPTION = "Create a persisted goal that keeps this session working across automatic continuation rounds. Use it when the direct human request is a long-running objective, even if the user did not say \"goal\"; not for single-turn work.";
123
+ const GET_DESCRIPTION = "Read the current session goal, including the id and revision that update_goal requires.";
124
+ const GOAL_VALUE_SCHEMA = { oneOf: [{
125
+ type: "object",
126
+ additionalProperties: false,
127
+ properties: { goal: {
128
+ type: "null",
129
+ required: true
130
+ } }
131
+ }, {
132
+ type: "object",
133
+ additionalProperties: false,
134
+ properties: {
135
+ goal: {
136
+ type: "object",
137
+ additionalProperties: false,
138
+ required: true,
139
+ properties: {
140
+ id: {
141
+ type: "string",
142
+ required: true
143
+ },
144
+ revision: {
145
+ type: "integer",
146
+ required: true
147
+ },
148
+ objective: {
149
+ type: "string",
150
+ required: true
151
+ },
152
+ phase: {
153
+ type: "string",
154
+ required: true,
155
+ enum: [
156
+ "active",
157
+ "paused",
158
+ "blocked",
159
+ "complete"
160
+ ]
161
+ },
162
+ roundsStarted: {
163
+ type: "integer",
164
+ required: true
165
+ },
166
+ maxGoalRounds: {
167
+ type: "integer",
168
+ required: true
169
+ },
170
+ blockedReason: {
171
+ type: "object",
172
+ additionalProperties: false,
173
+ properties: {
174
+ code: {
175
+ type: "string",
176
+ required: true
177
+ },
178
+ message: {
179
+ type: "string",
180
+ required: true
181
+ }
182
+ }
183
+ }
184
+ }
185
+ },
186
+ activation: {
187
+ type: "string",
188
+ required: true,
189
+ enum: ["armed", "disarmed"]
190
+ }
191
+ }
192
+ }] };
193
+ /** Render policy guidance with its deployment-selected blocked threshold. */
194
+ function guidance(blockedAfter) {
195
+ return `create_goal may infer goal intent from a direct human request in any language. After session resume or fork, an active goal is disarmed: when a human asks to continue or resume in any wording or language, use update_goal action resume to rearm it. Mark complete only when the objective is actually achieved. Mark blocked only after the same blocking condition persists for at least ${blockedAfter} consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, or useful remaining work is not blocked.`;
196
+ }
197
+ /** Validate config even when apply is called directly outside Loader normalization. */
198
+ function resolveConfig(config) {
199
+ const blockedAfter = config.blockedAfterConsecutiveRounds ?? 3;
200
+ if (!Number.isSafeInteger(blockedAfter) || blockedAfter < 1) throw new TypeError("blockedAfterConsecutiveRounds must be a positive safe integer");
201
+ return { blockedAfterConsecutiveRounds: blockedAfter };
202
+ }
203
+ /** Whether optional text is meaningful rather than a strict-schema empty filler. */
204
+ function hasText(value) {
205
+ return value !== void 0 && value !== "";
206
+ }
207
+ /** Whether an optional round cap is meaningful rather than a strict-schema zero filler. */
208
+ function hasRoundCap(value) {
209
+ return value !== void 0 && value !== 0;
210
+ }
211
+ /** Build the exact compare-and-set ref from model arguments. */
212
+ function goalRef(goalId, revision) {
213
+ if (goalId.length === 0 || goalId !== goalId.trim() || !Number.isSafeInteger(revision) || revision < 1) throw new HarnessError("goal_id must be non-empty and revision must be a positive safe integer", "GOAL_TOOL_INVALID_UPDATE");
214
+ return {
215
+ id: GoalId(goalId),
216
+ revision
217
+ };
218
+ }
219
+ /** Stable compact model result; activation is an observation, not replay state. */
220
+ function goalValue(goal) {
221
+ if (goal === void 0) return { goal: null };
222
+ return {
223
+ goal: {
224
+ id: goal.id,
225
+ revision: goal.revision,
226
+ objective: goal.objective,
227
+ phase: goal.phase,
228
+ roundsStarted: goal.roundsStarted,
229
+ maxGoalRounds: goal.maxGoalRounds,
230
+ ...goal.blockedReason === void 0 ? {} : { blockedReason: {
231
+ code: goal.blockedReason.code,
232
+ message: goal.blockedReason.message
233
+ } }
234
+ },
235
+ activation: goal.activation
236
+ };
237
+ }
238
+ /** Reusable canonical output declaration for all three goal controls. */
239
+ const GOAL_OUTPUT = {
240
+ schema: GOAL_VALUE_SCHEMA,
241
+ render: (_args, value) => [{
242
+ type: "text",
243
+ text: JSON.stringify(value)
244
+ }]
245
+ };
246
+ /** Generic, args-only pending presentation shared by the goal tools. */
247
+ function present(title, kind, rawInput) {
248
+ return {
249
+ card: "generic",
250
+ title,
251
+ kind,
252
+ ...rawInput === void 0 ? {} : { rawInput }
253
+ };
254
+ }
255
+ /** Register the three Codex-shaped goal tools and their shared policy section. */
256
+ function apply(ctx, config) {
257
+ const resolved = resolveConfig(config);
258
+ ctx.systemPrompt.section({
259
+ name: "tool:goal",
260
+ order: ctx.systemPrompt.getSectionOrder("TOOL_GOAL"),
261
+ text: guidance(resolved.blockedAfterConsecutiveRounds)
262
+ });
263
+ ctx.tools.register(defineTool({
264
+ name: "get_goal",
265
+ description: GET_DESCRIPTION,
266
+ parameters: {},
267
+ output: GOAL_OUTPUT,
268
+ execute(_args, exec) {
269
+ const execution = goalToolExecution(ctx, exec);
270
+ return Promise.resolve(goalValue(ctx.goals.get(execution.agent)));
271
+ },
272
+ presentCall: () => present("Read current goal", "read")
273
+ }));
274
+ ctx.tools.register(defineTool({
275
+ name: "create_goal",
276
+ description: CREATE_DESCRIPTION,
277
+ parameters: {
278
+ objective: {
279
+ type: "string",
280
+ required: true,
281
+ description: "The concrete completion objective inferred from the direct human request."
282
+ },
283
+ max_goal_rounds: {
284
+ type: "number",
285
+ description: "Optional positive safe-integer limit on automatic continuation rounds."
286
+ }
287
+ },
288
+ output: GOAL_OUTPUT,
289
+ execute(args, exec) {
290
+ const execution = goalToolExecution(ctx, exec);
291
+ requireDirectHuman(ctx, execution);
292
+ const goal = ctx.goals.create(execution.agent, {
293
+ objective: args.objective,
294
+ ...args.max_goal_rounds === void 0 ? {} : { maxGoalRounds: args.max_goal_rounds }
295
+ });
296
+ return Promise.resolve(goalValue(goal));
297
+ },
298
+ presentCall: (args) => present("Create goal", "other", args.objective)
299
+ }));
300
+ ctx.tools.register(defineTool({
301
+ name: "update_goal",
302
+ description: "Update the current goal.",
303
+ parameters: {
304
+ goal_id: {
305
+ type: "string",
306
+ required: true,
307
+ description: "Exact id returned by get_goal."
308
+ },
309
+ revision: {
310
+ type: "number",
311
+ required: true,
312
+ description: "Exact positive revision returned by get_goal."
313
+ },
314
+ action: {
315
+ type: "string",
316
+ required: true,
317
+ enum: UPDATE_ACTIONS,
318
+ description: "edit, pause, and resume require a direct top-level human request. complete and blocked are also allowed during an automatic continuation of this goal; blocked is rejected before the configured minimum round count."
319
+ },
320
+ objective: {
321
+ type: "string",
322
+ description: "Replacement objective; valid only with action edit."
323
+ },
324
+ max_goal_rounds: {
325
+ type: "number",
326
+ description: "Replacement cap; valid only with action edit."
327
+ },
328
+ blocked_reason: {
329
+ type: "string",
330
+ description: "Required only with action blocked: the concrete condition that persisted across rounds and blocks progress."
331
+ }
332
+ },
333
+ output: GOAL_OUTPUT,
334
+ execute(args, exec) {
335
+ const execution = goalToolExecution(ctx, exec);
336
+ const ref = goalRef(args.goal_id, args.revision);
337
+ if (args.action === "edit") {
338
+ requireDirectHuman(ctx, execution);
339
+ const goal = ctx.goals.edit(execution.agent, ref, {
340
+ ...hasText(args.objective) ? { objective: args.objective } : {},
341
+ ...hasRoundCap(args.max_goal_rounds) ? { maxGoalRounds: args.max_goal_rounds } : {}
342
+ });
343
+ return Promise.resolve(goalValue(goal));
344
+ }
345
+ if (args.action === "pause" || args.action === "resume") {
346
+ requireDirectHuman(ctx, execution);
347
+ const current = ctx.goals.get(execution.agent);
348
+ if (args.action === "resume" && current?.id === ref.id && current.revision === ref.revision && current.phase === "paused") throw new HarnessError("the model cannot resume a paused goal; the user must resume it", "GOAL_TOOL_RESUME_PAUSED");
349
+ const goal = args.action === "pause" ? ctx.goals.pause(execution.agent, ref) : ctx.goals.resume(execution.agent, ref);
350
+ return Promise.resolve(goalValue(goal));
351
+ }
352
+ const authority = completionAuthority(ctx, execution);
353
+ if (args.action === "blocked" && (args.blocked_reason === void 0 || args.blocked_reason.trim().length === 0)) throw new HarnessError("blocked_reason is required with action blocked", "GOAL_TOOL_INVALID_UPDATE");
354
+ if (args.action === "blocked" && authority.kind === "goal-round" && authority.goal.roundsStarted < resolved.blockedAfterConsecutiveRounds) throw new HarnessError(`blocked requires at least ${resolved.blockedAfterConsecutiveRounds} consecutive goal rounds; current round is ${authority.goal.roundsStarted}`, "GOAL_TOOL_BLOCK_THRESHOLD");
355
+ const goal = args.action === "complete" ? ctx.goals.complete(execution.agent, ref) : ctx.goals.block(execution.agent, ref, {
356
+ code: "model-reported",
357
+ message: args.blocked_reason
358
+ });
359
+ if (authority.kind === "goal-round") exec.deferContext(createUserMessage({
360
+ content: args.action === "complete" ? renderWrapupContext(goal.objective) : renderWrapupContext(goal.objective, args.blocked_reason),
361
+ source: {
362
+ kind: "tool-goal",
363
+ form: "notice",
364
+ summary: boundContextSummary(`${args.action}: ${goal.objective}`)
365
+ }
366
+ }));
367
+ return Promise.resolve(goalValue(goal));
368
+ },
369
+ presentCall: (args) => present(`${args.action === "blocked" ? "Mark" : args.action.charAt(0).toUpperCase() + args.action.slice(1)} goal`, "other", args.action === "blocked" && hasText(args.blocked_reason) ? args.blocked_reason : args.action === "edit" && hasText(args.objective) ? args.objective : args.action === "edit" && hasRoundCap(args.max_goal_rounds) ? args.max_goal_rounds : args.goal_id)
370
+ }));
371
+ }
372
+ //#endregion
373
+ export { Config, apply, inject, name };
@@ -0,0 +1,40 @@
1
+ /** Execution-time authority checks for the model-facing goal tools. */
2
+ import type { Context } from '@unieai/cordis';
3
+ import type { Agent } from '@unieai/rabi-agent';
4
+ import type { GoalView } from '@unieai/rabi-goal';
5
+ import type { SessionEvent, SessionSeq } from '@unieai/rabi-session';
6
+ import type { ToolRunContext } from '@unieai/rabi-tools';
7
+ /** The calling agent plus the immutable event cut and open-turn start seq used for authority checks. */
8
+ export interface GoalToolExecution {
9
+ readonly agent: Agent;
10
+ readonly events: readonly SessionEvent[];
11
+ readonly openTurnStartSeq: SessionSeq;
12
+ }
13
+ /** Hard authority granted to one state-changing call. */
14
+ export type GoalToolAuthority = {
15
+ readonly kind: 'direct-human';
16
+ } | {
17
+ readonly kind: 'goal-round';
18
+ readonly goal: GoalView;
19
+ };
20
+ /**
21
+ * Resolve and authenticate the calling agent and its driver boundary.
22
+ * @param ctx - Context carrying the live agent registry.
23
+ * @param exec - Tool execution metadata supplied by the registry.
24
+ * @returns The authenticated agent, immutable event cut, and open-turn boundary.
25
+ */
26
+ export declare function goalToolExecution(ctx: Context, exec: ToolRunContext): GoalToolExecution;
27
+ /**
28
+ * Require authority originating in a human message accepted by a runtime root.
29
+ * @param ctx - Context carrying the live agent graph.
30
+ * @param execution - Authenticated current tool execution.
31
+ */
32
+ export declare function requireDirectHuman(ctx: Context, execution: GoalToolExecution): void;
33
+ /**
34
+ * Resolve completion authority from either direct human input or the exact goal round.
35
+ * @param ctx - Context carrying live agents and goal state.
36
+ * @param execution - Authenticated current tool execution.
37
+ * @returns The direct-human or exact-goal-round authority grant.
38
+ */
39
+ export declare function completionAuthority(ctx: Context, execution: GoalToolExecution): GoalToolAuthority;
40
+ //# sourceMappingURL=authority.d.ts.map
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Model-facing `get_goal`, `create_goal`, and `update_goal` tools over the
3
+ * persisted same-session goal domain.
4
+ * @module @unieai/rabi-tool-goal
5
+ */
6
+ import type { Context } from '@unieai/cordis';
7
+ import z from '@unieai/schemastery';
8
+ import type { ContextFormed } from '@unieai/rabi-llm';
9
+ declare module '@unieai/rabi-llm' {
10
+ interface MessageSourceMap {
11
+ 'tool-goal': {
12
+ kind: 'tool-goal';
13
+ } & ContextFormed;
14
+ }
15
+ }
16
+ export declare const name = "tool-goal";
17
+ export declare const inject: string[];
18
+ /** Model policy and hard lower bounds for goal-state updates. */
19
+ export interface Config {
20
+ /** Minimum admitted goal rounds before the model may self-report `blocked`. */
21
+ blockedAfterConsecutiveRounds?: number;
22
+ }
23
+ /** Schemastery config for the goal-tool policy. */
24
+ export declare const Config: z<Config>;
25
+ /** Register the three Codex-shaped goal tools and their shared policy section. */
26
+ export declare function apply(ctx: Context, config: Config): void;
27
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,12 @@
1
+ /** Model-visible wrap-up instruction for a terminal autonomous goal update. */
2
+ import type { ContentBlock } from '@unieai/rabi-llm';
3
+ /**
4
+ * Render the closing-message instruction injected after an autonomous goal
5
+ * round reports `complete` or `blocked`, replacing the former hard turn stop
6
+ * so the model still addresses the user once before the turn ends.
7
+ * @param objective - the terminal goal's objective, echoed for grounding.
8
+ * @param blockedReason - the validated report for `blocked`; omitted for `complete`.
9
+ * @returns a fresh one-block context for `ToolRunContext.deferContext()`.
10
+ */
11
+ export declare function renderWrapupContext(objective: string, blockedReason?: string): ContentBlock[];
12
+ //# sourceMappingURL=wrapup.d.ts.map
package/locale/de.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Zielmanagement-Tool",
4
+ "description": "Lassen Sie die KI aktuelle Sitzungsziele festlegen, anzeigen und aktualisieren."
5
+ }
6
+ }
package/locale/en.json ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "meta": {
3
+ "title": "tool-goal"
4
+ }
5
+ }
package/locale/es.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Herramienta de gestión de objetivos",
4
+ "description": "Deje que la IA establezca, vea y actualice los objetivos de la sesión actual."
5
+ }
6
+ }
package/locale/fr.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Outil de gestion des objectifs",
4
+ "description": "Laissez l'IA définir, afficher et mettre à jour les objectifs de la session en cours."
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": "Ferramenta de gerenciamento de metas",
4
+ "description": "Deixe a IA definir, visualizar e atualizar as metas da sessão atual."
5
+ }
6
+ }
package/locale/ru.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Инструмент управления целями",
4
+ "description": "Позвольте ИИ устанавливать, просматривать и обновлять текущие цели сеанса."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "目标管理工具",
4
+ "description": "让 AI 设置、查看和更新当前会话目标。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@unieai/rabi-tool-goal",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "description": "Model-facing same-session goal tools with execution-time authority checks",
4
+ "version": "0.2.2-rc.5",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "type": "module",
9
+ "main": "lib/index.js",
10
+ "types": "lib/types/index.d.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./lib/types/index.d.ts",
14
+ "default": "./lib/index.js"
15
+ },
16
+ "./src/*": "./src/*",
17
+ "./package.json": "./package.json",
18
+ "./locale/*.json": "./locale/*.json"
19
+ },
20
+ "files": [
21
+ "locale/*.json",
22
+ "lib/index.js",
23
+ "lib/types/**/*.d.ts",
24
+ "lib/types/**/*.d.ts.map",
25
+ "lib/**/*.js.map",
26
+ "src",
27
+ "README.md"
28
+ ],
29
+ "license": "MIT",
30
+ "peerDependencies": {
31
+ "@unieai/rabi-agent": "0.2.2-rc.5",
32
+ "@unieai/rabi-goal": "0.2.2-rc.5",
33
+ "@unieai/rabi-llm": "0.2.2-rc.5",
34
+ "@unieai/rabi-session": "0.2.2-rc.5",
35
+ "@unieai/rabi-system-prompt": "0.2.2-rc.5",
36
+ "@unieai/rabi-tools": "0.2.2-rc.5",
37
+ "@unieai/cordis": "4.1.0"
38
+ },
39
+ "dependencies": {
40
+ "@unieai/schemastery": "3.19.0"
41
+ }
42
+ }
@@ -0,0 +1,117 @@
1
+ /** Execution-time authority checks for the model-facing goal tools. */
2
+
3
+ import type { Context } from '@unieai/cordis'
4
+ import type { Agent } from '@unieai/rabi-agent'
5
+ import type { GoalView } from '@unieai/rabi-goal'
6
+ import { HarnessError } from '@unieai/rabi-llm'
7
+ import type { SessionEvent, SessionSeq } from '@unieai/rabi-session'
8
+ import type { ToolRunContext } from '@unieai/rabi-tools'
9
+
10
+ /** The calling agent plus the immutable event cut and open-turn start seq used for authority checks. */
11
+ export interface GoalToolExecution {
12
+ readonly agent: Agent
13
+ readonly events: readonly SessionEvent[]
14
+ readonly openTurnStartSeq: SessionSeq
15
+ }
16
+
17
+ /** Hard authority granted to one state-changing call. */
18
+ export type GoalToolAuthority =
19
+ | { readonly kind: 'direct-human' }
20
+ | { readonly kind: 'goal-round'; readonly goal: GoalView }
21
+
22
+ /** Throw one structured tool-policy failure. */
23
+ function reject(message: string, code = 'GOAL_TOOL_AUTHORITY_REQUIRED'): never {
24
+ throw new HarnessError(message, code)
25
+ }
26
+
27
+ /** Resolve the immutable event cut and open-turn boundary without copying the turn suffix. */
28
+ function openTurnEvents(
29
+ ctx: Context,
30
+ agent: Agent,
31
+ ): Pick<GoalToolExecution, 'events' | 'openTurnStartSeq'> {
32
+ // oxlint-disable-next-line typescript/no-deprecated -- Existing Session history read; migration deferred.
33
+ const events = agent.session.snapshotEvents()
34
+ const boundary = ctx.agents.turnBoundaryOf(agent.session)
35
+ if (boundary.openTurnStartSeq === null) {
36
+ reject('goal tools require an open model turn', 'GOAL_TOOL_DRIVER_REQUIRED')
37
+ }
38
+ return { events, openTurnStartSeq: boundary.openTurnStartSeq }
39
+ }
40
+
41
+ /**
42
+ * Resolve and authenticate the calling agent and its driver boundary.
43
+ * @param ctx - Context carrying the live agent registry.
44
+ * @param exec - Tool execution metadata supplied by the registry.
45
+ * @returns The authenticated agent, immutable event cut, and open-turn boundary.
46
+ */
47
+ export function goalToolExecution(ctx: Context, exec: ToolRunContext): GoalToolExecution {
48
+ const agent = exec.agent
49
+ if (agent === undefined) {
50
+ return reject('goal tools require a calling agent', 'GOAL_TOOL_AGENT_REQUIRED')
51
+ }
52
+ if (ctx.agents.get(agent.id) !== agent || agent.status !== 'running'
53
+ || ctx.agents.currentInitiator() !== agent) {
54
+ return reject(
55
+ 'goal tools require the exact live calling agent inside its active driver',
56
+ 'GOAL_TOOL_DRIVER_REQUIRED',
57
+ )
58
+ }
59
+ return { agent, ...openTurnEvents(ctx, agent) }
60
+ }
61
+
62
+ /** Whether the captured open turn contains an event accepted by `predicate`. */
63
+ function someOpenTurnEvent(
64
+ execution: GoalToolExecution,
65
+ predicate: (event: SessionEvent) => boolean,
66
+ ): boolean {
67
+ for (let seq = execution.openTurnStartSeq + 1; seq < execution.events.length; seq += 1) {
68
+ const event = execution.events[seq]
69
+ if (event !== undefined && predicate(event)) return true
70
+ }
71
+ return false
72
+ }
73
+
74
+ /**
75
+ * Whether host-attested human input appears in the current root-agent turn.
76
+ * An omitted `Agent.followup()` / `steer()` source resolves to `user`, so non-human
77
+ * producers must supply their own source rather than inheriting this authority.
78
+ */
79
+ function hasDirectHumanInput(ctx: Context, execution: GoalToolExecution): boolean {
80
+ if (ctx.agents.get(execution.agent.id) !== execution.agent || execution.agent.session.header.origin === 'subagent') return false
81
+ return someOpenTurnEvent(execution, event =>
82
+ event.type === 'user/message' && event.data.source.kind === 'user')
83
+ }
84
+
85
+ /** Whether this turn is the current goal's exact admitted round. */
86
+ function isMatchingGoalRound(execution: GoalToolExecution, goal: GoalView): boolean {
87
+ return someOpenTurnEvent(execution, event => event.type === 'user/message'
88
+ && event.data.source.kind === 'goal'
89
+ && event.data.source.goalId === goal.id
90
+ && event.data.source.revision === goal.revision
91
+ && event.data.source.round === goal.roundsStarted)
92
+ }
93
+
94
+ /**
95
+ * Require authority originating in a human message accepted by a runtime root.
96
+ * @param ctx - Context carrying the live agent graph.
97
+ * @param execution - Authenticated current tool execution.
98
+ */
99
+ export function requireDirectHuman(ctx: Context, execution: GoalToolExecution): void {
100
+ if (hasDirectHumanInput(ctx, execution)) return
101
+ reject('this goal operation requires a direct human turn on a top-level agent')
102
+ }
103
+
104
+ /**
105
+ * Resolve completion authority from either direct human input or the exact goal round.
106
+ * @param ctx - Context carrying live agents and goal state.
107
+ * @param execution - Authenticated current tool execution.
108
+ * @returns The direct-human or exact-goal-round authority grant.
109
+ */
110
+ export function completionAuthority(ctx: Context, execution: GoalToolExecution): GoalToolAuthority {
111
+ if (hasDirectHumanInput(ctx, execution)) return { kind: 'direct-human' }
112
+ const goal = ctx.goals.get(execution.agent)
113
+ if (goal !== undefined && isMatchingGoalRound(execution, goal)) {
114
+ return { kind: 'goal-round', goal }
115
+ }
116
+ return reject('complete and blocked require a direct human turn or the current goal round')
117
+ }
package/src/index.ts ADDED
@@ -0,0 +1,324 @@
1
+ /**
2
+ * Model-facing `get_goal`, `create_goal`, and `update_goal` tools over the
3
+ * persisted same-session goal domain.
4
+ * @module @unieai/rabi-tool-goal
5
+ */
6
+
7
+ import type { Context } from '@unieai/cordis'
8
+ import z from '@unieai/schemastery'
9
+ import { GoalId } from '@unieai/rabi-goal'
10
+ import type { GoalRef, GoalView } from '@unieai/rabi-goal'
11
+ import { boundContextSummary, createUserMessage, HarnessError } from '@unieai/rabi-llm'
12
+ import type { ContextFormed } from '@unieai/rabi-llm'
13
+ declare module '@unieai/rabi-llm' {
14
+ interface MessageSourceMap {
15
+ 'tool-goal': { kind: 'tool-goal' } & ContextFormed
16
+ }
17
+ }
18
+
19
+ import { defineTool } from '@unieai/rabi-tools'
20
+ import type { GenericCallView } from '@unieai/rabi-tools'
21
+ import {
22
+ completionAuthority,
23
+ goalToolExecution,
24
+ requireDirectHuman,
25
+ } from './authority.ts'
26
+ import { renderWrapupContext } from './wrapup.ts'
27
+
28
+ export const name = 'tool-goal'
29
+ export const inject = ['agents', 'goals', 'tools', 'systemPrompt']
30
+
31
+ /** Model policy and hard lower bounds for goal-state updates. */
32
+ export interface Config {
33
+ /** Minimum admitted goal rounds before the model may self-report `blocked`. */
34
+ blockedAfterConsecutiveRounds?: number
35
+ }
36
+
37
+ /** Schemastery config for the goal-tool policy. */
38
+ export const Config: z<Config> = z.object({
39
+ blockedAfterConsecutiveRounds: z.number().step(1).min(1).default(3),
40
+ })
41
+
42
+ /** Fully materialized tool policy. */
43
+ interface ResolvedConfig {
44
+ readonly blockedAfterConsecutiveRounds: number
45
+ }
46
+
47
+ type UpdateAction = 'edit' | 'pause' | 'resume' | 'complete' | 'blocked'
48
+
49
+ const UPDATE_ACTIONS: UpdateAction[] = ['edit', 'pause', 'resume', 'complete', 'blocked']
50
+
51
+ const CREATE_DESCRIPTION =
52
+ 'Create a persisted goal that keeps this session working across automatic continuation rounds. '
53
+ + 'Use it when the direct human request is a long-running objective, even if the user did not say "goal"; '
54
+ + 'not for single-turn work.'
55
+
56
+ const GET_DESCRIPTION = 'Read the current session goal, including the id and revision that update_goal requires.'
57
+
58
+ /** Canonical goal-tool output, matching the existing compact Native JSON. */
59
+ type GoalToolValue =
60
+ | { goal: null }
61
+ | {
62
+ goal: {
63
+ id: string
64
+ revision: number
65
+ objective: string
66
+ phase: GoalView['phase']
67
+ roundsStarted: number
68
+ maxGoalRounds: number
69
+ blockedReason?: { code: string; message: string }
70
+ }
71
+ activation: GoalView['activation']
72
+ }
73
+
74
+ const GOAL_VALUE_SCHEMA = {
75
+ oneOf: [
76
+ {
77
+ type: 'object',
78
+ additionalProperties: false,
79
+ properties: {
80
+ goal: { type: 'null', required: true },
81
+ },
82
+ },
83
+ {
84
+ type: 'object',
85
+ additionalProperties: false,
86
+ properties: {
87
+ goal: {
88
+ type: 'object',
89
+ additionalProperties: false,
90
+ required: true,
91
+ properties: {
92
+ id: { type: 'string', required: true },
93
+ revision: { type: 'integer', required: true },
94
+ objective: { type: 'string', required: true },
95
+ phase: { type: 'string', required: true, enum: ['active', 'paused', 'blocked', 'complete'] },
96
+ roundsStarted: { type: 'integer', required: true },
97
+ maxGoalRounds: { type: 'integer', required: true },
98
+ blockedReason: {
99
+ type: 'object',
100
+ additionalProperties: false,
101
+ properties: {
102
+ code: { type: 'string', required: true },
103
+ message: { type: 'string', required: true },
104
+ },
105
+ },
106
+ },
107
+ },
108
+ activation: { type: 'string', required: true, enum: ['armed', 'disarmed'] },
109
+ },
110
+ },
111
+ ],
112
+ } as const
113
+
114
+ /** Render policy guidance with its deployment-selected blocked threshold. */
115
+ function guidance(blockedAfter: number): string {
116
+ return 'create_goal may infer goal intent from a direct human request in any language. '
117
+ + 'After session resume or fork, an active goal is disarmed: when '
118
+ + 'a human asks to continue or resume in any wording or language, use update_goal action '
119
+ + 'resume to rearm it. Mark complete only when the objective is actually achieved. Mark '
120
+ + `blocked only after the same blocking condition persists for at least ${blockedAfter} `
121
+ + 'consecutive goal rounds, and report that concrete condition in blocked_reason; difficulty, uncertainty, '
122
+ + 'or useful remaining work is not blocked.'
123
+ }
124
+
125
+ /** Validate config even when apply is called directly outside Loader normalization. */
126
+ function resolveConfig(config: Config): ResolvedConfig {
127
+ const blockedAfter = config.blockedAfterConsecutiveRounds ?? 3
128
+ if (!Number.isSafeInteger(blockedAfter) || blockedAfter < 1) {
129
+ throw new TypeError('blockedAfterConsecutiveRounds must be a positive safe integer')
130
+ }
131
+ return { blockedAfterConsecutiveRounds: blockedAfter }
132
+ }
133
+
134
+ /** Whether optional text is meaningful rather than a strict-schema empty filler. */
135
+ function hasText(value: string | undefined): value is string {
136
+ return value !== undefined && value !== ''
137
+ }
138
+
139
+ /** Whether an optional round cap is meaningful rather than a strict-schema zero filler. */
140
+ function hasRoundCap(value: number | undefined): value is number {
141
+ return value !== undefined && value !== 0
142
+ }
143
+
144
+ /** Build the exact compare-and-set ref from model arguments. */
145
+ function goalRef(goalId: string, revision: number): GoalRef {
146
+ if (goalId.length === 0 || goalId !== goalId.trim()
147
+ || !Number.isSafeInteger(revision) || revision < 1) {
148
+ throw new HarnessError(
149
+ 'goal_id must be non-empty and revision must be a positive safe integer',
150
+ 'GOAL_TOOL_INVALID_UPDATE',
151
+ )
152
+ }
153
+ return { id: GoalId(goalId), revision }
154
+ }
155
+
156
+ /** Stable compact model result; activation is an observation, not replay state. */
157
+ function goalValue(goal: GoalView | undefined): GoalToolValue {
158
+ if (goal === undefined) return { goal: null }
159
+ return {
160
+ goal: {
161
+ id: goal.id,
162
+ revision: goal.revision,
163
+ objective: goal.objective,
164
+ phase: goal.phase,
165
+ roundsStarted: goal.roundsStarted,
166
+ maxGoalRounds: goal.maxGoalRounds,
167
+ ...goal.blockedReason === undefined ? {} : {
168
+ blockedReason: { code: goal.blockedReason.code, message: goal.blockedReason.message },
169
+ },
170
+ },
171
+ activation: goal.activation,
172
+ }
173
+ }
174
+
175
+ /** Reusable canonical output declaration for all three goal controls. */
176
+ const GOAL_OUTPUT = {
177
+ schema: GOAL_VALUE_SCHEMA,
178
+ render: (_args: unknown, value: GoalToolValue) => [{ type: 'text' as const, text: JSON.stringify(value) }],
179
+ }
180
+
181
+ /** Generic, args-only pending presentation shared by the goal tools. */
182
+ function present(title: string, kind: 'read' | 'other', rawInput?: unknown): GenericCallView {
183
+ return { card: 'generic', title, kind, ...rawInput === undefined ? {} : { rawInput } }
184
+ }
185
+
186
+ /** Register the three Codex-shaped goal tools and their shared policy section. */
187
+ export function apply(ctx: Context, config: Config): void {
188
+ const resolved = resolveConfig(config)
189
+ ctx.systemPrompt.section({
190
+ name: 'tool:goal',
191
+ order: ctx.systemPrompt.getSectionOrder('TOOL_GOAL'),
192
+ text: guidance(resolved.blockedAfterConsecutiveRounds),
193
+ })
194
+
195
+ ctx.tools.register(defineTool({
196
+ name: 'get_goal',
197
+ description: GET_DESCRIPTION,
198
+ parameters: {},
199
+ output: GOAL_OUTPUT,
200
+ execute(_args, exec) {
201
+ const execution = goalToolExecution(ctx, exec)
202
+ return Promise.resolve(goalValue(ctx.goals.get(execution.agent)))
203
+ },
204
+ presentCall: () => present('Read current goal', 'read'),
205
+ }))
206
+
207
+ ctx.tools.register(defineTool({
208
+ name: 'create_goal',
209
+ description: CREATE_DESCRIPTION,
210
+ parameters: {
211
+ objective: {
212
+ type: 'string',
213
+ required: true,
214
+ description: 'The concrete completion objective inferred from the direct human request.',
215
+ },
216
+ max_goal_rounds: {
217
+ type: 'number',
218
+ description: 'Optional positive safe-integer limit on automatic continuation rounds.',
219
+ },
220
+ },
221
+ output: GOAL_OUTPUT,
222
+ execute(args, exec) {
223
+ const execution = goalToolExecution(ctx, exec)
224
+ requireDirectHuman(ctx, execution)
225
+ const goal = ctx.goals.create(execution.agent, {
226
+ objective: args.objective,
227
+ ...args.max_goal_rounds === undefined ? {} : { maxGoalRounds: args.max_goal_rounds },
228
+ })
229
+ return Promise.resolve(goalValue(goal))
230
+ },
231
+ presentCall: args => present('Create goal', 'other', args.objective),
232
+ }))
233
+
234
+ ctx.tools.register(defineTool({
235
+ name: 'update_goal',
236
+ description: 'Update the current goal.',
237
+ parameters: {
238
+ goal_id: { type: 'string', required: true, description: 'Exact id returned by get_goal.' },
239
+ revision: { type: 'number', required: true, description: 'Exact positive revision returned by get_goal.' },
240
+ action: {
241
+ type: 'string',
242
+ required: true,
243
+ enum: UPDATE_ACTIONS,
244
+ description: 'edit, pause, and resume require a direct top-level human request. complete and blocked are also allowed '
245
+ + 'during an automatic continuation of this goal; blocked is rejected before the configured minimum round count.',
246
+ },
247
+ objective: { type: 'string', description: 'Replacement objective; valid only with action edit.' },
248
+ max_goal_rounds: { type: 'number', description: 'Replacement cap; valid only with action edit.' },
249
+ blocked_reason: {
250
+ type: 'string',
251
+ description: 'Required only with action blocked: the concrete condition that persisted across rounds and blocks progress.',
252
+ },
253
+ },
254
+ output: GOAL_OUTPUT,
255
+ execute(args, exec) {
256
+ const execution = goalToolExecution(ctx, exec)
257
+ const ref = goalRef(args.goal_id, args.revision)
258
+ if (args.action === 'edit') {
259
+ requireDirectHuman(ctx, execution)
260
+ const goal = ctx.goals.edit(execution.agent, ref, {
261
+ ...hasText(args.objective) ? { objective: args.objective } : {},
262
+ ...hasRoundCap(args.max_goal_rounds) ? { maxGoalRounds: args.max_goal_rounds } : {},
263
+ })
264
+ return Promise.resolve(goalValue(goal))
265
+ }
266
+ if (args.action === 'pause' || args.action === 'resume') {
267
+ requireDirectHuman(ctx, execution)
268
+ const current = ctx.goals.get(execution.agent)
269
+ if (args.action === 'resume' && current?.id === ref.id && current.revision === ref.revision
270
+ && current.phase === 'paused') {
271
+ throw new HarnessError(
272
+ 'the model cannot resume a paused goal; the user must resume it',
273
+ 'GOAL_TOOL_RESUME_PAUSED',
274
+ )
275
+ }
276
+ const goal = args.action === 'pause'
277
+ ? ctx.goals.pause(execution.agent, ref)
278
+ : ctx.goals.resume(execution.agent, ref)
279
+ return Promise.resolve(goalValue(goal))
280
+ }
281
+ const authority = completionAuthority(ctx, execution)
282
+ if (args.action === 'blocked'
283
+ && (args.blocked_reason === undefined || args.blocked_reason.trim().length === 0)) {
284
+ throw new HarnessError('blocked_reason is required with action blocked', 'GOAL_TOOL_INVALID_UPDATE')
285
+ }
286
+ if (args.action === 'blocked' && authority.kind === 'goal-round'
287
+ && authority.goal.roundsStarted < resolved.blockedAfterConsecutiveRounds) {
288
+ throw new HarnessError(
289
+ `blocked requires at least ${resolved.blockedAfterConsecutiveRounds} consecutive goal rounds; `
290
+ + `current round is ${authority.goal.roundsStarted}`,
291
+ 'GOAL_TOOL_BLOCK_THRESHOLD',
292
+ )
293
+ }
294
+ const goal = args.action === 'complete'
295
+ ? ctx.goals.complete(execution.agent, ref)
296
+ : ctx.goals.block(execution.agent, ref, {
297
+ code: 'model-reported',
298
+ message: args.blocked_reason as string,
299
+ })
300
+ if (authority.kind === 'goal-round') {
301
+ exec.deferContext(createUserMessage({
302
+ content: args.action === 'complete'
303
+ ? renderWrapupContext(goal.objective)
304
+ : renderWrapupContext(goal.objective, args.blocked_reason as string),
305
+ source: {
306
+ kind: 'tool-goal',
307
+ form: 'notice',
308
+ summary: boundContextSummary(`${args.action as string}: ${goal.objective}`),
309
+ },
310
+ }))
311
+ }
312
+ return Promise.resolve(goalValue(goal))
313
+ },
314
+ presentCall: args => present(
315
+ `${args.action === 'blocked' ? 'Mark' : args.action.charAt(0).toUpperCase() + args.action.slice(1)} goal`,
316
+ 'other',
317
+ args.action === 'blocked' && hasText(args.blocked_reason)
318
+ ? args.blocked_reason
319
+ : args.action === 'edit' && hasText(args.objective)
320
+ ? args.objective
321
+ : args.action === 'edit' && hasRoundCap(args.max_goal_rounds) ? args.max_goal_rounds : args.goal_id,
322
+ ),
323
+ }))
324
+ }
package/src/wrapup.ts ADDED
@@ -0,0 +1,41 @@
1
+ /** Model-visible wrap-up instruction for a terminal autonomous goal update. */
2
+
3
+ import type { ContentBlock } from '@unieai/rabi-llm'
4
+
5
+ const GROUNDING =
6
+ 'Report only what earlier rounds and tool results in this session actually establish; '
7
+ + 'when a detail is not in the session, say so instead of inventing it. '
8
+
9
+ /**
10
+ * Render the closing-message instruction injected after an autonomous goal
11
+ * round reports `complete` or `blocked`, replacing the former hard turn stop
12
+ * so the model still addresses the user once before the turn ends.
13
+ * @param objective - the terminal goal's objective, echoed for grounding.
14
+ * @param blockedReason - the validated report for `blocked`; omitted for `complete`.
15
+ * @returns a fresh one-block context for `ToolRunContext.deferContext()`.
16
+ */
17
+ export function renderWrapupContext(objective: string, blockedReason?: string): ContentBlock[] {
18
+ const heading = `Objective: ${JSON.stringify(objective)}\n`
19
+ const text = blockedReason === undefined
20
+ ? '<goal_complete>\n'
21
+ + heading
22
+ + 'The goal is marked complete and this autonomous run is ending. Write the closing '
23
+ + 'message to the user now: state the outcome, summarize what was done and how it was '
24
+ + 'verified, and point to the concrete results (files, commits, or other artifacts). '
25
+ + GROUNDING
26
+ + 'Note anything the user should review or do next. Address the user directly. Do not '
27
+ + "call any more tools in this run; further work waits for the user's next instruction.\n"
28
+ + '</goal_complete>'
29
+ : '<goal_blocked>\n'
30
+ + heading
31
+ + `Blocked: ${JSON.stringify(blockedReason)}\n`
32
+ + 'The goal is marked blocked and this autonomous run is ending. Write the closing '
33
+ + 'message to the user now: state what has been completed so far, describe the concrete '
34
+ + 'blocking condition and what you tried, and say exactly what you need from the user to '
35
+ + 'continue. '
36
+ + GROUNDING
37
+ + 'Address the user directly. Do not call any more tools in this run; further work '
38
+ + "waits for the user's next instruction.\n"
39
+ + '</goal_blocked>'
40
+ return [{ type: 'text', text }]
41
+ }