You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by "Joob1n (via GitHub)" <gi...@apache.org> on 2026/08/24 03:53:59 UTC

[PR] feat(storage): import opencode sessions through ExternalSessionAdapter [maka]

Joob1n opened a new pull request, #3671:
URL: https://github.com/apache/maka/pull/3671

   ## Summary
   
   A user with history in opencode had no way to bring it into Maka. This adds `OpenCodeSessionAdapter` and registers it, so the source-agnostic importer gains a third source without the importer or the persistence path changing — the property #2499 asked for.
   
   **The storage layout in the issue body is obsolete.** It documents a `storage/session/{info,message,part}` JSON tree plus a migration between two directory layouts. On opencode 1.18.21 neither exists — `find ~/.local/share/opencode -name '*.json'` returns nothing. State is one SQLite database at `~/.local/share/opencode/opencode.db`, which the CLI will name with `opencode db path`. A conversation is `session` plus `message` and `part`, each keeping its payload in an opaque `data` JSON column. Full findings are in [this comment](https://github.com/apache/maka/issues/3403#issuecomment-5390400252).
   
   **Turn state is derivable, so this does not inherit the Ledger constraint discussed on #3142.** Read from captured sessions rather than from the binary:
   
   - `step-finish` is durably persisted, carrying `reason`, tokens and cost;
   - the field is `time.completed`, not `time.end`, and it is set on every assistant message — including the aborted one;
   - `finish` is `stop` on a closing step, `tool-calls` on an intermediate one, and absent on a message carrying `error.name: "MessageAbortedError"`.
   
   So a turn closes as `completed` only on `stop`, as `aborted` on an abort error, and as `aborted` when the last step asked for tools and no answer followed. A run stopped between a call and its result did not complete, and recording it as completed would assert a reply the session never produced.
   
   **Two shapes had no captured sample, and both fail closed rather than guess.** Every `tool` part observed had `state.status: "completed"` (6 of 6), so a call in any other status is imported without a synthesised result. A child session (`parent_id` set) is neither listed nor readable as a conversation, since it is one leg of a parent dialogue rather than something a user started.
   
   Part of #2499. Fixes #3403
   
   ## Verification
   
   New suite, 11 tests:
   
   ```
   $ node --test packages/storage/dist/__tests__/opencode-session-adapter.test.js
   ℹ tests 11
   ℹ pass 11
   ℹ fail 0
   ```
   
   The three load-bearing rules of the mapping were mutation-checked — each break turns the suite red, so the tests fail without the change rather than merely running alongside it:
   
   | Mutation | Result |
   |---|---|
   | stop filtering non-completed tool calls | 10 pass, **1 fail** |
   | stop recognising `MessageAbortedError` | 10 pass, **1 fail** |
   | stop filtering child sessions | 10 pass, **1 fail** |
   
   Every emitted message is asserted to survive `decodeCanonicalMessage`, so an import is rejected here rather than at the persistence boundary.
   
   Whole package, plus the dependent that consumes the registry:
   
   ```
   $ node --test --test-concurrency=2 "packages/storage/dist/__tests__/*.test.js"
   ℹ tests 931
   ℹ pass 917
   ℹ fail 0
   
   $ npm --workspace @maka/runtime-host run build     clean
   $ npm run format:check    Checked 1608 files. No fixes applied.
   $ npx biome lint <the two new files>   no findings
   ```
   
   ## Fixture
   
   `opencode-session-1.18.21.json` is a real captured session — two file reads, three commands, one write, and a final aborted message — exported with `opencode db`. Paths are rewritten to `/workspace/project` and `/home/user`, and tool output longer than 400 characters is truncated. Record shapes are verbatim, because the shapes are the thing under test.
   
   ## AI use
   
   Select exactly one:
   
   - [ ] No generative tool made a substantive contribution
   - [x] Generative tooling made a substantive contribution
   
   Tool(s) and scope: Claude Opus 5 via Claude Code — read the live database to establish the current format, captured and sanitised the fixture, wrote the adapter and its tests, and ran the mutation checks. Every claim above came from running the command shown against real opencode data. The commit carries a `Generated-by` trailer.
   
   ## Checklist
   
   - [x] Tests cover the change and fail without it
   - [x] Lint, format, typecheck and the affected suites pass locally
   
   Does this PR entail a change in behavior?
   
   - [x] Yes — described under Summary above
   - [ ] No
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(storage): import opencode sessions through ExternalSessionAdapter [maka]

Posted by "Joob1n (via GitHub)" <gi...@apache.org>.
Joob1n commented on PR #3671:
URL: https://github.com/apache/maka/pull/3671#issuecomment-5390972625

   Thank you — all three are real, and two of them I had not seen. Fixed in `e0506ba`.
   
   **[P2] Terminal tool failures.** You are right that `status !== 'completed'` is not "in flight". I checked the installed 1.18.21 binary rather than only the linked types: the union is `pending | running | completed | error`, and the error state is recorded as `{ status: "error", input, error: <string>, metadata, time }` — including the `"Tool execution aborted"` and `"Cancelled"` cases. `error` now emits a `tool_result` with `isError: true` carrying the recorded message. `pending` and `running` still get none, since those are the calls that genuinely had no answer.
   
   Your reproduction is now a test: user → assistant `finish: "tool-calls"` holding `{status:"error", input:{...}, error:"exit 1"}` → assistant `finish:"stop"`. It asserts the errored result exists and pairs with the call, so a persisted failure can no longer be rewritten as an unresolved call inside a completed turn.
   
   **[P2] Source part order.** Also right, and the fixture hid it exactly as you say — every mixed assistant message in the capture happens to be reasoning-first. The three passes are gone; parts are walked once in recorded order. The new test feeds `text → reasoning → tool` and asserts the import comes out `text → thinking → tool_call → tool_result`.
   
   **[P2] Transcript read failure.** This one overlapped a defect I found in my own review and fixed in `9a0e526` — but I fixed only half of it. The read failure now throws, which covers your missing-tables reproduction; what I had left in place was the silent filtering of undecodable rows at what were lines 187-195, so a transcript could still import a message or a part short while reporting success. That is fixed too: a selected import now carries what the session recorded or fails. Discovery and listing stay best-effort, as you suggested.
   
   Each fix is pinned by reverting it: dropping terminal failures fails 1 test, restoring the silent row filter fails 1, re-bucketing parts by type fails 1.
   
   `@maka/storage`: 938 tests, 0 failures.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(storage): import opencode sessions through ExternalSessionAdapter [maka]

Posted by "likun666661 (via GitHub)" <gi...@apache.org>.
likun666661 merged PR #3671:
URL: https://github.com/apache/maka/pull/3671


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(storage): import opencode sessions through ExternalSessionAdapter [maka]

Posted by "M4n5ter (via GitHub)" <gi...@apache.org>.
M4n5ter commented on code in PR #3671:
URL: https://github.com/apache/maka/pull/3671#discussion_r3840666209


##########
packages/storage/src/opencode-session-adapter.ts:
##########
@@ -0,0 +1,502 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+// opencode sessions as Maka Sessions.
+//
+// State lives in one SQLite database, `~/.local/share/opencode/opencode.db`,
+// which the CLI itself will name (`opencode db path`). Earlier releases wrote
+// a `storage/session/{info,message,part}` JSON tree; that layout is gone, so
+// this reads the database and nothing else. Verified against 1.18.21.
+//
+// A conversation is three tables. `session` holds identity and `directory`,
+// which is the cwd a project-scoped query reads. `message` and `part` each
+// keep their payload in an opaque `data` JSON column — the schema names the
+// container, the column names the shape.
+//
+// Turn state is derivable here, unlike a Claude Code transcript: every
+// assistant message records `time.completed`, and `finish` is `stop` on a
+// closing step, `tool-calls` on an intermediate one, and absent on a message
+// that was aborted, which also carries `error.name`.
+import { existsSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+import { externalSessionMatchesQuery } from '@maka/core/external-session';
+import type {
+  ExternalMakaSession,
+  ExternalSessionAdapter,
+  ExternalSessionQuery,
+  ExternalSessionSummary,
+} from '@maka/core/external-session';
+import { sanitizeForeignTitle } from '@maka/core/foreign-session';
+import type { StoredMessage } from '@maka/core/session';
+
+export const OPENCODE_SESSION_ADAPTER_ID = 'opencode';
+
+const EXTERNAL_SNAPSHOT_ABORT_SOURCE = 'external_session_snapshot';
+
+/** Guards the value interpolated into no SQL, but read back out of one. */
+const SESSION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/u;
+
+export interface OpenCodeSessionAdapterOptions {
+  /** Overrides `~/.local/share/opencode`. */
+  opencodeHome?: string;
+}
+
+interface SessionRow {
+  readonly id: string;
+  readonly title: string;
+  readonly directory: string;
+  readonly timeCreated?: number;
+  readonly timeUpdated?: number;
+  readonly archived: boolean;
+  readonly parentId?: string;
+}
+
+interface MessageRow {
+  readonly id: string;
+  readonly timeCreated: number;
+  readonly data: Record<string, unknown>;
+}
+
+interface PartRow {
+  readonly messageId: string;
+  readonly data: Record<string, unknown>;
+}
+
+export class OpenCodeSessionAdapter implements ExternalSessionAdapter {
+  readonly id = OPENCODE_SESSION_ADAPTER_ID;
+  readonly #home: string;
+
+  constructor(options: OpenCodeSessionAdapterOptions = {}) {
+    this.#home = options.opencodeHome ?? join(homedir(), '.local', 'share', 'opencode');
+  }
+
+  async detect(): Promise<boolean> {
+    return existsSync(this.#databasePath());
+  }
+
+  async listSessions(query?: ExternalSessionQuery): Promise<readonly ExternalSessionSummary[]> {
+    const rows = await this.#readSessions();
+    const summaries: ExternalSessionSummary[] = [];
+    for (const row of rows) {
+      // A child session is one operator's leg of a parent conversation, not a
+      // conversation a user started. Listing it offers an import of half a
+      // dialogue whose other half is a separate entry.
+      if (row.parentId !== undefined) continue;
+      const summary = toSummary(row);
+      if (externalSessionMatchesQuery(summary, query)) summaries.push(summary);
+    }
+    summaries.sort((left, right) => (right.updatedAt ?? 0) - (left.updatedAt ?? 0));
+    return summaries;
+  }
+
+  async readSession(sessionId: string): Promise<ExternalMakaSession> {
+    if (!SESSION_ID_PATTERN.test(sessionId)) {
+      throw new Error(`opencode session id is not usable: ${sessionId}`);
+    }
+    const rows = await this.#readSessions();
+    const row = rows.find((candidate) => candidate.id === sessionId);
+    if (!row) throw new Error(`opencode session not found: ${sessionId}`);
+    if (row.parentId !== undefined) {
+      throw new Error(`opencode session is a child of another session: ${sessionId}`);
+    }
+    const { messages, parts } = await this.#readTranscript(sessionId);
+    return {
+      sourceSessionId: sessionId,
+      metadata: { name: row.title || sessionId, cwd: row.directory },
+      messages: convertTranscript(sessionId, messages, parts),
+    };
+  }
+
+  #databasePath(): string {
+    return join(this.#home, 'opencode.db');
+  }
+
+  async #withDatabase<T>(read: (db: OpenCodeDatabase) => T): Promise<T | undefined> {
+    const path = this.#databasePath();
+    if (!existsSync(path)) return undefined;
+    let sqlite: typeof import('node:sqlite');
+    try {
+      sqlite = await import('node:sqlite');
+    } catch {
+      return undefined;
+    }
+    let db: OpenCodeDatabase;
+    try {
+      db = new sqlite.DatabaseSync(path, { readOnly: true }) as OpenCodeDatabase;
+    } catch {
+      return undefined;
+    }
+    try {
+      return read(db);
+    } catch {
+      return undefined;
+    } finally {
+      try {
+        db.close();
+      } catch {
+        // A close that fails leaves nothing for a reader to do; the process
+        // releases the handle either way, and throwing here would replace a
+        // usable result with an error about cleanup.
+      }
+    }
+  }
+
+  async #readSessions(): Promise<readonly SessionRow[]> {
+    const rows = await this.#withDatabase((db) => {
+      const columns = tableColumns(db, 'session');
+      if (!columns.has('id') || !columns.has('directory')) return undefined;
+      const selected = [
+        'id',
+        'title',
+        'directory',
+        'time_created',
+        'time_updated',
+        'time_archived',
+        'parent_id',
+      ].filter((column) => columns.has(column));
+      const raw = db.prepare(`SELECT ${selected.join(', ')} FROM session`).all();
+      return raw.map(toSessionRow).filter((row): row is SessionRow => row !== undefined);
+    });
+    return rows ?? [];
+  }
+
+  async #readTranscript(
+    sessionId: string,
+  ): Promise<{ messages: readonly MessageRow[]; parts: readonly PartRow[] }> {
+    const read = await this.#withDatabase((db) => {
+      const messages = db
+        .prepare('SELECT id, time_created, data FROM message WHERE session_id = ?')
+        .all(sessionId)
+        .map(toMessageRow)
+        .filter((row): row is MessageRow => row !== undefined);
+      // Ordered by the message they belong to and then by their own id, which
+      // is how the writer orders them; `time_created` ties within one step.
+      const parts = db
+        .prepare('SELECT message_id, data FROM part WHERE session_id = ? ORDER BY time_created, id')
+        .all(sessionId)
+        .map(toPartRow)
+        .filter((row): row is PartRow => row !== undefined);
+      return { messages, parts };
+    });
+    return read ?? { messages: [], parts: [] };

