π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(work): register github works from hetero shell gh runs (#17666)
YuTengjing8d1f04ba8a91
diff --git a/.agents/skills/agent-work/SKILL.md b/.agents/skills/agent-work/SKILL.mdnew file mode 100644index 00000000000..6297377c473--- /dev/null+++ b/.agents/skills/agent-work/SKILL.md@@ -0,0 +1,124 @@+---+name: agent-work+description: 'Agent Work registry (works / work_versions): how agent outputs β github/linear entities, files, documents, tasks β get registered, deduped, and rendered as cards, and how to extend it with a new skill provider, a new shell CLI scanner, or a new Work type.'+user-invocable: false+---++# Agent Works++A **Work** is a durable record of something an agent produced or touched β a GitHub PR/issue, a Linear issue, an entity file (pptx/xlsx/docx/pdf), a document, a task. Works render as cards under the assistant message that produced them and accumulate **versions** across operations, so the same PR edited twice shows one card with history.++Two tables (`packages/database/src/schemas/work.ts`):++- `works` β one row per resource. Identity/dedup key: `(resourceType, resourceId)` within the user/workspace scope. `currentVersionId` soft-references the latest version.+- `work_versions` β one row per registration event. Dedup: unique `(workId, toolCallId)`, so a retried registration with the same real tool call id is a no-op. Versions carry provenance (source message, producing tool) and operation-level `cumulativeCost` / `cumulativeUsage`.++## Type registry++`packages/database/src/models/work/registry.ts` is the single registry of Work types (`document` / `external` / `file` / `task`): `WORK_TYPE_ADAPTERS` is `satisfies Record<WorkType, WorkTypeAdapter>`, so a type added to `@lobechat/types` without an adapter is a compile error.++**Read-path compatibility gate**: `OPT_IN_WORK_TYPES` (currently `{'file'}`) hides newer types from clients that did not opt in (`includeFileWorks`). Released Electron clients lag by weeks and crash on unknown type descriptors (`descriptor.getIcon` on `undefined`), so a request without the opt-in receives exactly the pre-`file` set. Any NEW Work type must ship behind the same kind of opt-in.++## Registration write paths++Four write paths, two timing classes:++| Path | When | Where |+| ----------------------------------------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Skill structured tools + sandbox `runCommand` (github / linear) | at tool execution | `WorkModel.handleSkillToolResult`, called from server `toolExecution` and the client executor (`registerClientWorkFromIntent.ts` on the legacy non-gateway runtime) |+| Shell Work scan (hetero codex/claude-code + device `lobe-local-system`) | at operation completion | `apps/server/src/services/agentRuntime/shellWorkRegistration.ts` via `registerWorksForOperation` |+| File Work scan (sandbox entity files) | at operation completion | `apps/server/src/services/agentRuntime/workRegistration.ts` |+| Task / document works | at creation by their owning feature | `WorkModel.registerTask` / `registerDocument` |++### Execution-time: skill providers++`SKILL_TOOL_RESULT_NORMALIZERS` in `packages/database/src/models/work/index.ts` maps `WorkSkillProvider` (`github`, `linear`; vocabulary in `packages/types/src/work.ts`) to a normalizer. Both `satisfies` a `Record<WorkSkillProvider, β¦>`, so provider list and normalizer map cannot drift.++A normalizer turns one tool result into `ExternalToolWorkOperation | null` β null means "not Work-worthy", which is the common case and never an error.++### Completion-time: the shell Work scan framework++Heterogeneous CLI agents (codex, claude-code) and the device `lobe-local-system` tool run CLIs like `gh` through their own shell surfaces, which never pass the skill-tool hook. `registerWorksForOperation` recovers their Works at completion from the persisted command text + stdout. Layering:++```+registerWorksForOperation (workRegistration.ts)+ ββ collectOperationRecords one pass over the operation tree, shared by both scans+ ββ registerShellWorks (shellWorkRegistration.ts β the ENGINE, command-agnostic)+ β ββ SHELL_COMMAND_SOURCES identifierβapiName scoping of shell surfaces+ β ββ success gate plugin error / state.success===false / state.error β skip+ β ββ extract {command, exitCode, output} from arguments / state / message content+ β ββ shellWorkScanners/ one file per CLI family+ β ββ types.ts ShellWorkScanner = { matches, name, register }+ β ββ github.ts matches: includes('gh ') β workModel.registerShellGithubResult+ β ββ index.ts SHELL_WORK_SCANNERS registry+ ββ file Work scan aggregate per-path fold + sandbox export pipeline (NOT a scanner)+```++Command parsing is split the same way: `packages/database/src/models/work/shellCommandParsing.ts` holds the command-agnostic layer (POSIX-ish tokenizer, control-operator segmenting, codex `/bin/zsh -lc` wrapper expansion β `parseShellCommandSegments`), while `githubToolResult.ts` holds only the gh-specific `parseGhSegment` + field mapping.++### Cost granularity: execution-time vs completion-time++`cumulativeCost` / `cumulativeUsage` are per-version SNAPSHOTS ("spend up to this version"), never deltas β summing them across versions double-counts on every path.++- **Execution-time registrations** (skill providers) snapshot right after `UsageCounter.accumulateTool` for that call, so create + edit + edit within one run carries an INCREASING series (e.g. $0.30 β $0.70 β $1.20) and step deltas are recoverable.+- **Completion-time registrations** (shell scan, file scan) attach one OPERATION-LEVEL figure β the completing run's terminal total plus terminal child-op totals β to EVERY version registered that round: the scan only has persisted command text + stdout, no per-call intermediate snapshots (hetero CLI usage is aggregated per step by the trace recorder, not per tool call). The same create + edit + edit therefore yields three versions all carrying $1.20, indistinguishable per step.+- Cross-operation is independent: a later run editing the same resource appends a version with THAT run's total only.++**Why file Works are not a scanner**: their unit is a file path folded across ALL records (multi-edit merge, renames, last-edit provenance), the registration is a heavy IO pipeline (idempotency probe β sandbox export β upload β version β redeploy, bounded concurrency), hetero records are deliberately EXCLUDED (the file lives on the executing device, not the exportable sandbox), and the version key is the synthetic `op:${operationId}` instead of a real toolCallId. Shoehorning that into `ShellWorkScanner` would break the interface. If a second aggregate-style scan ever appears, extract an aggregate layer then.++## Display anchor & completion marker++A Works card renders only under an assistant message stamped with `metadata.work.rootOperationId` (the "anchor"). Who stamps it:++- **In-process runs**: `callLlmFinalizer` stamps the round's final assistant message.+- **Hetero runs** never pass that executor, so `registerWorksForOperation` stamps the anchor itself when the shell scan registered anything β using the completion's `assistantMessageId`, falling back to the `parentId` of the last registered tool message (hetero single-step runs persist no final-assistant pointer at all; see `heteroFinish`).++The whole scan returns `{attempted, failed}` and the completion backstop (`CompletionLifecycle`) writes its idempotency marker only when `failed === 0`. Anything that must be retried β a thrown registration, a `{success: false}` anchor stamp, an unresolvable anchor β counts into `failed`. Registration is retry-safe end to end (probe short-circuits, `(workId, toolCallId)` guard backs it up), so counting a failure is always the right move.++## Key decisions (from the Work PRs)++- **Only successful create/edit results become Works** (LOBE-10967). Read-only queries, comments, merges/closes, and branch/repo operations are excluded β `gh pr view` printing an entity URL must NOT register.+- **`owner/repo#number` is the canonical github identity**, not node\_id: the gh CLI surface never returns node\_id, and the same entity touched via REST tools and CLI must land on one Work row.+- **stdout is the source of truth for identity** on the CLI path (`gh β¦ create/edit` prints the entity URL); the command's edit target is the fallback. The LAST gh create/edit segment of a chained command owns the trailing URL.+- **Persisted URLs are http(s)-allowlisted** (`sanitizeExternalUrl`): gh stdout / tool results are member-controlled and the URL reaches `shell.openExternal` on desktop.+- **The tokenizer is deliberately hand-rolled** (no `shell-quote` dep): a real parser would expand what must stay literal, and the worst failure mode is skipping a bookkeeping registration.+- **Error-terminated runs skip the completion scan** (same success gate as file Works): a `gh` create that succeeds before a later terminal failure registers no Work that round. Accepted β bounded cost, missing card only.+- **Hetero Works register after the terminal snapshot** (`agent_runtime_end` publishes before `completeOperation`), so a hetero-created card appears on the next refetch, not in the terminal snapshot. Accepted for now.+- **PRs pushed via codex's own GitHub integration are not covered** β no shell record exists; text-mention parsing was rejected as too false-positive-prone.++## Extension recipes++**New skill provider (structured tools), e.g. Notion:**++1. `packages/types/src/work.ts` β extend `WORK_SKILL_PROVIDERS` + `WORK_PROVIDER_RESOURCE_TYPES` (+ resource-type unions).+2. `packages/database/src/models/work/<provider>ToolResult.ts` β write the normalizer; mirror `linearToolResult.ts`.+3. `packages/database/src/models/work/index.ts` β add it to `SKILL_TOOL_RESULT_NORMALIZERS` (the `satisfies` forces this).+4. Pick a stable cross-surface `resourceId` (the github lesson: choose the identity every surface can produce).++**New shell CLI scanner, e.g. `linear` CLI or `vercel deploy`:**++1. Add a normalizer in `packages/database/src/models/work/` reusing `parseShellCommandSegments`, plus a `WorkModel.registerShell<X>Result` facade method.+2. Add `apps/server/src/services/agentRuntime/shellWorkScanners/<name>.ts` with `{ matches, name, register }` β `matches` stays a cheap substring check.+3. Append it to `SHELL_WORK_SCANNERS` in `shellWorkScanners/index.ts`. The engine needs zero changes.+4. Pin the parsing edge cases in `packages/database/src/models/work/__tests__/` (wrapper unwrap, chained segments, failed/read-only commands must not register).++**New Work type (new card kind):**++1. `@lobechat/types` β extend `WorkType` and related unions.+2. `packages/database/src/models/work/` β new adapter module + `WORK_TYPE_ADAPTERS` entry (compile-enforced).+3. Client β add the type descriptor for the card UI.+4. **Add the type to the read-path opt-in gate** (`OPT_IN_WORK_TYPES` pattern) β released clients throw on unknown types; never ship a new type into the legacy result set.++## File map++| Concern | Path |+| ---------------------------------------------------- | ---------------------------------------------------------------- |+| Schema | `packages/database/src/schemas/work.ts` |+| Type registry + read gate | `packages/database/src/models/work/registry.ts` |+| WorkModel facade + provider normalizer map | `packages/database/src/models/work/index.ts` |+| gh CLI + structured github normalizer | `packages/database/src/models/work/githubToolResult.ts` |+| Command-agnostic shell parsing | `packages/database/src/models/work/shellCommandParsing.ts` |+| Completion scan orchestrator (file + shell + anchor) | `apps/server/src/services/agentRuntime/workRegistration.ts` |+| Shell scan engine | `apps/server/src/services/agentRuntime/shellWorkRegistration.ts` |+| Per-CLI scanners | `apps/server/src/services/agentRuntime/shellWorkScanners/` |+| Client (non-gateway) registration | `src/store/chat/agents/registerClientWorkFromIntent.ts` |diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.tsindex ab93f5a871e..bc92309c7fd 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts@@ -64,7 +64,6 @@ import { BuiltinToolsExecutor } from '@/server/services/toolExecution/builtin';import { isAbortError, throwIfAborted } from './abort';import { CompletionLifecycle, isSuccessLikeCompletionReason } from './CompletionLifecycle';-import { stateHasEntityFileEdits } from './fileWorkRegistration';import { hookDispatcher } from './hooks';import { HumanInterventionHandler } from './HumanInterventionHandler';import { OperationTraceRecorder } from './OperationTraceRecorder';@@ -87,6 +86,7 @@ import {type StepCompletionReason,type SubAgentBridgeParams,} from './types';+import { stateHasEntityFileEdits } from './workRegistration';if (process.env.VERCEL) {// Route debug output to stdout (`console.info`) instead of stderr, whichdiff --git a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts b/apps/server/src/services/agentRuntime/CompletionLifecycle.tsindex 4769ba08f07..90c64b97fea 100644--- a/apps/server/src/services/agentRuntime/CompletionLifecycle.ts+++ b/apps/server/src/services/agentRuntime/CompletionLifecycle.ts@@ -21,8 +21,8 @@ import { toAgentSignalTraceEvents } from '@/server/services/agentSignal/observabimport { extractSelfIterationCompletionPayload } from '@/server/services/agentSignal/services/selfIteration/completion';import { instantiateVerifyPlanOnStart, runVerifyOnCompletion } from '@/server/services/verify';-import { registerFileWorksForOperation } from './fileWorkRegistration';import { hookDispatcher, type SerializedHook } from './hooks';+import { registerWorksForOperation } from './workRegistration';const log = debug('lobe-server:completion-lifecycle');@@ -506,17 +506,21 @@ export class CompletionLifecycle {}/**- * Register entity files edited by this operation (pptx/xlsx/docx/pdf, β¦) as- * `file` Works β one version per operation, exported from the sandbox.+ * Register the operation's Works: entity files edited this round+ * (pptx/xlsx/docx/pdf, β¦) as `file` Works β one version per operation,+ * exported from the sandbox β plus github issue/PR Works recovered from+ * hetero / device shell records (codex / claude-code / lobe-local-system+ * `gh` runs), which never pass the skill-tool registration hook.*- * Idempotent per state object: only when EVERY file registered (the returned- * outcome reports `failed === 0`) is a `_fileWorksRegistered` marker stamped- * onto `state.metadata` so the dispatchHooks backstop (which receives the same- * state later in the request) skips the duplicate scan. A PARTIAL failure- * leaves the marker unset so the backstop re-runs and retries just the failed- * files β the underlying registration is idempotent per (operation, file) via a- * DB existence probe, so already-registered files short-circuit and a QStash- * retry that lost the marker is safe.+ * Idempotent per state object: only when EVERY candidate registered (the+ * returned outcome reports `failed === 0`) is a `_fileWorksRegistered` marker+ * stamped onto `state.metadata` so the dispatchHooks backstop (which receives+ * the same state later in the request) skips the duplicate scan. A PARTIAL+ * failure leaves the marker unset so the backstop re-runs and retries just the+ * failed candidates β file registration is idempotent per (operation, file)+ * via a DB existence probe, github registration per (work, toolCallId) via+ * the version write's unique guard, so a QStash retry that lost the marker is+ * safe.** The gateway/queue executor calls this BEFORE the terminal* `coordinator.saveStepResult`: that save publishes `agent_runtime_end`,@@ -535,7 +539,10 @@ export class CompletionLifecycle {async registerFileWorks(operationId: string, state: any): Promise<void> {if (state?.metadata?._fileWorksRegistered) return;try {- const outcome = await registerFileWorksForOperation({+ const outcome = await registerWorksForOperation({+ // The round's final assistant message β the shell github scan stamps the+ // Work display anchor onto it for hetero runs (see registerWorksForOperation).+ assistantMessageId: state?.metadata?.assistantMessageId ?? null,// Live terminal totals: on the pre-snapshot path the op row's cost/usage// columns are not persisted yet (recordCompletion runs later), so the// registration must not rely on reading them back from the DB.@@ -552,7 +559,7 @@ export class CompletionLifecycle {// retry and the user gets neither a Work nor the edited-files fallback.if (state?.metadata && outcome.failed === 0) state.metadata._fileWorksRegistered = true;} catch (error) {- log('[%s] registerFileWorksForOperation failed (non-fatal): %O', operationId, error);+ log('[%s] registerWorksForOperation failed (non-fatal): %O', operationId, error);}}diff --git a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.tsindex 9103d42026f..f35ba6b519d 100644--- a/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts+++ b/apps/server/src/services/agentRuntime/__tests__/CompletionLifecycle.test.ts@@ -7,8 +7,8 @@ import * as agentSignalService from '@/server/services/agentSignal';import * as verifyServices from '@/server/services/verify';import { CompletionLifecycle, isSuccessLikeCompletionReason } from '../CompletionLifecycle';-import { registerFileWorksForOperation } from '../fileWorkRegistration';import { hookDispatcher } from '../hooks';+import { registerWorksForOperation } from '../workRegistration';// Default async no-op implementation: the production code chains `.catch` on// the returned promise, so a bare vi.fn() (returning undefined) would throw@@ -22,8 +22,8 @@ vi.mock('@/business/server/agent-run/notifyAgentRunCompleted', () => ({notifyAgentRunCompleted: mockNotifyAgentRunCompleted,}));-vi.mock('../fileWorkRegistration', () => ({- registerFileWorksForOperation: vi.fn(),+vi.mock('../workRegistration', () => ({+ registerWorksForOperation: vi.fn(),}));const flushMicrotasks = () => new Promise((resolve) => setTimeout(resolve, 0));@@ -774,7 +774,7 @@ describe('CompletionLifecycle.dispatchHooks β parks do not register file works// terminal registration entirely) and freeze per-(op, file) versions at// pre-approval content.it('does NOT register on a human-approval park (same op resumes and registers later)', async () => {- const mockRegister = vi.mocked(registerFileWorksForOperation);+ const mockRegister = vi.mocked(registerWorksForOperation);mockRegister.mockClear();mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });const lifecycle = buildLifecycle();@@ -789,7 +789,7 @@ describe('CompletionLifecycle.dispatchHooks β parks do not register file works});it('does NOT register on an async-tool park (same op resumes and registers later)', async () => {- const mockRegister = vi.mocked(registerFileWorksForOperation);+ const mockRegister = vi.mocked(registerWorksForOperation);mockRegister.mockClear();mockRegister.mockResolvedValue({ attempted: 0, failed: 0 });const lifecycle = buildLifecycle();@@ -1052,7 +1052,7 @@ describe('CompletionLifecycle.emitSignalEvents β assistant anchor', () => {});describe('CompletionLifecycle.registerFileWorks', () => {- const mockRegister = vi.mocked(registerFileWorksForOperation);+ const mockRegister = vi.mocked(registerWorksForOperation);it('registers once and stamps the state marker so later calls skip', async () => {mockRegister.mockClear();@@ -1101,7 +1101,7 @@ describe('CompletionLifecycle.registerFileWorks', () => {});it('leaves the marker unset on a PARTIAL failure, then stamps it once all files land', async () => {- // Regression: registerFileWorksForOperation swallows per-file failures and+ // Regression: registerWorksForOperation swallows per-file failures and// never rejects, so a partial failure resolves normally. The marker must be// gated on the outcome (`failed === 0`), NOT stamped unconditionally β else// the dispatchHooks backstop skips the retry and the user gets neither a Workdiff --git a/apps/server/src/services/agentRuntime/shellWorkRegistration.ts b/apps/server/src/services/agentRuntime/shellWorkRegistration.tsnew file mode 100644index 00000000000..713f5f5e344--- /dev/null+++ b/apps/server/src/services/agentRuntime/shellWorkRegistration.ts@@ -0,0 +1,190 @@+import { LocalSystemIdentifier } from '@lobechat/builtin-tool-local-system';+import {+ CLAUDE_CODE_IDENTIFIER,+ CODEX_IDENTIFIER,+} from '@lobechat/heterogeneous-agents/transcript';+import type { WorkVersionCumulativeUsage } from '@lobechat/types';+import debug from 'debug';++import type { WorkModel } from '@/database/models/work';++import { SHELL_WORK_SCANNERS } from './shellWorkScanners';++const log = debug('lobe-server:shell-work-registration');++/**+ * Shell tool surfaces whose raw command text may carry Work-registerable CLI+ * runs (mirrors the hetero-shell sources of+ * `@lobechat/builtin-tools/fileEditScan`), keyed by plugin `identifier` β+ * shell `apiName`:+ *+ * - codex `command_execution` β stdout in `state.stdout` / `state.output`,+ * `state.exitCode` on completion (`adapters/codex.ts`).+ * - claude-code `Bash` β stdout is the tool MESSAGE CONTENT (the adapter+ * persists the tool_result text as content, no structured state); failures+ * surface via the plugin `error` column (is_error), never an exit code.+ * - lobe-local-system `runCommand` β device-executed homogeneous tool; its+ * `RunCommandState` carries `stdout` / `output` / `exitCode` / `success`.+ *+ * The github SKILL's surfaces (structured tools + sandbox `runCommand`) are+ * deliberately absent: they register at execution time through+ * `handleSkillToolResult` (server `toolExecution/builtin.ts` and the client+ * executor), so scanning them here would double-register.+ */+const SHELL_COMMAND_SOURCES: Record<string, string> = {+ [CLAUDE_CODE_IDENTIFIER]: 'Bash',+ [CODEX_IDENTIFIER]: 'command_execution',+ [LocalSystemIdentifier]: 'runCommand',+};++/** One tool-call row from the operation tree, as collected by the works scan. */+export interface ShellWorkScanRecord {+ apiName: string;+ arguments?: string | null;+ /** Tool message text body β claude-code Bash stdout lives here. */+ content?: string;+ error?: unknown;+ /** Owning tool message id β becomes the version's source message. */+ id: string;+ identifier?: string | null;+ state?: unknown;+ toolCallId: string;+}++export interface ShellWorksOutcome {+ /**+ * Tool MESSAGE id of the last successfully registered record. Lets the+ * caller derive a display-anchor fallback (the tool message's `parentId` is+ * its owning assistant) when the completion carries no final-assistant+ * pointer β hetero single-step runs persist neither `heteroCurrentMsgId`+ * nor `runningOperation.assistantMessageId` (see `heteroFinish`).+ */+ anchorCandidateMessageId: string | null;+ /** Records a scanner resolved into a registerable external entity. */+ attempted: number;+ /**+ * Failures counted against the completion backstop's idempotency marker:+ * registration throws from this scan, plus anchor-stamp failures the caller+ * (`registerWorksForOperation`) folds in after the fact.+ */+ failed: number;+ /** How many of `attempted` registered (or idempotently re-registered). */+ registered: number;+}++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++const stringField = (record: Record<string, unknown> | undefined, key: string) => {+ const value = record?.[key];+ return typeof value === 'string' && value.length > 0 ? value : undefined;+};++/**+ * Register external Works from the shell tool calls of a completed operation:+ * heterogeneous CLI agents (codex / claude-code) and the device+ * `lobe-local-system` tool run CLIs like `gh` through their OWN shell+ * surfaces, which never pass the skill-tool registration hook β so their+ * Work-worthy runs are recovered here, at completion time, from the persisted+ * command text + stdout (same completion-scan pattern as file-Work+ * registration). Each entry in {@link SHELL_WORK_SCANNERS} covers one CLI+ * family; github is the only one today.+ *+ * Best-effort per record: registration failures are counted, never thrown. A+ * retry is idempotent β the version write dedupes on `(workId, toolCallId)`+ * with the record's REAL tool call id.+ */+export const registerShellWorks = async (params: {+ agentId?: string | null;+ cumulativeCost: number | null;+ cumulativeUsage: WorkVersionCumulativeUsage | null;+ operationId: string;+ records: ShellWorkScanRecord[];+ threadId?: string | null;+ topicId: string;+ workModel: WorkModel;+}): Promise<ShellWorksOutcome> => {+ const outcome: ShellWorksOutcome = {+ anchorCandidateMessageId: null,+ attempted: 0,+ failed: 0,+ registered: 0,+ };++ for (const record of params.records) {+ if (!record.identifier || SHELL_COMMAND_SOURCES[record.identifier] !== record.apiName) continue;+ // A plugin-level error means the command never ran / failed (claude-code+ // is_error rides here); state-level failure signals mirror fileEditScan.+ if (record.error != null && record.error !== '') continue;+ const state = isRecord(record.state) ? record.state : undefined;+ if (state?.success === false) continue;+ if (state?.error != null && state.error !== '') continue;++ let command: unknown;+ try {+ command = JSON.parse(record.arguments ?? '')?.command;+ } catch {+ continue;+ }+ if (typeof command !== 'string') continue;++ const data = {+ command,+ // Absent for claude-code (no exit code is persisted); its failures were+ // already excluded via the plugin error above.+ exitCode: typeof state?.exitCode === 'number' ? state.exitCode : undefined,+ output: stringField(state, 'stdout') ?? stringField(state, 'output') ?? record.content,+ };++ for (const scanner of SHELL_WORK_SCANNERS) {+ if (!scanner.matches(command)) continue;++ try {+ const work = await scanner.register({+ agentId: params.agentId ?? null,+ cumulativeCost: params.cumulativeCost,+ cumulativeUsage: params.cumulativeUsage,+ data,+ messageId: record.id,+ rootOperationId: params.operationId,+ threadId: params.threadId ?? null,+ toolCallId: record.toolCallId || null,+ toolIdentifier: record.identifier,+ toolName: record.apiName,+ topicId: params.topicId,+ workModel: params.workModel,+ });+ if (!work) continue;+ outcome.attempted += 1;+ outcome.registered += 1;+ outcome.anchorCandidateMessageId = record.id;+ } catch (error) {+ // The normalizer runs before the write, so a throw here means a+ // resolved external entity failed to persist β count it so the+ // completion backstop withholds its idempotency marker and retries.+ outcome.attempted += 1;+ outcome.failed += 1;+ log(+ '[%s] Failed to register %s Work from %s:%s (non-fatal): %O',+ params.operationId,+ scanner.name,+ record.identifier,+ record.apiName,+ error,+ );+ }+ }+ }++ if (outcome.attempted > 0) {+ log(+ '[%s] Shell Work scan: attempted=%d registered=%d failed=%d',+ params.operationId,+ outcome.attempted,+ outcome.registered,+ outcome.failed,+ );+ }++ return outcome;+};diff --git a/apps/server/src/services/agentRuntime/shellWorkScanners/github.ts b/apps/server/src/services/agentRuntime/shellWorkScanners/github.tsnew file mode 100644index 00000000000..f2738102b62--- /dev/null+++ b/apps/server/src/services/agentRuntime/shellWorkScanners/github.ts@@ -0,0 +1,14 @@+import type { ShellWorkScanner } from './types';++/**+ * github issue/PR Works from `gh issue|pr create/edit` runs. Parsing reuses+ * the github skill's gh-CLI normalizer (via+ * `workModel.registerShellGithubResult` β `normalizeGithubShellToolResult`),+ * so identity lands on the same `owner/repo#number` Work row as+ * skill-registered versions.+ */+export const githubShellWorkScanner: ShellWorkScanner = {+ matches: (command) => command.includes('gh '),+ name: 'github',+ register: ({ workModel, ...input }) => workModel.registerShellGithubResult(input),+};diff --git a/apps/server/src/services/agentRuntime/shellWorkScanners/index.ts b/apps/server/src/services/agentRuntime/shellWorkScanners/index.tsnew file mode 100644index 00000000000..579f9f13294--- /dev/null+++ b/apps/server/src/services/agentRuntime/shellWorkScanners/index.ts@@ -0,0 +1,12 @@+import { githubShellWorkScanner } from './github';+import type { ShellWorkScanner } from './types';++export type { ShellWorkScanner } from './types';++/**+ * Every CLI family the completion-time shell Work scan recognizes. To support+ * a new CLI: add a normalizer next to the existing ones in+ * `@/database/models/work`, define its scanner in a sibling file here, and+ * append it to this list.+ */+export const SHELL_WORK_SCANNERS: ShellWorkScanner[] = [githubShellWorkScanner];diff --git a/apps/server/src/services/agentRuntime/shellWorkScanners/types.ts b/apps/server/src/services/agentRuntime/shellWorkScanners/types.tsnew file mode 100644index 00000000000..a4eefd36dd9--- /dev/null+++ b/apps/server/src/services/agentRuntime/shellWorkScanners/types.ts@@ -0,0 +1,41 @@+import type { WorkVersionCumulativeUsage } from '@lobechat/types';++import type { WorkModel } from '@/database/models/work';++/**+ * One CLI family the shell Work scan knows how to turn into Works. The engine+ * (`registerShellWorks` in `../shellWorkRegistration`) owns everything+ * command-agnostic β source scoping, success gating, command/output+ * extraction, outcome counting β while a scanner supplies the two+ * CLI-specific pieces: a cheap text prefilter and the normalize-and-persist+ * call. One scanner per file in this directory; register it in `./index`.+ */+export interface ShellWorkScanner {+ /**+ * Cheap prefilter on the raw command text; `register` runs only when it+ * returns true. Keep it a substring check β precise parsing belongs to the+ * normalizer behind `register`.+ */+ matches: (command: string) => boolean;+ /** Scanner name, for logs. */+ name: string;+ /**+ * Normalize + persist one shell command record. Returns the registered Work+ * (null when the command doesn't resolve into a registerable entity β not+ * counted as attempted). A throw is counted as a registration failure.+ */+ register: (input: {+ agentId: string | null;+ cumulativeCost: number | null;+ cumulativeUsage: WorkVersionCumulativeUsage | null;+ data: { command: string; exitCode?: number; output?: string };+ messageId: string;+ rootOperationId: string;+ threadId: string | null;+ toolCallId: string | null;+ toolIdentifier: string;+ toolName: string;+ topicId: string;+ workModel: WorkModel;+ }) => Promise<unknown | null>;+}diff --git a/apps/server/src/services/agentRuntime/fileWorkRegistration.test.ts b/apps/server/src/services/agentRuntime/workRegistration.test.tssimilarity index 77%rename from apps/server/src/services/agentRuntime/fileWorkRegistration.test.tsrename to apps/server/src/services/agentRuntime/workRegistration.test.tsindex 2ee541a2fa9..764171fa017 100644--- a/apps/server/src/services/agentRuntime/fileWorkRegistration.test.ts+++ b/apps/server/src/services/agentRuntime/workRegistration.test.ts@@ -2,26 +2,32 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import {redeployFileWork,- registerFileWorksForOperation,+ registerWorksForOperation,stateHasEntityFileEdits,-} from './fileWorkRegistration';+} from './workRegistration';const {mockFindById,mockListOperationTree,mockListPlugins,mockRegisterFile,+ mockRegisterShellGithubResult,mockFindFileVersionByToolCall,mockExportAndUploadFile,mockCreateSandboxService,+ mockUpdateMessage,+ mockFindMessageById,} = vi.hoisted(() => ({mockCreateSandboxService: vi.fn(),mockExportAndUploadFile: vi.fn(),mockFindById: vi.fn(),mockFindFileVersionByToolCall: vi.fn(),+ mockFindMessageById: vi.fn(),mockListOperationTree: vi.fn(),mockListPlugins: vi.fn(),mockRegisterFile: vi.fn(),+ mockRegisterShellGithubResult: vi.fn(),+ mockUpdateMessage: vi.fn(),}));vi.mock('@/database/models/agentOperation', () => ({@@ -32,13 +38,18 @@ vi.mock('@/database/models/agentOperation', () => ({}));vi.mock('@/database/models/message', () => ({- MessageModel: vi.fn(() => ({ listMessagePluginsForOperation: mockListPlugins })),+ MessageModel: vi.fn(() => ({+ findById: mockFindMessageById,+ listMessagePluginsForOperation: mockListPlugins,+ update: mockUpdateMessage,+ })),}));vi.mock('@/database/models/work', () => ({WorkModel: vi.fn(() => ({findFileVersionByToolCall: mockFindFileVersionByToolCall,registerFile: mockRegisterFile,+ registerShellGithubResult: mockRegisterShellGithubResult,})),}));@@ -103,6 +114,28 @@ const skillsExportRow = (id: string, path: string) => ({toolCallId: `tc-${id}`,});+/** A codex `command_execution` plugin row whose command may run `gh`. */+const codexCommandRow = (id: string, command: string, output: string, exitCode = 0) => ({+ apiName: 'command_execution',+ arguments: JSON.stringify({ command }),+ createdAt: new Date(`2026-07-20T00:0${id.length}:00.000Z`),+ id,+ identifier: 'codex',+ state: { exitCode, output, stdout: output, success: exitCode === 0 },+ toolCallId: `tc-${id}`,+});++/** A claude-code `Bash` plugin row β stdout rides the message CONTENT, no state. */+const claudeCodeBashRow = (id: string, command: string, content: string) => ({+ apiName: 'Bash',+ arguments: JSON.stringify({ command }),+ content,+ createdAt: new Date(`2026-07-20T00:0${id.length}:00.000Z`),+ id,+ identifier: 'claude-code',+ toolCallId: `tc-${id}`,+});+beforeEach(() => {vi.clearAllMocks();mockListOperationTree.mockResolvedValue([rootOp]);@@ -110,6 +143,9 @@ beforeEach(() => {mockFindById.mockResolvedValue(null);// No pre-existing version by default, so every entity file exports + registers.mockFindFileVersionByToolCall.mockResolvedValue(null);+ mockRegisterShellGithubResult.mockResolvedValue({ id: 'work-github' });+ mockUpdateMessage.mockResolvedValue({ success: true });+ mockFindMessageById.mockResolvedValue(undefined);mockCreateSandboxService.mockReturnValue({ exportAndUploadFile: mockExportAndUploadFile });mockRegisterFile.mockImplementation(async (params: any) => ({currentVersionId: `ver-${params.filePath}`,@@ -131,14 +167,14 @@ beforeEach(() => {});});-describe('registerFileWorksForOperation', () => {+describe('registerWorksForOperation', () => {it('registers one file Work version per edited entity file', async () => {mockListPlugins.mockResolvedValue([writeRow('a', '/mnt/data/deck.pptx'),writeRow('bb', '/mnt/data/sheet.xlsx'),]);- await registerFileWorksForOperation(baseParams);+ await registerWorksForOperation(baseParams);expect(mockRegisterFile).toHaveBeenCalledTimes(2);const deck = mockRegisterFile.mock.calls.find(@@ -192,7 +228,7 @@ describe('registerFileWorksForOperation', () => {{ ...writeRow('a', '/mnt/data/deck.pptx'), intervention: { status: 'approved' } },]);- await registerFileWorksForOperation(baseParams);+ await registerWorksForOperation(baseParams);expect(mockRegisterFile).toHaveBeenCalledTimes(1);expect(mockRegisterFile.mock.calls[0][0].filePath).toBe('/mnt/data/deck.pptx');@@ -212,7 +248,7 @@ describe('registerFileWorksForOperation', () => {},]);- await registerFileWorksForOperation(baseParams);+ await registerWorksForOperation(baseParams);expect(mockRegisterFile).toHaveBeenCalledTimes(1);const call = mockRegisterFile.mock.calls[0][0];@@ -241,7 +277,7 @@ describe('registerFileWorksForOperation', () => {};});- const outcome = await registerFileWorksForOperation(baseParams);+ const outcome = await registerWorksForOperation(baseParams);expect(mockRegisterFile).toHaveBeenCalledTimes(1);expect(mockRegisterFile.mock.calls[0][0].filePath).toBe('/mnt/data/ok.xlsx');@@ -256,7 +292,7 @@ describe('registerFileWorksForOperation', () => {writeRow('bb', '/mnt/data/sheet.xlsx'),]);- const outcome = await registerFileWorksForOperation(baseParams);+ const outcome = await registerWorksForOperation(baseParams);expect(outcome).toEqual({ attempted: 2, failed: 0 });});@@ -266,7 +302,7 @@ describe('registerFileWorksForOperation', () => {// The (op, file) version already exists from a previous attempt.mockFindFileVersionByToolCall.mockResolvedValue({ id: 'ver-existing' });- const outcome = await registerFileWorksForOperation(baseParams);+ const outcome = await registerWorksForOperation(baseParams);expect(mockExportAndUploadFile).not.toHaveBeenCalled();expect(mockRegisterFile).not.toHaveBeenCalled();@@ -280,7 +316,7 @@ describe('registerFileWorksForOperation', () => {writeRow('ccc', '/mnt/data/report.docx'),]);- await registerFileWorksForOperation(baseParams);+ await registerWorksForOperation(baseParams);expect(mockRegisterFile).toHaveBeenCalledTimes(1);expect(mockRegisterFile.mock.calls[0][0].filePath).toBe('/mnt/data/report.docx');@@ -303,7 +339,7 @@ describe('registerFileWorksForOperation', () => {},]);- await registerFileWorksForOperation(baseParams);+ await registerWorksForOperation(baseParams);expect(mockExportAndUploadFile).not.toHaveBeenCalled();expect(mockRegisterFile).not.toHaveBeenCalled();@@ -325,7 +361,7 @@ describe('registerFileWorksForOperation', () => {},]);- await registerFileWorksForOperation(baseParams);+ await registerWorksForOperation(baseParams);expect(mockRegisterFile).toHaveBeenCalledTimes(1);expect(mockRegisterFile.mock.calls[0][0].filePath).toBe('/mnt/data/deck.pptx');@@ -339,7 +375,7 @@ describe('registerFileWorksForOperation', () => {]);mockListPlugins.mockResolvedValue([writeRow('a', '/mnt/data/deck.pptx')]);- await registerFileWorksForOperation({+ await registerWorksForOperation({...baseParams,finalCost: { total: 1.25 },finalUsage: { tokens: 42 },@@ -359,7 +395,7 @@ describe('registerFileWorksForOperation', () => {]);mockListPlugins.mockResolvedValue([writeRow('a', '/mnt/data/deck.pptx')]);- await registerFileWorksForOperation({+ await registerWorksForOperation({...baseParams,finalCost: { total: 1 },finalUsage: { tokens: 42 },@@ -384,7 +420,7 @@ describe('registerFileWorksForOperation', () => {exportRow('bb', '/workspace/deck.pptx'),]);- await registerFileWorksForOperation(baseParams);+ await registerWorksForOperation(baseParams);expect(mockRegisterFile).toHaveBeenCalledTimes(1);// Re-exported through the collision-proof pipeline, not the exportFile blob.@@ -415,7 +451,7 @@ describe('registerFileWorksForOperation', () => {skillsExportRow('bb', '/workspace/deck.pptx'),]);- await registerFileWorksForOperation(baseParams);+ await registerWorksForOperation(baseParams);expect(mockRegisterFile).toHaveBeenCalledTimes(1);// Re-exported from the topic sandbox through the collision-proof pipeline.@@ -437,7 +473,7 @@ describe('registerFileWorksForOperation', () => {{ ...skillsExportRow('ccc', '/workspace/failed.pptx'), state: undefined },]);- await registerFileWorksForOperation(baseParams);+ await registerWorksForOperation(baseParams);expect(mockRegisterFile).not.toHaveBeenCalled();expect(mockExportAndUploadFile).not.toHaveBeenCalled();@@ -450,7 +486,7 @@ describe('registerFileWorksForOperation', () => {{ ...exportRow('ccc', '/workspace/pending.pptx'), state: undefined },]);- await registerFileWorksForOperation(baseParams);+ await registerWorksForOperation(baseParams);expect(mockRegisterFile).not.toHaveBeenCalled();expect(mockExportAndUploadFile).not.toHaveBeenCalled();@@ -462,7 +498,7 @@ describe('registerFileWorksForOperation', () => {exportRow('bb', '/mnt/data/data.csv'),]);- await registerFileWorksForOperation(baseParams);+ await registerWorksForOperation(baseParams);expect(mockRegisterFile).toHaveBeenCalledTimes(1);// The edit-scan entry wins (richer provenance/line data).@@ -487,7 +523,7 @@ describe('registerFileWorksForOperation', () => {},]);- await registerFileWorksForOperation(baseParams);+ await registerWorksForOperation(baseParams);expect(mockRegisterFile).not.toHaveBeenCalled();expect(mockExportAndUploadFile).not.toHaveBeenCalled();@@ -496,7 +532,7 @@ describe('registerFileWorksForOperation', () => {it('no-ops when the root operation has no topic', async () => {mockListOperationTree.mockResolvedValue([{ ...rootOp, topicId: null }]);- await registerFileWorksForOperation(baseParams);+ await registerWorksForOperation(baseParams);expect(mockListPlugins).not.toHaveBeenCalled();expect(mockRegisterFile).not.toHaveBeenCalled();@@ -508,7 +544,7 @@ describe('registerFileWorksForOperation', () => {mockListOperationTree.mockResolvedValue([{ ...rootOp, parentOperationId: 'parent-1' }]);mockFindById.mockResolvedValue({ status: 'running' });- await registerFileWorksForOperation(baseParams);+ await registerWorksForOperation(baseParams);expect(mockFindById).toHaveBeenCalledWith('parent-1');expect(mockListPlugins).not.toHaveBeenCalled();@@ -521,7 +557,7 @@ describe('registerFileWorksForOperation', () => {mockListOperationTree.mockResolvedValue([{ ...rootOp, parentOperationId: 'parent-1' }]);mockFindById.mockResolvedValue({ status: 'waiting_for_async_tool' });- await registerFileWorksForOperation(baseParams);+ await registerWorksForOperation(baseParams);expect(mockRegisterFile).not.toHaveBeenCalled();});@@ -534,7 +570,7 @@ describe('registerFileWorksForOperation', () => {mockFindById.mockResolvedValue({ status: 'done' });mockListPlugins.mockResolvedValue([writeRow('a', '/mnt/data/fix.xlsx')]);- await registerFileWorksForOperation(baseParams);+ await registerWorksForOperation(baseParams);expect(mockFindById).toHaveBeenCalledWith('parent-1');expect(mockRegisterFile).toHaveBeenCalledTimes(1);@@ -560,7 +596,7 @@ describe('registerFileWorksForOperation', () => {: [writeRow('bb', '/mnt/data/child.xlsx')],);- await registerFileWorksForOperation(baseParams);+ await registerWorksForOperation(baseParams);// Only the completing op's plugin window is queried β the child is skipped.expect(mockListPlugins).toHaveBeenCalledTimes(1);@@ -571,7 +607,7 @@ describe('registerFileWorksForOperation', () => {it('uploads under a collision-proof storage name while keeping a clean display filename', async () => {mockListPlugins.mockResolvedValue([writeRow('a', '/mnt/data/deck.pptx')]);- await registerFileWorksForOperation(baseParams);+ await registerWorksForOperation(baseParams);const [path, filename, options] = mockExportAndUploadFile.mock.calls[0];expect(path).toBe('/mnt/data/deck.pptx');@@ -588,8 +624,8 @@ describe('registerFileWorksForOperation', () => {mockListOperationTree.mockImplementation(async (opId: string) => [{ ...rootOp, id: opId }]);mockListPlugins.mockResolvedValue([writeRow('a', '/mnt/data/report.xlsx')]);- await registerFileWorksForOperation({ ...baseParams, operationId: 'op_1784632944000_abc' });- await registerFileWorksForOperation({ ...baseParams, operationId: 'op_1784632999000_def' });+ await registerWorksForOperation({ ...baseParams, operationId: 'op_1784632944000_abc' });+ await registerWorksForOperation({ ...baseParams, operationId: 'op_1784632999000_def' });const first = mockExportAndUploadFile.mock.calls[0][2].storageName;const second = mockExportAndUploadFile.mock.calls[1][2].storageName;@@ -603,7 +639,7 @@ describe('registerFileWorksForOperation', () => {mockListPlugins.mockResolvedValue([writeRow('a', '/mnt/data/deck.pptx')]);mockFindFileVersionByToolCall.mockResolvedValue({ id: 'existing-version' });- await registerFileWorksForOperation(baseParams);+ await registerWorksForOperation(baseParams);expect(mockFindFileVersionByToolCall).toHaveBeenCalledWith({filePath: '/mnt/data/deck.pptx',@@ -629,7 +665,7 @@ describe('registerFileWorksForOperation', () => {: [writeRow('bb', '/mnt/data/sub.xlsx')],);- await registerFileWorksForOperation(baseParams);+ await registerWorksForOperation(baseParams);expect(mockListPlugins).toHaveBeenCalledTimes(2);expect(mockRegisterFile).toHaveBeenCalledTimes(2);@@ -918,3 +954,171 @@ describe('stateHasEntityFileEdits', () => {).toBe(true);});});++describe('registerWorksForOperation Β· shell github works', () => {+ it('registers a github Work from a codex gh pr create and stamps the anchor', async () => {+ mockListPlugins.mockResolvedValue([+ codexCommandRow(+ 'a',+ `git push && gh pr create --title 'Fix tray' --body 'Body'`,+ 'https://github.com/lobehub/lobehub/pull/17654\n',+ ),+ ]);++ const outcome = await registerWorksForOperation({+ ...baseParams,+ assistantMessageId: 'msg-assistant',+ });++ expect(mockRegisterShellGithubResult).toHaveBeenCalledTimes(1);+ expect(mockRegisterShellGithubResult).toHaveBeenCalledWith(+ expect.objectContaining({+ data: expect.objectContaining({+ command: `git push && gh pr create --title 'Fix tray' --body 'Body'`,+ exitCode: 0,+ output: 'https://github.com/lobehub/lobehub/pull/17654\n',+ }),+ messageId: 'a',+ rootOperationId: 'op-1',+ toolCallId: 'tc-a',+ toolIdentifier: 'codex',+ toolName: 'command_execution',+ topicId: 'topic-1',+ }),+ );+ // Hetero runs never pass callLlmFinalizer β the anchor is stamped here.+ expect(mockUpdateMessage).toHaveBeenCalledWith('msg-assistant', {+ metadata: { work: { rootOperationId: 'op-1' } },+ });+ expect(outcome).toEqual({ attempted: 1, failed: 0 });+ });++ it('counts a failed anchor stamp so the completion backstop retries', async () => {+ // messageModel.update never throws β DB errors / no-matched-row come back+ // as { success: false }. A silent stamp failure would let the caller mark+ // the round complete while the Work stays invisible.+ mockUpdateMessage.mockResolvedValue({ success: false });+ mockListPlugins.mockResolvedValue([+ codexCommandRow(+ 'a',+ `gh pr create --title 'Fix tray'`,+ 'https://github.com/lobehub/lobehub/pull/17654\n',+ ),+ ]);++ const outcome = await registerWorksForOperation({+ ...baseParams,+ assistantMessageId: 'msg-assistant',+ });++ expect(mockRegisterShellGithubResult).toHaveBeenCalledTimes(1);+ expect(outcome).toEqual({ attempted: 1, failed: 1 });+ });++ it('reads claude-code Bash stdout from the message content', async () => {+ mockListPlugins.mockResolvedValue([+ claudeCodeBashRow(+ 'b',+ `gh issue edit 952 --repo lobehub/lobehub --title 'Better'`,+ 'https://github.com/lobehub/lobehub/issues/952',+ ),+ ]);++ await registerWorksForOperation({ ...baseParams, assistantMessageId: 'msg-assistant' });++ expect(mockRegisterShellGithubResult).toHaveBeenCalledWith(+ expect.objectContaining({+ data: expect.objectContaining({+ exitCode: undefined,+ output: 'https://github.com/lobehub/lobehub/issues/952',+ }),+ toolIdentifier: 'claude-code',+ toolName: 'Bash',+ }),+ );+ });++ it('skips failed shell records and never stamps the anchor without a registration', async () => {+ mockRegisterShellGithubResult.mockResolvedValue(null);+ mockListPlugins.mockResolvedValue([+ // Non-zero exit: excluded before the normalizer is even consulted? No β+ // exitCode rides the data blob; exclusion here is the state error signal.+ { ...codexCommandRow('c', `gh pr create --title 'x'`, 'boom', 1), state: { error: 'boom' } },+ // Passes the cheap `gh ` pre-filter but is read-only β normalizes to null.+ claudeCodeBashRow('d', 'gh pr view 17654', 'https://github.com/lobehub/lobehub/pull/17654'),+ // No `gh ` in the command at all β dropped before the model is consulted.+ claudeCodeBashRow('e', 'ls -la', 'README.md'),+ ]);++ const outcome = await registerWorksForOperation({+ ...baseParams,+ assistantMessageId: 'msg-assistant',+ });++ // Row `c` is dropped by its state error; row `d` reaches the model but+ // normalizes to null (not a gh create/edit) β neither registers.+ expect(mockRegisterShellGithubResult).toHaveBeenCalledTimes(1);+ expect(mockUpdateMessage).not.toHaveBeenCalled();+ expect(outcome).toEqual({ attempted: 0, failed: 0 });+ });++ it('counts a github registration failure so the completion marker is withheld', async () => {+ mockRegisterShellGithubResult.mockRejectedValue(new Error('db down'));+ mockListPlugins.mockResolvedValue([+ codexCommandRow(+ 'e',+ `gh pr create --title 'Fix'`,+ 'https://github.com/lobehub/lobehub/pull/1',+ ),+ ]);++ const outcome = await registerWorksForOperation({+ ...baseParams,+ assistantMessageId: 'msg-assistant',+ });++ expect(outcome).toEqual({ attempted: 1, failed: 1 });+ expect(mockUpdateMessage).not.toHaveBeenCalled();+ });++ it('falls back to the tool message parent as anchor when no assistantMessageId', async () => {+ // Hetero single-step runs persist neither heteroCurrentMsgId nor+ // runningOperation.assistantMessageId, so heteroFinish passes no pointer.+ // The scan anchors on the assistant owning the registered gh tool call.+ mockFindMessageById.mockResolvedValue({ id: 'f', parentId: 'msg-owner-assistant' });+ mockListPlugins.mockResolvedValue([+ codexCommandRow(+ 'f',+ `gh pr create --title 'Fix'`,+ 'https://github.com/lobehub/lobehub/pull/2',+ ),+ ]);++ const outcome = await registerWorksForOperation(baseParams);++ expect(mockFindMessageById).toHaveBeenCalledWith('f');+ expect(mockUpdateMessage).toHaveBeenCalledWith('msg-owner-assistant', {+ metadata: { work: { rootOperationId: 'op-1' } },+ });+ expect(outcome).toEqual({ attempted: 1, failed: 0 });+ });++ it('counts a missing anchor as failed so the completion marker is withheld', async () => {+ // No assistantMessageId and the fallback lookup resolves nothing β the+ // Work row exists but nothing would render it; the round must not be+ // marked complete.+ mockFindMessageById.mockResolvedValue(undefined);+ mockListPlugins.mockResolvedValue([+ codexCommandRow(+ 'g',+ `gh pr create --title 'Fix'`,+ 'https://github.com/lobehub/lobehub/pull/3',+ ),+ ]);++ const outcome = await registerWorksForOperation(baseParams);++ expect(mockUpdateMessage).not.toHaveBeenCalled();+ expect(outcome).toEqual({ attempted: 1, failed: 1 });+ });+});diff --git a/apps/server/src/services/agentRuntime/fileWorkRegistration.ts b/apps/server/src/services/agentRuntime/workRegistration.tssimilarity index 87%rename from apps/server/src/services/agentRuntime/fileWorkRegistration.tsrename to apps/server/src/services/agentRuntime/workRegistration.tsindex d107bfa9f77..c648d88275c 100644--- a/apps/server/src/services/agentRuntime/fileWorkRegistration.ts+++ b/apps/server/src/services/agentRuntime/workRegistration.ts@@ -22,10 +22,12 @@ import { FileService } from '@/server/services/file';import { MarketService } from '@/server/services/market';import { createSandboxService } from '@/server/services/sandbox';+import { registerShellWorks } from './shellWorkRegistration';+const log = debug('lobe-server:file-work-registration');/** One tool call gathered from the operation tree, tagged for ordering + provenance. */-type ScannedRecord = FileEditToolCallRecord & { createdAt: Date; id: string };+type ScannedRecord = FileEditToolCallRecord & { content?: string; createdAt: Date; id: string };/** The last-edit tool call for a file, used as the version's provenance. */interface FileProvenance {@@ -34,7 +36,14 @@ interface FileProvenance {messageId: string;}-export interface RegisterFileWorksForOperationParams {+export interface RegisterWorksForOperationParams {+ /**+ * The round's final assistant message. When the shell Work scan registers a+ * Work, the anchor stamp (`metadata.work.rootOperationId`) is merged onto this+ * message so the Works chip renders β heterogeneous runs never pass+ * `callLlmFinalizer`, which stamps the anchor for in-process runs.+ */+ assistantMessageId?: string | null;/*** Terminal in-memory cost blob of the completing operation (`state.cost`).*@@ -54,14 +63,15 @@ export interface RegisterFileWorksForOperationParams {}/**- * Per-operation outcome of {@link registerFileWorksForOperation}. Lets the caller+ * Per-operation outcome of {@link registerWorksForOperation}. Lets the caller* decide whether the idempotency marker may be stamped: only a run with* `failed === 0` is complete. Files that were already registered (probe* short-circuit) or newly registered count as attempted successes; a failed- * sandbox export or a thrown per-file chain counts as `failed`.+ * sandbox export or a thrown per-file chain counts as `failed`. Both counts+ * also fold in the shell Work scan (see `registerShellWorks`).*/-export interface FileWorksRegistrationOutcome {- /** Entity files this completion tried to register (edits + exported paths). */+export interface WorksRegistrationOutcome {+ /** Entity files + shell-scanned external entities this completion tried to register. */attempted: number;/** How many of `attempted` did not end up registered this round. */failed: number;@@ -360,6 +370,8 @@ const collectOperationRecords = async (byMessageId.set(row.id, {apiName: row.apiName ?? '',arguments: row.arguments,+ // Tool message text β claude-code Bash stdout for the github scan.+ content: row.content,createdAt: row.createdAt,// A plugin-level error means the edit never landed β the scanner skips// such records (mirrors the client's `tool.result?.error`).@@ -404,7 +416,15 @@ const collectOperationRecords = async (* - Best-effort per file: an export or registration failure for one file is* logged and skipped, never aborting the others.*- * Returns a {@link FileWorksRegistrationOutcome} summary (`attempted` / `failed`)+ * Besides file Works, the SAME collected records feed the shell github Work+ * scan (`registerShellWorks`): heterogeneous CLI shells (codex /+ * claude-code) and the device `lobe-local-system` tool run `gh issue|pr+ * create/edit` outside the skill-tool registration hook, so their github+ * entities are recovered here at completion time and β for hetero runs, which+ * never pass `callLlmFinalizer` β the Work display anchor is stamped onto the+ * round's final assistant message.+ *+ * Returns a {@link WorksRegistrationOutcome} summary (`attempted` / `failed`)* so the caller can gate its idempotency marker: because each file is wrapped in* its own try/catch and folded through `mapWithConcurrency` (a bounded* allSettled), this function NEVER rejects on a per-file failure β the counts are@@ -415,12 +435,12 @@ const collectOperationRecords = async (** Awaited (not fire-and-forget) by the completion lifecycle so a serverless* response freeze can't drop the background write; the caller still swallows any- * whole-function rejection so file-Work registration can never affect operation+ * whole-function rejection so Work registration can never affect operation* completion.*/-export const registerFileWorksForOperation = async (- params: RegisterFileWorksForOperationParams,-): Promise<FileWorksRegistrationOutcome> => {+export const registerWorksForOperation = async (+ params: RegisterWorksForOperationParams,+): Promise<WorksRegistrationOutcome> => {const { operationId, serverDB, userId, workspaceId } = params;const operationModel = new AgentOperationModel(serverDB, userId, workspaceId);@@ -509,6 +529,91 @@ export const registerFileWorksForOperation = async (return undefined;};+ const workModel = new WorkModel(serverDB, userId, workspaceId);++ // The whole operation's spend/usage is attached to each version registered+ // this round (an operation-level, not per-file, figure β the scanner can't+ // attribute cost to individual files). Prefer the terminal state's live blobs+ // over the op row: on the pre-snapshot path the row's cost/usage columns are+ // written only later by `recordCompletion`, so the row reads null/stale here.+ // The op row's `totalCost` also rolls up terminal child ops; replicate that+ // from the already-loaded tree (children complete before their root, so their+ // rows carry final totals) to keep the state-sourced figure equivalent.+ const childCost = tree+ .filter((op) => op.id !== operationId)+ .reduce((sum, op) => sum + (op.totalCost ?? 0), 0);+ const ownCost = params.finalCost?.total;+ const cumulativeCost =+ typeof ownCost === 'number' ? ownCost + childCost : (completingOp.totalCost ?? null);+ const usageBlob = params.finalUsage ?? completingOp.usage;+ const cumulativeUsage: WorkVersionCumulativeUsage | null = usageBlob+ ? {+ capturedAt: new Date().toISOString(),+ cost: params.finalCost ?? completingOp.cost ?? undefined,+ usage: usageBlob,+ }+ : null;++ // Recover external Works (github issue/PR today) from hetero / device shell+ // records (codex, claude-code, lobe-local-system) β these surfaces never pass+ // the skill-tool registration hook. Self-guarded: per-record failures are+ // counted, never thrown. Unlike file Works there is no device-provenance+ // objection: the registered entities are REMOTE resources whose identity/url+ // is independent of where the CLI ran.+ const shellOutcome = await registerShellWorks({+ agentId: completingOp.agentId,+ cumulativeCost,+ cumulativeUsage,+ operationId,+ records,+ threadId: completingOp.threadId,+ topicId,+ workModel,+ });++ // Heterogeneous runs never pass `callLlmFinalizer`, the executor that stamps+ // the Work display anchor (`metadata.work.rootOperationId`) for in-process+ // runs β without the stamp a registered Work never renders below the message.+ // `messageModel.update` deep-merges metadata, so re-stamping an anchor the+ // finalizer already wrote (same rootOperationId) is a no-op.+ if (shellOutcome.registered > 0) {+ let anchorMessageId = params.assistantMessageId ?? null;+ if (!anchorMessageId && shellOutcome.anchorCandidateMessageId) {+ // Hetero SINGLE-STEP runs can finish without a final-assistant pointer+ // (`heteroFinish` finds neither `heteroCurrentMsgId` nor+ // `runningOperation.assistantMessageId`). Fall back to the assistant+ // that OWNS the last registered shell tool call β every tool message+ // keeps `parentId` = its owning assistant β so the Work still renders+ // in the round instead of being persisted invisibly.+ try {+ const toolMessage = await messageModel.findById(shellOutcome.anchorCandidateMessageId);+ anchorMessageId = toolMessage?.parentId ?? null;+ } catch (error) {+ log('[%s] Failed to resolve fallback work anchor (non-fatal): %O', operationId, error);+ }+ }++ if (anchorMessageId) {+ // `messageModel.update` reports DB errors / no-matched-row as+ // `{ success: false }` instead of throwing β a failed stamp must count as+ // a failure so the completion backstop withholds its idempotency marker+ // and retries the (idempotent) scan + stamp next round.+ const stamp = await messageModel.update(anchorMessageId, {+ metadata: { work: { rootOperationId: operationId } },+ });+ if (!stamp.success) {+ shellOutcome.failed += 1;+ log('[%s] Failed to stamp work anchor on %s', operationId, anchorMessageId);+ }+ } else {+ // No resolvable anchor at all: the Work row exists but nothing would+ // ever render it. Withhold the completion marker so a later completion+ // retries the (idempotent) scan + stamp.+ shellOutcome.failed += 1;+ log('[%s] No anchor message available for registered shell Works', operationId);+ }+ }+const scannedEntities = scanOperationFileEdits(records).filter((entry) => entry.kind !== 'deleted' && classifyEditedFile(entry.path).category === 'entity',);@@ -566,7 +671,7 @@ export const registerFileWorksForOperation = async ();if (entities.length === 0) {log('[%s] Skipping file Work registration: no sandbox-backed entity candidates', operationId);- return { attempted: 0, failed: 0 };+ return { attempted: shellOutcome.attempted, failed: shellOutcome.failed };}// The sandbox is derived from userId + topicId and outlives the operation, so@@ -581,31 +686,6 @@ export const registerFileWorksForOperation = async (userId,});- const workModel = new WorkModel(serverDB, userId, workspaceId);-- // The whole operation's spend/usage is attached to each version registered- // this round (an operation-level, not per-file, figure β the scanner can't- // attribute cost to individual files). Prefer the terminal state's live blobs- // over the op row: on the pre-snapshot path the row's cost/usage columns are- // written only later by `recordCompletion`, so the row reads null/stale here.- // The op row's `totalCost` also rolls up terminal child ops; replicate that- // from the already-loaded tree (children complete before their root, so their- // rows carry final totals) to keep the state-sourced figure equivalent.- const childCost = tree- .filter((op) => op.id !== operationId)- .reduce((sum, op) => sum + (op.totalCost ?? 0), 0);- const ownCost = params.finalCost?.total;- const cumulativeCost =- typeof ownCost === 'number' ? ownCost + childCost : (completingOp.totalCost ?? null);- const usageBlob = params.finalUsage ?? completingOp.usage;- const cumulativeUsage: WorkVersionCumulativeUsage | null = usageBlob- ? {- capturedAt: new Date().toISOString(),- cost: params.finalCost ?? completingOp.cost ?? undefined,- usage: usageBlob,- }- : null;-// Register each entity file with bounded parallelism. Every file's own// export β register β redeploy chain stays sequential inside its task, and each// task keeps its own best-effort try/catch (returning 'ok' | 'failed' instead@@ -734,5 +814,8 @@ export const registerFileWorksForOperation = async (const failed = settled.filter((result) => result.status === 'rejected' || result.value === 'failed',).length;- return { attempted: entities.length, failed };+ return {+ attempted: entities.length + shellOutcome.attempted,+ failed: failed + shellOutcome.failed,+ };};diff --git a/packages/builtin-tools/src/fileEditScan/index.ts b/packages/builtin-tools/src/fileEditScan/index.tsindex 0204262ea3c..f09a17c7dc0 100644--- a/packages/builtin-tools/src/fileEditScan/index.ts+++ b/packages/builtin-tools/src/fileEditScan/index.ts@@ -802,7 +802,7 @@ const HTML_EXTENSIONS = new Set(['htm', 'html']);* slash; returns '' when the path has no usable segment.** Single source of truth for the consumers that used to hand-roll this β the- * server `fileWorkRegistration`, the `EditedFilesCard` and `Work/descriptors` UI.+ * server `workRegistration`, the `EditedFilesCard` and `Work/descriptors` UI.*/export const getBasename = (path: string): string =>path.replaceAll('\\', '/').split('/').findLast(Boolean)?.trim() ?? '';diff --git a/packages/database/src/models/message.ts b/packages/database/src/models/message.tsindex e5383f1e77b..d9fa940246e 100644--- a/packages/database/src/models/message.ts+++ b/packages/database/src/models/message.ts@@ -2712,7 +2712,7 @@ export class MessageModel {startedAt: Date;threadId?: string | null;topicId: string;- }): Promise<Array<MessagePluginItem & { createdAt: Date }>> => {+ }): Promise<Array<MessagePluginItem & { content?: string; createdAt: Date }>> => {const completedAt = params.completedAt ?? new Date();const withinWindow = and(@@ -2729,6 +2729,11 @@ export class MessageModel {apiName: messagePlugins.apiName,arguments: messagePlugins.arguments,clientId: messagePlugins.clientId,+ // The tool message's text body. Heterogeneous CLI adapters (claude-code+ // Bash) persist the command's stdout here rather than in a structured+ // `state` field, and the completion-time github Work scan reads the gh+ // CLI's printed entity URL from it.+ content: messages.content,createdAt: messages.createdAt,error: messagePlugins.error,id: messagePlugins.id,@@ -2748,6 +2753,7 @@ export class MessageModel {apiName: row.apiName ?? undefined,arguments: row.arguments ?? undefined,clientId: row.clientId ?? undefined,+ content: row.content ?? undefined,createdAt: row.createdAt,error: row.error ?? undefined,id: row.id,diff --git a/packages/database/src/models/work/__tests__/githubToolResult.test.ts b/packages/database/src/models/work/__tests__/githubToolResult.test.tsindex b1b74347607..dd618157d3e 100644--- a/packages/database/src/models/work/__tests__/githubToolResult.test.ts+++ b/packages/database/src/models/work/__tests__/githubToolResult.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { normalizeGithubToolResult } from '../githubToolResult';+import { normalizeGithubShellToolResult, normalizeGithubToolResult } from '../githubToolResult';/*** Pins the quoting edge cases of the hand-rolled shell tokenizer behind the@@ -178,3 +178,137 @@ describe('normalizeGithubToolResult (url scheme allowlist)', () => {expect(bad?.params.url).toBeUndefined();});});++/**+ * Heterogeneous / device shell surface (codex `command_execution`, claude-code+ * `Bash`, lobe-local-system `runCommand`): same gh-CLI parsing, but no+ * toolName gate β the caller has already scoped the record to a shell tool.+ */+describe('normalizeGithubShellToolResult', () => {+ it('registers a codex-style gh pr create from command + stdout', () => {+ const operation = normalizeGithubShellToolResult({+ data: {+ command: `git push -u origin fix/tray && gh pr create --title 'Fix tray' --body 'Details'`,+ exitCode: 0,+ output: 'https://github.com/lobehub/lobehub/pull/17654\n',+ },+ toolName: 'command_execution',+ });++ expect(operation?.params).toMatchObject({+ changeType: 'created',+ identifier: 'lobehub/lobehub#17654',+ resourceId: 'lobehub/lobehub#17654',+ resourceType: 'github_pull_request',+ title: 'Fix tray',+ toolName: 'command_execution',+ url: 'https://github.com/lobehub/lobehub/pull/17654',+ });+ });++ it('resolves a claude-code Bash edit target without an exit code', () => {+ // claude-code persists no exitCode; failures are excluded upstream via the+ // plugin error, so a missing exit code must not reject the record.+ const operation = normalizeGithubShellToolResult({+ data: {+ command: `gh issue edit 952 --repo lobehub/lobehub --title 'Better title'`,+ output: 'https://github.com/lobehub/lobehub/issues/952',+ },+ toolName: 'Bash',+ });++ expect(operation?.params).toMatchObject({+ changeType: 'updated',+ identifier: 'lobehub/lobehub#952',+ resourceType: 'github_issue',+ title: 'Better title',+ });+ });++ it('unwraps the codex login-shell wrapper before parsing', () => {+ // Codex spawns every command as `/bin/zsh -lc '<payload>'` and the adapter+ // records that argv verbatim (`adapters/codex.test.ts` fixtures).+ const operation = normalizeGithubShellToolResult({+ data: {+ command: `/bin/zsh -lc 'git push -u origin fix/tray && gh pr create --title "Fix tray"'`,+ exitCode: 0,+ output: 'https://github.com/lobehub/lobehub/pull/17654\n',+ },+ toolName: 'command_execution',+ });++ expect(operation?.params).toMatchObject({+ changeType: 'created',+ identifier: 'lobehub/lobehub#17654',+ resourceType: 'github_pull_request',+ title: 'Fix tray',+ url: 'https://github.com/lobehub/lobehub/pull/17654',+ });+ });++ it('keeps outer segments chained after a -c wrapper', () => {+ // The -c payload replaces only its own segment; `&& gh pr create ...`+ // lives at the OUTER level and must still parse.+ const operation = normalizeGithubShellToolResult({+ data: {+ command: `bash -c 'git push' && gh pr create --repo lobehub/lobehub --title 'Outer chain'`,+ exitCode: 0,+ output: 'https://github.com/lobehub/lobehub/pull/91',+ },+ toolName: 'command_execution',+ });++ expect(operation?.params).toMatchObject({+ changeType: 'created',+ identifier: 'lobehub/lobehub#91',+ title: 'Outer chain',+ });+ });++ it('keeps a non--c shell invocation as an ordinary command chain', () => {+ // `bash ./prepare.sh` runs a script, not a `-c` wrapper β the later gh+ // segment must still parse from the original token stream.+ const operation = normalizeGithubShellToolResult({+ data: {+ command: `bash ./prepare.sh && gh pr create --repo lobehub/lobehub --title 'After script'`,+ exitCode: 0,+ output: 'https://github.com/lobehub/lobehub/pull/90',+ },+ toolName: 'command_execution',+ });++ expect(operation?.params).toMatchObject({+ changeType: 'created',+ identifier: 'lobehub/lobehub#90',+ title: 'After script',+ });+ });++ it('skips failed commands and non-gh shell output', () => {+ expect(+ normalizeGithubShellToolResult({+ data: { command: `gh pr create --title 'x'`, exitCode: 1, output: 'error' },+ toolName: 'command_execution',+ }),+ ).toBeNull();++ expect(+ normalizeGithubShellToolResult({+ data: { command: 'ls -la', exitCode: 0, output: 'README.md' },+ toolName: 'Bash',+ }),+ ).toBeNull();++ // A github URL merely PRINTED by a non-create/edit command must not register.+ expect(+ normalizeGithubShellToolResult({+ data: {+ command: 'gh pr view 17654',+ exitCode: 0,+ output: 'https://github.com/lobehub/lobehub/pull/17654',+ },+ toolName: 'command_execution',+ }),+ ).toBeNull();+ });+});diff --git a/packages/database/src/models/work/githubToolResult.ts b/packages/database/src/models/work/githubToolResult.tsindex 071f25b81ca..361c8705e4f 100644--- a/packages/database/src/models/work/githubToolResult.ts+++ b/packages/database/src/models/work/githubToolResult.ts@@ -6,6 +6,7 @@ import type {} from '@lobechat/types';import { WORK_DESCRIPTION_PREVIEW_LENGTH } from './internal';+import { parseShellCommandSegments } from './shellCommandParsing';import {type ExternalToolWorkOperation,fromRecord,@@ -251,105 +252,6 @@ const buildParams = (// gh CLI (`runCommand`) parsing// ----------------------------------------------------------------------------const CONTROL_OPERATORS = new Set(['&&', '||', ';', '|', '&']);--/**- * Minimal POSIX-ish tokenizer: whitespace splitting with single/double quote- * and backslash handling. Returns null on unterminated quotes β better to- * skip registration than to mis-attribute flag values.- *- * Deliberately hand-rolled instead of adding a `shell-quote`-style dependency:- * a real shell parser would also expand what we must keep literal (`$VAR`,- * globs) and adds a dependency to the database package for a best-effort- * bookkeeping path whose worst failure mode is skipping a Work registration.- * Known trade-off: quoting is stripped before operator splitting, so a quoted- * literal like `--title '&&'` is treated as a control operator and at worst- * truncates the parsed segment. Edge cases are pinned in- * `__tests__/githubToolResult.test.ts`.- */-const tokenizeShellCommand = (input: string): string[] | null => {- const tokens: string[] = [];- let current = '';- let hasCurrent = false;- let i = 0;-- const push = () => {- if (hasCurrent) {- tokens.push(current);- current = '';- hasCurrent = false;- }- };-- while (i < input.length) {- const ch = input[i];-- if (ch === "'") {- const end = input.indexOf("'", i + 1);- if (end === -1) return null;- current += input.slice(i + 1, end);- hasCurrent = true;- i = end + 1;- } else if (ch === '"') {- i++;- let closed = false;- while (i < input.length) {- const c = input[i];- if (c === '\\' && '"\\$`'.includes(input[i + 1] ?? '')) {- current += input[i + 1];- i += 2;- } else if (c === '"') {- closed = true;- i++;- break;- } else {- current += c;- i++;- }- }- if (!closed) return null;- hasCurrent = true;- } else if (ch === '\\') {- // Backslash-newline is a line continuation; otherwise escape the next char.- if (input[i + 1] === '\n') {- i += 2;- } else {- current += input[i + 1] ?? '';- hasCurrent = true;- i += 2;- }- } else if (/\s/.test(ch)) {- push();- i++;- } else {- current += ch;- hasCurrent = true;- i++;- }- }-- push();- return tokens;-};--/** Split a token stream on whitespace-separated shell control operators. */-const splitCommandSegments = (tokens: string[]): string[][] => {- const segments: string[][] = [];- let current: string[] = [];-- for (const token of tokens) {- if (CONTROL_OPERATORS.has(token)) {- if (current.length > 0) segments.push(current);- current = [];- } else {- current.push(token);- }- }-- if (current.length > 0) segments.push(current);- return segments;-};-/*** gh flags that consume a value. Needed even for flags we don't extract, so* their values are not misread as positional targets (`gh issue edit 952`).@@ -520,12 +422,12 @@ const normalizeGithubCliResult = (const command = fromRecord(record, ['command']) ?? fromRecord(args, ['command']);if (!command) return null;- const tokens = tokenizeShellCommand(command);- if (!tokens) return null;+ const segments = parseShellCommandSegments(command);+ if (!segments) return null;// A chained command (`git push && gh pr create ...`) reports one combined// stdout; the trailing URL belongs to the last gh create/edit segment.- const parsed = splitCommandSegments(tokens)+ const parsed = segments.map(parseGhSegment).findLast((segment): segment is ParsedGhCommand => !!segment);if (!parsed) return null;@@ -586,6 +488,25 @@ const normalizeGithubCliResult = (};};+/**+ * Normalize a HETEROGENEOUS / device shell tool result (codex+ * `command_execution`, claude-code `Bash`, lobe-local-system `runCommand`) that+ * may have run `gh issue|pr create/edit`.+ *+ * Reuses the github skill's gh-CLI parsing wholesale: callers present the+ * record as `data: { command, output, exitCode }`. Unlike+ * {@link normalizeGithubToolResult} there is no toolName gate β the caller has+ * already scoped the record to a shell tool, and `toolName` carries the real+ * provenance name (`Bash` / `command_execution` / `runCommand`).+ */+export const normalizeGithubShellToolResult = (+ params: SkillToolResultWorkInput,+): ExternalToolWorkOperation | null => {+ if (isApplicationError(params.data)) return null;++ return normalizeGithubCliResult(params);+};+export const normalizeGithubToolResult = (params: SkillToolResultWorkInput,): ExternalToolWorkOperation | null => {diff --git a/packages/database/src/models/work/index.ts b/packages/database/src/models/work/index.tsindex 586b2c45efe..95512ac1919 100644--- a/packages/database/src/models/work/index.ts+++ b/packages/database/src/models/work/index.ts@@ -17,7 +17,7 @@ import type { WorkContext } from './context';import { registerDocumentWork } from './document';import { registerExternalWork } from './external';import { findFileWorkVersionByToolCall, registerFileWork } from './file';-import { normalizeGithubToolResult } from './githubToolResult';+import { normalizeGithubShellToolResult, normalizeGithubToolResult } from './githubToolResult';import { normalizeLinearToolResult } from './linearToolResult';import * as queries from './queries';import { registerTaskWork } from './task';@@ -89,6 +89,26 @@ export class WorkModel {return this.registerExternal({ ...operation.params, toolIdentifier: provider });};+ /**+ * Register a github Work from a heterogeneous / device SHELL tool result+ * (codex `command_execution`, claude-code `Bash`, lobe-local-system+ * `runCommand`) that ran `gh issue|pr create/edit`. Unlike+ * {@link handleSkillToolResult} the version keeps the REAL producing tool as+ * its identifier (codex / claude-code / β¦) instead of a skill provider β+ * the github identity still lands on the same `owner/repo#number` Work row,+ * so both surfaces dedupe together.+ */+ registerShellGithubResult = async (+ params: SkillToolResultWorkInput & { toolIdentifier: string },+ ): Promise<WorkItem | null> => {+ const { toolIdentifier, ...rest } = params;++ const operation = normalizeGithubShellToolResult(rest);+ if (!operation) return null;++ return this.registerExternal({ ...operation.params, toolIdentifier });+ };+deleteDocumentWork = (params: DeleteDocumentWorkParams): Promise<void> =>writes.deleteDocumentWork(this.ctx, params);diff --git a/packages/database/src/models/work/shellCommandParsing.ts b/packages/database/src/models/work/shellCommandParsing.tsnew file mode 100644index 00000000000..f34cc85f0c5--- /dev/null+++ b/packages/database/src/models/work/shellCommandParsing.ts@@ -0,0 +1,149 @@+/**+ * Command-agnostic shell command parsing shared by the shell-Work normalizers+ * (github today; any future CLI whose runs should register Works). Everything+ * here is about turning raw shell command TEXT into simple-command token+ * segments β nothing in this module knows about `gh` or any other CLI.+ */++const CONTROL_OPERATORS = new Set(['&&', '||', ';', '|', '&']);++/**+ * Minimal POSIX-ish tokenizer: whitespace splitting with single/double quote+ * and backslash handling. Returns null on unterminated quotes β better to+ * skip registration than to mis-attribute flag values.+ *+ * Deliberately hand-rolled instead of adding a `shell-quote`-style dependency:+ * a real shell parser would also expand what we must keep literal (`$VAR`,+ * globs) and adds a dependency to the database package for a best-effort+ * bookkeeping path whose worst failure mode is skipping a Work registration.+ * Known trade-off: quoting is stripped before operator splitting, so a quoted+ * literal like `--title '&&'` is treated as a control operator and at worst+ * truncates the parsed segment. Edge cases are pinned in+ * `__tests__/githubToolResult.test.ts`.+ */+const tokenizeShellCommand = (input: string): string[] | null => {+ const tokens: string[] = [];+ let current = '';+ let hasCurrent = false;+ let i = 0;++ const push = () => {+ if (hasCurrent) {+ tokens.push(current);+ current = '';+ hasCurrent = false;+ }+ };++ while (i < input.length) {+ const ch = input[i];++ if (ch === "'") {+ const end = input.indexOf("'", i + 1);+ if (end === -1) return null;+ current += input.slice(i + 1, end);+ hasCurrent = true;+ i = end + 1;+ } else if (ch === '"') {+ i++;+ let closed = false;+ while (i < input.length) {+ const c = input[i];+ if (c === '\\' && '"\\$`'.includes(input[i + 1] ?? '')) {+ current += input[i + 1];+ i += 2;+ } else if (c === '"') {+ closed = true;+ i++;+ break;+ } else {+ current += c;+ i++;+ }+ }+ if (!closed) return null;+ hasCurrent = true;+ } else if (ch === '\\') {+ // Backslash-newline is a line continuation; otherwise escape the next char.+ if (input[i + 1] === '\n') {+ i += 2;+ } else {+ current += input[i + 1] ?? '';+ hasCurrent = true;+ i += 2;+ }+ } else if (/\s/.test(ch)) {+ push();+ i++;+ } else {+ current += ch;+ hasCurrent = true;+ i++;+ }+ }++ push();+ return tokens;+};++/** Split a token stream on whitespace-separated shell control operators. */+const splitCommandSegments = (tokens: string[]): string[][] => {+ const segments: string[][] = [];+ let current: string[] = [];++ for (const token of tokens) {+ if (CONTROL_OPERATORS.has(token)) {+ if (current.length > 0) segments.push(current);+ current = [];+ } else {+ current.push(token);+ }+ }++ if (current.length > 0) segments.push(current);+ return segments;+};++/**+ * Codex `command_execution` records the spawn argv verbatim, and codex wraps+ * every command in a login shell β `/bin/zsh -lc '<real command>'` (see the+ * adapter fixtures in `heterogeneous-agents/src/adapters/codex.test.ts`). Such+ * a segment's first token is the shell path, not the CLI binary, so the `-c`+ * payload is re-tokenized and re-split (exactly what `-c` itself does) IN+ * PLACE of the wrapper segment β outer segments around it (`bash -c 'git push'+ * && gh pr create ...`) are preserved by the caller's flatMap. Non-wrapper+ * segments (`bash ./prepare.sh`) pass through untouched; a payload with+ * unterminated quoting drops only its own segment.+ */+const expandShellWrapperSegment = (segment: string[]): string[][] => {+ const shell = segment[0]?.split('/').pop();+ if (!shell || !/^(?:ba|da|k)?sh$|^zsh$/.test(shell)) return [segment];++ // Skip option flags; `-c` (possibly bundled, e.g. `-lc`) marks the first+ // non-flag token as the command string. Positionals after it are $0/$1+ // arguments, never part of the command text.+ let hasCommandFlag = false;+ for (let i = 1; i < segment.length; i++) {+ const token = segment[i];+ if (/^-[A-Z]+$/i.test(token)) {+ if (token.includes('c')) hasCommandFlag = true;+ continue;+ }+ if (!hasCommandFlag) return [segment];+ const payload = tokenizeShellCommand(token);+ return payload ? splitCommandSegments(payload) : [];+ }+ return [segment];+};++/**+ * Parse raw shell command text into simple-command token segments: tokenize,+ * split on control operators, and expand login-shell `-c` wrappers in place.+ * Returns null when the text cannot be tokenized (unterminated quoting).+ */+export const parseShellCommandSegments = (command: string): string[][] | null => {+ const tokens = tokenizeShellCommand(command);+ if (!tokens) return null;++ return splitCommandSegments(tokens).flatMap(expandShellWrapperSegment);+};