opencode-codex-memory 0.8.0 → 0.8.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.
- package/README.md +64 -525
- package/dist/src/claude-import.js +25 -27
- package/dist/src/v2/agents.js +19 -8
- package/dist/src/v2/plugin.js +24 -5
- package/dist/src/v2/search-sandbox.d.ts +4 -0
- package/dist/src/v2/search-sandbox.js +33 -0
- package/dist/src/v2/service.d.ts +2 -0
- package/dist/src/v2/service.js +43 -4
- package/dist/src/v2/shim.d.ts +2 -2
- package/dist/src/v2/shim.js +77 -38
- package/dist/src/v2/tui.js +532 -287
- package/package.json +2 -2
|
@@ -73,8 +73,10 @@ function lstatKind(p) {
|
|
|
73
73
|
return "dir";
|
|
74
74
|
return "other";
|
|
75
75
|
}
|
|
76
|
-
catch {
|
|
77
|
-
|
|
76
|
+
catch (err) {
|
|
77
|
+
if (err.code === "ENOENT")
|
|
78
|
+
return "missing";
|
|
79
|
+
throw err;
|
|
78
80
|
}
|
|
79
81
|
}
|
|
80
82
|
/**
|
|
@@ -83,13 +85,7 @@ function lstatKind(p) {
|
|
|
83
85
|
* cwd that canonicalizes to an existing directory wins.
|
|
84
86
|
*/
|
|
85
87
|
export function projectCwdFromSessions(projectRoot) {
|
|
86
|
-
|
|
87
|
-
try {
|
|
88
|
-
entries = fs.readdirSync(projectRoot, { withFileTypes: true });
|
|
89
|
-
}
|
|
90
|
-
catch {
|
|
91
|
-
return null;
|
|
92
|
-
}
|
|
88
|
+
const entries = fs.readdirSync(projectRoot, { withFileTypes: true });
|
|
93
89
|
const sessions = entries
|
|
94
90
|
.filter((e) => e.isFile() && e.name.endsWith(".jsonl"))
|
|
95
91
|
.map((e) => {
|
|
@@ -139,13 +135,9 @@ export function projectCwdFromSessions(projectRoot) {
|
|
|
139
135
|
return null;
|
|
140
136
|
}
|
|
141
137
|
function collectMarkdownFiles(sourceRoot, currentDir, projectKey, projectCwd, out) {
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
}
|
|
146
|
-
catch {
|
|
147
|
-
return;
|
|
148
|
-
}
|
|
138
|
+
// A partial scan is not a deletion signal. Codex propagates discovery errors
|
|
139
|
+
// before replacing/pruning any imported project.
|
|
140
|
+
const entries = fs.readdirSync(currentDir, { withFileTypes: true });
|
|
149
141
|
entries.sort((a, b) => a.name.localeCompare(b.name));
|
|
150
142
|
for (const entry of entries) {
|
|
151
143
|
const full = path.join(currentDir, entry.name);
|
|
@@ -179,13 +171,7 @@ export function discoverExternalMemoryFiles(claudeHome) {
|
|
|
179
171
|
if (lstatKind(projectsRoot) !== "dir")
|
|
180
172
|
return [];
|
|
181
173
|
const files = [];
|
|
182
|
-
|
|
183
|
-
try {
|
|
184
|
-
projectEntries = fs.readdirSync(projectsRoot, { withFileTypes: true });
|
|
185
|
-
}
|
|
186
|
-
catch {
|
|
187
|
-
return [];
|
|
188
|
-
}
|
|
174
|
+
const projectEntries = fs.readdirSync(projectsRoot, { withFileTypes: true });
|
|
189
175
|
projectEntries.sort((a, b) => a.name.localeCompare(b.name));
|
|
190
176
|
for (const entry of projectEntries) {
|
|
191
177
|
if (!entry.isDirectory() || entry.isSymbolicLink())
|
|
@@ -317,6 +303,14 @@ function removeProjectResources(projectKey) {
|
|
|
317
303
|
fs.rmSync(targetRoot, { recursive: true, force: true });
|
|
318
304
|
return true;
|
|
319
305
|
}
|
|
306
|
+
/** Codex project_has_unscoped_target: keep valid scoped imports when cwd is unavailable. */
|
|
307
|
+
function projectHasUnscopedTarget(projectKey) {
|
|
308
|
+
const target = path.join(memoryRoot(), "extensions", EXTENSION_NAME, "resources", projectKey);
|
|
309
|
+
const kind = lstatKind(target);
|
|
310
|
+
if (kind === "missing")
|
|
311
|
+
return false;
|
|
312
|
+
return kind !== "dir" || lstatKind(path.join(target, PROJECT_SCOPE_FILE)) !== "file";
|
|
313
|
+
}
|
|
320
314
|
function replaceProjectResources(projectKey, projectCwd, projectFiles) {
|
|
321
315
|
// Read all sources first so a mid-copy failure never leaves a half-empty dir
|
|
322
316
|
// after we deleted the previous resources (codex replace_project_resources).
|
|
@@ -372,8 +366,13 @@ export function syncClaudeImport(opts) {
|
|
|
372
366
|
if (!opts.enabled)
|
|
373
367
|
return empty;
|
|
374
368
|
const claudeHome = resolveClaudeHome(opts);
|
|
375
|
-
|
|
376
|
-
|
|
369
|
+
try {
|
|
370
|
+
if (lstatKind(claudeHome) !== "dir")
|
|
371
|
+
return empty;
|
|
372
|
+
}
|
|
373
|
+
catch {
|
|
374
|
+
return empty; // Unreachable home is the documented quiet no-op.
|
|
375
|
+
}
|
|
377
376
|
const allFiles = discoverExternalMemoryFiles(claudeHome);
|
|
378
377
|
const byProject = groupByProject(allFiles);
|
|
379
378
|
const sourceKeys = new Set(byProject.keys());
|
|
@@ -417,8 +416,7 @@ export function syncClaudeImport(opts) {
|
|
|
417
416
|
skippedNoCwd.push(projectKey);
|
|
418
417
|
// Unscoped leftovers under this key → remove (codex project_has_unscoped_target).
|
|
419
418
|
try {
|
|
420
|
-
|
|
421
|
-
if (lstatKind(target) !== "missing") {
|
|
419
|
+
if (projectHasUnscopedTarget(projectKey)) {
|
|
422
420
|
if (removeProjectResources(projectKey)) {
|
|
423
421
|
changed = true;
|
|
424
422
|
synchronizedProjects.push(projectKey);
|
package/dist/src/v2/agents.js
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* hidden definition preserves the health snapshot both agents report into.
|
|
15
15
|
*/
|
|
16
16
|
import path from "path";
|
|
17
|
-
import { memoryRoot } from "../paths.js";
|
|
17
|
+
import { allMemoryRoots, memoryRoot } from "../paths.js";
|
|
18
18
|
import { pluginOptions } from "../options.js";
|
|
19
19
|
import { writeMemoryVersions } from "../memory-version.js";
|
|
20
20
|
import { recordAgentConfig } from "../agent-health.js";
|
|
@@ -35,9 +35,7 @@ export function buildMemorizeAgent() {
|
|
|
35
35
|
// Memories live outside every project: without this grant the wildcard
|
|
36
36
|
// deny blocks consolidation from touching the memory workspace (same
|
|
37
37
|
// role as external_directory in the V1 definition).
|
|
38
|
-
...writeMemoryVersions().flatMap((version) =>
|
|
39
|
-
action, resource: path.join(memoryRoot(version), "*"), effect: "allow",
|
|
40
|
-
}))),
|
|
38
|
+
...writeMemoryVersions().flatMap((version) => workspacePermissions(memoryRoot(version))),
|
|
41
39
|
],
|
|
42
40
|
};
|
|
43
41
|
}
|
|
@@ -45,9 +43,17 @@ export function buildMemorizeAgent() {
|
|
|
45
43
|
export function consolidationPermissions(root) {
|
|
46
44
|
return [
|
|
47
45
|
{ action: "*", resource: "*", effect: "deny" },
|
|
48
|
-
...
|
|
49
|
-
|
|
50
|
-
|
|
46
|
+
...workspacePermissions(root),
|
|
47
|
+
];
|
|
48
|
+
}
|
|
49
|
+
function workspacePermissions(root) {
|
|
50
|
+
return [
|
|
51
|
+
...["read", "edit", "external_directory"].flatMap((action) => [root, path.join(root, "*")].map((resource) => ({
|
|
52
|
+
action, resource, effect: "allow",
|
|
53
|
+
}))),
|
|
54
|
+
// These actions check the search pattern, not a path. search-sandbox.ts
|
|
55
|
+
// wraps the built-in executors to enforce this helper's single root.
|
|
56
|
+
...["glob", "grep"].map((action) => ({ action, resource: "*", effect: "allow" })),
|
|
51
57
|
];
|
|
52
58
|
}
|
|
53
59
|
/**
|
|
@@ -77,6 +83,9 @@ export function toV1AgentDefinition(def, agentId) {
|
|
|
77
83
|
continue;
|
|
78
84
|
}
|
|
79
85
|
if (rule.action === "external_directory") {
|
|
86
|
+
// V1 health expects only root/*; its V1 sandbox already includes root.
|
|
87
|
+
if (allMemoryRoots().includes(rule.resource))
|
|
88
|
+
continue;
|
|
80
89
|
const cur = (permission.external_directory ?? {});
|
|
81
90
|
cur[rule.resource] = rule.effect;
|
|
82
91
|
permission.external_directory = cur;
|
|
@@ -181,7 +190,7 @@ function isShippedIncomplete(id, existing, shipped) {
|
|
|
181
190
|
const perms = existing.permissions;
|
|
182
191
|
if (!Array.isArray(perms))
|
|
183
192
|
return true;
|
|
184
|
-
return !perms.some((rule) => rule &&
|
|
193
|
+
return shipped.permissions.some((expected) => !perms.some((rule) => rule?.action === expected.action && rule?.resource === expected.resource && rule?.effect === expected.effect));
|
|
185
194
|
}
|
|
186
195
|
function v2PermissionsToV1Map(permissions) {
|
|
187
196
|
const out = {};
|
|
@@ -195,6 +204,8 @@ function v2PermissionsToV1Map(permissions) {
|
|
|
195
204
|
continue;
|
|
196
205
|
}
|
|
197
206
|
if (rule.action === "external_directory" && typeof rule.resource === "string") {
|
|
207
|
+
if (allMemoryRoots().includes(rule.resource))
|
|
208
|
+
continue;
|
|
198
209
|
const cur = (out.external_directory ?? {});
|
|
199
210
|
cur[rule.resource] = rule.effect;
|
|
200
211
|
out.external_directory = cur;
|
package/dist/src/v2/plugin.js
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
* - agent.transform → memorize sub-agent provisioning (was config hook)
|
|
14
14
|
* - tool.transform → memory tool registration (was returned tool map)
|
|
15
15
|
*
|
|
16
|
-
* Known V2 adaptations (see
|
|
16
|
+
* Known V2 adaptations (see ARCHITECTURE.md): global session reads use the
|
|
17
17
|
* registered public service; finalized citations are accounted from durable
|
|
18
18
|
* text events and stripped from model-bound context; config documents are
|
|
19
19
|
* adapted for the shared model resolver.
|
|
@@ -34,6 +34,7 @@ import { applyPluginOptions, handleSessionDeleted } from "../index.js";
|
|
|
34
34
|
import { setV2Context, buildV1ClientShim, rememberV2Session, } from "./shim.js";
|
|
35
35
|
import { ensureV2Agents } from "./agents.js";
|
|
36
36
|
import { buildV2Tools } from "./tools.js";
|
|
37
|
+
import { guardMemorySearchTools } from "./search-sandbox.js";
|
|
37
38
|
import { MemoryStatusRpc } from "./status-rpc.js";
|
|
38
39
|
import { readMemoryStatus } from "./status.js";
|
|
39
40
|
import { recordInjection, resetInjectionStats } from "./injection.js";
|
|
@@ -77,8 +78,9 @@ function recordV2Citations(sessionId, assistantMessageId, text) {
|
|
|
77
78
|
withSessionMemoryVersion(sessionId, () => getStore().recordUsageOnce(sessionId, assistantMessageId, ids));
|
|
78
79
|
}
|
|
79
80
|
function stripAndReconcileCitations(sessionId, messages) {
|
|
80
|
-
for (const
|
|
81
|
-
|
|
81
|
+
for (const msg of messages ?? []) {
|
|
82
|
+
// Model-bound LLM.Message uses role; persisted/legacy rows use type.
|
|
83
|
+
if ((msg?.role ?? msg?.type) !== "assistant" || !Array.isArray(msg.content))
|
|
82
84
|
continue;
|
|
83
85
|
for (const part of msg.content) {
|
|
84
86
|
if (part?.type !== "text" || typeof part.text !== "string")
|
|
@@ -86,7 +88,10 @@ function stripAndReconcileCitations(sessionId, messages) {
|
|
|
86
88
|
if (!hasCitationMarkup(part.text))
|
|
87
89
|
continue;
|
|
88
90
|
try {
|
|
89
|
-
|
|
91
|
+
// Context fragments may have no durable id. Inventing one would count
|
|
92
|
+
// the same citation again after text.ended (and after compaction).
|
|
93
|
+
if (typeof msg.id === "string")
|
|
94
|
+
recordV2Citations(sessionId, msg.id, part.text);
|
|
90
95
|
}
|
|
91
96
|
catch (e) {
|
|
92
97
|
console.error("[opencode-codex-memory] citation recording failed:", e);
|
|
@@ -205,7 +210,7 @@ async function triggerPhase2() {
|
|
|
205
210
|
notifyStatusChanged();
|
|
206
211
|
}
|
|
207
212
|
}
|
|
208
|
-
/**
|
|
213
|
+
/** Panel "Consolidate now": one phase-1 pass over idle sessions, then phase 2 without cooldown. */
|
|
209
214
|
async function consolidateNow() {
|
|
210
215
|
notifyStatusChanged();
|
|
211
216
|
try {
|
|
@@ -256,7 +261,20 @@ export async function setup(ctx) {
|
|
|
256
261
|
return { ok: false };
|
|
257
262
|
}
|
|
258
263
|
}
|
|
264
|
+
const previous = pluginOptions[key];
|
|
259
265
|
pluginOptions[key] = value;
|
|
266
|
+
if (key === "use_memories" && value !== previous) {
|
|
267
|
+
try {
|
|
268
|
+
// Transforms capture options but the host only replays them after an
|
|
269
|
+
// explicit registry invalidation. Affect future tool snapshots now.
|
|
270
|
+
await ctx.tool.reload();
|
|
271
|
+
}
|
|
272
|
+
catch (error) {
|
|
273
|
+
pluginOptions[key] = previous;
|
|
274
|
+
console.error("[opencode-codex-memory] failed to reload V2 memory tools:", error);
|
|
275
|
+
return { ok: false };
|
|
276
|
+
}
|
|
277
|
+
}
|
|
260
278
|
invalidateCache();
|
|
261
279
|
notifyStatusChanged();
|
|
262
280
|
return { ok: true };
|
|
@@ -282,6 +300,7 @@ export async function setup(ctx) {
|
|
|
282
300
|
});
|
|
283
301
|
};
|
|
284
302
|
await ctx.tool.transform((editor) => {
|
|
303
|
+
guardMemorySearchTools(editor, (sessionID) => ctx.session.get({ sessionID }));
|
|
285
304
|
for (const t of buildV2Tools())
|
|
286
305
|
editor.add(t);
|
|
287
306
|
});
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { allMemoryRoots } from "../paths.js";
|
|
3
|
+
import { safeResolveUnderRoot } from "../path-guard.js";
|
|
4
|
+
import { MEMORIZE_AGENT_ID } from "./agents.js";
|
|
5
|
+
/** Pattern permissions cannot constrain paths. Wrap executors, not fail-open hooks. */
|
|
6
|
+
export function guardMemorySearchTools(editor, getSession) {
|
|
7
|
+
const roots = allMemoryRoots();
|
|
8
|
+
for (const name of ["glob", "grep"]) {
|
|
9
|
+
editor.update(name, (tool) => {
|
|
10
|
+
const execute = tool.execute;
|
|
11
|
+
tool.execute = async (input, context) => {
|
|
12
|
+
if (context.agent !== MEMORIZE_AGENT_ID)
|
|
13
|
+
return execute(input, context);
|
|
14
|
+
const response = await getSession(context.sessionID);
|
|
15
|
+
const session = response?.data ?? response;
|
|
16
|
+
// Helper permissions persist across plugin reloads and select one writer
|
|
17
|
+
// even during dual-write. Never fall back to the active project or version.
|
|
18
|
+
const allowed = roots.filter((root) => session?.permissions?.some((rule) => rule.action === "read" && rule.resource === root && rule.effect === "allow"));
|
|
19
|
+
if (allowed.length !== 1)
|
|
20
|
+
throw new Error("memory search requires one session-scoped memory workspace");
|
|
21
|
+
const root = allowed[0];
|
|
22
|
+
const requested = input.path ?? ".";
|
|
23
|
+
if (typeof requested !== "string")
|
|
24
|
+
throw new Error("invalid memory search path");
|
|
25
|
+
const target = safeResolveUnderRoot(root, path.relative(root, path.resolve(root, requested)));
|
|
26
|
+
if (name === "glob" && (path.isAbsolute(input.pattern) || /(^|[\\/,{])\.\.([\\/},]|$)/.test(input.pattern))) {
|
|
27
|
+
throw new Error("glob pattern escapes memory workspace");
|
|
28
|
+
}
|
|
29
|
+
return execute({ ...input, path: target }, context);
|
|
30
|
+
};
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
}
|
package/dist/src/v2/service.d.ts
CHANGED
|
@@ -59,6 +59,8 @@ export declare function setV2ServiceDependenciesForTest(dependencies: V2ServiceD
|
|
|
59
59
|
export declare function invalidateOwnService(): void;
|
|
60
60
|
/** Last discoverOwnService failure, if ownServiceClient returned null. */
|
|
61
61
|
export declare function lastServiceFailure(): string | null;
|
|
62
|
+
/** Invalidate broken endpoints for the next call. Never replay mutations or generation. */
|
|
63
|
+
export declare function serviceRequest<T>(client: V2ServiceClient, request: () => Promise<T>): Promise<T>;
|
|
62
64
|
/** Auth headers for the registered local service. */
|
|
63
65
|
export declare function serviceHeaders(endpoint: V2ServiceEndpoint): Record<string, string> | undefined;
|
|
64
66
|
export declare function parseReadyStatus(body: unknown): V2ServiceStatus | null;
|
package/dist/src/v2/service.js
CHANGED
|
@@ -15,22 +15,57 @@ import { OpenCode } from "@opencode/client";
|
|
|
15
15
|
import { Service } from "@opencode/client/service";
|
|
16
16
|
let testDependencies = null;
|
|
17
17
|
let clientPromise = null;
|
|
18
|
+
let cachedClient = null;
|
|
18
19
|
let lastFailure = null;
|
|
19
20
|
const SERVICE_REQUEST_TIMEOUT_MS = 3_000;
|
|
20
21
|
/** Test seam: replace discovery without changing the production connection path. */
|
|
21
22
|
export function setV2ServiceDependenciesForTest(dependencies) {
|
|
22
23
|
testDependencies = dependencies;
|
|
23
|
-
|
|
24
|
+
invalidateOwnService();
|
|
24
25
|
}
|
|
25
26
|
/** Forget a cached endpoint after a service restart or failed request. */
|
|
26
27
|
export function invalidateOwnService() {
|
|
27
28
|
clientPromise = null;
|
|
29
|
+
cachedClient = null;
|
|
28
30
|
lastFailure = null;
|
|
29
31
|
}
|
|
30
32
|
/** Last discoverOwnService failure, if ownServiceClient returned null. */
|
|
31
33
|
export function lastServiceFailure() {
|
|
32
34
|
return lastFailure;
|
|
33
35
|
}
|
|
36
|
+
function connectionFailed(error) {
|
|
37
|
+
let failed = false;
|
|
38
|
+
const seen = new Set();
|
|
39
|
+
for (let current = error; current && !seen.has(current); current = current.cause ?? current.error) {
|
|
40
|
+
seen.add(current);
|
|
41
|
+
if (current.name === "AbortError")
|
|
42
|
+
return false;
|
|
43
|
+
const status = current.status ?? current.statusCode ?? current.response?.status;
|
|
44
|
+
if (status === 401 || status === 403 || current.reason === "Transport")
|
|
45
|
+
failed = true;
|
|
46
|
+
if (/ECONNREFUSED|ECONNRESET|EPIPE|ENOTFOUND|ETIMEDOUT|fetch failed|unauthori[sz]ed/i.test([current.code, current.type, current._tag, current.name, current.message].join(" ")))
|
|
47
|
+
failed = true;
|
|
48
|
+
}
|
|
49
|
+
return failed;
|
|
50
|
+
}
|
|
51
|
+
/** Invalidate broken endpoints for the next call. Never replay mutations or generation. */
|
|
52
|
+
export async function serviceRequest(client, request) {
|
|
53
|
+
const invalidate = (error) => {
|
|
54
|
+
if (client === cachedClient && connectionFailed(error)) {
|
|
55
|
+
invalidateOwnService();
|
|
56
|
+
lastFailure = error instanceof Error ? error.message : "registered OpenCode service connection failed";
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
try {
|
|
60
|
+
const result = await request();
|
|
61
|
+
invalidate(result?.error);
|
|
62
|
+
return result;
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
invalidate(error);
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
34
69
|
/** Auth headers for the registered local service. */
|
|
35
70
|
export function serviceHeaders(endpoint) {
|
|
36
71
|
return Service.headers(endpoint);
|
|
@@ -192,17 +227,21 @@ export async function ownServiceClient() {
|
|
|
192
227
|
if (!clientPromise) {
|
|
193
228
|
const request = discoverOwnService()
|
|
194
229
|
.then((found) => {
|
|
195
|
-
|
|
230
|
+
if (clientPromise === request) {
|
|
231
|
+
cachedClient = found?.client ?? null;
|
|
232
|
+
lastFailure = found ? null : "no registered OpenCode 2 service.json";
|
|
233
|
+
}
|
|
196
234
|
return found?.client ?? null;
|
|
197
235
|
})
|
|
198
236
|
.catch((err) => {
|
|
199
|
-
|
|
237
|
+
if (clientPromise === request)
|
|
238
|
+
lastFailure = err instanceof Error ? err.message : String(err);
|
|
200
239
|
console.warn("[opencode-codex-memory] registered OpenCode service unavailable:", err);
|
|
201
240
|
return null;
|
|
202
241
|
});
|
|
203
242
|
clientPromise = request;
|
|
204
243
|
const result = await request;
|
|
205
|
-
if (!result)
|
|
244
|
+
if (!result && clientPromise === request)
|
|
206
245
|
clientPromise = null;
|
|
207
246
|
return result;
|
|
208
247
|
}
|
package/dist/src/v2/shim.d.ts
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
* the V1 shutdown/liveness logic keeps working across hosts.
|
|
19
19
|
* - config.get → public service config documents adapted for the V1 resolver;
|
|
20
20
|
* callers fall back to session defaults if the service is unavailable.
|
|
21
|
-
* - provider.list →
|
|
21
|
+
* - provider.list → model.list adapted to the V1 catalog shape for
|
|
22
22
|
* reasoning-variant mapping.
|
|
23
23
|
* - mcp.status → mcp.list adapted to the V1 status map.
|
|
24
24
|
*
|
|
@@ -49,7 +49,7 @@ export declare function adaptV2Messages(msgs: unknown): Array<{
|
|
|
49
49
|
};
|
|
50
50
|
parts?: unknown[];
|
|
51
51
|
}>;
|
|
52
|
-
/** V2 catalog.model.list → V1 provider-list shape
|
|
52
|
+
/** V2 model.list (legacy catalog.model.list) → V1 provider-list shape. */
|
|
53
53
|
export declare function adaptProviderCatalog(v2: unknown): unknown;
|
|
54
54
|
/** V2 mcp.list → V1 mcp.status map shape. */
|
|
55
55
|
export declare function adaptMcpStatus(v2: unknown): unknown;
|
package/dist/src/v2/shim.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { memoryRoot } from "../paths.js";
|
|
2
2
|
import { consolidationPermissions } from "./agents.js";
|
|
3
|
-
import { invalidateOwnService, lastServiceFailure, ownServiceClient } from "./service.js";
|
|
3
|
+
import { invalidateOwnService, lastServiceFailure, ownServiceClient, serviceRequest } from "./service.js";
|
|
4
4
|
let v2ctx = null;
|
|
5
5
|
export function setV2Context(ctx) {
|
|
6
6
|
v2ctx = ctx;
|
|
@@ -33,7 +33,7 @@ async function sessionGoneOnService(client, sessionID) {
|
|
|
33
33
|
if (typeof client.session.get !== "function")
|
|
34
34
|
return false;
|
|
35
35
|
try {
|
|
36
|
-
const info = await client.session.get({ sessionID });
|
|
36
|
+
const info = await serviceRequest(client, () => client.session.get({ sessionID }));
|
|
37
37
|
if (info?.error && isNotFoundError(info.error)) {
|
|
38
38
|
return true;
|
|
39
39
|
}
|
|
@@ -205,7 +205,7 @@ export function adaptV2Messages(msgs) {
|
|
|
205
205
|
}
|
|
206
206
|
return rows;
|
|
207
207
|
}
|
|
208
|
-
/** V2 catalog.model.list → V1 provider-list shape
|
|
208
|
+
/** V2 model.list (legacy catalog.model.list) → V1 provider-list shape. */
|
|
209
209
|
export function adaptProviderCatalog(v2) {
|
|
210
210
|
const items = und(v2);
|
|
211
211
|
const list = Array.isArray(items) ? items : items?.data ?? [];
|
|
@@ -214,7 +214,9 @@ export function adaptProviderCatalog(v2) {
|
|
|
214
214
|
if (!m || typeof m !== "object")
|
|
215
215
|
continue;
|
|
216
216
|
const providerID = m.providerID;
|
|
217
|
-
|
|
217
|
+
// id is the selectable OpenCode alias; modelID can be a different provider
|
|
218
|
+
// wire name. Legacy catalogs exposed only modelID.
|
|
219
|
+
const modelID = m.id ?? m.modelID;
|
|
218
220
|
if (typeof providerID !== "string" || typeof modelID !== "string")
|
|
219
221
|
continue;
|
|
220
222
|
if (!providers.has(providerID))
|
|
@@ -226,7 +228,7 @@ export function adaptProviderCatalog(v2) {
|
|
|
226
228
|
}
|
|
227
229
|
}
|
|
228
230
|
;
|
|
229
|
-
providers.get(providerID)[modelID] = { variants };
|
|
231
|
+
providers.get(providerID)[modelID] = { ...(m.variants !== undefined ? { variants } : {}) };
|
|
230
232
|
}
|
|
231
233
|
return { all: [...providers.entries()].map(([id, models]) => ({ id, models })) };
|
|
232
234
|
}
|
|
@@ -264,6 +266,60 @@ function responseNextCursor(response) {
|
|
|
264
266
|
const next = direct ?? payload?.cursor?.next;
|
|
265
267
|
return typeof next === "string" && next.length > 0 ? next : undefined;
|
|
266
268
|
}
|
|
269
|
+
/** Read durable messages in source order, including terminal errors/idle rows. */
|
|
270
|
+
async function loadV2Messages(sessionID, context, signal) {
|
|
271
|
+
const client = await ownServiceClient();
|
|
272
|
+
if (typeof client?.message?.list === "function") {
|
|
273
|
+
const messages = [];
|
|
274
|
+
const seenCursors = new Set();
|
|
275
|
+
let cursor;
|
|
276
|
+
while (true) {
|
|
277
|
+
const response = await serviceRequest(client, () => client.message.list(cursor ? { sessionID, cursor } : { sessionID, order: "asc" }, signal ? { signal } : undefined));
|
|
278
|
+
const rows = responseRows(response);
|
|
279
|
+
if (!rows)
|
|
280
|
+
throw new Error("registered service returned an invalid message list");
|
|
281
|
+
messages.push(...rows);
|
|
282
|
+
const next = responseNextCursor(response);
|
|
283
|
+
if (!next)
|
|
284
|
+
return messages;
|
|
285
|
+
if (seenCursors.has(next))
|
|
286
|
+
throw new Error("registered service repeated a message cursor");
|
|
287
|
+
seenCursors.add(next);
|
|
288
|
+
cursor = next;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
const raw = await (context ?? ctx()).session.context({ sessionID });
|
|
292
|
+
const rows = responseRows(raw);
|
|
293
|
+
if (!rows)
|
|
294
|
+
throw new Error("session context returned an invalid message list");
|
|
295
|
+
return rows;
|
|
296
|
+
}
|
|
297
|
+
function completedPromptResponse(rows, promptID) {
|
|
298
|
+
const boundary = typeof promptID === "string" ? rows.findIndex((m) => m?.id === promptID && m.type === "user") : -1;
|
|
299
|
+
if (boundary < 0)
|
|
300
|
+
throw new Error("submitted prompt missing from consolidation transcript");
|
|
301
|
+
const turn = rows.slice(boundary + 1);
|
|
302
|
+
const nextUser = turn.findIndex((m) => m?.type === "user");
|
|
303
|
+
const messages = nextUser < 0 ? turn : turn.slice(0, nextUser);
|
|
304
|
+
const assistant = messages.findLast((m) => m?.type === "assistant");
|
|
305
|
+
if (!assistant)
|
|
306
|
+
throw new Error("no assistant reply after consolidation wait");
|
|
307
|
+
if (assistant.error) {
|
|
308
|
+
// V1 runPrompt recognizes info.error, including its quota status code.
|
|
309
|
+
const error = assistant.error;
|
|
310
|
+
return { data: { info: { error: {
|
|
311
|
+
name: error.type ?? error.name,
|
|
312
|
+
data: { message: error.message ?? error.data?.message, statusCode: error.status ?? error.statusCode ?? error.data?.statusCode },
|
|
313
|
+
} }, parts: [] } };
|
|
314
|
+
}
|
|
315
|
+
const idle = messages.findLast((m) => m?.type === "idle");
|
|
316
|
+
if (idle && idle.outcome !== "succeeded")
|
|
317
|
+
throw new Error(`consolidation ${idle.outcome} after session.wait`);
|
|
318
|
+
if (!assistant.time?.completed || !["stop", "length", "content-filter"].includes(assistant.finish)) {
|
|
319
|
+
throw new Error(`consolidation turn incomplete after session.wait (${assistant.finish ?? "no finish"})`);
|
|
320
|
+
}
|
|
321
|
+
return { data: { info: {}, parts: [{ type: "text", text: joinTextParts(assistant.content) }] } };
|
|
322
|
+
}
|
|
267
323
|
function adaptV2SessionRow(row) {
|
|
268
324
|
if (!row || typeof row !== "object")
|
|
269
325
|
return row;
|
|
@@ -303,7 +359,7 @@ async function v2promptWithWait(sessionID, body, signal) {
|
|
|
303
359
|
throw new Error("sub-agent prompt cancelled");
|
|
304
360
|
const publicClient = await ownServiceClient();
|
|
305
361
|
if (typeof publicClient?.generate?.text === "function") {
|
|
306
|
-
const gen = await publicClient.generate.text(payload, signal ? { signal } : undefined);
|
|
362
|
+
const gen = await serviceRequest(publicClient, () => publicClient.generate.text(payload, signal ? { signal } : undefined));
|
|
307
363
|
const outText = typeof gen?.text === "string" ? gen.text : JSON.stringify(gen);
|
|
308
364
|
return { data: { parts: [{ type: "text", text: outText }] } };
|
|
309
365
|
}
|
|
@@ -358,7 +414,9 @@ async function v2promptWithWait(sessionID, body, signal) {
|
|
|
358
414
|
else {
|
|
359
415
|
await waitP;
|
|
360
416
|
}
|
|
361
|
-
|
|
417
|
+
// wait means idle, not successful. Codex requires Completed before phase 2
|
|
418
|
+
// may validate artifacts and reset the last-successful workspace baseline.
|
|
419
|
+
return completedPromptResponse(await loadV2Messages(sessionID, c, signal), und(posted)?.id);
|
|
362
420
|
}
|
|
363
421
|
/** Build the V1-shaped client. Passed to setPluginInput() by V2 setup(). */
|
|
364
422
|
export function buildV1ClientShim() {
|
|
@@ -418,7 +476,7 @@ export function buildV1ClientShim() {
|
|
|
418
476
|
}
|
|
419
477
|
const client = await ownServiceClient();
|
|
420
478
|
if (client && typeof client.session.list === "function") {
|
|
421
|
-
return paginateSessionList((input) => client.session.list(input), limit, cursor, search);
|
|
479
|
+
return paginateSessionList((input) => serviceRequest(client, () => client.session.list(input)), limit, cursor, search);
|
|
422
480
|
}
|
|
423
481
|
if (client)
|
|
424
482
|
throw new Error("registered service does not support session.list");
|
|
@@ -463,30 +521,7 @@ export function buildV1ClientShim() {
|
|
|
463
521
|
try {
|
|
464
522
|
if (isReleasedSubSession(opts.path.id))
|
|
465
523
|
throw Object.assign(new Error("SessionNotFound"), { _tag: "SessionNotFoundError" });
|
|
466
|
-
|
|
467
|
-
if (typeof client?.message?.list === "function") {
|
|
468
|
-
const messages = [];
|
|
469
|
-
const seenCursors = new Set();
|
|
470
|
-
let cursor;
|
|
471
|
-
while (true) {
|
|
472
|
-
const response = await client.message.list(cursor ? { sessionID: opts.path.id, cursor } : { sessionID: opts.path.id, order: "asc" });
|
|
473
|
-
const rows = responseRows(response);
|
|
474
|
-
if (!rows)
|
|
475
|
-
throw new Error("registered service returned an invalid message list");
|
|
476
|
-
messages.push(...rows);
|
|
477
|
-
const next = responseNextCursor(response);
|
|
478
|
-
if (!next || seenCursors.has(next))
|
|
479
|
-
break;
|
|
480
|
-
seenCursors.add(next);
|
|
481
|
-
cursor = next;
|
|
482
|
-
}
|
|
483
|
-
return { data: adaptV2Messages(messages) };
|
|
484
|
-
}
|
|
485
|
-
const raw = await ctx().session.context({
|
|
486
|
-
sessionID: opts.path.id,
|
|
487
|
-
});
|
|
488
|
-
const rows = Array.isArray(raw) ? raw : responseRows(raw) ?? [];
|
|
489
|
-
return { data: adaptV2Messages(rows) };
|
|
524
|
+
return { data: adaptV2Messages(await loadV2Messages(opts.path.id)) };
|
|
490
525
|
}
|
|
491
526
|
catch (e) {
|
|
492
527
|
return { error: e };
|
|
@@ -504,7 +539,7 @@ export function buildV1ClientShim() {
|
|
|
504
539
|
const client = await serviceOrThrow();
|
|
505
540
|
if (typeof client.session.remove !== "function")
|
|
506
541
|
throw new Error("registered service does not support session.remove");
|
|
507
|
-
const result = await client.session.remove({ sessionID: opts.path.id }, opts.signal ? { signal: opts.signal } : undefined);
|
|
542
|
+
const result = await serviceRequest(client, () => client.session.remove({ sessionID: opts.path.id }, opts.signal ? { signal: opts.signal } : undefined));
|
|
508
543
|
if (result?.error)
|
|
509
544
|
throw result.error;
|
|
510
545
|
if (await sessionGoneOnService(client, opts.path.id)) {
|
|
@@ -530,7 +565,7 @@ export function buildV1ClientShim() {
|
|
|
530
565
|
try {
|
|
531
566
|
const client = await ownServiceClient();
|
|
532
567
|
if (client?.session?.get) {
|
|
533
|
-
const info = await client.session.get({ sessionID: opts.path.id });
|
|
568
|
+
const info = await serviceRequest(client, () => client.session.get({ sessionID: opts.path.id }));
|
|
534
569
|
if (info?.error && isNotFoundError(info.error)) {
|
|
535
570
|
markReleased(opts.path.id);
|
|
536
571
|
return {};
|
|
@@ -563,7 +598,7 @@ export function buildV1ClientShim() {
|
|
|
563
598
|
const client = await ownServiceClient();
|
|
564
599
|
if (client?.session?.get) {
|
|
565
600
|
try {
|
|
566
|
-
const info = und(await client.session.get({ sessionID: opts.path.id }));
|
|
601
|
+
const info = und(await serviceRequest(client, () => client.session.get({ sessionID: opts.path.id })));
|
|
567
602
|
return { data: info };
|
|
568
603
|
}
|
|
569
604
|
catch (e) {
|
|
@@ -588,7 +623,7 @@ export function buildV1ClientShim() {
|
|
|
588
623
|
const client = await serviceOrThrow();
|
|
589
624
|
if (typeof client.session.interrupt !== "function")
|
|
590
625
|
throw new Error("registered service does not support session.interrupt");
|
|
591
|
-
const result = await client.session.interrupt({ sessionID: opts.path.id });
|
|
626
|
+
const result = await serviceRequest(client, () => client.session.interrupt({ sessionID: opts.path.id }));
|
|
592
627
|
if (!result?.error)
|
|
593
628
|
return {};
|
|
594
629
|
}
|
|
@@ -608,7 +643,7 @@ export function buildV1ClientShim() {
|
|
|
608
643
|
get: async () => {
|
|
609
644
|
try {
|
|
610
645
|
const client = await serviceOrThrow();
|
|
611
|
-
const response = await client.config?.get({ location: { directory: ctx().location.directory } });
|
|
646
|
+
const response = await serviceRequest(client, async () => client.config?.get({ location: { directory: ctx().location.directory } }));
|
|
612
647
|
const documents = und(response);
|
|
613
648
|
const candidates = Array.isArray(documents) ? documents : documents?.type === "document" ? [documents] : [];
|
|
614
649
|
let info = {};
|
|
@@ -639,7 +674,11 @@ export function buildV1ClientShim() {
|
|
|
639
674
|
const provider = {
|
|
640
675
|
list: async () => {
|
|
641
676
|
try {
|
|
642
|
-
const
|
|
677
|
+
const c = ctx();
|
|
678
|
+
const models = c.model ?? c.catalog?.model;
|
|
679
|
+
if (typeof models?.list !== "function")
|
|
680
|
+
throw new Error("host does not support model.list");
|
|
681
|
+
const res = await models.list();
|
|
643
682
|
return { data: adaptProviderCatalog(res) };
|
|
644
683
|
}
|
|
645
684
|
catch (e) {
|