Review Comment:
   <details open>
   <summary>English</summary>
   
   **[P2] Fail a selected import when transcript reading fails**
   
   This fallback makes a real read failure indistinguishable from a legitimately empty session. I created a read-only database with a valid, listable `session` row but no `message`/`part` tables. Both SELECTs throw; `#withDatabase` catches the exception, this line returns empty arrays, and the real `ExternalSessionImporter` + `SessionStore` publishes one Session with `externalOrigin:{adapterId:"opencode", sourceSessionId:"ses_schema"}` and zero messages. The same path silently filters malformed JSON rows at lines 187-195, producing a partial transcript.
   
   Existing guards cannot stop this: `decodeCanonicalMessage` only validates rows that were emitted, and the generic importer intentionally accepts an empty message array. Keep discovery/listing best-effort if desired, but once `readSession` selects a source, missing schema, query failure, and undecodable message/part rows need to throw rather than commit an empty or truncated canonical history.
   
   </details>
   
   <details>
   <summary>中文</summary>
   
   **[P2] 选定会话后,transcript 读取失败必须让导入失败**
   
   这个 fallback 把真实读取失败与“会话确实为空”合并成了同一个结果。我构造了一个只读数据库:有合法、可列出的 `session` 行,但没有 `message` / `part` 表。两个 SELECT 抛错后,`#withDatabase` 吞掉异常,本行返回空数组;真实 `ExternalSessionImporter` + `SessionStore` 随后发布了一个带 `externalOrigin:{adapterId:"opencode", sourceSessionId:"ses_schema"}`、但消息数为 0 的 Session。187-195 行对畸形 JSON 行的静默过滤也会通过同一路径生成残缺 transcript。
   
   现有守卫拦不住:`decodeCanonicalMessage` 只验证实际 emitted 的行,而通用 importer 有意接受空消息数组。discovery/listing 可以继续 best-effort;但 `readSession` 一旦选定源会话,缺失 schema、查询失败、无法解码的 message/part 行都应抛错,不能提交空的或截断的 canonical history。
   
   </details>



