pantheon-opencode 1.6.0-beta.15 → 1.6.0-beta.17

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 (39) hide show
  1. package/CHANGELOG.md +33 -3
  2. package/README.md +120 -26
  3. package/README.pt-BR.md +14 -14
  4. package/package.json +3 -3
  5. package/plugin.json +1 -1
  6. package/pyproject.toml +1 -1
  7. package/scripts/_pantheon_paths.py +24 -0
  8. package/scripts/doctor.mjs +7 -2
  9. package/scripts/install-mcp.mjs +1 -1
  10. package/scripts/mcp_persistence.py +1260 -1017
  11. package/scripts/memory_mcp.py +12 -843
  12. package/scripts/test-opencode-v2-sandbox.sh +2 -115
  13. package/skills-lock.json +3 -3
  14. package/src/agents/apollo.md +1 -2
  15. package/src/agents/athena.md +1 -2
  16. package/src/agents/gaia.md +0 -1
  17. package/src/agents/hermes.md +1 -1
  18. package/src/agents/iris.md +0 -1
  19. package/src/agents/mnemosyne.md +3 -2
  20. package/src/agents/zeus.md +1 -1
  21. package/src/mcp/_pantheon_paths.py +24 -0
  22. package/src/mcp/mcp_codemap_module.py +86 -18
  23. package/src/mcp/mcp_persistence.py +1260 -1017
  24. package/src/mcp/memory_mcp.py +101 -57
  25. package/src/pantheon/goal-loop.ts +11 -8
  26. package/src/pantheon/task-result-guard.ts +38 -2
  27. package/src/pantheon/v2-execute-after.ts +117 -20
  28. package/src/pantheon/v2-tools.ts +10 -1
  29. package/src/plugin-v2.ts +6 -4
  30. package/src/plugin.ts +3 -2
  31. package/src/plugins/tui/dist/tui-v2.js +2 -2
  32. package/src/plugins/tui/dist/tui.js +1 -1
  33. package/src/plugins/tui/package-lock.json +2 -2
  34. package/src/plugins/tui/package.json +1 -1
  35. package/src/routing.yml +4 -4
  36. package/src/skills/codemap/SKILL.md +1 -1
  37. package/src/skills/memory-bank/SKILL.md +17 -13
  38. package/src/skills/session-goal/SKILL.md +12 -22
  39. package/scripts/probe-context-rehydrate.mjs +0 -263
@@ -17,6 +17,9 @@ Tools:
17
17
  memory_forget — Delete by ID or key
18
18
  memory_list — Chronological listing
19
19
  memory_stats — DB statistics
20
+ code_index — Index code entities
21
+ code_query — Search indexed code entities
22
+ code_neighbors — Find related code entities
20
23
 
21
24
  Usage:
22
25
  python scripts/memory_mcp.py
@@ -27,13 +30,14 @@ from __future__ import annotations
27
30
  import contextlib
28
31
  import functools
29
32
  import json
33
+ import logging
30
34
  import sqlite3
31
35
  import time
32
36
  from datetime import UTC, datetime
33
37
  from pathlib import Path
34
- from typing import Annotated, Any
38
+ from typing import Annotated, Any, Literal, TypedDict
35
39
 
36
- from _pantheon_paths import pantheon_home
40
+ from _pantheon_paths import pantheon_home, trusted_project_root
37
41
  from fastmcp import FastMCP
38
42
  from pydantic import BeforeValidator, Field
39
43
 
@@ -119,6 +123,20 @@ mcp = FastMCP(
119
123
  "index, so a query must share a token with the stored text to match."
120
124
  ),
121
125
  )
126
+ _LOGGER = logging.getLogger(__name__)
127
+
128
+
129
+ class MemorySearchErrorDetail(TypedDict):
130
+ """Safe, typed error detail returned when a memory search cannot run."""
131
+
132
+ type: Literal["DatabaseUnavailableError", "MemorySearchError"]
133
+ message: str
134
+
135
+
136
+ class MemorySearchError(TypedDict):
137
+ """Structured error envelope for ``memory_search``."""
138
+
139
+ error: MemorySearchErrorDetail
122
140
 
