opencode-model-router 2.9.1 → 2.10.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/CHANGELOG.md +176 -0
- package/README.md +2 -1
- package/package.json +5 -5
- package/src/compat/background.ts +51 -19
- package/src/compat/child-history.ts +134 -0
- package/src/compat/child-report.ts +185 -0
- package/src/compat/child-session.ts +10 -0
- package/src/compat/v2-client.ts +124 -6
- package/src/compat/v2-hooks.ts +301 -147
- package/src/executor/create.ts +44 -28
- package/src/executor/git.ts +121 -9
- package/src/executor/integrate/land.ts +32 -2
- package/src/executor/runtime.ts +52 -17
- package/src/index.ts +84 -4
- package/src/router/config.ts +157 -28
- package/src/router/git-metadata-guard.ts +180 -0
- package/src/router/git-tools.ts +238 -8
- package/src/router/read-only.ts +37 -13
- package/src/router/run-tools.ts +32 -2
- package/src/router/sessions.ts +9 -0
- package/src/router/tool-paths.ts +62 -4
- package/src/routing/roles/read-set.ts +10 -1
- package/src/routing/roles/work-root.ts +20 -3
- package/src/verify/head.ts +6 -1
- package/src/verify/pending.ts +14 -1
- package/src/verify/reference.ts +60 -7
- package/src/verify/tree.ts +30 -10
- package/src/verify/wiring.ts +47 -12
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,182 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [2.10.0] - 2026-11-27
|
|
11
|
+
|
|
12
|
+
### Changed
|
|
13
|
+
|
|
14
|
+
- **OpenCode v2: plans in different repositories can run at the same time in one Claude Code process.** Executor
|
|
15
|
+
ownership is scoped to the repository's shared git common-directory home, not the whole process. A second plugin
|
|
16
|
+
copy for the same repository (including linked worktrees) still waits for the owner to dispose before taking over.
|
|
17
|
+
- **A filter defined only in a repository's own configuration now stops the verification reference (OpenCode v1 and
|
|
18
|
+
v2) and the plan executor (OpenCode v2) instead of being skipped.** Where git writes (executor commits, WIP saves
|
|
19
|
+
and restores, checkouts, resets, cleans, the reference's `stash create` and checkout), a filter that only the
|
|
20
|
+
repository's local, worktree or included configuration defines is blanked and marked required, so git refuses rather
|
|
21
|
+
than storing or checking out unfiltered content. Repositories whose filter lives only in local config (git-crypt,
|
|
22
|
+
`nbstripout --install`, a local-only Git LFS) now get an executor error or no reference. Remedy: define the filter in
|
|
23
|
+
global config (`git config --global filter.<name>.clean …`); a repository copy identical to the global one keeps
|
|
24
|
+
working, and the plan executor currently needs that copy: with the filter only in global config, the executor's git
|
|
25
|
+
does not see it and commits the content unfiltered (see Fixed). The executor also refuses to land into an owner
|
|
26
|
+
checkout with populated submodules (land manually), because the cleanliness check would run git inside them with
|
|
27
|
+
their own configuration.
|
|
28
|
+
|
|
29
|
+
### Fixed
|
|
30
|
+
|
|
31
|
+
- **OpenCode v2: held results are held again on OpenCode 2.3.0 and later, and the host's reports about the router's own
|
|
32
|
+
children no longer show their raw text to the orchestrator (#174, observed on 2.4.2).** Those hosts report a finished
|
|
33
|
+
child to its parent as `<background-result kind="subagent" sessionID="…" state="…" …>…</background-result>`, which
|
|
34
|
+
the router did not recognise (it knew only OpenCode 2.0's `<subagent …>`): a held background result reached the
|
|
35
|
+
orchestrator before its verdict, and the router did not take the completion from that report. One matcher now reads
|
|
36
|
+
both shapes, attributes in any order, for the completion scan, the held placeholder (in every request and every
|
|
37
|
+
compaction), the `[router` line rewrite of child text and the fail-closed redaction. The host also reports the
|
|
38
|
+
router's own children (an LLM grader, a `router_delegate` producer, a plan-executor task) to the session that ran
|
|
39
|
+
them. In every request and every compaction their report now carries one line,
|
|
40
|
+
`[router] internal child finished; its result is handled by the router.`, in place of the child's text; the router
|
|
41
|
+
still knows its children for an hour after their run, also after it removed them. The extra turns the host starts
|
|
42
|
+
for those reports are not removed.
|
|
43
|
+
- **OpenCode v2: the router's own child runs work again on OpenCode 2.3.0 and later (#167, reported on 2.4.1).** Those
|
|
44
|
+
hosts answer every native `subagent` call at once with a running result, so every child the router runs itself (an
|
|
45
|
+
LLM grader, a `router_delegate` producer, a plan-executor task) was refused as pending and interrupted: verification
|
|
46
|
+
came out UNVERIFIABLE, and delegations and plan tasks failed. The router now waits for its own running child
|
|
47
|
+
(`session.wait`; the wait ends with the run's deadline or cancellation even where the host does not cancel it) and
|
|
48
|
+
uses the child's final answer: the newest assistant entry of its current turn, only when that step ended and has
|
|
49
|
+
text. A child whose run ended on a step without a final answer (cut mid-stream, or stopped after a tool call) is not
|
|
50
|
+
used, and the text of an earlier step is never taken instead. A resumed child (delegate producer or plan task) is
|
|
51
|
+
read only from what its new run added after a marker taken before the run, and only from an answer that follows this
|
|
52
|
+
run's own prompt there; otherwise the previous turn's answer could be taken. A child that ends with no answer, an
|
|
53
|
+
empty one or an error, a run that ended failed or interrupted, a failed, aborted or timed-out result, or a cancelled
|
|
54
|
+
wait is not used: the run fails as before and the child is interrupted. The grading service span reports `completed`
|
|
55
|
+
only once the child really completed.
|
|
56
|
+
- **Router-run git commands in the work root no longer run repository-configured programs.** The verification
|
|
57
|
+
snapshot of the work root and the reference worktree's git calls now turn off `core.fsmonitor`, hooks (including
|
|
58
|
+
`post-index-change` on an index write), `gpg.ssh.defaultKeyCommand` and the external diff, refuse the `ext`, `file`,
|
|
59
|
+
`ssh`, `git`, `http`, `https`, `ftp` and `ftps` transports and any `protocol.<name>.allow` the repository sets, and
|
|
60
|
+
run with `GIT_NO_LAZY_FETCH=1`, while keeping git's index refresh, so snapshot fingerprints are unchanged. The
|
|
61
|
+
default snapshot's `status` no longer rewrites the user's index, and a submodule is refused before `status` or `diff`
|
|
62
|
+
runs. The snapshot (default and hardened), the reference worktree and every executor git call (GitOps, the
|
|
63
|
+
runtime's commits, WIP saves and restores, resets and cleans, the integration git and the landing probes) also blank
|
|
64
|
+
the filter (`clean`, `smudge`, `process`) and merge drivers that only the repository's own configuration names,
|
|
65
|
+
including the drivers its include files set, whatever the include's condition (a missing include target is skipped,
|
|
66
|
+
as git skips it, and so is a dangling include link; on Windows one naming a reserved device such as `NUL` is
|
|
67
|
+
refused); the executor reads them again for every git call. A driver set identically in system or global
|
|
68
|
+
configuration keeps working, so for the default snapshot and the reference a global Git LFS and its
|
|
69
|
+
`git lfs install --local` copy are unaffected (the hardened snapshot reads no system or global configuration and
|
|
70
|
+
sees only the repository's copy, read-only, as before). The plan executor's hardened git does not read system or
|
|
71
|
+
global configuration either, so it currently needs the filter in the repository's local configuration too (for Git
|
|
72
|
+
LFS, `git lfs install --local`): a filter set only globally is not applied by the executor, so it stores and checks
|
|
73
|
+
out that content unfiltered (tracked in #162). The listing runs in the environment of the command it protects. The
|
|
74
|
+
router's other hardened git calls now blank `gpg.ssh.defaultKeyCommand` and refuse `ftp`/`ftps` too. Reading driver
|
|
75
|
+
scopes needs git 2.26 or newer. If the driver configuration cannot be read (or the legacy `GIT_CONFIG` variable is
|
|
76
|
+
set, for the reference), there is no snapshot or reference, and no executor git call runs.
|
|
77
|
+
- **One invalid value in an overrides file no longer drops the whole file (#80).** A bad tier `effort`, an
|
|
78
|
+
`activePreset` naming no preset or an out-of-range `routing` key used to discard every other key of that file too,
|
|
79
|
+
`routing` included. Now only the offending key path goes: the top-level key it sits under, or inside `presets` the
|
|
80
|
+
narrowest of preset, tier and tier key (`presets.anthropic.fast.effort`). Each dropped path adds one config notice,
|
|
81
|
+
`ignoring <path> from <file>: <reason>; the rest of the file applies` (`/router` lists it as
|
|
82
|
+
`router: config notice: …`), and the rest of the file applies. The global override is still settled before the
|
|
83
|
+
project-local one, so a conflicting project key is the one dropped (QA-4.1-21). A file none of whose top-level keys
|
|
84
|
+
can be kept is dropped as a whole, as before. Valid configs load unchanged. OpenCode v1 and v2.
|
|
85
|
+
- **OpenCode v2: a background dispatch whose acknowledgement fails gives its reserved held handle back at once.** The
|
|
86
|
+
handle reserved for the hold just before the in-flight attempt is registered was released only once an attempt
|
|
87
|
+
existed: when the registration returned nothing or threw, the reservation stayed for `HELD_RESERVATION_TTL_MS`
|
|
88
|
+
(7 h), took one of the session's pending slots and made `router_verify` answer `held` for a dispatch that is not held.
|
|
89
|
+
It is now released on both failure paths.
|
|
90
|
+
- **OpenCode v2: `router_verify` on a background handle whose child is still running answers `held`, not `unknown handle`.**
|
|
91
|
+
The handle is reserved and listed every turn from the background ack but registered only when the child finishes, so
|
|
92
|
+
until then the registry did not know it and an orchestrator that polled it got `unknown handle` again and again. The
|
|
93
|
+
session the handle was issued to now gets the held answer, and the verdict is replayed once it settles. Another
|
|
94
|
+
session's reserved handle still reads as unknown, and a reservation is released when the held entry cannot be
|
|
95
|
+
registered, so the handle is not answered `held` for hours after the gate posted its verdict directly.
|
|
96
|
+
- **`router_verify` answers an unknown handle terminally, and a call without a session id explicitly.** `unknown handle`
|
|
97
|
+
now says the session has no record of it (never issued here, issued to another session, or no longer tracked after a restart,
|
|
98
|
+
eviction or a failed background run) and that retrying will not change the answer. A call with no session id, for handles or `pending: true`,
|
|
99
|
+
is answered `no session` instead of `unknown handle` or "no unverified delegations in this session". Wording only on
|
|
100
|
+
OpenCode v1.
|
|
101
|
+
- **Plan executor: task commits and slot WIP saves use the user's resolved git identity even when it is only global.**
|
|
102
|
+
Both paths explicitly disable signing and keep hooks and global config disabled in hardened git. Failures retain a
|
|
103
|
+
sanitized stderr tail and exit code in warnings, metrics or attempt contexts, and blocking inbox items, with identity
|
|
104
|
+
setup guidance when no identity is configured.
|
|
105
|
+
- **OpenCode v2: a hung plan-executor disposal no longer holds location cleanup forever.** The adapter waits at most
|
|
106
|
+
30 seconds, warns on timeout, aborts the launcher's controllers and continues teardown. The original disposal remains
|
|
107
|
+
observed and keeps the repository claim until it completes; restart the host if that claim stays stuck.
|
|
108
|
+
- **OpenCode v2: resumed background dispatches keep their own results and verification handles.** Historical completions
|
|
109
|
+
first scanned after a resume no longer supply the resumed attempt's result, and held placeholders retain their attempt's
|
|
110
|
+
announced handle instead of changing to the newest handle for the same child session.
|
|
111
|
+
- **OpenCode v2: repeated background finishes no longer discard a dispatch's verification.** A live held call keeps
|
|
112
|
+
its original gate and verdict instead of being reclassified as a read-only delegation after its inputs were consumed.
|
|
113
|
+
Missing dispatch inputs are reported explicitly as UNVERIFIABLE, never inferred as no acceptance and no changes.
|
|
114
|
+
- **OpenCode v2 / roles mode: `router_run` points script calls with arguments to configured commands.** Refusals
|
|
115
|
+
list argument patterns, with commands running the same package script first (such as the default `test-files`);
|
|
116
|
+
the tool description also includes a bounded list of commands accepting arguments. Argument acceptance is unchanged.
|
|
117
|
+
- **Plan executor: recompiling a plan after abort and purge in the same process can be approved again.** A new plan
|
|
118
|
+
reusing the same id gets fresh slot pools and collection state; stale slot handles from the purged plan remain fenced.
|
|
119
|
+
- **OpenCode v2 / roles mode: each parallel tool call of a role agent is checked against its own arguments (#86).** The
|
|
120
|
+
`execute.before` authority check now reads the call's tool and input when the hook is invoked, not after its awaits,
|
|
121
|
+
so a refusal no longer names another parallel call's path when the host reuses or rewrites a pending call's event.
|
|
122
|
+
- **OpenCode v2: read-only tiers recognise the host 2.0.31 default permissions.** Host 2.0.31 dropped the
|
|
123
|
+
`external_directory * ask` default, so its defaults were treated as explicit rules: the host's `.env` read rules were
|
|
124
|
+
re-appended after the tier policy and `host default permissions not recognised` was logged. Both the 2.0.22 and the
|
|
125
|
+
2.0.31 default sequences are now recognised (longest match); unknown sequences still fail closed. The v2 adapter now
|
|
126
|
+
typechecks against `@opencode/plugin` 2.0.31.
|
|
127
|
+
- **Verification never runs a `git` found in the work root (#141).** The verification's git calls in a work root (the
|
|
128
|
+
commits-since-dispatch diff, the test searches, the HEAD and reflog reads, the tree snapshot and the failure-recheck
|
|
129
|
+
reference) ran a bare `git`, which Windows can resolve from the working directory, so a model could plant a `git.exe`
|
|
130
|
+
there. They now run git by absolute path from outside the work root, as the router's git tools do, and refuse to run
|
|
131
|
+
when the only git is inside it. The diff, the test searches and the HEAD reads also pass the router's hardening
|
|
132
|
+
options (no hooks, fsmonitor, pager or signature programs, no optional locks). A security fix, on OpenCode v1 and v2.
|
|
133
|
+
- **OpenCode v2: a host session lookup that never answers no longer stalls the file tools (#161).** The session
|
|
134
|
+
record (directory, parent, agent) that the role checks, the file leases and the stale-resume check read gives up
|
|
135
|
+
after 10 seconds and then counts as a failed lookup, repeated after 2 seconds. A role agent's call is then refused
|
|
136
|
+
(its check needs the record), and a resume of that session is not checked for staleness. The file leases give up at
|
|
137
|
+
their own 5-second bound and skip their check for the call. A host answer that is no session record counts as a
|
|
138
|
+
failed lookup too. The session's current directory, which a tool call looks up once for both a relative
|
|
139
|
+
`read`/`write`/`edit` path and the git metadata guard, gives up after 2 seconds; the call then uses the directory of
|
|
140
|
+
the session's last successful lookup, else the session record's. When no directory is known, a relative `read`,
|
|
141
|
+
`write` or `edit` path fails the call (`[router] Refused: the session's location could not be read (…)`), as a
|
|
142
|
+
failed lookup did before, and the git metadata guard refuses a delegated session's write (see Security).
|
|
143
|
+
- **OpenCode v2: the git metadata guard checks a moved session in its current location (#161).** The `filePath` that a
|
|
144
|
+
relative `write` or `edit` `path` becomes was already resolved against a lookup made per call, but the guard resolved
|
|
145
|
+
everything else against the directory the session had at its first lookup: patch and `apply_patch` headers and their
|
|
146
|
+
path arguments, `multiedit` targets, the other path keys of a `write` or `edit` (`path` as written, `file`,
|
|
147
|
+
`file_path`), and the session's repository (its git and common directories). After the host moved the session these
|
|
148
|
+
were checked against the old directory. The guard now uses the call's own lookup, the one the relative path uses. The
|
|
149
|
+
file leases and the role checks still use the session's first directory.
|
|
150
|
+
|
|
151
|
+
### Security
|
|
152
|
+
|
|
153
|
+
- **A patch call whose extra patch text cannot be read is refused (#161).** The host reads the first string among
|
|
154
|
+
`patchText`, `patch_text`, `patch` and `input`; the git metadata guard also reads the others. One of those with a file
|
|
155
|
+
header that names no path (`*** Add File:` and nothing after it) was skipped, and now makes the call refused like an
|
|
156
|
+
unreadable patch. Another key's text without file headers is still ignored. OpenCode v1 and v2.
|
|
157
|
+
- **OpenCode v2: a delegated session's write is refused while its directory is unknown (#161).** When the session's
|
|
158
|
+
directory cannot be looked up and none is known, the git metadata guard cannot resolve the call's paths and the
|
|
159
|
+
session's repository. An `edit`, `write`, `multiedit`, `patch` or `apply_patch` call of a delegated session (a tier
|
|
160
|
+
or plugin agent, any session the router has not proven to be the root) is then refused: `[router] Refused: the
|
|
161
|
+
session's location could not be read, so this write cannot be checked for git metadata, which delegated agents may
|
|
162
|
+
not write (fail closed).` A path that names git metadata keeps the usual refusal. Before, the guard resolved such a
|
|
163
|
+
call against the plugin's directory and could miss the git metadata of the session's own repository (for example
|
|
164
|
+
`../<name>.git/config` from a linked worktree of a bare repository). The cost: while no lookup of that session's
|
|
165
|
+
directory has succeeded in this process (neither a tool call's own lookup nor the session record; other host
|
|
166
|
+
answers about the session do not count), its `patch`, `apply_patch` and `multiedit` calls and its `write` and
|
|
167
|
+
`edit` calls with an absolute path fail (with a relative path they fail already, see Fixed). A refused call first
|
|
168
|
+
waits for its lookups to give up: 2 seconds for the call's own lookup, and up to 10 more for the session record
|
|
169
|
+
when there is none yet. This refusal does not apply to read-class calls, but a relative `read` path fails in the
|
|
170
|
+
same state, as described under Fixed. The orchestrator is not affected once the router knows it as the root; a
|
|
171
|
+
root session not yet resolved as the root is refused like a delegated one, or waits for that lookup.
|
|
172
|
+
- **Delegated agents can no longer write repository git metadata with the file tools (edit, write, multiedit,
|
|
173
|
+
patch).** Role agents were already refused; tier agents, plugin agents (#81) and every other delegated session now are
|
|
174
|
+
too. An `edit`, `write`, `multiedit`, `patch` or `apply_patch` call is refused when a file it names is `.git` or below
|
|
175
|
+
it, in any spelling the filesystem treats as `.git` (case, trailing dots or spaces, NTFS streams, 8.3 names, a link,
|
|
176
|
+
`..` read either as the filesystem or as the host resolves it), or lies in the git or common directory of the
|
|
177
|
+
session's repository (a linked worktree's too, also a bare repository that holds the worktree; the checkout's own
|
|
178
|
+
files stay writable). On OpenCode v2 paths resolve against the session's own location. A path the router cannot
|
|
179
|
+
resolve, and a patch whose files it cannot read, is refused as well; that includes UNC and device paths, except paths
|
|
180
|
+
inside the session's own directory when the project itself is on a share. The refusal reads `[router] Refused:
|
|
181
|
+
writing git metadata (<path>) is not allowed for delegated agents.` The orchestrator session is not affected;
|
|
182
|
+
`/bypass` and the enforcement mode do not turn the check off. Shell commands are not covered. Ordinary files and
|
|
183
|
+
`.gitattributes`, `.gitignore` or `.github/` are unaffected. The published agent permissions are unchanged. OpenCode
|
|
184
|
+
v1 and v2.
|
|
185
|
+
|
|
10
186
|
## [2.9.1] - 2026-10-25
|
|
11
187
|
|
|
12
188
|
### Changed
|
package/README.md
CHANGED
|
@@ -265,7 +265,7 @@ Then install and configure model-router to handle the rest.
|
|
|
265
265
|
### OpenCode v2
|
|
266
266
|
|
|
267
267
|
The v2 adapter supports OpenCode hosts **2.0.20 or later** and typechecks against
|
|
268
|
-
`@opencode/plugin` **2.
|
|
268
|
+
`@opencode/plugin` **2.3.2**. Use the v2 `plugins` key:
|
|
269
269
|
|
|
270
270
|
```json
|
|
271
271
|
{
|
|
@@ -1226,6 +1226,7 @@ With `routing.delegation: "roles"` the orchestrator stops picking tiers: it disp
|
|
|
1226
1226
|
| `general` | anything else; authority follows the task's needs | fast–heavy |
|
|
1227
1227
|
|
|
1228
1228
|
- **Least privilege.** Each role has a fixed maximum authority, and no role holds the web together with reads, runs or edits. Commands run through `router_run` (allowlisted scripts and commands, fixed argv, no shell controlled by the caller; npm script bodies still run in npm's pinned script shell); raw shell stays with the tier agents.
|
|
1229
|
+
- **Scoped test runs.** Use `router_run` with `script: "test-files"` and `args: ["test/unit/x.test.ts"]` (plus the dispatch's `cwd`). Package-script calls with arguments are refused with configured command names and patterns, same-script commands first; argument acceptance is unchanged.
|
|
1229
1230
|
- **Authority sets the floor.** Reading may use the cheapest tier; an edit goes below `medium` only when the router itself runs the acceptance checks on a low-risk, single-file change, and edit + run never goes below `medium` (`heavy` without those checks).
|
|
1230
1231
|
- **Budgets per role.** A role that runs out of calls returns `NEED MORE: budget` and is resumed in the same session; that is never counted as a failure.
|
|
1231
1232
|
- **Evidence from verification only.** Only verdicts move the routing evidence: the router's deterministic checks, and an independent LLM grader at half weight. Router-observed runs, incomplete returns and re-dispatches are recorded as routing statistics; a bare `DONE` counts for nothing.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-model-router",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.10.0",
|
|
4
4
|
"description": "OpenCode plugin that routes tasks to tiered subagents (fast/medium/heavy) based on complexity",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./src/index.ts",
|
|
@@ -62,14 +62,14 @@
|
|
|
62
62
|
},
|
|
63
63
|
"devDependencies": {
|
|
64
64
|
"@lydell/node-pty": "1.2.0-beta.15",
|
|
65
|
-
"@opencode/plugin": "2.
|
|
65
|
+
"@opencode/plugin": "2.3.2",
|
|
66
66
|
"@types/node": "^26.2.0",
|
|
67
|
-
"@vitest/coverage-v8": "^5.
|
|
67
|
+
"@vitest/coverage-v8": "^5.1.1",
|
|
68
68
|
"@xterm/headless": "6.0.0",
|
|
69
69
|
"cross-env": "^10.1.0",
|
|
70
70
|
"istanbul-lib-coverage": "^3.2.2",
|
|
71
|
-
"solid-js": "1.9.
|
|
71
|
+
"solid-js": "1.9.17",
|
|
72
72
|
"typescript": "^7.0.2",
|
|
73
|
-
"vitest": "^5.
|
|
73
|
+
"vitest": "^5.1.1"
|
|
74
74
|
}
|
|
75
75
|
}
|
package/src/compat/background.ts
CHANGED
|
@@ -10,6 +10,7 @@ import { createLeaseRegistry, foldKeyPath, formatRunNote } from "../router/lease
|
|
|
10
10
|
import type { LeaseActor, LeaseRegistry, LeaseSeams, Holder, HolderInput } from "../router/leases";
|
|
11
11
|
import { toolTargets } from "../router/tool-paths";
|
|
12
12
|
import { observeV2, type V2Observations } from "./v2-observations";
|
|
13
|
+
import { childReportClose, nextChildReportOpening } from "./child-report";
|
|
13
14
|
|
|
14
15
|
// ---- constants -------------------------------------------------------------------------------
|
|
15
16
|
|
|
@@ -497,6 +498,24 @@ export function attemptKey(childSessionID: string, callID: string): string {
|
|
|
497
498
|
return `${childSessionID}\u0000${callID}`;
|
|
498
499
|
}
|
|
499
500
|
|
|
501
|
+
/** Index a history once; keep the first occurrence, as the boundary lookup's former `findIndex` did. */
|
|
502
|
+
export function indexMessageIDs(messages: readonly unknown[]): ReadonlyMap<string, number> {
|
|
503
|
+
const indices = new Map<string, number>();
|
|
504
|
+
messages.forEach((message, index) => {
|
|
505
|
+
const id: unknown = message !== null && typeof message === "object" ? Reflect.get(message, "id") : undefined;
|
|
506
|
+
if (typeof id === "string" && !indices.has(id)) indices.set(id, index);
|
|
507
|
+
});
|
|
508
|
+
return indices;
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/** A completion at or before the message dispatching an attempt belongs to an earlier turn, even if never scanned before. */
|
|
512
|
+
export function precedesDispatch(messageIndices: ReadonlyMap<string, number>, index: number, callerMessageID: string | undefined): boolean {
|
|
513
|
+
if (callerMessageID === undefined) return false;
|
|
514
|
+
// An absent caller may have been compacted out before OR after these messages; its position cannot be inferred safely.
|
|
515
|
+
const caller = messageIndices.get(callerMessageID);
|
|
516
|
+
return caller !== undefined && caller >= index;
|
|
517
|
+
}
|
|
518
|
+
|
|
500
519
|
/** 3.1.7 W5: the record belongs to the plan executor (excluded from the ordinary completion and verification path). */
|
|
501
520
|
export function isExecutorOwned(rec: CallRecord | undefined): boolean {
|
|
502
521
|
return rec?.owner === "executor";
|
|
@@ -860,7 +879,6 @@ export interface HeldResults extends HeldSink {
|
|
|
860
879
|
persisted(): PersistedRecord[];
|
|
861
880
|
}
|
|
862
881
|
|
|
863
|
-
const SUBAGENT_CLOSE = "</subagent>";
|
|
864
882
|
const VERDICT_PREFIX = "<router-verdict ";
|
|
865
883
|
const SYNTHETIC_ATTEMPTS = 3;
|
|
866
884
|
/** = BACKGROUND_RETRY_BASE_MS (verify/pending.ts:442); kept local so this module imports nothing heavy. */
|
|
@@ -956,7 +974,7 @@ export function createHeldResults(deps: {
|
|
|
956
974
|
byHandle.delete(entry.handle);
|
|
957
975
|
const children = byParent.get(entry.parentSessionID);
|
|
958
976
|
if (children === undefined) return;
|
|
959
|
-
|
|
977
|
+
children.delete(entry.handle);
|
|
960
978
|
if (children.size === 0) byParent.delete(entry.parentSessionID);
|
|
961
979
|
}
|
|
962
980
|
|
|
@@ -966,7 +984,8 @@ export function createHeldResults(deps: {
|
|
|
966
984
|
children = new Map();
|
|
967
985
|
byParent.set(entry.parentSessionID, children);
|
|
968
986
|
}
|
|
969
|
-
|
|
987
|
+
// Keep released attempts too: their historical completions must retain their own placeholders after a resume.
|
|
988
|
+
children.set(entry.handle, entry);
|
|
970
989
|
byHandle.set(entry.handle, entry);
|
|
971
990
|
}
|
|
972
991
|
|
|
@@ -991,18 +1010,23 @@ export function createHeldResults(deps: {
|
|
|
991
1010
|
return [...(byParent.get(sessionID)?.values() ?? [])];
|
|
992
1011
|
}
|
|
993
1012
|
|
|
994
|
-
function applyText(sessionID: string, text: string
|
|
1013
|
+
function applyText(sessionID: string, text: string,
|
|
1014
|
+
entries: ReadonlyMap<string, HoldEntry> = new Map(heldChildren(sessionID).map((entry) => [entry.childSessionID, entry]))): string {
|
|
995
1015
|
if (text.startsWith(VERDICT_PREFIX)) return text;
|
|
996
1016
|
let out = text;
|
|
997
|
-
|
|
998
|
-
|
|
1017
|
+
// One attempt per child, selected by the containing message's dispatch boundary in `apply`.
|
|
1018
|
+
const placeholders = heldChildren(sessionID).map((entry) => heldPlaceholder(entry.handle, entry.childSessionID));
|
|
1019
|
+
for (const entry of entries.values()) {
|
|
999
1020
|
const placeholder = heldPlaceholder(entry.handle, entry.childSessionID);
|
|
1000
1021
|
let from = 0;
|
|
1001
1022
|
for (;;) {
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
if (
|
|
1005
|
-
|
|
1023
|
+
// #174: the child's completion element in either envelope (`<subagent …>`, 2.3+ `<background-result kind="subagent" …>`).
|
|
1024
|
+
const opening = nextChildReportOpening(out, from, entry.childSessionID);
|
|
1025
|
+
if (opening === undefined) break;
|
|
1026
|
+
const at = opening.index;
|
|
1027
|
+
const prior = placeholders.find((known) => out.startsWith(known, at));
|
|
1028
|
+
if (prior !== undefined) {
|
|
1029
|
+
from = at + prior.length;
|
|
1006
1030
|
continue;
|
|
1007
1031
|
}
|
|
1008
1032
|
if (at === 0) {
|
|
@@ -1012,12 +1036,10 @@ export function createHeldResults(deps: {
|
|
|
1012
1036
|
}
|
|
1013
1037
|
// O13: an embedded record. Cut precisely only when the known body follows verbatim, else through the end.
|
|
1014
1038
|
let end = out.length;
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
const bodyEnd =
|
|
1018
|
-
if (out.startsWith(entry.body,
|
|
1019
|
-
end = bodyEnd + SUBAGENT_CLOSE.length;
|
|
1020
|
-
}
|
|
1039
|
+
if (entry.body !== undefined) {
|
|
1040
|
+
const close = childReportClose(opening.tag);
|
|
1041
|
+
const bodyEnd = opening.bodyStart + entry.body.length;
|
|
1042
|
+
if (out.startsWith(entry.body, opening.bodyStart) && out.startsWith(close, bodyEnd)) end = bodyEnd + close.length;
|
|
1021
1043
|
}
|
|
1022
1044
|
out = out.slice(0, at) + placeholder + out.slice(end);
|
|
1023
1045
|
from = at + placeholder.length;
|
|
@@ -1196,7 +1218,9 @@ export function createHeldResults(deps: {
|
|
|
1196
1218
|
},
|
|
1197
1219
|
|
|
1198
1220
|
isHeld(child) {
|
|
1199
|
-
for (const children of byParent.values())
|
|
1221
|
+
for (const children of byParent.values()) {
|
|
1222
|
+
for (const entry of children.values()) if (entry.childSessionID === child && entry.active) return true;
|
|
1223
|
+
}
|
|
1200
1224
|
return false;
|
|
1201
1225
|
},
|
|
1202
1226
|
|
|
@@ -1205,9 +1229,17 @@ export function createHeldResults(deps: {
|
|
|
1205
1229
|
|
|
1206
1230
|
apply<M>(sessionID: string, messages: readonly M[]): M[] | undefined {
|
|
1207
1231
|
if (!byParent.has(sessionID)) return undefined;
|
|
1232
|
+
const messageIndices = indexMessageIDs(messages);
|
|
1233
|
+
const entries = heldChildren(sessionID);
|
|
1234
|
+
const fallback = new Map(entries.map((entry) => [entry.childSessionID, entry]));
|
|
1208
1235
|
let changed = false;
|
|
1209
|
-
const out = messages.map((message) => {
|
|
1210
|
-
const
|
|
1236
|
+
const out = messages.map((message, index) => {
|
|
1237
|
+
const selected = new Map(fallback);
|
|
1238
|
+
// With a boundary, select the latest eligible attempt. Missing/compacted boundaries still redact fail-closed.
|
|
1239
|
+
for (const entry of entries) {
|
|
1240
|
+
if (!precedesDispatch(messageIndices, index, entry.callerMessageID)) selected.set(entry.childSessionID, entry);
|
|
1241
|
+
}
|
|
1242
|
+
const next = redactMessage(message, (text) => applyText(sessionID, text, selected));
|
|
1211
1243
|
if (next === undefined) return message;
|
|
1212
1244
|
changed = true;
|
|
1213
1245
|
return next;
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Readers of a v2 child's own history (`ctx.session.context`), shared by the adapter (`v2-hooks.ts`) and the native child
|
|
3
|
+
* runner (`v2-client.ts`). v2 only: OpenCode v1 never loads this module.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** The text of one session-context message: its `text`, else its text parts (`content` or `parts`) joined. */
|
|
7
|
+
export function messageText(message: unknown): string | undefined {
|
|
8
|
+
if (!message || typeof message !== "object") return undefined;
|
|
9
|
+
const m = message as Record<string, unknown>;
|
|
10
|
+
if (typeof m.text === "string") return m.text;
|
|
11
|
+
if (typeof m.content === "string") return m.content;
|
|
12
|
+
const parts = Array.isArray(m.content) ? m.content : Array.isArray(m.parts) ? m.parts : undefined;
|
|
13
|
+
if (parts === undefined) return undefined;
|
|
14
|
+
const texts = parts.flatMap((part) => part && typeof part === "object" && (part as Record<string, unknown>).type === "text"
|
|
15
|
+
&& typeof (part as Record<string, unknown>).text === "string" ? [(part as Record<string, unknown>).text as string] : []);
|
|
16
|
+
return texts.length > 0 ? texts.join("\n") : undefined;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The child's last assistant message of its current turn (after its newest user prompt, DF-1-4): walking back from the newest
|
|
21
|
+
* entry, the first assistant entry with text; the newest user prompt ends the walk, as an answer before it belongs to an
|
|
22
|
+
* earlier turn (a resume). The host's context entries are discriminated by `type` ("user" | "assistant" | "synthetic", see the
|
|
23
|
+
* instruction filter in the system hook); the model-facing messages of the context hook use `role`. Both name the assistant
|
|
24
|
+
* the same way. `failed` (#167): between that answer and the newest entry, an assistant entry carries an error, or the run's
|
|
25
|
+
* end marker (`{ type: "idle", outcome }`) has an outcome other than "succeeded" ("failed" | "interrupted"): the turn did not
|
|
26
|
+
* end in success and its text may be partial. An end marker without an outcome changes nothing.
|
|
27
|
+
*
|
|
28
|
+
* `final` (#167, the native runner's waited result; QA-2.1-18: text alone is not an end): the NEWEST assistant entry of the
|
|
29
|
+
* turn decides. It is the answer only when it has text and ended its step (`assistantStepCompleted`); otherwise there is no
|
|
30
|
+
* answer, never an earlier step's text (a draft before a tool call). Its `finish: "error"` also fails the reply.
|
|
31
|
+
*
|
|
32
|
+
* `after` (#167, a resume): `id` is the history's newest entry before this run (`newestEntryId`). Only entries after it count,
|
|
33
|
+
* and the answer must follow a user entry, also after it, whose text contains this run's `prompt` (trimmed; the host may put
|
|
34
|
+
* its preamble line before it): the host adds the prompt to the history only when the run takes it, and a resume often
|
|
35
|
+
* repeats the previous prompt, so the marker tells this run's entry from an identical earlier one. A run end (`idle`) between
|
|
36
|
+
* the newest such entry and the answer means the answer is a later run's. Without such an entry, with a run end between, or
|
|
37
|
+
* when the marker is no longer in the history (compacted, see `historyHasEntry`), there is no answer of this run.
|
|
38
|
+
*/
|
|
39
|
+
export function lastAssistantReply(
|
|
40
|
+
history: unknown, options: { final?: boolean; after?: { id: string; prompt: string } } = {},
|
|
41
|
+
): { text: string; failed: boolean } | undefined {
|
|
42
|
+
const messages: readonly unknown[] = Array.isArray(history) ? history : [];
|
|
43
|
+
const { after, final = false } = options;
|
|
44
|
+
let start = 0;
|
|
45
|
+
if (after !== undefined) {
|
|
46
|
+
const marker = entryIndex(messages, after.id);
|
|
47
|
+
if (marker < 0) return undefined;
|
|
48
|
+
start = marker + 1;
|
|
49
|
+
}
|
|
50
|
+
const isUser = (message: unknown): boolean => {
|
|
51
|
+
const m = message as { type?: unknown; role?: unknown } | null | undefined;
|
|
52
|
+
return m?.type === "user" || m?.role === "user";
|
|
53
|
+
};
|
|
54
|
+
const normalized = (text: string): string => text.replace(/\r\n/g, "\n").trim();
|
|
55
|
+
const ownPrompt = after === undefined ? "" : normalized(after.prompt);
|
|
56
|
+
const isOwnPrompt = (message: unknown): boolean =>
|
|
57
|
+
isUser(message) && ownPrompt !== "" && normalized(messageText(message) ?? "").includes(ownPrompt);
|
|
58
|
+
let failed = false;
|
|
59
|
+
for (let index = messages.length - 1; index >= start; index--) {
|
|
60
|
+
const message = messages[index] as {
|
|
61
|
+
type?: unknown; role?: unknown; outcome?: unknown; error?: unknown; finish?: unknown; info?: { error?: unknown; finish?: unknown };
|
|
62
|
+
} | undefined;
|
|
63
|
+
if (message?.type === "idle" && message.outcome !== undefined && message.outcome !== null && message.outcome !== "succeeded") {
|
|
64
|
+
failed = true;
|
|
65
|
+
}
|
|
66
|
+
if (message?.type === "assistant" || message?.role === "assistant") {
|
|
67
|
+
const error = message.error ?? message.info?.error;
|
|
68
|
+
if (error !== undefined && error !== null && error !== false) failed = true;
|
|
69
|
+
if (final && (message.finish ?? message.info?.finish) === "error") failed = true;
|
|
70
|
+
const text = messageText(message);
|
|
71
|
+
if (final && (text === undefined || !assistantStepCompleted(message))) return undefined;
|
|
72
|
+
if (text !== undefined) {
|
|
73
|
+
if (after !== undefined) {
|
|
74
|
+
// The newest own prompt before the answer; a run end (`idle`, any outcome) between them means the answer belongs to
|
|
75
|
+
// a later run than ours (ours ended, then another prompt was taken), so it is not this run's answer.
|
|
76
|
+
let own = index - 1;
|
|
77
|
+
while (own >= start && !isOwnPrompt(messages[own])) own--;
|
|
78
|
+
if (own < start) return undefined;
|
|
79
|
+
if (messages.slice(own + 1, index).some((m) => (m as { type?: unknown } | null | undefined)?.type === "idle")) return undefined;
|
|
80
|
+
}
|
|
81
|
+
return { text, failed };
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (isUser(message)) break;
|
|
85
|
+
}
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* QA-2.1-18: whether an assistant entry of a child's history ended its step (top level or under `info`): a finish reason other
|
|
91
|
+
* than a tool-call continuation, or a completed time; and no tool part still `pending` or `running`. A step cut mid-stream has
|
|
92
|
+
* none of these, and a `tool-calls` finish means the child meant to go on: neither is an end, whatever text it already has.
|
|
93
|
+
*/
|
|
94
|
+
export function assistantStepCompleted(message: unknown): boolean {
|
|
95
|
+
if (message === null || typeof message !== "object") return false;
|
|
96
|
+
const m = message as Record<string, unknown>;
|
|
97
|
+
const info = m.info !== null && typeof m.info === "object" ? m.info as Record<string, unknown> : undefined;
|
|
98
|
+
const parts: readonly unknown[] = Array.isArray(m.content) ? m.content : Array.isArray(m.parts) ? m.parts : [];
|
|
99
|
+
const toolOpen = parts.some((part) => {
|
|
100
|
+
if (part === null || typeof part !== "object" || (part as Record<string, unknown>).type !== "tool") return false;
|
|
101
|
+
const state = (part as Record<string, unknown>).state;
|
|
102
|
+
const status = state !== null && typeof state === "object" ? (state as Record<string, unknown>).status : state ?? (part as Record<string, unknown>).status;
|
|
103
|
+
// The v2 tool state is `streaming` | `running` | `completed` | `error` (`pending` is the v1 name of the first).
|
|
104
|
+
return status === "streaming" || status === "pending" || status === "running";
|
|
105
|
+
});
|
|
106
|
+
if (toolOpen) return false;
|
|
107
|
+
const finish = m.finish ?? info?.finish;
|
|
108
|
+
if (typeof finish === "string" && finish !== "") return finish !== "tool-calls" && finish !== "unknown";
|
|
109
|
+
const time = m.time ?? info?.time;
|
|
110
|
+
// `time.completed` is set once the step ended: epoch millis on the wire, a DateTime once decoded; either counts.
|
|
111
|
+
const completed = time !== null && typeof time === "object" ? (time as Record<string, unknown>).completed : undefined;
|
|
112
|
+
return completed !== undefined && completed !== null && completed !== "" && completed !== false;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** #167: the id of a history's newest entry (every v2 context entry carries one), or undefined when it has none. */
|
|
116
|
+
export function newestEntryId(history: unknown): string | undefined {
|
|
117
|
+
return Array.isArray(history) && history.length > 0 ? entryId(history[history.length - 1]) : undefined;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** #167: whether the history still holds the entry with this id (a resume's marker; gone after a compaction). */
|
|
121
|
+
export function historyHasEntry(history: unknown, id: string): boolean {
|
|
122
|
+
return Array.isArray(history) && entryIndex(history, id) >= 0;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function entryIndex(messages: readonly unknown[], id: string): number {
|
|
126
|
+
let index = messages.length - 1;
|
|
127
|
+
while (index >= 0 && entryId(messages[index]) !== id) index--;
|
|
128
|
+
return index;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function entryId(message: unknown): string | undefined {
|
|
132
|
+
const id = message !== null && typeof message === "object" ? (message as { id?: unknown }).id : undefined;
|
|
133
|
+
return typeof id === "string" && id !== "" ? id : undefined;
|
|
134
|
+
}
|