@narumitw/pi-goal 0.49.7 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/tools.ts CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  formatStatus,
12
12
  GOAL_BLOCKED_TOOL,
13
13
  GOAL_COMPLETE_TOOL,
14
+ GOAL_WAIT_TOOL,
14
15
  type GoalRuntime,
15
16
  goalIdRejectionReason,
16
17
  isContradictoryCompletionSummary,
@@ -19,6 +20,13 @@ import {
19
20
  transitionGoal,
20
21
  truncateNotification,
21
22
  } from "./runtime.js";
23
+ import {
24
+ createGoalWait,
25
+ MAX_GOAL_WAIT_DELAY_MS,
26
+ MAX_GOAL_WAIT_REASON_LENGTH,
27
+ MIN_GOAL_WAIT_DELAY_MS,
28
+ resolveGoalWaitDelay,
29
+ } from "./wait.js";
22
30
 
23
31
  interface GoalCompleteDetails {
24
32
  goal: string;
@@ -34,6 +42,15 @@ interface GoalBlockedDetails {
34
42
  repeated_turns: number;
35
43
  }
36
44
 
45
+ interface GoalWaitDetails {
46
+ goal: string;
47
+ goal_id: string;
48
+ reason: string;
49
+ requested_resume_after_ms?: number;
50
+ resume_after_ms?: number;
51
+ resume_at?: number;
52
+ }
53
+
37
54
  const MAX_GOAL_TEXT_LENGTH = 4_000;
38
55
  const MAX_COMPLETION_SUMMARY_LENGTH = 4_000;
39
56
  const MAX_BLOCKER_REASON_LENGTH = 1_000;
@@ -153,6 +170,7 @@ export function registerGoalTools(pi: ExtensionAPI, runtime: GoalRuntime) {
153
170
  };
154
171
  }
155
172
 
173
+ runtime.clearGoalWaitTimer();
156
174
  runtime.activeGoal = transitionGoal(completedGoal, "complete");
157
175
  runtime.setCompletionSummary(runtime.activeGoal.id, summary);
158
176
  runtime.recordGoalUsage(runtime.activeGoal, ctx);
@@ -298,8 +316,104 @@ export function registerGoalTools(pi: ExtensionAPI, runtime: GoalRuntime) {
298
316
  },
299
317
  });
300
318
 