123
141
 
124
142
  # ── Database ──────────────────────────────────────────────────────────────────
@@ -304,22 +322,21 @@ def _build_fts_query(query: str) -> str:
304
322
 
305
323
  Tokens surviving both filters are still prefix-matched, so a query term
306
324
  retrieves documents containing a longer word that starts with it. If every
307
- token is a stopword the unfiltered tokens are matched exactly, so an
308
- all-stopword query degrades to a literal lookup rather than to no results.
325
+ token is a stopword, the query is empty and returns no results.
309
326
 
310
327
  Args:
311
328
  query: Raw, user-supplied search text.
312
329
 
313
330
  Returns:
314
- An FTS5 expression (terms joined with ``OR``), or ``""`` for an empty
315
- query.
331
+ An FTS5 expression (terms joined with ``OR``), or ``""`` when there are
332
+ no searchable terms.
316
333
  """
317
334
  words = [word for word in query.split() if word]
318
335
  if not words:
319
336
  return ""
320
337
  content = [word for word in words if word.lower() not in _STOPWORDS]
321
338
  if not content:
322
- content = words
339
+ return ""
323
340
  return " OR ".join(
324
341
  f'"{word}"*' if len(word) >= _MIN_PREFIX_LEN else f'"{word}"'
325
342
  for word in content
@@ -376,20 +393,17 @@ def _fetch_created_at_map(db: sqlite3.Connection, ids: list[int]) -> dict[int, s
376
393
  ids: Memory row IDs to look up.
377
394
 
378
395
  Returns:
379
- Mapping of id -> created_at ISO string. Empty on failure.
396
+ Mapping of id -> created_at ISO string.
380
397
  """
381
398
  created_at_map: dict[int, str] = {}
382
399
  if not ids:
383
400
  return created_at_map
384
- try:
385
- placeholders = ",".join("?" * len(ids))
386
- rows = db.execute(
387
- f"SELECT id, created_at FROM memories WHERE id IN ({placeholders})",
388
- ids,
389
- ).fetchall()
390
- created_at_map = {r["id"]: r["created_at"] for r in rows}
391
- except Exception:
392
- created_at_map = {}
401
+ placeholders = ",".join("?" * len(ids))
402
+ rows = db.execute(
403
+ f"SELECT id, created_at FROM memories WHERE id IN ({placeholders})",
404
+ ids,
405
+ ).fetchall()
406
+ created_at_map = {r["id"]: r["created_at"] for r in rows}
393
407
  return created_at_map
394
408
 
395
409
 
@@ -584,14 +598,15 @@ def memory_store(
584
598
  "prefix-matched, so a query must share a token with the stored text — "
585
599
  "there is no semantic/vector retrieval. Optional decay_days applies a "
586
600
  "freshness half-life (2^(-days/decay_days)) so recent entries rank "
587
- "higher; default None keeps the raw BM25 order.",
601
+ "higher; default None keeps the raw BM25 order. An empty result means "
602
+ "nothing matched; an error means the memory store could not be read.",
588
603
  )
589
604
  def memory_search(
590
605
  query: str,
591
606
  namespace: str | None = None,
592
607
  top_k: int = 5,
593
608
  decay_days: float | None = None,
594
- ) -> list[dict[str, Any]]:
609
+ ) -> list[dict[str, Any]] | MemorySearchError:
595
610
  """Search memories with FTS5 BM25.
596
611
 
597
612
  Args:
@@ -604,17 +619,31 @@ def memory_search(
604
619
 
605
620
  Returns:
606
621
  List of memory entries with a ``score`` (BM25, higher is better,
607
- freshness-decayed when ``decay_days`` is set) and parsed metadata.
622
+ freshness-decayed when ``decay_days`` is set) and parsed metadata, or a
623
+ typed error when the memory store cannot be read.
608
624
  """
609
625
  if not query or not query.strip():
610
626
  return []
611
627
 
612
- top_k = max(1, min(50, int(top_k)))
613
- db = _get_conn()
614
628
  fts_query = _build_fts_query(query)
615
629
  if not fts_query:
616
630
  return []
617
631
 