##########
packages/storage/src/opencode-session-adapter.ts:
##########
@@ -0,0 +1,502 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+// opencode sessions as Maka Sessions.
+//
+// State lives in one SQLite database, `~/.local/share/opencode/opencode.db`,
+// which the CLI itself will name (`opencode db path`). Earlier releases wrote
+// a `storage/session/{info,message,part}` JSON tree; that layout is gone, so
+// this reads the database and nothing else. Verified against 1.18.21.
+//
+// A conversation is three tables. `session` holds identity and `directory`,
+// which is the cwd a project-scoped query reads. `message` and `part` each
+// keep their payload in an opaque `data` JSON column — the schema names the
+// container, the column names the shape.
+//
+// Turn state is derivable here, unlike a Claude Code transcript: every
+// assistant message records `time.completed`, and `finish` is `stop` on a
+// closing step, `tool-calls` on an intermediate one, and absent on a message
+// that was aborted, which also carries `error.name`.
+import { existsSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+import { externalSessionMatchesQuery } from '@maka/core/external-session';
+import type {
+  ExternalMakaSession,
+  ExternalSessionAdapter,
+  ExternalSessionQuery,
+  ExternalSessionSummary,
+} from '@maka/core/external-session';
+import { sanitizeForeignTitle } from '@maka/core/foreign-session';
+import type { StoredMessage } from '@maka/core/session';
+
+export const OPENCODE_SESSION_ADAPTER_ID = 'opencode';
+
+const EXTERNAL_SNAPSHOT_ABORT_SOURCE = 'external_session_snapshot';
+
+/** Guards the value interpolated into no SQL, but read back out of one. */
+const SESSION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/u;
+
+export interface OpenCodeSessionAdapterOptions {
+  /** Overrides `~/.local/share/opencode`. */
+  opencodeHome?: string;
+}
+
+interface SessionRow {
+  readonly id: string;
+  readonly title: string;
+  readonly directory: string;
+  readonly timeCreated?: number;
+  readonly timeUpdated?: number;
+  readonly archived: boolean;
+  readonly parentId?: string;
+}
+
+interface MessageRow {
+  readonly id: string;
+  readonly timeCreated: number;
+  readonly data: Record<string, unknown>;
+}
+
+interface PartRow {
+  readonly messageId: string;
+  readonly data: Record<string, unknown>;
+}
+
+export class OpenCodeSessionAdapter implements ExternalSessionAdapter {
+  readonly id = OPENCODE_SESSION_ADAPTER_ID;
+  readonly #home: string;
+
+  constructor(options: OpenCodeSessionAdapterOptions = {}) {
+    this.#home = options.opencodeHome ?? join(homedir(), '.local', 'share', 'opencode');
+  }
+
+  async detect(): Promise<boolean> {
+    return existsSync(this.#databasePath());
+  }
+
+  async listSessions(query?: ExternalSessionQuery): Promise<readonly ExternalSessionSummary[]> {
+    const rows = await this.#readSessions();
+    const summaries: ExternalSessionSummary[] = [];
+    for (const row of rows) {
+      // A child session is one operator's leg of a parent conversation, not a
+      // conversation a user started. Listing it offers an import of half a
+      // dialogue whose other half is a separate entry.
+      if (row.parentId !== undefined) continue;
+      const summary = toSummary(row);
+      if (externalSessionMatchesQuery(summary, query)) summaries.push(summary);
+    }
+    summaries.sort((left, right) => (right.updatedAt ?? 0) - (left.updatedAt ?? 0));
+    return summaries;
+  }
+
+  async readSession(sessionId: string): Promise<ExternalMakaSession> {
+    if (!SESSION_ID_PATTERN.test(sessionId)) {
+      throw new Error(`opencode session id is not usable: ${sessionId}`);
+    }
+    const rows = await this.#readSessions();
+    const row = rows.find((candidate) => candidate.id === sessionId);
+    if (!row) throw new Error(`opencode session not found: ${sessionId}`);
+    if (row.parentId !== undefined) {
+      throw new Error(`opencode session is a child of another session: ${sessionId}`);
+    }
+    const { messages, parts } = await this.#readTranscript(sessionId);
+    return {
+      sourceSessionId: sessionId,
+      metadata: { name: row.title || sessionId, cwd: row.directory },
+      messages: convertTranscript(sessionId, messages, parts),
+    };
+  }
+
+  #databasePath(): string {
+    return join(this.#home, 'opencode.db');
+  }
+
+  async #withDatabase<T>(read: (db: OpenCodeDatabase) => T): Promise<T | undefined> {
+    const path = this.#databasePath();
+    if (!existsSync(path)) return undefined;
+    let sqlite: typeof import('node:sqlite');
+    try {
+      sqlite = await import('node:sqlite');
+    } catch {
+      return undefined;
+    }
+    let db: OpenCodeDatabase;
+    try {
+      db = new sqlite.DatabaseSync(path, { readOnly: true }) as OpenCodeDatabase;
+    } catch {
+      return undefined;
+    }
+    try {
+      return read(db);
+    } catch {
+      return undefined;
+    } finally {
+      try {
+        db.close();
+      } catch {
+        // A close that fails leaves nothing for a reader to do; the process
+        // releases the handle either way, and throwing here would replace a
+        // usable result with an error about cleanup.
+      }
+    }
+  }
+
+  async #readSessions(): Promise<readonly SessionRow[]> {
+    const rows = await this.#withDatabase((db) => {
+      const columns = tableColumns(db, 'session');
+      if (!columns.has('id') || !columns.has('directory')) return undefined;
+      const selected = [
+        'id',
+        'title',
+        'directory',
+        'time_created',
+        'time_updated',
+        'time_archived',
+        'parent_id',
+      ].filter((column) => columns.has(column));
+      const raw = db.prepare(`SELECT ${selected.join(', ')} FROM session`).all();
+      return raw.map(toSessionRow).filter((row): row is SessionRow => row !== undefined);
+    });
+    return rows ?? [];
+  }
+
+  async #readTranscript(
+    sessionId: string,
+  ): Promise<{ messages: readonly MessageRow[]; parts: readonly PartRow[] }> {
+    const read = await this.#withDatabase((db) => {
+      const messages = db
+        .prepare('SELECT id, time_created, data FROM message WHERE session_id = ?')
+        .all(sessionId)
+        .map(toMessageRow)
+        .filter((row): row is MessageRow => row !== undefined);
+      // Ordered by the message they belong to and then by their own id, which
+      // is how the writer orders them; `time_created` ties within one step.
+      const parts = db
+        .prepare('SELECT message_id, data FROM part WHERE session_id = ? ORDER BY time_created, id')
+        .all(sessionId)
+        .map(toPartRow)
+        .filter((row): row is PartRow => row !== undefined);
+      return { messages, parts };
+    });
+    return read ?? { messages: [], parts: [] };
+  }
+}
+
+interface OpenCodeDatabase {
+  prepare(sql: string): { all(...params: unknown[]): unknown[] };
+  close(): void;
+}
+
+function tableColumns(db: OpenCodeDatabase, table: string): Set<string> {
+  const rows = db.prepare(`PRAGMA table_info(${table})`).all() as { name?: unknown }[];
+  return new Set(
+    rows.map((column) => (typeof column.name === 'string' ? column.name : '')).filter(Boolean),
+  );
+}
+
+function toSummary(row: SessionRow): ExternalSessionSummary {
+  return {
+    id: row.id,
+    name: sanitizeForeignTitle(row.title) || row.id,
+    cwd: row.directory,
+    ...(row.timeCreated !== undefined ? { createdAt: row.timeCreated } : {}),
+    ...(row.timeUpdated !== undefined ? { updatedAt: row.timeUpdated } : {}),
+    ...(row.archived ? { archived: true } : {}),
+  };
+}
+
+/**
+ * Turns one opencode conversation into Maka messages.
+ *
+ * Exported for the fixture tests, which exercise the mapping without a
+ * database: the conversion is where the source format is interpreted, and it
+ * is the part worth pinning.
+ */
+export function convertTranscript(
+  sessionId: string,
+  messages: readonly MessageRow[],
+  parts: readonly PartRow[],
+): readonly StoredMessage[] {
+  const partsByMessage = new Map<string, Record<string, unknown>[]>();
+  for (const part of parts) {
+    const existing = partsByMessage.get(part.messageId);
+    if (existing) existing.push(part.data);
+    else partsByMessage.set(part.messageId, [part.data]);
+  }
+
+  const ordered = [...messages].sort((left, right) =>
+    left.timeCreated === right.timeCreated
+      ? left.id.localeCompare(right.id)
+      : left.timeCreated - right.timeCreated,
+  );
+
+  const out: StoredMessage[] = [];
+  let sequence = 0;
+  const id = (kind: string): string => `opencode:${sessionId}:${kind}:${sequence++}`;
+  let turnSequence = 0;
+
+  interface Turn {
+    turnId: string;
+    lastTs: number;
+    aborted: boolean;
+    closed: boolean;
+    errorName?: string;
+  }
+  let turn: Turn | undefined;
+
+  const closeTurn = (): void => {
+    if (!turn) return;
+    if (turn.errorName !== undefined && !turn.aborted) {
+      out.push({
+        type: 'turn_state',
+        id: id('turn-state'),
+        turnId: turn.turnId,
+        ts: turn.lastTs,
+        status: 'failed',
+        errorClass: 'opencode_error',
+        partialOutputRetained: true,
+      });
+    } else if (turn.aborted) {
+      out.push({
+        type: 'turn_state',
+        id: id('turn-state'),
+        turnId: turn.turnId,
+        ts: turn.lastTs,
+        status: 'aborted',
+        abortedAt: turn.lastTs,
+        abortSource: EXTERNAL_SNAPSHOT_ABORT_SOURCE,
+        partialOutputRetained: true,
+      });
+    } else if (turn.closed) {
+      out.push({
+        type: 'turn_state',
+        id: id('turn-state'),
+        turnId: turn.turnId,
+        ts: turn.lastTs,
+        status: 'completed',
+        partialOutputRetained: true,
+      });
+    } else {
+      // A turn whose last assistant step asked for tools and never came back:
+      // the run stopped between a call and its answer. Recording it as
+      // completed would assert a reply the session never produced.
+      out.push({
+        type: 'turn_state',
+        id: id('turn-state'),
+        turnId: turn.turnId,
+        ts: turn.lastTs,
+        status: 'aborted',
+        abortedAt: turn.lastTs,
+        abortSource: EXTERNAL_SNAPSHOT_ABORT_SOURCE,
+        partialOutputRetained: true,
+      });
+    }
+    turn = undefined;
+  };
+
+  for (const message of ordered) {
+    const data = message.data;
+    const role = stringOf(data.role);
+    const ts =
+      numberOf((data.time as Record<string, unknown> | undefined)?.created) ?? message.timeCreated;
+    const messageParts = partsByMessage.get(message.id) ?? [];
+
+    if (role === 'user') {
+      closeTurn();
+      turn = {
+        turnId: `opencode:${sessionId}:turn:${turnSequence++}`,
+        lastTs: ts,
+        aborted: false,
+        closed: false,
+      };
+      const text = messageParts
+        .filter((part) => stringOf(part.type) === 'text')
+        .map((part) => stringOf(part.text) ?? '')
+        .filter((part) => part.length > 0)
+        .join('\n\n');
+      // A user message with no text part carries no prompt to import. Emitting
+      // an empty user turn would put a blank message in the user's history.
+      if (text.length > 0) {
+        out.push({ type: 'user', id: id('user'), turnId: turn.turnId, ts, text });
+      }
+      continue;
+    }
+
+    if (role !== 'assistant') continue;
+
+    if (!turn) {
+      // An assistant message with no preceding user message: a resumed
+      // session whose opening prompt is not in this transcript. Give it a turn
+      // rather than dropping the content.
+      turn = {
+        turnId: `opencode:${sessionId}:turn:${turnSequence++}`,
+        lastTs: ts,
+        aborted: false,
+        closed: false,
+      };
+    }
+    turn.lastTs = Math.max(turn.lastTs, ts);
+
+    const errorName = stringOf((data.error as Record<string, unknown> | undefined)?.name);
+    if (errorName !== undefined) {
+      if (errorName === 'MessageAbortedError') turn.aborted = true;
+      else turn.errorName = errorName;
+    }
+    const finish = stringOf(data.finish);
+    // `stop` is the only finish that closes a turn. `tool-calls` means the
+    // step handed off to a tool and another assistant message follows.
+    if (finish === 'stop') turn.closed = true;
+    else if (finish !== undefined) turn.closed = false;
+
+    const modelId = stringOf(data.modelID) ?? 'opencode';
+
+    const reasoning = messageParts
+      .filter((part) => stringOf(part.type) === 'reasoning')
+      .map((part) => stringOf(part.text) ?? '')
+      .filter((part) => part.length > 0)
+      .join('\n\n');
+    if (reasoning.length > 0) {
+      out.push({
+        type: 'assistant',
+        id: id('thinking'),
+        turnId: turn.turnId,
+        ts,
+        text: '',
+        thinking: { text: reasoning },
+        contentOrder: ['thinking'],
+        modelId,
+      });
+    }
+
+    const text = messageParts
+      .filter((part) => stringOf(part.type) === 'text')
+      .map((part) => stringOf(part.text) ?? '')
+      .filter((part) => part.length > 0)
+      .join('\n\n');
+    if (text.length > 0) {
+      out.push({
+        type: 'assistant',
+        id: id('assistant'),
+        turnId: turn.turnId,
+        ts,
+        text,
+        contentOrder: ['text'],
+        modelId,
+      });
+    }
+
+    for (const part of messageParts) {
+      if (stringOf(part.type) !== 'tool') continue;
+      const callId = stringOf(part.callID);
+      // A call with no id cannot be paired with its result. Minting one
+      // produces a row guaranteed not to match anything, which reads as a
+      // detached call rather than an absent one.
+      if (callId === undefined) continue;
+      const state = asRecord(part.state);
+      const status = stringOf(state?.status);
+      out.push({
+        type: 'tool_call',
+        id: callId,
+        turnId: turn.turnId,
+        ts,
+        toolName: stringOf(part.tool) ?? 'unknown',
+        args: asRecord(state?.input) ?? {},
+      });
+      // Only a completed call has an answer to import. Every other status —
+      // pending, running, and whatever else the union carries — describes a
+      // call still in flight when the session was written, and this adapter
+      // has no captured sample of their shape. Synthesising a result for one
+      // would put words the tool never said into the transcript.
+      if (status !== 'completed') continue;

Review Comment:
   <details open>
   <summary>English</summary>
   
   **[P2] Preserve terminal opencode tool failures**
   
   `status !== 'completed'` is not equivalent to an in-flight call. opencode 1.18.21 defines a distinct terminal [`ToolStateError`](https://github.com/anomalyco/opencode/blob/v1.18.21/packages/sdk/js/src/gen/types.gen.ts#L277-L292), and its own replay maps that state to [`output-error`](https://github.com/anomalyco/opencode/blob/v1.18.21/packages/opencode/src/session/message-v2.ts#L325-L357).
   
   Reproduction with supported rows: user message -> assistant `finish: "tool-calls"` containing `{status:"error", input:{...}, error:"exit 1"}` -> assistant `finish:"stop"`. `convertTranscript` emits `user -> tool_call -> assistant -> turn_state(completed)` with no `tool_result`. The existing guard only mutates captured calls to `running`; canonical decoding accepts the dangling call, and the later `stop` makes the whole turn look completed. Please emit a terminal `tool_result` with `isError:true` from the recorded error (while handling pending/running separately), so a persisted failure cannot be rewritten as an unresolved call inside a completed turn.
   
   </details>
   
   <details>
   <summary>中文</summary>
   
   **[P2] 保留 opencode 的终态工具失败**
   
   `status !== 'completed'` 不等于“仍在执行”。opencode 1.18.21 明确定义了终态 [`ToolStateError`](https://github.com/anomalyco/opencode/blob/v1.18.21/packages/sdk/js/src/gen/types.gen.ts#L277-L292),它自己的 replay 也把该状态映射为 [`output-error`](https://github.com/anomalyco/opencode/blob/v1.18.21/packages/opencode/src/session/message-v2.ts#L325-L357)。
   
   可复现路径:user -> 含 `{status:"error", input:{...}, error:"exit 1"}` 且 `finish:"tool-calls"` 的 assistant -> `finish:"stop"` 的 assistant。当前 `convertTranscript` 输出 `user -> tool_call -> assistant -> turn_state(completed)`,没有 `tool_result`。现有测试只把捕获样本改成 `running`;canonical decoder 接受这个悬空 call,后续 `stop` 又把整个 turn 标成 completed。请从已记录的 error 生成 `isError:true` 的终态 `tool_result`,并把 pending/running 分开处理,避免把真实失败改写成 completed turn 中的未决调用。
   
   </details>



##########
packages/storage/src/opencode-session-adapter.ts:
##########
@@ -0,0 +1,502 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+// opencode sessions as Maka Sessions.
+//
+// State lives in one SQLite database, `~/.local/share/opencode/opencode.db`,
+// which the CLI itself will name (`opencode db path`). Earlier releases wrote
+// a `storage/session/{info,message,part}` JSON tree; that layout is gone, so
+// this reads the database and nothing else. Verified against 1.18.21.
+//
+// A conversation is three tables. `session` holds identity and `directory`,
+// which is the cwd a project-scoped query reads. `message` and `part` each
+// keep their payload in an opaque `data` JSON column — the schema names the
+// container, the column names the shape.
+//
+// Turn state is derivable here, unlike a Claude Code transcript: every
+// assistant message records `time.completed`, and `finish` is `stop` on a
+// closing step, `tool-calls` on an intermediate one, and absent on a message
+// that was aborted, which also carries `error.name`.
+import { existsSync } from 'node:fs';
+import { homedir } from 'node:os';
+import { join } from 'node:path';
+import { externalSessionMatchesQuery } from '@maka/core/external-session';
+import type {
+  ExternalMakaSession,
+  ExternalSessionAdapter,
+  ExternalSessionQuery,
+  ExternalSessionSummary,
+} from '@maka/core/external-session';
+import { sanitizeForeignTitle } from '@maka/core/foreign-session';
+import type { StoredMessage } from '@maka/core/session';
+
+export const OPENCODE_SESSION_ADAPTER_ID = 'opencode';
+
+const EXTERNAL_SNAPSHOT_ABORT_SOURCE = 'external_session_snapshot';
+
+/** Guards the value interpolated into no SQL, but read back out of one. */
+const SESSION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/u;
+
+export interface OpenCodeSessionAdapterOptions {
+  /** Overrides `~/.local/share/opencode`. */
+  opencodeHome?: string;
+}
+
+interface SessionRow {
+  readonly id: string;
+  readonly title: string;
+  readonly directory: string;
+  readonly timeCreated?: number;
+  readonly timeUpdated?: number;
+  readonly archived: boolean;
+  readonly parentId?: string;
+}
+
+interface MessageRow {
+  readonly id: string;
+  readonly timeCreated: number;
+  readonly data: Record<string, unknown>;
+}
+
+interface PartRow {
+  readonly messageId: string;
+  readonly data: Record<string, unknown>;
+}
+
+export class OpenCodeSessionAdapter implements ExternalSessionAdapter {
+  readonly id = OPENCODE_SESSION_ADAPTER_ID;
+  readonly #home: string;
+
+  constructor(options: OpenCodeSessionAdapterOptions = {}) {
+    this.#home = options.opencodeHome ?? join(homedir(), '.local', 'share', 'opencode');
+  }
+
+  async detect(): Promise<boolean> {
+    return existsSync(this.#databasePath());
+  }
+
+  async listSessions(query?: ExternalSessionQuery): Promise<readonly ExternalSessionSummary[]> {
+    const rows = await this.#readSessions();
+    const summaries: ExternalSessionSummary[] = [];
+    for (const row of rows) {
+      // A child session is one operator's leg of a parent conversation, not a
+      // conversation a user started. Listing it offers an import of half a
+      // dialogue whose other half is a separate entry.
+      if (row.parentId !== undefined) continue;
+      const summary = toSummary(row);
+      if (externalSessionMatchesQuery(summary, query)) summaries.push(summary);
+    }
+    summaries.sort((left, right) => (right.updatedAt ?? 0) - (left.updatedAt ?? 0));
+    return summaries;
+  }
+
+  async readSession(sessionId: string): Promise<ExternalMakaSession> {
+    if (!SESSION_ID_PATTERN.test(sessionId)) {
+      throw new Error(`opencode session id is not usable: ${sessionId}`);
+    }
+    const rows = await this.#readSessions();
+    const row = rows.find((candidate) => candidate.id === sessionId);
+    if (!row) throw new Error(`opencode session not found: ${sessionId}`);
+    if (row.parentId !== undefined) {
+      throw new Error(`opencode session is a child of another session: ${sessionId}`);
+    }
+    const { messages, parts } = await this.#readTranscript(sessionId);
+    return {
+      sourceSessionId: sessionId,
+      metadata: { name: row.title || sessionId, cwd: row.directory },
+      messages: convertTranscript(sessionId, messages, parts),
+    };
+  }
+
+  #databasePath(): string {
+    return join(this.#home, 'opencode.db');
+  }
+
+  async #withDatabase<T>(read: (db: OpenCodeDatabase) => T): Promise<T | undefined> {
+    const path = this.#databasePath();
+    if (!existsSync(path)) return undefined;
+    let sqlite: typeof import('node:sqlite');
+    try {
+      sqlite = await import('node:sqlite');
+    } catch {
+      return undefined;
+    }
+    let db: OpenCodeDatabase;
+    try {
+      db = new sqlite.DatabaseSync(path, { readOnly: true }) as OpenCodeDatabase;
+    } catch {
+      return undefined;
+    }
+    try {
+      return read(db);
+    } catch {
+      return undefined;
+    } finally {
+      try {
+        db.close();
+      } catch {
+        // A close that fails leaves nothing for a reader to do; the process
+        // releases the handle either way, and throwing here would replace a
+        // usable result with an error about cleanup.
+      }
+    }
+  }
+
+  async #readSessions(): Promise<readonly SessionRow[]> {
+    const rows = await this.#withDatabase((db) => {
+      const columns = tableColumns(db, 'session');
+      if (!columns.has('id') || !columns.has('directory')) return undefined;
+      const selected = [
+        'id',
+        'title',
+        'directory',
+        'time_created',
+        'time_updated',
+        'time_archived',
+        'parent_id',
+      ].filter((column) => columns.has(column));
+      const raw = db.prepare(`SELECT ${selected.join(', ')} FROM session`).all();
+      return raw.map(toSessionRow).filter((row): row is SessionRow => row !== undefined);
+    });
+    return rows ?? [];
+  }
+
+  async #readTranscript(
+    sessionId: string,
+  ): Promise<{ messages: readonly MessageRow[]; parts: readonly PartRow[] }> {
+    const read = await this.#withDatabase((db) => {
+      const messages = db
+        .prepare('SELECT id, time_created, data FROM message WHERE session_id = ?')
+        .all(sessionId)
+        .map(toMessageRow)
+        .filter((row): row is MessageRow => row !== undefined);
+      // Ordered by the message they belong to and then by their own id, which
+      // is how the writer orders them; `time_created` ties within one step.
+      const parts = db
+        .prepare('SELECT message_id, data FROM part WHERE session_id = ? ORDER BY time_created, id')
+        .all(sessionId)
+        .map(toPartRow)
+        .filter((row): row is PartRow => row !== undefined);
+      return { messages, parts };
+    });
+    return read ?? { messages: [], parts: [] };
+  }
+}
+
+interface OpenCodeDatabase {
+  prepare(sql: string): { all(...params: unknown[]): unknown[] };
+  close(): void;
+}
+
+function tableColumns(db: OpenCodeDatabase, table: string): Set<string> {
+  const rows = db.prepare(`PRAGMA table_info(${table})`).all() as { name?: unknown }[];
+  return new Set(
+    rows.map((column) => (typeof column.name === 'string' ? column.name : '')).filter(Boolean),
+  );
+}
+
+function toSummary(row: SessionRow): ExternalSessionSummary {
+  return {
+    id: row.id,
+    name: sanitizeForeignTitle(row.title) || row.id,
+    cwd: row.directory,
+    ...(row.timeCreated !== undefined ? { createdAt: row.timeCreated } : {}),
+    ...(row.timeUpdated !== undefined ? { updatedAt: row.timeUpdated } : {}),
+    ...(row.archived ? { archived: true } : {}),
+  };
+}
+
+/**
+ * Turns one opencode conversation into Maka messages.
+ *
+ * Exported for the fixture tests, which exercise the mapping without a
+ * database: the conversion is where the source format is interpreted, and it
+ * is the part worth pinning.
+ */
+export function convertTranscript(
+  sessionId: string,
+  messages: readonly MessageRow[],
+  parts: readonly PartRow[],
+): readonly StoredMessage[] {
+  const partsByMessage = new Map<string, Record<string, unknown>[]>();
+  for (const part of parts) {
+    const existing = partsByMessage.get(part.messageId);
+    if (existing) existing.push(part.data);
+    else partsByMessage.set(part.messageId, [part.data]);
+  }
+
+  const ordered = [...messages].sort((left, right) =>
+    left.timeCreated === right.timeCreated
+      ? left.id.localeCompare(right.id)
+      : left.timeCreated - right.timeCreated,
+  );
+
+  const out: StoredMessage[] = [];
+  let sequence = 0;
+  const id = (kind: string): string => `opencode:${sessionId}:${kind}:${sequence++}`;
+  let turnSequence = 0;
+
+  interface Turn {
+    turnId: string;
+    lastTs: number;
+    aborted: boolean;
+    closed: boolean;
+    errorName?: string;
+  }
+  let turn: Turn | undefined;
+
+  const closeTurn = (): void => {
+    if (!turn) return;
+    if (turn.errorName !== undefined && !turn.aborted) {
+      out.push({
+        type: 'turn_state',
+        id: id('turn-state'),
+        turnId: turn.turnId,
+        ts: turn.lastTs,
+        status: 'failed',
+        errorClass: 'opencode_error',
+        partialOutputRetained: true,
+      });
+    } else if (turn.aborted) {
+      out.push({
+        type: 'turn_state',
+        id: id('turn-state'),
+        turnId: turn.turnId,
+        ts: turn.lastTs,
+        status: 'aborted',
+        abortedAt: turn.lastTs,
+        abortSource: EXTERNAL_SNAPSHOT_ABORT_SOURCE,
+        partialOutputRetained: true,
+      });
+    } else if (turn.closed) {
+      out.push({
+        type: 'turn_state',
+        id: id('turn-state'),
+        turnId: turn.turnId,
+        ts: turn.lastTs,
+        status: 'completed',
+        partialOutputRetained: true,
+      });
+    } else {
+      // A turn whose last assistant step asked for tools and never came back:
+      // the run stopped between a call and its answer. Recording it as
+      // completed would assert a reply the session never produced.
+      out.push({
+        type: 'turn_state',
+        id: id('turn-state'),
+        turnId: turn.turnId,
+        ts: turn.lastTs,
+        status: 'aborted',
+        abortedAt: turn.lastTs,
+        abortSource: EXTERNAL_SNAPSHOT_ABORT_SOURCE,
+        partialOutputRetained: true,
+      });
+    }
+    turn = undefined;
+  };
+
+  for (const message of ordered) {
+    const data = message.data;
+    const role = stringOf(data.role);
+    const ts =
+      numberOf((data.time as Record<string, unknown> | undefined)?.created) ?? message.timeCreated;
+    const messageParts = partsByMessage.get(message.id) ?? [];
+
+    if (role === 'user') {
+      closeTurn();
+      turn = {
+        turnId: `opencode:${sessionId}:turn:${turnSequence++}`,
+        lastTs: ts,
+        aborted: false,
+        closed: false,
+      };
+      const text = messageParts
+        .filter((part) => stringOf(part.type) === 'text')
+        .map((part) => stringOf(part.text) ?? '')
+        .filter((part) => part.length > 0)
+        .join('\n\n');
+      // A user message with no text part carries no prompt to import. Emitting
+      // an empty user turn would put a blank message in the user's history.
+      if (text.length > 0) {
+        out.push({ type: 'user', id: id('user'), turnId: turn.turnId, ts, text });
+      }
+      continue;
+    }
+
+    if (role !== 'assistant') continue;
+
+    if (!turn) {
+      // An assistant message with no preceding user message: a resumed
+      // session whose opening prompt is not in this transcript. Give it a turn
+      // rather than dropping the content.
+      turn = {
+        turnId: `opencode:${sessionId}:turn:${turnSequence++}`,
+        lastTs: ts,
+        aborted: false,
+        closed: false,
+      };
+    }
+    turn.lastTs = Math.max(turn.lastTs, ts);
+
+    const errorName = stringOf((data.error as Record<string, unknown> | undefined)?.name);
+    if (errorName !== undefined) {
+      if (errorName === 'MessageAbortedError') turn.aborted = true;
+      else turn.errorName = errorName;
+    }
+    const finish = stringOf(data.finish);
+    // `stop` is the only finish that closes a turn. `tool-calls` means the
+    // step handed off to a tool and another assistant message follows.
+    if (finish === 'stop') turn.closed = true;
+    else if (finish !== undefined) turn.closed = false;
+
+    const modelId = stringOf(data.modelID) ?? 'opencode';
+
+    const reasoning = messageParts

Review Comment:
   <details open>
   <summary>English</summary>
   
   **[P2] Preserve the source part order instead of bucketing by type**
   
   The three-pass mapping (`reasoning`, then `text`, then `tool`) rewrites a valid source sequence. opencode 1.18.21's own test accepts `text -> reasoning -> tool` and expects that order to survive conversion ([input](https://github.com/anomalyco/opencode/blob/v1.18.21/packages/opencode/test/session/message-v2.test.ts#L620-L650), [expected output](https://github.com/anomalyco/opencode/blob/v1.18.21/packages/opencode/test/session/message-v2.test.ts#L654-L684)). Feeding that same supported order to this function produces `reasoning -> text -> tool_call -> tool_result`.
   
   The fixture does not guard this because every mixed assistant message happens to be reasoning-first, and the tests only assert that message kinds exist. Iterate the ordered parts (or encode their order in the canonical assistant step) so imported display/replay history does not move reasoning or text across another source part.
   
   </details>
   
   <details>
   <summary>中文</summary>
   
   **[P2] 按源 part 顺序转换,不要按类型分桶**
   
   当前三遍处理(先 `reasoning`、再 `text`、最后 `tool`)会改写合法的源顺序。opencode 1.18.21 自己的测试接受 `text -> reasoning -> tool`,并要求转换后仍保持该顺序([输入](https://github.com/anomalyco/opencode/blob/v1.18.21/packages/opencode/test/session/message-v2.test.ts#L620-L650),[预期输出](https://github.com/anomalyco/opencode/blob/v1.18.21/packages/opencode/test/session/message-v2.test.ts#L654-L684))。把同一支持形状交给本函数,实际得到 `reasoning -> text -> tool_call -> tool_result`。
   
   现有 fixture 没有守住它:所有混合 assistant message 恰好都是 reasoning-first,测试也只检查 message kind 是否存在。请遍历已有顺序的 parts(或在 canonical assistant step 中编码其顺序),避免导入后的展示/重放历史把 reasoning 或 text 移到另一个源 part 前后。
   
   </details>



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org