pantheon-opencode 1.7.0 → 2.0.0-beta.2

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.
Files changed (173) hide show
  1. package/AGENTS.global.md +2 -2
  2. package/AGENTS.md +3 -3
  3. package/CHANGELOG.md +85 -59
  4. package/README.md +74 -48
  5. package/README.pt-BR.md +19 -19
  6. package/bin/pantheon-init.mjs +11 -48
  7. package/package.json +9 -13
  8. package/plugin.json +2 -2
  9. package/pyproject.toml +1 -1
  10. package/scripts/build-agents-md.mjs +7 -6
  11. package/scripts/{check-plugin-v2-coverage.mjs → check-plugin-coverage.mjs} +7 -7
  12. package/scripts/{decision-router-v2-budget.mjs → decision-router-budget-gates.mjs} +1 -1
  13. package/scripts/{decision-router-v2-egress.mjs → decision-router-egress.mjs} +1 -1
  14. package/scripts/decision-router.mjs +2 -2
  15. package/scripts/docs-media.mjs +1 -1
  16. package/scripts/doctor.mjs +225 -136
  17. package/scripts/install/behavior-overrides.bundle.mjs +123 -0
  18. package/scripts/install/{v2-capabilities.mjs → capabilities.mjs} +7 -7
  19. package/scripts/install/config-migration.mjs +60 -253
  20. package/scripts/install/file-inventory.mjs +6 -4
  21. package/scripts/install/interactive.mjs +1 -1
  22. package/scripts/install/opencode-state.mjs +13 -12
  23. package/scripts/install/opencode-version.mjs +97 -162
  24. package/scripts/install/opencode.mjs +271 -428
  25. package/scripts/install/plan.mjs +1 -9
  26. package/scripts/install/plugin.mjs +19 -35
  27. package/scripts/install/shared.mjs +40 -1
  28. package/scripts/package-evidence.mjs +1 -4
  29. package/scripts/probe-pantheon-cost.mjs +1 -1
  30. package/scripts/reconcile.mjs +5 -7
  31. package/scripts/release-gates.mjs +22 -61
  32. package/scripts/setup-v2-config.mjs +10 -8
  33. package/scripts/setup.mjs +12 -22
  34. package/scripts/sync-tui.mjs +9 -17
  35. package/scripts/{test-opencode-v2-sandbox.sh → test-opencode-sandbox.sh} +9 -9
  36. package/scripts/update-skills-lock.mjs +24 -12
  37. package/scripts/update.mjs +17 -1
  38. package/scripts/validate-routing.mjs +79 -4
  39. package/scripts/validate-sandbox-install.mjs +3 -3
  40. package/skills-lock.json +25 -8
  41. package/src/agents/zeus.md +1 -0
  42. package/src/pantheon/behavior-overrides.ts +191 -0
  43. package/src/pantheon/{v2-bounded-read.ts → bounded-read.ts} +1 -1
  44. package/src/pantheon/cost-command.ts +1 -1
  45. package/src/pantheon/{v2-decision-contracts.ts → decision-contracts.ts} +3 -3
  46. package/src/pantheon/{v2-decision-points → decision-points}/p1-agent.ts +3 -3
  47. package/src/pantheon/{v2-decision-points → decision-points}/p10-claims.ts +2 -2
  48. package/src/pantheon/{v2-decision-points → decision-points}/p11-catalog.ts +2 -2
  49. package/src/pantheon/{v2-decision-points → decision-points}/p2-skill.ts +3 -3
  50. package/src/pantheon/{v2-decision-points → decision-points}/p3-complexity.ts +6 -6
  51. package/src/pantheon/{v2-decision-points → decision-points}/p4-memory.ts +2 -2
  52. package/src/pantheon/{v2-decision-points → decision-points}/p5-themis-verify.ts +2 -2
  53. package/src/pantheon/{v2-decision-points → decision-points}/p6-council.ts +3 -3
  54. package/src/pantheon/{v2-decision-points → decision-points}/p7-loop.ts +5 -5
  55. package/src/pantheon/{v2-decision-points → decision-points}/p8-guardrail.ts +2 -2
  56. package/src/pantheon/{v2-decision-points → decision-points}/p9-memory-compaction.ts +2 -2
  57. package/src/pantheon/{v2-decision-points.ts → decision-points.ts} +5 -5
  58. package/src/pantheon/{v2-decision-policy.ts → decision-policy.ts} +2 -2
  59. package/src/pantheon/{v2-decision-prompt-surface.ts → decision-prompt-surface.ts} +3 -3
  60. package/src/pantheon/{v2-decision-registry.ts → decision-registry.ts} +10 -13
  61. package/src/pantheon/{v2-decision-resource-ids.ts → decision-resource-ids.ts} +1 -1
  62. package/src/pantheon/{v2-decision-shadow.ts → decision-shadow.ts} +1 -1
  63. package/src/pantheon/{v2-decision-telemetry.ts → decision-telemetry.ts} +1 -1
  64. package/src/pantheon/{v2-execute-after.ts → execute-after.ts} +4 -4
  65. package/src/pantheon/goal-store.ts +7 -0
  66. package/src/pantheon/{v2-hook-engine.ts → hook-engine.ts} +3 -3
  67. package/src/pantheon/jev-decision-tool.ts +3 -3
  68. package/src/pantheon/jev-decisions.ts +12 -6
  69. package/src/pantheon/jev-escalation.ts +6 -6
  70. package/src/pantheon/jev-quality-score.ts +2 -2
  71. package/src/pantheon/jev-rank-verify.ts +2 -2
  72. package/src/pantheon/jev-risk-gate.ts +4 -4
  73. package/src/pantheon/local-decision-agents.ts +1 -1
  74. package/src/pantheon/local-decision-router.ts +1 -1
  75. package/src/pantheon/local-decision-tool.ts +2 -2
  76. package/src/pantheon/local-orchestration.ts +1 -1
  77. package/src/pantheon/model-command.ts +1 -1
  78. package/src/pantheon/{v2-vision.ts → native-vision.ts} +12 -15
  79. package/src/pantheon/pantheon-decision-catalog.ts +12 -0
  80. package/src/pantheon/{v2-shell-hooks.ts → shell-hooks.ts} +4 -4
  81. package/src/pantheon/{v2-tools.ts → tools.ts} +4 -4
  82. package/src/pantheon/{v2-unsupported.d.mts → unsupported.d.mts} +3 -3
  83. package/src/pantheon/{v2-unsupported.mjs → unsupported.mjs} +8 -8
  84. package/src/pantheon/update-notifier.ts +101 -0
  85. package/src/pantheon/vision-local.ts +12 -3
  86. package/src/pantheon/vision.ts +120 -2
  87. package/src/{plugin-v2 → plugin}/index.ts +7 -7
  88. package/src/plugin.ts +2870 -500
  89. package/src/plugins/hook-runner.ts +3 -3
  90. package/src/plugins/tui/dist/server.d.ts +23 -9
  91. package/src/plugins/tui/dist/server.d.ts.map +1 -1
  92. package/src/plugins/tui/dist/server.js +25 -12
  93. package/src/plugins/tui/dist/server.js.map +1 -1
  94. package/src/plugins/tui/dist/tui.d.ts +1023 -494
  95. package/src/plugins/tui/dist/tui.d.ts.map +1 -1
  96. package/src/plugins/tui/dist/tui.js +5612 -2086
  97. package/src/plugins/tui/dist/tui.js.map +1 -1
  98. package/src/plugins/tui/{index-v2.ts → index.ts} +1 -1
  99. package/src/plugins/tui/package-lock.json +2 -42
  100. package/src/plugins/tui/package.json +4 -10
  101. package/src/plugins/tui/src/cost-data.ts +1 -1
  102. package/src/plugins/tui/src/decision-router-state.ts +242 -0
  103. package/src/plugins/tui/src/doctor-state.ts +198 -0
  104. package/src/plugins/tui/src/index.tsx +4222 -2822
  105. package/src/plugins/tui/src/j1-gate-status.ts +85 -0
  106. package/src/plugins/tui/src/pantheon-settings-state.ts +245 -0
  107. package/src/plugins/tui/src/pantheon-settings.tsx +442 -0
  108. package/src/plugins/tui/src/preset-state.ts +143 -0
  109. package/src/plugins/tui/src/server.ts +23 -10
  110. package/src/plugins/tui/src/update-notice.ts +90 -0
  111. package/src/plugins/tui/src/update-status.ts +98 -0
  112. package/src/plugins/tui/tsconfig.typecheck.json +9 -2
  113. package/src/plugins/tui/tsdown.config.ts +3 -5
  114. package/src/plugins/tui/tui.ts +1 -2
  115. package/src/routing.yml +36 -0
  116. package/src/skills/README.md +16 -1
  117. package/src/skills/artifact-management/SKILL.md +10 -67
  118. package/src/skills/artifact-management/references/artifact-templates.md +71 -0
  119. package/src/skills/auto-continue/SKILL.md +10 -0
  120. package/src/skills/code-review-checklist/SKILL.md +11 -44
  121. package/src/skills/code-review-checklist/references/review-checklists.md +54 -0
  122. package/src/skills/instruction-forge/SKILL.md +57 -0
  123. package/src/skills/instruction-forge/references/agents-md-doctrine.md +50 -0
  124. package/src/skills/instruction-forge/references/eval-doctrine.md +37 -0
  125. package/src/skills/instruction-forge/references/skill-doctrine.md +62 -0
  126. package/src/skills/memory-bank/SKILL.md +11 -90
  127. package/src/skills/memory-bank/references/anti-patterns.md +33 -0
  128. package/src/skills/memory-bank/references/product-adoption.md +19 -0
  129. package/src/skills/memory-bank/references/storage-model.md +21 -0
  130. package/src/skills/memory-bank/references/structure-and-frequency.md +44 -0
  131. package/src/skills/reflect/SKILL.md +1 -0
  132. package/src/skills/session-goal/SKILL.md +7 -54
  133. package/src/skills/session-goal/references/goal-format.md +26 -0
  134. package/src/skills/session-goal/references/session-reuse.md +44 -0
  135. package/src/skills/tdd-with-agents/SKILL.md +11 -101
  136. package/src/skills/tdd-with-agents/references/advanced-testing-patterns.md +58 -0
  137. package/src/skills/tdd-with-agents/references/testing-by-layer.md +60 -0
  138. package/src/skills/visual-review-pipeline/SKILL.md +11 -120
  139. package/src/skills/visual-review-pipeline/references/findings-schema.md +49 -0
  140. package/src/skills/visual-review-pipeline/references/workflow-steps.md +111 -0
  141. package/scripts/hooks/log-session-start.sh +0 -48
  142. package/scripts/hooks/validate-post-conditions.sh +0 -21
  143. package/scripts/hooks/validate-talos-scope.sh +0 -50
  144. package/scripts/hooks/validate-tool-safety.sh +0 -49
  145. package/src/pantheon/goal-loop.ts +0 -314
  146. package/src/pantheon/idle-continuation.ts +0 -52
  147. package/src/pantheon/todo-preserve.ts +0 -301
  148. package/src/pantheon/tool-ceiling.ts +0 -159
  149. package/src/pantheon/v2-bridge.ts +0 -153
  150. package/src/plugin-v2.ts +0 -2954
  151. package/src/plugins/pantheon-hooks.ts +0 -1433
  152. package/src/plugins/tui/dist/server-v2.d.ts +0 -30
  153. package/src/plugins/tui/dist/server-v2.d.ts.map +0 -1
  154. package/src/plugins/tui/dist/server-v2.js +0 -33
  155. package/src/plugins/tui/dist/server-v2.js.map +0 -1
  156. package/src/plugins/tui/dist/tui-v2.d.ts +0 -1039
  157. package/src/plugins/tui/dist/tui-v2.d.ts.map +0 -1
  158. package/src/plugins/tui/dist/tui-v2.js +0 -4597
  159. package/src/plugins/tui/dist/tui-v2.js.map +0 -1
  160. package/src/plugins/tui/src/index-v2.tsx +0 -4496
  161. package/src/plugins/tui/src/server-v2.ts +0 -28
  162. package/src/plugins/tui/tui-v2.ts +0 -2
  163. /package/src/pantheon/{v2-decision-budget.ts → decision-budget.ts} +0 -0
  164. /package/src/pantheon/{v2-decision-egress.ts → decision-egress.ts} +0 -0
  165. /package/src/pantheon/{v2-decision-events.ts → decision-events.ts} +0 -0
  166. /package/src/pantheon/{v2-decision-heuristic.ts → decision-heuristic.ts} +0 -0
  167. /package/src/pantheon/{v2-decision-premises.ts → decision-premises.ts} +0 -0
  168. /package/src/pantheon/{v2-decision-rank.ts → decision-rank.ts} +0 -0
  169. /package/src/pantheon/{v2-decision-verify.ts → decision-verify.ts} +0 -0
  170. /package/src/pantheon/{v2-delegation-enforce.ts → delegation-policy.ts} +0 -0
  171. /package/src/pantheon/{v2-model-overrides.ts → model-overrides.ts} +0 -0
  172. /package/src/pantheon/{v2-native-decisions.ts → native-decisions.ts} +0 -0
  173. /package/src/plugins/tui/src/{opencode-v2.d.ts → opencode.d.ts} +0 -0