632
+ top_k = max(1, min(50, int(top_k)))
633
+ try:
634
+ db = _get_conn()
635
+ except Exception:
636
+ _LOGGER.warning("memory_search failed: memory database could not be opened")
637
+ return {
638
+ "error": {
639
+ "type": "DatabaseUnavailableError",
640
+ "message": (
641
+ "Memory database could not be opened. Check its configured "
642
+ "location and permissions, then retry."
643
+ ),
644
+ }
645
+ }
646
+
618
647
  try:
619
648
  params: list[Any] = [fts_query]
620
649
  namespace_clause = ""
@@ -634,46 +663,51 @@ def memory_search(
634
663
  params,
635
664
  ).fetchall()
636
665
  hits = [(r["rowid"], r["bm25"]) for r in rows]
637
- except Exception:
638
- return []
639
-
640
- if not hits:
641
- return []
642
-
643
- candidate_ids = [doc_id for doc_id, _ in hits]
644
- created_at_map = (
645
- _fetch_created_at_map(db, candidate_ids)
646
- if decay_days is not None and decay_days > 0
647
- else {}
648
- )
649
- ranked = _score_hits(hits, top_k, created_at_map, decay_days)
666
+ if not hits:
667
+ return []
650
668
 
651
- results: list[dict[str, Any]] = []
652
- if ranked:
653
- # 5. Fetch full entries
654
- id_list = [doc_id for doc_id, _ in ranked]
655
- score_map = {doc_id: score for doc_id, score in ranked}
669
+ candidate_ids = [doc_id for doc_id, _ in hits]
670
+ created_at_map = (
671
+ _fetch_created_at_map(db, candidate_ids)
672
+ if decay_days is not None and decay_days > 0
673
+ else {}
674
+ )
675
+ ranked = _score_hits(hits, top_k, created_at_map, decay_days)
656
676
 
657
- try:
677
+ results: list[dict[str, Any]] = []
678
+ if ranked:
679
+ # 5. Fetch full entries
680
+ id_list = [doc_id for doc_id, _ in ranked]
681
+ score_map = {doc_id: score for doc_id, score in ranked}
658
682
  placeholders = ",".join("?" * len(id_list))
659
683
  rows = db.execute(
660
684
  f"""SELECT id, namespace, key, value, metadata, created_at
661
685
  FROM memories WHERE id IN ({placeholders})""",
662
686
  id_list,
663
687
  ).fetchall()
664
- except Exception:
665
- return []
666
688
 
667
- # Preserve ranking order
668
- row_map = {r["id"]: r for r in rows}
669
- for doc_id in id_list:
670
- row = row_map.get(doc_id)
671
- if row is None:
672
- continue
673
- entry = dict(row)
674
- entry = _parse_metadata(entry)
675
- entry["score"] = round(score_map.get(doc_id, 0.0), 4)
676
- results.append(entry)
689
+ # Preserve ranking order
690
+ row_map = {r["id"]: r for r in rows}
691
+ for doc_id in id_list:
692
+ row = row_map.get(doc_id)
693
+ if row is None:
694
+ continue
695
+ entry = dict(row)
696
+ entry = _parse_metadata(entry)
697
+ entry["score"] = round(score_map.get(doc_id, 0.0), 4)
698
+ results.append(entry)
699
+ except Exception:
700
+ _LOGGER.warning("memory_search failed: FTS or stored-entry read failed")
701
+ return {
702
+ "error": {
703
+ "type": "MemorySearchError",
704
+ "message": (
705
+ "Memory search failed while reading the SQLite FTS index "
706
+ "or stored entries. Check the memory store and FTS index, "
707
+ "then retry."
708
+ ),
709
+ }
710
+ }
677
711
 
678
712
  return results
679
713
 
@@ -870,8 +904,8 @@ def memory_stats() -> dict[str, Any]:
870
904
 
871
905
 
872
906
  @mcp.tool(
873
- description="Index codebase files incrementally (hash-based skip). "
874
- "Parses Python (ast) and TypeScript (regex) to build knowledge graph.",
907
+ description="Index supported files inside the host-bound project root only. "
908
+ "Parses Python (ast) and TypeScript (regex) into the shared Memory DB.",
875
909
  )