319
+ const goalWaitTool = defineTool({
320
+ name: GOAL_WAIT_TOOL,
321
+ label: "Goal Wait",
322
+ description: `Keep the active /goal alive but quiet while an external event is expected. Call goal_wait alone after arranging a wake message, or provide resume_after_ms as a safety deadline. Requests below ${MIN_GOAL_WAIT_DELAY_MS}ms are clamped to ${MIN_GOAL_WAIT_DELAY_MS}ms. Do not use it for ordinary unfinished work.`,
323
+ promptSnippet:
324
+ "Wait quietly for an external event without stopping the active /goal or starting automatic continuations",
325
+ promptGuidelines: [
326
+ "Use goal_wait only when progress depends on a later non-goal message, or when resume_after_ms provides a bounded safety wake-up rather than a polling interval.",
327
+ `Prefer longer waits measured in minutes to avoid busy polling; goal_wait requests below ${MIN_GOAL_WAIT_DELAY_MS}ms are clamped to ${MIN_GOAL_WAIT_DELAY_MS}ms.`,
328
+ "Arrange the external monitor or wake source before calling goal_wait, and call goal_wait alone because parallel sibling tools can prevent immediate turn termination.",
329
+ "Pass the exact current goal_id so a stale turn cannot put a replacement goal into waiting.",
330
+ "Do not use goal_blocked for a recoverable external wait that can be resumed by a message or deadline.",
331
+ ],
332
+ parameters: Type.Object({
333
+ goal_id: Type.String({
334
+ minLength: 1,
335
+ maxLength: MAX_GOAL_ID_LENGTH,
336
+ description: "The exact goal_id shown in the current active /goal prompt.",
337
+ }),
338
+ reason: Type.String({
339
+ minLength: 1,
340
+ maxLength: MAX_GOAL_WAIT_REASON_LENGTH,
341
+ description: "Why the goal is waiting and which external event should wake it.",
342
+ }),
343
+ resume_after_ms: Type.Optional(
344
+ Type.Integer({
345
+ minimum: 1,
346
+ maximum: MAX_GOAL_WAIT_DELAY_MS,
347
+ description: `Optional safety deadline in milliseconds that requests one continuation if no wake message arrives. Values below ${MIN_GOAL_WAIT_DELAY_MS} are accepted but clamped to ${MIN_GOAL_WAIT_DELAY_MS}.`,
348
+ }),
349
+ ),
350
+ }),
351
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
352
+ const activeGoal = runtime.activeGoal;
353
+ const goal = activeGoal?.text ?? "unknown goal";
354
+ const requestedGoalId = typeof params.goal_id === "string" ? params.goal_id.trim() : "";
355
+ const reason = typeof params.reason === "string" ? params.reason.trim() : "";
356
+ const resumeAfterMs =
357
+ typeof params.resume_after_ms === "number" ? params.resume_after_ms : undefined;
358
+ const reject = (rejectionReason: string) => {
359
+ const rejection = `goal_wait rejected: ${rejectionReason}.`;
360
+ notifyTerminal(ctx.ui, rejection, "warning");
361
+ return {
362
+ content: toolContent(rejection),
363
+ details: waitDetails(goal, requestedGoalId, reason, resumeAfterMs),
364
+ };
365
+ };
366
+
367
+ if (!activeGoal) return reject("no active goal");
368
+ if (!runtime.canRecordGoalUsage()) {
369
+ return reject("current run does not own the active goal");
370
+ }
371
+ if (runtime.pendingQueueAction) return reject("a goal queue transition is pending");
372
+ const staleGoalRejection = goalIdRejectionReason(activeGoal, requestedGoalId);
373
+ if (staleGoalRejection) return reject(staleGoalRejection);
374
+ if (activeGoal.status !== "active") {
375
+ return reject(`goal is ${activeGoal.status}, not active`);
376
+ }
377
+ if (activeGoal.waiting) return reject("goal is already waiting");
378
+ if (!reason) return reject("reason is empty");
379
+ if (reason.length > MAX_GOAL_WAIT_REASON_LENGTH) return reject("reason is too long");
380
+ if (
381
+ resumeAfterMs !== undefined &&
382
+ (!Number.isInteger(resumeAfterMs) ||
383
+ resumeAfterMs < 1 ||
384
+ resumeAfterMs > MAX_GOAL_WAIT_DELAY_MS)
385
+ ) {
386
+ return reject(`resume_after_ms must be a whole number from 1 to ${MAX_GOAL_WAIT_DELAY_MS}`);
387
+ }
388
+
389
+ const { requestedMs, effectiveMs } = resolveGoalWaitDelay(resumeAfterMs);
390
+ const waiting = createGoalWait(reason, resumeAfterMs);
391
+ const waitingGoal = runtime.enterGoalWait(ctx, activeGoal.id, waiting);
392
+ if (!waitingGoal) return reject("active goal changed before waiting transition");
393
+ const clamped = requestedMs !== undefined && effectiveMs !== requestedMs;
394
+ notifyTerminal(ctx.ui, `Goal waiting: ${truncateNotification(reason)}`, "info");
395
+ return {
396
+ content: toolContent(
397
+ clamped
398
+ ? `Goal waiting: ${reason}\nRequested resume_after_ms ${requestedMs} was clamped to ${effectiveMs}.`
399
+ : `Goal waiting: ${reason}`,
400
+ ),
401
+ details: waitDetails(
402
+ goal,
403
+ requestedGoalId,
404
+ reason,
405
+ effectiveMs,
406
+ waiting.resumeAt,
407
+ clamped ? requestedMs : undefined,
408
+ ),
409
+ terminate: true,
410
+ };
411
+ },
412
+ });
413
+
301
414
  pi.registerTool(goalCompleteTool);
302
415
  pi.registerTool(goalBlockedTool);
416
+ pi.registerTool(goalWaitTool);
303
417
  }
304
418
 
305
419
  function toolContent(text: string) {
@@ -338,6 +452,26 @@ function blockerDetails(
338
452
  };
339
453
  }
340
454
 