@@ -1,50 +0,0 @@
1
- #!/usr/bin/env bash
2
- # validate-talos-scope.sh — PreToolUse hook for Talos
3
- # Receives JSON on stdin, enforces Talos boundaries
4
- set -euo pipefail
5
-
6
- # Read JSON input from stdin (Claude Code hook protocol)
7
- INPUT=$(cat)
8
-
9
- # Extract tool info from JSON input
10
- TOOL_NAME=$(echo "$INPUT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('tool_name',''))" 2>/dev/null || echo "")
11
- TOOL_INPUT=$(echo "$INPUT" | python3 -c "import sys,json; d=json.load(sys.stdin); print(json.dumps(d.get('tool_input',{})))" 2>/dev/null || echo "")
12
-
13
- # Only validate for Talos agent
14
- AGENT_NAME=$(echo "$INPUT" | python3 -c "import sys,json; print(json.load(sys.stdin).get('agent_id',''))" 2>/dev/null || echo "")
15
- if [ "$AGENT_NAME" != "talos" ]; then
16
- # Not Talos — allow pass-through
17
- echo "[TALOS SCOPE] Not Talos agent, skipping" >&2
18
- exit 0
19
- fi
20
-
21
- # Get changed files from the tool input
22
- if echo "$TOOL_INPUT" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d.get('command','') or d.get('filePath','') or d.get('file_path',''))" 2>/dev/null | grep -qE '(migration|schema\.sql|alembic|models/.*\.py|auth|security|password|token|secret)'; then
23
- echo "[TALOS SCOPE] ❌ Blocked: Talos cannot modify schema/security files" >&2
24
- exit 2
25
- fi
26
-
27
- # Count files in the edit/write operation
28
- FILE_COUNT=$(echo "$TOOL_INPUT" | python3 -c "
29
- import sys, json
30
- try:
31
- d = json.load(sys.stdin)
32
- # Count unique file paths in the input
33
- files = set()
34
- for key in ['filePath', 'file_path', 'command', 'content']:
35
- if key in d and d[key]:
36
- files.add(str(d[key]))
37
- print(len(files))
38
- except:
39
- print('0')
40
- " 2>/dev/null || echo "0")
41
-
42
- # P0-4: enforce the Talos max-files boundary (default 3, overridable)
43
- TALOS_MAX_FILES="${TALOS_MAX_FILES:-3}"
44
- if [ "$FILE_COUNT" -gt "$TALOS_MAX_FILES" ]; then
45
- echo "[TALOS SCOPE] ❌ Blocked: operation touches $FILE_COUNT files (max $TALOS_MAX_FILES)" >&2
46
- exit 2
47
- fi
48
-
49
- echo "[TALOS SCOPE] ✅ Scope check passed" >&2
50
- exit 0
@@ -1,49 +0,0 @@
1
- #!/usr/bin/env bash
2
- # validate-tool-safety.sh — Pantheon PreToolUse Security Hook
3
- # Blocks destructive commands: rm -rf, DROP TABLE, TRUNCATE, etc.
4
- set -euo pipefail
5
-
6
- BLOCKED_PATTERNS=(
7
- # "rm -rf /" appears mid-JSON in the hook stdin protocol (e.g.
8
- # {"tool_input":{"command":"rm -rf /"}}), so the old `/$` end-of-line
9
- # anchor never matched. Match "/" followed by a JSON delimiter (", },
10
- # comma), whitespace, or end of line — catches bare "rm -rf /" anywhere
11
- # in the payload while keeping "rm -rf /some/path" (safe) unblocked.
12
- "rm\s+-rf\s+/([\"},\t[:space:]]|$)" # rm -rf / (root only)
13
- "rm\s+-rf\s+/\*" # rm -rf /*
14
- "rm\s+-rf\s+~([\",[:space:]]|$)" # rm -rf ~ (home only)
15
- "rm\s+-rf\s+~/" # rm -rf ~/...
16
- "rm\s+-rf\s+\.\.?/" # rm -rf ./ or rm -rf ../
17
- "DROP\s+TABLE"
18
- "DROP\s+DATABASE"
19
- "TRUNCATE\s+TABLE"
20
- "DELETE\s+FROM\s+.*;?\s*$"
21
- # DEAD PATTERN REMOVED: `rm\s+.*\s+--no-preserve-root` — redundant with
22
- # pattern #1 which already blocks `rm -rf /` regardless of flags.
23
- # DEAD PATTERN REMOVED: `:(){ :|:& };:` — fork bomb syntax never appears
24
- # in real tool_input.command payloads (the entire stdin would need to be
25
- # exactly this 13-char token with zero surrounding JSON/context).
26
- ">\s*/dev/\(sd[a-z]\|hd[a-z]\|disk[0-9]*\)"
27
- "dd\s+if=.*of=/dev/"
28
- "mkfs\."
29
- "fdisk\s+/dev/"
30
- )
31
-
32
- INPUT="${1:-${TOOL_INPUT:-}}"
33
- if [[ -z "$INPUT" ]] && [[ ! -t 0 ]]; then
34
- INPUT=$(cat)
35
- fi
36
-
37
- if [[ -z "$INPUT" ]]; then
38
- exit 0
39
- fi
40
-
41
- for pattern in "${BLOCKED_PATTERNS[@]}"; do
42
- if echo "$INPUT" | grep -iqE "$pattern"; then
43
- echo "[SECURITY BLOCKED] Pattern matched: $pattern" >&2
44
- echo "[SECURITY BLOCKED] Destructive command detected and blocked by Pantheon hook." >&2
45
- exit 1
46
- fi
47
- done
48
-
49
- exit 0
@@ -1,314 +0,0 @@
1
- /**
2
- * Goal Loop (Wave 3, PR #46) — when enabled, one active goal per session is
3
- * continued automatically while idle. `pantheon_goal_create` starts a goal;
4
- * `pantheon_goal_update` moves it pending → in_progress → done; while
5
- * active, `GoalLoop.onIdle` re-injects the continuation prompt (objective
6
- * restated from the store) until marked done. Council-approved cut: NO LLM
7
- * completion-audit prompt — the state machine is the source of truth.
8
- *
9
- * Persistence: FILE-based GoalStore (`.pantheon/goals/<sessionID>.json`,
10
- * atomic tmp+rename). The plugin uses hard-coded defaults; no runtime config
11
- * enables the loop in this build. Guards:
12
- * board-running skip, in-flight Set, cooldown, max_continuations cap (25).
13
- * Injectable now() clock. Pure TypeScript — zero runtime deps.
14
- *
15
- * @module goal-loop
16
- */
17
-
18
- import { z } from 'zod'
19
-
20
- import type { BackgroundJobBoard } from './background-job-board.ts'
21
- import { GoalStore } from './goal-store.ts'
22
- import { createPantheonLogger } from './logger.ts'
23
- import { safeSessionPath } from './session-guard.ts'
24
- import type { TodoEnforcerMessage } from './todo-enforcer.ts'
25
- import type { ToolContextLike } from './tool-context.ts'
26
-
27
- // Silence-by-default TUI policy (pantheon-hooks L42-58): warn → hooks.log,
28
- // console echo opt-in via PANTHEON_HOOKS_LOG=1. `deps.logger` stays for tests.
29
- const log = createPantheonLogger({ module: 'pantheon-goal' })
30
-
31
- export type { Goal, GoalStatus } from './goal-store.ts'
32
- export { GoalStore }
33
-
34
- // ─── Constants ─────────────────────────────────────────────────────────
35
-
36
- /** Continuation text injected into idle sessions. `{objective}` is substituted. */
37
- export const GOAL_CONTINUATION_PROMPT = 'Continue goal: {objective}'
38
-
39
- /** Hard-coded runtime defaults; routing.yml is documentation-only. */
40
- export const GOAL_LOOP_DEFAULTS = {
41
- enabled: false,
42
- cooldownMs: 5000,
43
- maxContinuations: 25,
44
- } as const
45
-
46
- // ─── Types ─────────────────────────────────────────────────────────────
47
-
48
- /** Structural client surface — the subset of the SDK the loop uses. */
49
- export interface GoalLoopClient {
50
- session: {
51
- messages(input: { path: { id: string } }): Promise<TodoEnforcerMessage[]>
52
- promptAsync(input: {
53
- path: { id: string }
54
- body: {
55
- agent?: string
56
- model?: { providerID: string; modelID: string }
57
- parts: Array<{ type: 'text'; text: string }>
58
- }
59
- }): Promise<unknown>
60
- }
61
- }
62
-
63
- /** Tunables (all optional — see GOAL_LOOP_DEFAULTS). */
64
- export interface GoalLoopOptions {
65
- enabled?: boolean
66
- /** Minimum gap between continuations (ms). */
67
- cooldownMs?: number
68
- /** Hard cap on continuations per goal — after this the loop halts. */
69
- maxContinuations?: number
70
- /** Injectable clock (testable), defaults to `Date.now`. */
71
- now?: () => number
72
- }
73
-
74
- /** Dependencies threaded to the loop (structural board — list only). */
75
- export interface GoalLoopDeps {
76
- store: GoalStore
77
- client: GoalLoopClient
78
- board: Pick<BackgroundJobBoard, 'list'>
79
- options?: GoalLoopOptions
80
- logger?: { warn: (message: string) => void }
81
- }
82
-
83
- type InheritedContext = {
84
- agent?: string
85
- model?: { providerID: string; modelID: string }
86
- }
87
-
88
- /** Render a tool failure as error text (tools return errors as TEXT). */
89
- function toolFailure(prefix: string, err: unknown): string {
90
- const reason = err instanceof Error ? err.message : String(err)
91
- return `${prefix} failed: ${reason}`
92
- }
93
-
94
- // ─── Args schemas ──────────────────────────────────────────────────────
95
-
96
- const goalCreateArgs = {
97
- objective: z.string().min(1).describe('The objective recorded in this legacy session goal.'),
98
- } satisfies z.ZodRawShape
99
-
100
- const goalUpdateArgs = {
101
- status: z.enum(['pending', 'in_progress', 'done']).optional().describe('New goal status.'),
102
- objective: z.string().min(1).optional().describe('New goal objective.'),
103
- } satisfies z.ZodRawShape
104
-
105
- const goalGetArgs = {} satisfies z.ZodRawShape
106
-
107
- /** One structural goal tool: description + zod args shape + execute (delegation.ts shape). */
108
- export type GoalTool<Args extends z.ZodRawShape> = {
109
- description: string
110
- args: Args
111
- execute(args: z.infer<z.ZodObject<Args>>, ctx: ToolContextLike): Promise<string>
112
- }
113
-
114
- /** The three goal tools. */
115
- export interface GoalToolset {
116
- pantheon_goal_create: GoalTool<typeof goalCreateArgs>
117
- pantheon_goal_update: GoalTool<typeof goalUpdateArgs>
118
- pantheon_goal_get: GoalTool<typeof goalGetArgs>
119
- }
120
-
121
- // ─── GoalLoop ──────────────────────────────────────────────────────────
122
-
123
- /**
124
- * Re-inject a continuation prompt into idle sessions with an active goal.
125
- * Per-session state: last-continuation timestamp (cooldown) and an in-flight
126
- * set (never concurrent). `onIdle` never throws — the event hook can never
127
- * break the session.
128
- */
129
- export class GoalLoop {
130
- private readonly store: GoalStore
131
- private readonly client: GoalLoopClient
132
- private readonly board: Pick<BackgroundJobBoard, 'list'>
133
- private readonly options: Required<GoalLoopOptions>
134
- private readonly warn: (message: string) => void
135
-
136
- private readonly inFlight = new Set<string>()
137
- private readonly lastContinuationAt = new Map<string, number>()
138
-
139
- constructor(deps: GoalLoopDeps) {
140
- this.store = deps.store
141
- this.client = deps.client
142
- this.board = deps.board
143
- const opts = deps.options ?? {}
144
- this.options = {
145
- enabled: opts.enabled ?? GOAL_LOOP_DEFAULTS.enabled,
146
- cooldownMs: opts.cooldownMs ?? GOAL_LOOP_DEFAULTS.cooldownMs,
147
- maxContinuations: opts.maxContinuations ?? GOAL_LOOP_DEFAULTS.maxContinuations,
148
- now: opts.now ?? Date.now,
149
- }
150
- this.warn = deps.logger?.warn ?? ((message: string) => log.warn(message))
151
- }
152
-
153
- /** True when the enabled loop can own idle for this session. */
154
- async hasActiveGoal(sessionID: string): Promise<boolean> {
155
- if (!this.options.enabled) return false
156
- return this.store.hasActive(sessionID)
157
- }
158
-
159
- /** Handle a `session.idle` event for a session with an active goal. Never throws. */
160
- async onIdle(sessionID: string): Promise<void> {
161
- if (!this.options.enabled) return
162
- if (this.inFlight.has(sessionID)) return
163
- this.inFlight.add(sessionID)
164
- try {
165
- await this.handleIdle(sessionID)
166
- } catch (err: unknown) {
167
- const reason = err instanceof Error ? err.message : String(err)
168
- this.warn(`goal continuation failed for session ${sessionID}: ${reason}`)
169
- } finally {
170
- this.inFlight.delete(sessionID)
171
- }
172
- }
173
-
174
- private async handleIdle(sessionID: string): Promise<void> {
175
- const goal = await this.store.load(sessionID)
176
- // DONE (or absent) goal → nothing to continue.
177
- if (goal === undefined || goal.status === 'done') return
178
-
179
- // A session with a running background job is busy — skip.
180
- if (this.board.list(sessionID).some((job) => job.state === 'running')) return
181
-
182
- // Hard cap: stop the loop once the cap is reached.
183
- if (goal.continuationCount >= this.options.maxContinuations) return
184
-
185
- const now = this.options.now()
186
- const last = this.lastContinuationAt.get(sessionID)
187
- if (last !== undefined && now - last < this.options.cooldownMs) return
188
-
189
- // Timestamp BEFORE the call — a failed injection still applies the
190
- // cooldown (no hot retry loop).
191
- this.lastContinuationAt.set(sessionID, now)
192
- const inherited = await this.inheritAgentOrModel(sessionID)
193
- const prompt = GOAL_CONTINUATION_PROMPT.replace('{objective}', goal.objective)
194
- const promptPath = safeSessionPath(sessionID)
195
- if (!promptPath) {
196
- this.warn(`goal continuation skipped: invalid sessionID "${sessionID}"`)
197
- return
198
- }
199
- await this.client.session.promptAsync({
200
- path: promptPath.path,
201
- body: {
202
- ...(inherited.agent !== undefined ? { agent: inherited.agent } : {}),
203
- ...(inherited.model !== undefined ? { model: inherited.model } : {}),
204
- parts: [{ type: 'text', text: prompt }],
205
- },
206
- })
207
- goal.continuationCount += 1
208
- goal.updatedAt = now
209
- await this.store.save(goal)
210
- }
211
-
212
- /**
213
- * Inherit the agent (or model) from the LAST assistant message so the
214
- * continuation runs in the same context as the session's last turn.
215
- */
216
- private async inheritAgentOrModel(sessionID: string): Promise<InheritedContext> {
217
- const path = safeSessionPath(sessionID)
218
- if (!path) {
219
- this.warn(`inherit skipped: invalid sessionID "${sessionID}"`)
220
- return {}
221
- }
222
- const messages = await this.client.session.messages(path)
223
- for (const msg of [...messages].reverse()) {
224
- const info = msg.info
225
- if (info === undefined || info.role !== 'assistant') continue
226
- if (typeof info.agent === 'string' && info.agent !== '') {
227
- return { agent: info.agent }
228
- }
229
- const providerID = info.model?.providerID ?? info.providerID
230
- const modelID = info.model?.modelID ?? info.modelID
231
- if (
232
- typeof providerID === 'string' &&
233
- providerID !== '' &&
234
- typeof modelID === 'string' &&
235
- modelID !== ''
236
- ) {
237
- return { model: { providerID, modelID } }
238
- }
239
- }
240
- return {}
241
- }
242
-
243
- /** Build the three structural goal tools (single active goal per session). */
244
- tools(): GoalToolset {
245
- return {
246
- pantheon_goal_create: {
247
- description:
248
- 'Deprecated legacy V1 tool. Create and store the single active goal for this session. Goals are stored but are not automatically continued in the current build. For durable manual goals, use the Persistence MCP `goal_*` tools available in this branch.',
249
- args: goalCreateArgs,
250
- execute: async (args, ctx) => {
251
- try {
252
- this.store.sanitizeSessionID(ctx.sessionID)
253
- const existing = await this.store.load(ctx.sessionID)
254
- if (existing !== undefined && existing.status !== 'done') {
255
- return `pantheon_goal_create failed: session ${ctx.sessionID} already has an active goal`
256
- }
257
- const now = this.options.now()
258
- await this.store.save({
259
- id: ctx.sessionID,
260
- sessionID: ctx.sessionID,
261
- objective: args.objective,
262
- status: 'pending',
263
- createdAt: now,
264
- updatedAt: now,
265
- continuationCount: 0,
266
- })
267
- return `Goal created (${ctx.sessionID}): ${args.objective}`
268
- } catch (err: unknown) {
269
- return toolFailure('pantheon_goal_create', err)
270
- }
271
- },
272
- },
273
- pantheon_goal_update: {
274
- description:
275
- 'Deprecated legacy V1 tool. Update the stored active goal: set status (pending/in_progress/done) and/or rewrite the objective. Goal records are not automatically continued in the current build. For durable manual goals, use the Persistence MCP `goal_*` tools available in this branch.',
276
- args: goalUpdateArgs,
277
- execute: async (args, ctx) => {
278
- try {
279
- const goal = await this.store.load(ctx.sessionID)
280
- if (goal === undefined) {
281
- return `pantheon_goal_update failed: no active goal for session ${ctx.sessionID}`
282
- }
283
- if (args.status === undefined && args.objective === undefined) {
284
- return 'pantheon_goal_update failed: provide status and/or objective'
285
- }
286
- if (args.objective !== undefined) goal.objective = args.objective
287
- if (args.status !== undefined) goal.status = args.status
288
- goal.updatedAt = this.options.now()
289
- await this.store.save(goal)
290
- return `Goal updated: status=${goal.status}, objective=${goal.objective}`
291
- } catch (err: unknown) {
292
- return toolFailure('pantheon_goal_update', err)
293
- }
294
- },
295
- },
296
- pantheon_goal_get: {
297
- description:
298
- 'Deprecated legacy V1 tool. Return the stored active V1 goal (status, objective, continuation count). Goals are not automatically continued in the current build. For durable manual goals, use the Persistence MCP `goal_*` tools available in this branch.',
299
- args: goalGetArgs,
300
- execute: async (_args, ctx) => {
301
- try {
302
- const goal = await this.store.load(ctx.sessionID)
303
- if (goal === undefined) {
304
- return `No active goal for session ${ctx.sessionID}`
305
- }
306
- return `Goal (${goal.id}): status=${goal.status}, objective=${goal.objective}, continuations=${goal.continuationCount}`
307
- } catch (err: unknown) {
308
- return toolFailure('pantheon_goal_get', err)
309
- }
310
- },
311
- },
312
- }
313
- }
314
- }
@@ -1,52 +0,0 @@
1
- /**
2
- * Idle Continuation Dispatcher (Wave 3, PR #46) — routes `session.idle`
3
- * events to the subsystem that owns the idle.
4
- *
5
- * Priority: an ACTIVE GOAL owns the idle — `GoalLoop.onIdle` continues the
6
- * goal. Without an active goal, the TODO enforcer gets the idle (it
7
- * self-guards on its own enabled flag + guards). Board-child sessions never
8
- * reach the dispatcher — the plugin's event hook owns board transitions and
9
- * only calls the dispatcher for non-board sessions.
10
- *
11
- * Independently testable — the loop and enforcer are structural interfaces;
12
- * the real GoalLoop/TodoEnforcer satisfy them.
13
- *
14
- * Pure TypeScript — zero runtime dependencies.
15
- *
16
- * @module idle-continuation
17
- */
18
-
19
- /** Structural goal-loop surface the dispatcher needs. */
20
- export interface GoalLoopLike {
21
- hasActiveGoal(sessionID: string): Promise<boolean>
22
- onIdle(sessionID: string): Promise<void>
23
- }
24
-
25
- /** Structural todo-enforcer surface the dispatcher needs. */
26
- export interface TodoEnforcerLike {
27
- onIdle(sessionID: string): Promise<void>
28
- }
29
-
30
- /** The dispatcher's onIdle surface (used by the plugin event hook). */
31
- export interface IdleDispatcher {
32
- onIdle(sessionID: string): Promise<void>
33
- }
34
-
35
- /**
36
- * Build the idle router. The plugin event hook calls this only for non-board
37
- * sessions, so board children never arrive here.
38
- */
39
- export function createIdleDispatcher(deps: {
40
- goalLoop: GoalLoopLike
41
- todoEnforcer: TodoEnforcerLike
42
- }): IdleDispatcher {
43
- return {
44
- onIdle: async (sessionID: string): Promise<void> => {
45
- if (await deps.goalLoop.hasActiveGoal(sessionID)) {
46
- await deps.goalLoop.onIdle(sessionID)
47
- return
48
- }
49
- await deps.todoEnforcer.onIdle(sessionID)
50
- },
51
- }
52
- }