876
910
  def code_index(
877
911
  path: str | None = None,
@@ -880,7 +914,7 @@ def code_index(
880
914
  """Index code files into knowledge graph.
881
915
 
882
916
  Args:
883
- path: File or directory to index; None = cwd.
917
+ path: File or directory within the trusted project root; None = project root.
884
918
  force: Re-parse even if hash unchanged.
885
919
 
886
920
  Returns:
@@ -888,8 +922,18 @@ def code_index(
888
922
  """
889
923
  if _codemap is None:
890
924
  return {"error": "codemap module not available"}
925
+ project_root = trusted_project_root()
926
+ if project_root is None:
927
+ return {
928
+ "error": (
929
+ "Trusted project root unavailable; code_index requires the MCP "
930
+ "host to set PANTHEON_PROJECT to an absolute project directory"
931
+ ),
932
+ "indexed": 0,
933
+ "skipped": 0,
934
+ }
891
935
  db = _get_conn()
892
- return _codemap.code_index(db, path, force)
936
+ return _codemap.code_index(db, path, force, project_root=project_root)
893
937
 
894
938
 
895
939
  @mcp.tool(
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Full-auto Goal Loop (Wave 3, PR #46) — one active goal per session,
2
+ * Goal Loop (Wave 3, PR #46) — when enabled, one active goal per session is
3
3
  * continued automatically while idle. `pantheon_goal_create` starts a goal;
4
4
  * `pantheon_goal_update` moves it pending → in_progress → done; while
5
5
  * active, `GoalLoop.onIdle` re-injects the continuation prompt (objective
@@ -7,7 +7,8 @@
7
7
  * completion-audit prompt — the state machine is the source of truth.
8
8
  *
9
9
  * Persistence: FILE-based GoalStore (`.pantheon/goals/<sessionID>.json`,
10
- * atomic tmp+rename). Opt-in `full_auto.enabled: false` default. Guards:
10
+ * atomic tmp+rename). The plugin uses hard-coded defaults; no runtime config
11
+ * enables the loop in this build. Guards:
11
12
  * board-running skip, in-flight Set, cooldown, max_continuations cap (25).
12
13
  * Injectable now() clock. Pure TypeScript — zero runtime deps.
13
14
  *
@@ -35,7 +36,7 @@ export { GoalStore }
35
36
  /** Continuation text injected into idle sessions. `{objective}` is substituted. */
36
37
  export const GOAL_CONTINUATION_PROMPT = 'Continue goal: {objective}'
37
38
 
38
- /** Defaults matching routing.yml `full_auto`. */
39
+ /** Hard-coded runtime defaults; routing.yml is documentation-only. */
39
40
  export const GOAL_LOOP_DEFAULTS = {
40
41
  enabled: false,
41
42
  cooldownMs: 5000,
@@ -93,7 +94,7 @@ function toolFailure(prefix: string, err: unknown): string {
93
94
  // ─── Args schemas ──────────────────────────────────────────────────────
94
95
 
95
96
  const goalCreateArgs = {
96
- objective: z.string().min(1).describe('The goal objective the session keeps working toward.'),
97
+ objective: z.string().min(1).describe('The objective recorded in this legacy session goal.'),
97
98
  } satisfies z.ZodRawShape
98
99
 
99
100
  const goalUpdateArgs = {
@@ -149,8 +150,9 @@ export class GoalLoop {
149
150
  this.warn = deps.logger?.warn ?? ((message: string) => log.warn(message))
150
151
  }
151
152
 
152
- /** True when the session has an active (non-done) goal. Used by the idle dispatcher. */
153
+ /** True when the enabled loop can own idle for this session. */
153
154
  async hasActiveGoal(sessionID: string): Promise<boolean> {
155
+ if (!this.options.enabled) return false
154
156
  return this.store.hasActive(sessionID)
155
157
  }
156
158
 
@@ -243,7 +245,7 @@ export class GoalLoop {
243
245
  return {
244
246
  pantheon_goal_create: {
245
247
  description:
246
- 'Create the single active goal for this session. The goal loop then continues the session automatically on idle until the goal is marked done.',
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.',
247
249
  args: goalCreateArgs,
248
250
  execute: async (args, ctx) => {
249
251
  try {
@@ -270,7 +272,7 @@ export class GoalLoop {
270
272
  },
271
273
  pantheon_goal_update: {
272
274
  description:
273
- 'Update the active goal: set status (pending/in_progress/done) and/or rewrite the objective. Setting status to done stops all further continuations.',
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.',
274
276
  args: goalUpdateArgs,
275
277
  execute: async (args, ctx) => {
276
278
  try {
@@ -292,7 +294,8 @@ export class GoalLoop {
292
294
  },
293
295
  },
294
296
  pantheon_goal_get: {
295
- description: 'Return the active goal for this session (status, objective, continuations).',
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.',
296
299
  args: goalGetArgs,
297
300
  execute: async (_args, ctx) => {
298
301
  try {
@@ -66,15 +66,51 @@ export const EMPTY_TASK_ERROR =
66
66
  'or the child session crashed before producing any response. ' +
67
67
  'Consider splitting the work into a smaller task. No retry is automatic; investigate before retrying manually.'
68
68
 
69
+ /**
70
+ * The placeholder text the HOST substitutes into a child-dispatch tool result
71
+ * when the child produced no assistant text.
72
+ *
73
+ * Field-measured on an OpenCode V2 host: the host binary contains the literal
74
+ * `Subagent completed without a text response.` and injects it into the tool
75
+ * result, so the parent sees a success-looking string instead of silence.
76
+ *
77
+ * This MUST be re-confirmed against each host build — if a host changes the
78
+ * wording, this branch silently stops firing again.
79
+ */
80
+ export const HOST_EMPTY_RESULT_TEXT = 'Subagent completed without a text response.'
81
+
82
+ /**
83
+ * Whether a tool label is a child dispatch the guard must inspect.
84
+ *
85
+ * The accepted labels are `task` and `subagent`. Exported so the V2 adapter's
86
+ * pre-guard early return uses the SAME set: a label the guard handles must
87
+ * never be dropped before the guard sees it.
88
+ *
89
+ * @param tool - the tool label reported by the host
90
+ * @returns `true` for `task` and `subagent`
91
+ */
92
+ export function isChildDispatchTool(tool: string): boolean {
93
+ return tool === 'task' || tool === 'subagent'
94
+ }
95
+
69
96
  // ─── Implementation ────────────────────────────────────────────────────
70
97
 
71
98
  /**
72
99
  * Whether a result carries any text content (whitespace-only counts as empty).
100
+ *
101
+ * The host placeholder ({@link HOST_EMPTY_RESULT_TEXT}) also counts as empty:
102
+ * it means "no child text", not "the child answered".
103
+ *
104
+ * The host placeholder is matched EXACTLY (after trimming). Substring or
105
+ * prefix matching would rewrite legitimate agent messages that merely quote
106
+ * the phrase, which is worse than the defect being fixed.
73
107
  */
74
108
  function isEmptyOutput(output: unknown): boolean {
75
109
  if (output == null) return true
76
110
  if (typeof output !== 'string') return true
77
- return output.trim() === ''
111
+ const trimmed = output.trim()
112
+ if (trimmed === '') return true
113
+ return trimmed === HOST_EMPTY_RESULT_TEXT
78
114
  }
79
115
 
80
116
  /**
@@ -91,7 +127,7 @@ export function createTaskResultGuard(options?: TaskResultGuardOptions): TaskRes
91
127
 
92
128
  return async (input: TaskGuardInput, output: TaskGuardOutput): Promise<void> => {
93
129
  // Accept both labels without claiming which one a live host emits.
94
- if (input.tool !== 'task' && input.tool !== 'subagent') return
130
+ if (!isChildDispatchTool(input.tool)) return
95
131
 
96
132
  // Only flag truly empty results — non-empty content is the happy path.
97
133
  if (!isEmptyOutput(output.output)) return
@@ -40,7 +40,11 @@ import {
40
40
  DEFAULT_CONFIG as SANDBOX_DEFAULT_CONFIG,
41
41
  } from './context-sandbox.ts'
42
42
  import { createReadEnhancer } from './hashline/read-enhancer.ts'
43
- import { createTaskResultGuard } from './task-result-guard.ts'
43
+ import {
44
+ createTaskResultGuard,
45
+ HOST_EMPTY_RESULT_TEXT,
46
+ isChildDispatchTool,
47
+ } from './task-result-guard.ts'
44
48
 
45
49
  /** The `Tool.Result` fields this adapter reads and writes back. */
46
50
  export interface V2ToolResult {
@@ -69,7 +73,7 @@ export interface V2ExecuteAfterOptions {
69
73
  }
70
74
 
71
75
  /** Which `Tool.Result` field carries the (mutable) text this adapter enhances. */
72
- type TextField = 'output' | 'content' | 'content-array'
76
+ type TextField = 'output' | 'content' | 'content-array' | 'child-output-envelope'
73
77
 
74
78
  /**
75
79
  * Extract the mutable text from a `Tool.Result`.
@@ -80,7 +84,24 @@ type TextField = 'output' | 'content' | 'content-array'
80
84
  *
81
85
  * @returns `{ text, field }` or `null` when there is nothing to enhance.
82
86
  */
83
- function extractText(result: V2ToolResult): { text: string; field: TextField } | null {
87
+ function extractText(
88
+ result: V2ToolResult,
89
+ tool: string,
90
+ ): { text: string; field: TextField } | null {
91
+ // OpenCode 2.0.30's native `subagent` result wraps the effective output in
92
+ // result.output.output, while result.content also carries a display wrapper.
93
+ // Prefer that child-only envelope over the non-empty wrapper text, otherwise
94
+ // the exact host empty-result sentinel is hidden from the task guard.
95
+ const childOutput =
96
+ isChildDispatchTool(tool) &&
97
+ result.output !== null &&
98
+ typeof result.output === 'object' &&
99
+ !Array.isArray(result.output)
100
+ ? (result.output as { output?: unknown }).output
101
+ : undefined
102
+ if (typeof childOutput === 'string' && childOutput.trim() !== '') {
103
+ return { text: childOutput, field: 'child-output-envelope' }
104
+ }
84
105
  if (typeof result.output === 'string' && result.output.trim() !== '') {
85
106
  return { text: result.output, field: 'output' }
86
107
  }
@@ -99,20 +120,95 @@ function extractText(result: V2ToolResult): { text: string; field: TextField } |
99
120
  if (text.trim() !== '') return { text, field: 'content-array' }
100
121
  }
101
122
  if (typeof result.output === 'string') return { text: result.output, field: 'output' }
123
+ if (typeof childOutput === 'string') {
124
+ return { text: childOutput, field: 'child-output-envelope' }
125
+ }
102
126
  return null
103
127
  }
104
128
 
105
- /**
106
- * Write enhanced text back into the SAME field it came from, preserving the
107
- * result's other fields.
108
- */
109
- function writeText(result: V2ToolResult, field: TextField, text: string): void {
129
+ /** Whether content includes an attachment or meaningful object-form text. */
130
+ function hasMeaningfulStructuredContent(content: unknown): boolean {
131
+ if (Array.isArray(content)) {
132
+ return content.some((part) => {
133
+ if (typeof part === 'string') return false
134
+ return (
135
+ part === null || typeof part !== 'object' || (part as { type?: unknown }).type !== 'text'
136
+ )
137
+ })
138
+ }
139
+
140
+ if (content !== null && typeof content === 'object') {
141
+ const part = content as { type?: unknown; text?: unknown }
142
+ return part.type === 'text'
143
+ ? typeof part.text === 'string' && part.text.trim() !== ''
144
+ : Object.keys(content).length > 0
145
+ }
146
+
147
+ return false
148
+ }
149
+
150
+ /** Keep the duplicate child content view synchronized without changing attachments. */
151
+ function rewriteChildContentMirror(
152
+ content: unknown,
153
+ originalText: string,
154
+ replacement: string,
155
+ ): unknown {
156
+ const isHostPlaceholder = originalText.trim() === HOST_EMPTY_RESULT_TEXT
157
+ const matches = (value: unknown): value is string =>
158
+ typeof value === 'string' &&
159
+ (isHostPlaceholder
160
+ ? value.includes(HOST_EMPTY_RESULT_TEXT)
161
+ : originalText.trim() === '' && value.trim() === '')
162
+
163
+ if (typeof content === 'string') return matches(content) ? replacement : content
164
+ if (Array.isArray(content)) {
165
+ return content.map((part) => {
166
+ if (typeof part === 'string') return matches(part) ? replacement : part
167
+ if (
168
+ part !== null &&
169
+ typeof part === 'object' &&
170
+ (part as { type?: unknown }).type === 'text' &&
171
+ matches((part as { text?: unknown }).text)
172
+ ) {
173
+ return { ...part, text: replacement }
174
+ }
175
+ return part
176
+ })
177
+ }
178
+ if (
179
+ content !== null &&
180
+ typeof content === 'object' &&
181
+ (content as { type?: unknown }).type === 'text' &&
182
+ matches((content as { text?: unknown }).text)
183
+ ) {
184
+ return { ...content, text: replacement }
185
+ }
186
+ return content
187
+ }
188
+
189
+ /** Write enhanced text back into its original result field. */
190
+ function writeText(
191
+ result: V2ToolResult,
192
+ field: TextField,
193
+ text: string,
194
+ originalText: string,
195
+ tool: string,
196
+ ): void {
110
197
  if (field === 'output') {
111
198
  result.output = text
112
199
  } else if (field === 'content') {
113
200
  result.content = text
114
- } else {
201
+ } else if (field === 'content-array') {
115
202
  result.content = [{ type: 'text', text }]
203
+ } else {
204
+ const envelope = result.output as { output?: unknown }
205
+ envelope.output = text
206
+ }
207
+ // Native subagent results expose both an output envelope and display content.
208
+ // Keep the parent-visible text aligned, replacing only blank text or text
209
+ // containing the exact known host sentinel; all non-text parts are preserved.
210
+ if (isChildDispatchTool(tool) && field !== 'content' && field !== 'content-array') {
211
+ result.content = rewriteChildContentMirror(result.content, originalText, text)
116
212
  }
117
213
  }
118
214
 
@@ -144,22 +240,23 @@ export function createV2ExecuteAfter(
144
240
  const sessionID = typeof payload.sessionID === 'string' ? payload.sessionID : ''
145
241
  const callID = typeof payload.id === 'string' ? payload.id : ''
146
242
 
147
- const extracted = extractText(result as V2ToolResult)
148
- // Preserve non-empty structured payloads that are intentionally not
149
- // editable as text; they are not empty child results.
243
+ const extracted = extractText(result as V2ToolResult, tool)
244
+ // Preserve meaningful non-text structured payloads (file/image/etc.) and
245
+ // non-empty object-form text parts. Empty text-only content, whether an
246
+ // array of text parts or a single object-form text part, must reach the
247
+ // child-dispatch guard below instead of bypassing it.
150
248
  const resultContent = (result as V2ToolResult).content
151
249
  if (
152
- extracted === null &&
153
- ((Array.isArray(resultContent) && resultContent.length > 0) ||
154
- (resultContent !== null &&
155
- typeof resultContent === 'object' &&
156
- Object.keys(resultContent).length > 0))
250
+ hasMeaningfulStructuredContent(resultContent) &&
251
+ (extracted === null || extracted.text.trim() === '')
157
252
  ) {
158
253
  return
159
254
  }
160
255
  // Child-dispatch results with no text or structured payload are empty;
161
- // other tools with no text remain a no-op.
162
- if (extracted === null && tool !== 'task' && tool !== 'subagent') return
256
+ // other tools with no text remain a no-op. The label set is the guard's
257
+ // own set, so a label the guard handles cannot be dropped before the
258
+ // guard sees it.
259
+ if (extracted === null && !isChildDispatchTool(tool)) return
163
260
  const original = extracted === null ? { text: '', field: 'output' as TextField } : extracted
164
261
 
165
262
  const input = { tool, sessionID, callID, args: payload.input }
@@ -173,7 +270,7 @@ export function createV2ExecuteAfter(
173
270
  await readEnhancer(input, output)
174
271
 
175
272
  if (output.output !== original.text) {
176
- writeText(result as V2ToolResult, original.field, output.output)
273
+ writeText(result as V2ToolResult, original.field, output.output, original.text, tool)
177
274
  }
178
275
  // Surface sandbox metadata onto the result (merge, never replace). It is
179
276
  // only present when the sandbox actually truncated something.
@@ -2,7 +2,7 @@
2
2
  * V2 tool surface — the Pantheon tools that are self-sufficient on the
3
3
  * OpenCode V2 host, declared for `ctx.tool.transform`'s `draft.add`.
4
4
  *
5
- * ## Why only three tools
5
+ * ## Why only three unconditional tools
6
6
  *
7
7
  * A V2 tool can only be served here when it needs no V1 infrastructure. The
8
8
  * three goal tools (`pantheon_goal_create`, `pantheon_goal_get`,
@@ -18,6 +18,15 @@
18
18
  * `pantheon_model` (reads/writes `active-preset.json`) need none of that, so
19
19
  * they are wired to their real V1 implementations.
20
20
  *
21
+ * ## Three unconditional tools, up to two host-dependent ones
22
+ *
23
+ * The three above are always built. Two more exist on the V2 host and are
24
+ * conditional: `vision_describe` is added here when the caller supplies a
25
+ * vision runtime (the host model catalog), and `pantheon_bounded_read` is
26
+ * appended by the plugin when the host exposes its permission and session APIs
27
+ * (root Zeus sessions only). The effective count is therefore 3 unconditional
28
+ * plus up to 2 host-dependent — never a flat 3.
29
+ *
21
30
  * ## The output declaration is mandatory
22
31
  *
23
32
  * The host enforces a biconditional between a tool's declared `output` and the
package/src/plugin-v2.ts CHANGED
@@ -2,10 +2,12 @@
2
2
  * Pantheon V2 Plugin — full orchestration plugin for OpenCode V2.
3
3
  *
4
4
  * Registers:
5
- * - 3 self-sufficient tools via V2 tool.transform (hashline_edit,
6
- * pantheon_cost, pantheon_model) plus native `vision_describe` when the host
7
- * exposes the V2 model catalog; Vision resolves OpenCode Zen auth and sends
8
- * images directly to the selected multimodal model.
5
+ * - 3 unconditional self-sufficient tools via V2 tool.transform (hashline_edit,
6
+ * pantheon_cost, pantheon_model) plus up to 2 host-dependent ones: native
7
+ * `vision_describe` when the host exposes the V2 model catalog (it resolves
8
+ * OpenCode Zen auth and sends images directly to the selected multimodal
9
+ * model), and `pantheon_bounded_read` when the host exposes its permission
10
+ * and session APIs (root Zeus sessions only).
9
11
  * The goal tools need V1 infrastructure and are absent from this surface.
10
12
  * - 5 event subscriptions (session.created, idle, deleted, error, compacted)
11
13
  * - Session hooks (prompt, context, compaction)
package/src/plugin.ts CHANGED
@@ -300,8 +300,9 @@ const plugin: Plugin = async (input: PluginInput) => {
300
300
  client: adaptTodoEnforcerClient(input.client),
301
301
  })
302
302
 
303
- // Wave 3 (PR #46): full-auto goal loop — opt-in (`full_auto.enabled:
304
- // false` default, mirrored by GOAL_LOOP_DEFAULTS). File-based GoalStore
303
+ // Wave 3 (PR #46): goal loop. The plugin uses hard-coded GOAL_LOOP_DEFAULTS;
304
+ // routing.yml documents defaults/guards but no runtime config enables the
305
+ // loop in this build. File-based GoalStore
305
306
  // (`.pantheon/goals/<sessionID>.json` — the plugin layer cannot reach MCP
306
307
  // KV). Idle routing: an active goal owns the idle (goal loop); otherwise
307
308
  // the todo enforcer gets it (see idle-continuation.ts).