455
+ function waitDetails(
456
+ goal: string,
457
+ goalId: string,
458
+ reason: string,
459
+ resumeAfterMs: number | undefined,
460
+ resumeAt?: number,
461
+ requestedResumeAfterMs?: number,
462
+ ): GoalWaitDetails {
463
+ return {
464
+ goal: goal.slice(0, MAX_GOAL_TEXT_LENGTH),
465
+ goal_id: goalId.slice(0, MAX_GOAL_ID_LENGTH),
466
+ reason: reason.slice(0, MAX_GOAL_WAIT_REASON_LENGTH),
467
+ ...(requestedResumeAfterMs === undefined
468
+ ? {}
469
+ : { requested_resume_after_ms: requestedResumeAfterMs }),
470
+ ...(resumeAfterMs === undefined ? {} : { resume_after_ms: resumeAfterMs }),
471
+ ...(resumeAt === undefined ? {} : { resume_at: resumeAt }),
472
+ };
473
+ }
474
+
341
475
  function hasPendingSkipForGoal(runtime: GoalRuntime, goalId: string) {
342
476
  return (
343
477
  runtime.pendingQueueAction?.kind === "advance" &&
package/src/wait.ts ADDED
@@ -0,0 +1,75 @@
1
+ export interface GoalWait {
2
+ reason: string;
3
+ resumeAt?: number;
4
+ }
5
+
6
+ export const MAX_GOAL_WAIT_REASON_LENGTH = 1_000;
7
+ export const MIN_GOAL_WAIT_DELAY_MS = 10_000;
8
+ export const MAX_GOAL_WAIT_DELAY_MS = 2_147_483_647;
9
+ const MAX_DATE_TIMESTAMP_MS = 8_640_000_000_000_000;
10
+
11
+ export function resolveGoalWaitDelay(resumeAfterMs: number | undefined): {
12
+ requestedMs?: number;
13
+ effectiveMs?: number;
14
+ } {
15
+ if (resumeAfterMs === undefined) return {};
16
+ return {
17
+ requestedMs: resumeAfterMs,
18
+ effectiveMs: Math.max(MIN_GOAL_WAIT_DELAY_MS, resumeAfterMs),
19
+ };
20
+ }
21
+
22
+ export function createGoalWait(
23
+ reason: string,
24
+ resumeAfterMs: number | undefined,
25
+ now = Date.now(),
26
+ ): GoalWait {
27
+ const { effectiveMs } = resolveGoalWaitDelay(resumeAfterMs);
28
+ return {
29
+ reason,
30
+ ...(effectiveMs === undefined ? {} : { resumeAt: now + effectiveMs }),
31
+ };
32
+ }
33
+
34
+ export function normalizeGoalWait(value: unknown): GoalWait | undefined {
35
+ if (!isRecord(value)) return undefined;
36
+ const reason = typeof value.reason === "string" ? value.reason.trim() : "";
37
+ if (!reason || reason.length > MAX_GOAL_WAIT_REASON_LENGTH) return undefined;
38
+ if (!Object.hasOwn(value, "resumeAt")) return { reason };
39
+ if (
40
+ typeof value.resumeAt !== "number" ||
41
+ !Number.isSafeInteger(value.resumeAt) ||
42
+ value.resumeAt < 0 ||
43
+ value.resumeAt > MAX_DATE_TIMESTAMP_MS
44
+ ) {
45
+ return undefined;
46
+ }
47
+ return { reason, resumeAt: value.resumeAt };
48
+ }
49
+
50
+ export class GoalWaitTimer {
51
+ private generation = 0;
52
+ private timer?: NodeJS.Timeout;
53
+
54
+ clear() {
55
+ this.generation += 1;
56
+ if (!this.timer) return;
57
+ clearTimeout(this.timer);
58
+ this.timer = undefined;
59
+ }
60
+
61
+ schedule(resumeAt: number, onDue: () => void) {
62
+ this.clear();
63
+ const generation = this.generation;
64
+ const delay = Math.max(0, Math.min(MAX_GOAL_WAIT_DELAY_MS, resumeAt - Date.now()));
65
+ this.timer = setTimeout(() => {
66
+ if (generation !== this.generation) return;
67
+ this.timer = undefined;
68
+ onDue();
69
+ }, delay);
70
+ }
71
+ }
72
+
73
+ function isRecord(value: unknown): value is Record<string, unknown> {
74
+ return typeof value === "object" && value !== null && !Array.isArray(value);
75
+ }