@neta-art/cohub-cli 10.5.0 → 10.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/dist/commands/runtime.js +21 -8
- package/dist/commands/spaces.js +3 -3
- package/dist/runtime/archive-store.d.ts +2 -2
- package/dist/runtime/archive-store.js +2 -2
- package/dist/runtime/diagnostics.d.ts +3 -3
- package/dist/runtime/harnesses/chained-projection.d.ts +40 -0
- package/dist/runtime/harnesses/chained-projection.js +95 -0
- package/dist/runtime/harnesses/claude.d.ts +8 -0
- package/dist/runtime/harnesses/claude.js +94 -0
- package/dist/runtime/harnesses/codex.d.ts +4 -0
- package/dist/runtime/harnesses/codex.js +229 -0
- package/dist/runtime/harnesses/index.d.ts +16 -0
- package/dist/runtime/harnesses/index.js +57 -0
- package/dist/runtime/harnesses/pi.d.ts +4 -0
- package/dist/runtime/harnesses/pi.js +247 -0
- package/dist/runtime/harnesses/process.d.ts +31 -0
- package/dist/runtime/harnesses/process.js +75 -0
- package/dist/runtime/harnesses/stream-json.d.ts +28 -0
- package/dist/runtime/harnesses/stream-json.js +291 -0
- package/dist/runtime/harnesses/types.d.ts +108 -0
- package/dist/runtime/harnesses/types.js +1 -0
- package/dist/runtime/harnesses/workbuddy.d.ts +15 -0
- package/dist/runtime/harnesses/workbuddy.js +99 -0
- package/dist/runtime/json-rpc.d.ts +7 -1
- package/dist/runtime/json-rpc.js +23 -2
- package/dist/runtime/launch.d.ts +6 -4
- package/dist/runtime/launch.js +21 -11
- package/dist/runtime/native/adapters.d.ts +11 -28
- package/dist/runtime/native/adapters.js +7 -75
- package/dist/runtime/native/archive.d.ts +9 -7
- package/dist/runtime/native/archive.js +99 -38
- package/dist/runtime/native/attach.d.ts +3 -5
- package/dist/runtime/native/attach.js +8 -2
- package/dist/runtime/native/daemon.d.ts +2 -2
- package/dist/runtime/native/daemon.js +5 -4
- package/dist/runtime/native/execution.d.ts +9 -30
- package/dist/runtime/native/execution.js +7 -325
- package/dist/runtime/native/identity.d.ts +4 -4
- package/dist/runtime/native/identity.js +4 -4
- package/dist/runtime/native/ingest.d.ts +2 -2
- package/dist/runtime/native/ingest.js +20 -25
- package/dist/runtime/native/sessions.d.ts +4 -4
- package/dist/runtime/native/sessions.js +12 -22
- package/dist/runtime/native/transcript.d.ts +3 -0
- package/dist/runtime/native/transcript.js +6 -5
- package/dist/runtime/native/translate.d.ts +2 -0
- package/dist/runtime/native/translate.js +34 -1
- package/dist/runtime/native/version.js +1 -1
- package/dist/runtime/presentation.js +2 -1
- package/dist/runtime/projection-store.js +2 -12
- package/dist/runtime/supervisor.d.ts +4 -4
- package/dist/runtime/supervisor.js +1 -1
- package/dist/runtime/turn-projection.d.ts +1 -1
- package/dist/runtime/turn-projection.js +2 -2
- package/package.json +2 -2
- package/dist/runtime/harness.d.ts +0 -26
- package/dist/runtime/harness.js +0 -142
package/README.md
CHANGED
|
@@ -137,7 +137,9 @@ cohub -s home spaces files ls
|
|
|
137
137
|
|
|
138
138
|
## Local Runtime
|
|
139
139
|
|
|
140
|
-
Connect one local workspace to a Space and select Pi or
|
|
140
|
+
Connect one local workspace to a Space and select Pi, Codex, Claude Code or WorkBuddy per turn.
|
|
141
|
+
Claude Code (`claude`) and WorkBuddy (`codebuddy`) run Cohub Turns only; terminal sync covers Pi and Codex.
|
|
142
|
+
Without `--harness`, every installed harness is tried; one that cannot start is skipped with a warning.
|
|
141
143
|
|
|
142
144
|
To keep using native terminals with ordinary Cohub Chats / Turns:
|
|
143
145
|
|
|
@@ -179,7 +181,7 @@ are never uploaded automatically. Use `runtime logs --json` to export a failure
|
|
|
179
181
|
events carry the local `runtimeId` plus server `requestId` / `traceparent` when a turn has
|
|
180
182
|
reached the Agent trace.
|
|
181
183
|
|
|
182
|
-
The Runtime uses WebSockets, native Pi RPC / Codex app-server, and existing cloud
|
|
184
|
+
The Runtime uses WebSockets, native Pi RPC / Codex app-server / Claude Code stream-json, and existing cloud
|
|
183
185
|
streaming. Local executables and credentials are required. `sandbox up` has been
|
|
184
186
|
removed. Reconnection and result reconciliation are automatic; no recovery command is needed.
|
|
185
187
|
When a result genuinely cannot be determined, the affected Chat offers an explicit stop
|
package/dist/commands/runtime.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { setTimeout as delay } from "node:timers/promises";
|
|
2
|
+
import { LOCAL_HARNESS_SPECS, LOCAL_HARNESSES } from "@neta-art/cohub";
|
|
2
3
|
import { createClient } from "../client.js";
|
|
3
4
|
import { json as outJson, jsonRequested } from "../output.js";
|
|
4
5
|
import { currentIdentityKey } from "../space.js";
|
|
@@ -9,6 +10,7 @@ import { RuntimeArchiveStore } from "../runtime/archive-store.js";
|
|
|
9
10
|
import { readNativeConfig, runtimeStateRoot, writeNativeConfig } from "../runtime/native/config.js";
|
|
10
11
|
import { MAX_IMPORT_CONCURRENCY, DEFAULT_IMPORT_CONCURRENCY } from "../runtime/native/ingest.js";
|
|
11
12
|
import { installPiExtension, piExtensionState } from "../runtime/native/install.js";
|
|
13
|
+
import { nativeSyncHarnesses } from "../runtime/harnesses/index.js";
|
|
12
14
|
import { controlRuntimeInstance, requestRuntimeInstance, runtimeInstanceDirectory } from "../runtime/instance.js";
|
|
13
15
|
import { atLeastLevel, diagnosticLevels, formatDiagnostic, formatImportProgress, formatNativeSync, printRuntimeSummary } from "../runtime/presentation.js";
|
|
14
16
|
import { readRuntimeDiagnosticEvents, RuntimeDiagnosticReader, runtimeDiagnosticsDirectory, serializeDiagnosticError } from "../runtime/diagnostics.js";
|
|
@@ -17,6 +19,16 @@ const reportFailure = (cause) => {
|
|
|
17
19
|
process.stderr.write(`Runtime failed: ${serializeDiagnosticError(cause).message}\n`);
|
|
18
20
|
process.exitCode = 1;
|
|
19
21
|
};
|
|
22
|
+
const SYNCED = nativeSyncHarnesses(LOCAL_HARNESSES);
|
|
23
|
+
const SYNCED_LABELS = SYNCED.map((harness) => LOCAL_HARNESS_SPECS[harness].label).join(" or ");
|
|
24
|
+
/** Native sync and import cover only harnesses whose terminal conversations sync. */
|
|
25
|
+
function parseSyncedHarnesses(values) {
|
|
26
|
+
const harnesses = parseRuntimeHarnesses(values);
|
|
27
|
+
const unsynced = harnesses.filter((harness) => !SYNCED.includes(harness));
|
|
28
|
+
if (unsynced.length)
|
|
29
|
+
throw new Error(`${unsynced.map((harness) => LOCAL_HARNESS_SPECS[harness].label).join(", ")} conversations do not sync; native sync covers ${SYNCED_LABELS}`);
|
|
30
|
+
return harnesses;
|
|
31
|
+
}
|
|
20
32
|
const megabytes = (bytes) => `${(bytes / 1024 / 1024).toFixed(1)} MB`;
|
|
21
33
|
/** The bound Space of a directory, with its running Runtime; import and attach act through it. */
|
|
22
34
|
async function boundRuntime(program, dir, space) {
|
|
@@ -32,15 +44,16 @@ async function boundRuntime(program, dir, space) {
|
|
|
32
44
|
}
|
|
33
45
|
export function registerRuntime(program) {
|
|
34
46
|
const runtime = program.command("runtime").description("Connect a local workspace");
|
|
35
|
-
runtime.command("up [dir]")
|
|
47
|
+
const up = runtime.command("up [dir]")
|
|
36
48
|
.description("Connect local Harnesses and files")
|
|
37
49
|
.option("-s, --space <space>", "Target Space: ID, slug, or username/slug")
|
|
38
50
|
.option("-n, --new", "Create a new Space")
|
|
39
51
|
.option("--name <name>", "New Space name")
|
|
40
52
|
.option("-d, --detach", "Run in the background")
|
|
41
|
-
.option("--harness <name>", "
|
|
42
|
-
|
|
43
|
-
.option(
|
|
53
|
+
.option("--harness <name>", `${LOCAL_HARNESSES.join(", ")}; repeatable`, (value, previous) => [...previous, value], []);
|
|
54
|
+
for (const harness of LOCAL_HARNESSES)
|
|
55
|
+
up.option(`--${harness} <path>`, `${LOCAL_HARNESS_SPECS[harness].label} executable`);
|
|
56
|
+
up
|
|
44
57
|
.option("--display [screen]", "Share a screen (default: auto when available), or xvfb[:WIDTHxHEIGHT] for a virtual one")
|
|
45
58
|
.option("--no-display", "Disable screen sharing and skip its confirmation")
|
|
46
59
|
.option("-y, --yes", "Accept defaults and authorize local execution, native sync, and screen sharing")
|
|
@@ -63,7 +76,7 @@ export function registerRuntime(program) {
|
|
|
63
76
|
try {
|
|
64
77
|
const harnesses = parseRuntimeHarnesses(options.harness.length ? options.harness : ["pi"]);
|
|
65
78
|
if (!harnesses.includes("pi"))
|
|
66
|
-
throw new Error("
|
|
79
|
+
throw new Error("Only Pi uses an extension; Codex syncs through runtime up's shared app-server");
|
|
67
80
|
const before = await piExtensionState();
|
|
68
81
|
if (before === "foreign")
|
|
69
82
|
throw new Error("A Pi extension named cohub exists and is not managed by Cohub; move it aside, then retry");
|
|
@@ -84,14 +97,14 @@ export function registerRuntime(program) {
|
|
|
84
97
|
runtime.command("detach")
|
|
85
98
|
.description("Pause native sync; keep all data")
|
|
86
99
|
.option("-s, --space <space>", "Target Space: ID, slug, or username/slug")
|
|
87
|
-
.option("--harness <name>",
|
|
100
|
+
.option("--harness <name>", `${SYNCED_LABELS}; repeatable`, (value, previous) => [...previous, value], [])
|
|
88
101
|
.option("--json", "JSON output")
|
|
89
102
|
.action(async (options) => {
|
|
90
103
|
try {
|
|
91
104
|
const { identity, spaceId, directory } = await boundRuntime(program, undefined, options.space);
|
|
92
105
|
const stateRoot = runtimeStateRoot(spaceId);
|
|
93
106
|
const config = await readNativeConfig(stateRoot, identity);
|
|
94
|
-
const paused =
|
|
107
|
+
const paused = options.harness.length ? parseSyncedHarnesses(options.harness) : config?.harnesses ?? SYNCED;
|
|
95
108
|
const harnesses = (config?.harnesses ?? []).filter((harness) => !paused.includes(harness));
|
|
96
109
|
if (config)
|
|
97
110
|
await writeNativeConfig(stateRoot, { ...config, harnesses, codexShared: harnesses.includes("codex") && config.codexShared });
|
|
@@ -131,7 +144,7 @@ export function registerRuntime(program) {
|
|
|
131
144
|
throw new Error(`Use a concurrency from 1 to ${MAX_IMPORT_CONCURRENCY}`);
|
|
132
145
|
const { spaceId, root, directory } = await boundRuntime(program, dir, options.space);
|
|
133
146
|
// The Runtime does the work, so an import survives this command: Ctrl-C only pauses it.
|
|
134
|
-
const filter = { harnesses: options.harness.length ?
|
|
147
|
+
const filter = { harnesses: options.harness.length ? parseSyncedHarnesses(options.harness) : [], ...(options.session ? { nativeSessionId: options.session } : {}) };
|
|
135
148
|
const control = async (command, timeoutMs = 60_000) => {
|
|
136
149
|
const response = await controlRuntimeInstance(directory, "import", { ...filter, command, concurrency }, timeoutMs);
|
|
137
150
|
if (!response)
|
package/dist/commands/spaces.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { readdir, stat } from "node:fs/promises";
|
|
2
2
|
import { basename, dirname, relative, resolve, sep } from "node:path";
|
|
3
|
-
import { readSentTurns, readSessionTurnOrigin, resolveCohubEnvironment } from "@neta-art/cohub";
|
|
3
|
+
import { harnessSchema, readSentTurns, readSessionTurnOrigin, resolveCohubEnvironment } from "@neta-art/cohub";
|
|
4
4
|
import { uploadAvatarAsset, uploadChatImageAsset } from "../avatar.js";
|
|
5
5
|
import { createClient } from "../client.js";
|
|
6
6
|
import { collectOption, readPromptContent } from "../command-input.js";
|
|
@@ -344,7 +344,7 @@ export function registerPrompt(program) {
|
|
|
344
344
|
.option("--title <title>", "Title for a newly created session or schedule")
|
|
345
345
|
.option("-m, --model <model>", "Model name")
|
|
346
346
|
.option("-p, --provider <provider>", "Provider name")
|
|
347
|
-
.option("--harness <harness>",
|
|
347
|
+
.option("--harness <harness>", `Harness: ${harnessSchema.options.join(", ")}`, "cohub")
|
|
348
348
|
.option("--thinking-level <level>", "Thinking level: off|minimal|low|medium|high|xhigh|max")
|
|
349
349
|
.option("--read-only", "Use read-only tools")
|
|
350
350
|
.option("--steer", "Interrupt the current turn and run immediately")
|
|
@@ -703,7 +703,7 @@ export function registerSpaces(program) {
|
|
|
703
703
|
.command("prompt [content...]", { hidden: true })
|
|
704
704
|
.alias("send")
|
|
705
705
|
.description("Send or schedule a prompt in the target space")
|
|
706
|
-
.option("--harness <harness>",
|
|
706
|
+
.option("--harness <harness>", `Harness: ${harnessSchema.options.join(", ")}`, "cohub")
|
|
707
707
|
.option("--session <id>", "Target session ID")
|
|
708
708
|
.option("--title <title>", "Title for a newly created session or schedule")
|
|
709
709
|
.option("-m, --model <model>", "Model name")
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type HarnessArchive, type HarnessArchiveIndex, type RuntimeArchivePage, type RuntimeArchiveUpload } from "@neta-art/cohub";
|
|
1
|
+
import { type LocalHarness, type HarnessArchive, type HarnessArchiveIndex, type RuntimeArchivePage, type RuntimeArchiveUpload } from "@neta-art/cohub";
|
|
2
2
|
export type ArchiveTransport = {
|
|
3
3
|
fetchObject?: typeof fetch;
|
|
4
4
|
prepareRuntimeArchive(index: HarnessArchiveIndex, options?: {
|
|
@@ -41,7 +41,7 @@ export declare class RuntimeArchiveStore {
|
|
|
41
41
|
private readIndex;
|
|
42
42
|
stage(state: {
|
|
43
43
|
sessionId: string;
|
|
44
|
-
harness:
|
|
44
|
+
harness: LocalHarness;
|
|
45
45
|
nativeSessionId: string;
|
|
46
46
|
path: string;
|
|
47
47
|
sizeBytes?: number;
|
|
@@ -2,7 +2,7 @@ import { createHash, randomUUID } from "node:crypto";
|
|
|
2
2
|
import { createReadStream } from "node:fs";
|
|
3
3
|
import { mkdir, open, readFile, readdir, rename, rm, stat, link } from "node:fs/promises";
|
|
4
4
|
import { dirname, join } from "node:path";
|
|
5
|
-
import { RUNTIME_ARCHIVE_SEGMENT_BYTES, harnessArchiveIndexSchema, validateArchiveBoundary, } from "@neta-art/cohub";
|
|
5
|
+
import { LOCAL_HARNESS_SPECS, RUNTIME_ARCHIVE_SEGMENT_BYTES, harnessArchiveIndexSchema, validateArchiveBoundary, } from "@neta-art/cohub";
|
|
6
6
|
const missing = (error) => error?.code === "ENOENT";
|
|
7
7
|
/** Raised when local capture bytes fail integrity checks (checksum, truncation, boundary); retryable via cache rebuild. */
|
|
8
8
|
export class ArchiveCaptureIntegrityError extends Error {
|
|
@@ -195,7 +195,7 @@ export class RuntimeArchiveStore {
|
|
|
195
195
|
}
|
|
196
196
|
}
|
|
197
197
|
index = harnessArchiveIndexSchema.parse({ ...identity, version: 1, nativeSessionId: state.nativeSessionId,
|
|
198
|
-
nativeFormat: state.harness
|
|
198
|
+
nativeFormat: LOCAL_HARNESS_SPECS[state.harness].nativeFormat, parentTurnId: parent?.turnId ?? null,
|
|
199
199
|
sizeBytes, sha256: digest.digest("hex"), segments });
|
|
200
200
|
validateArchiveBoundary(index, parent);
|
|
201
201
|
if (state.expectedChecksum && index.sha256 !== state.expectedChecksum)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { RuntimeTraceContext } from "@neta-art/cohub";
|
|
1
|
+
import type { LocalHarness, RuntimeTraceContext } from "@neta-art/cohub";
|
|
2
2
|
export type RuntimeDiagnosticLevel = "debug" | "info" | "warn" | "error";
|
|
3
3
|
export type RuntimeDiagnosticError = {
|
|
4
4
|
name?: string;
|
|
@@ -27,7 +27,7 @@ export type RuntimeDiagnostic = {
|
|
|
27
27
|
spaceId: string;
|
|
28
28
|
sessionId?: string | null;
|
|
29
29
|
turnId?: string | null;
|
|
30
|
-
harness?:
|
|
30
|
+
harness?: LocalHarness | null;
|
|
31
31
|
traceContext?: RuntimeTraceContext;
|
|
32
32
|
data?: Record<string, unknown>;
|
|
33
33
|
error?: RuntimeDiagnosticError;
|
|
@@ -39,7 +39,7 @@ export type RuntimeDiagnosticContext = {
|
|
|
39
39
|
spaceId?: string;
|
|
40
40
|
sessionId?: string | null;
|
|
41
41
|
turnId?: string | null;
|
|
42
|
-
harness?:
|
|
42
|
+
harness?: LocalHarness | null;
|
|
43
43
|
traceContext?: RuntimeTraceContext;
|
|
44
44
|
};
|
|
45
45
|
export type RuntimeDiagnosticsOptions = {
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { type CanonicalProjectionMessage, type ContentBlock, type LocalHarness, type NativeProjection, type ProjectionInput, type ProjectionRecord } from "@neta-art/cohub";
|
|
2
|
+
type ToolResult = Extract<ContentBlock, {
|
|
3
|
+
type: "tool_result";
|
|
4
|
+
}>;
|
|
5
|
+
/** Deterministic, UUID-shaped record ids keep re-projection stable without local state. */
|
|
6
|
+
export declare function projectionUuid(key: string): string;
|
|
7
|
+
/** Provider APIs restrict tool ids; hashing keeps call/result pairs linked. */
|
|
8
|
+
export declare function projectionToolId(id: string): string;
|
|
9
|
+
export type ProjectedSegment = {
|
|
10
|
+
role: "user" | "assistant";
|
|
11
|
+
blocks: ContentBlock[];
|
|
12
|
+
message: CanonicalProjectionMessage;
|
|
13
|
+
compactSummary: boolean;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Shared walk for transcript formats whose records form a parent-linked chain. `write` maps one
|
|
17
|
+
* user/assistant segment to native records; ids and parent links are assigned here.
|
|
18
|
+
*/
|
|
19
|
+
export declare function projectChainedSession(input: ProjectionInput, target: LocalHarness, fields: {
|
|
20
|
+
id: string;
|
|
21
|
+
parent: string;
|
|
22
|
+
}, write: (segment: ProjectedSegment) => Record<string, unknown>[]): NativeProjection;
|
|
23
|
+
export declare const projectionMeta: (input: ProjectionInput, message: CanonicalProjectionMessage) => {
|
|
24
|
+
messageId: string;
|
|
25
|
+
turnId: string;
|
|
26
|
+
schema: string;
|
|
27
|
+
spaceId: string;
|
|
28
|
+
sessionId: string;
|
|
29
|
+
};
|
|
30
|
+
export declare const toolResultText: (block: ToolResult) => string;
|
|
31
|
+
/** Session id is stored on every record of these formats. */
|
|
32
|
+
export declare const rebindSessionId: (records: ProjectionRecord[], nativeSessionId: string) => {
|
|
33
|
+
key: string;
|
|
34
|
+
sourceTurnId: string | null;
|
|
35
|
+
sourceMessageId: string | null;
|
|
36
|
+
record: {
|
|
37
|
+
sessionId: string;
|
|
38
|
+
};
|
|
39
|
+
}[];
|
|
40
|
+
export {};
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { fingerprintProjectionTurns, isProjectionCompaction, isProjectionPendingGeneration, projectNativeMessageMeta, trimProjectionTurnsToCompaction, } from "@neta-art/cohub";
|
|
3
|
+
/** Deterministic, UUID-shaped record ids keep re-projection stable without local state. */
|
|
4
|
+
export function projectionUuid(key) {
|
|
5
|
+
const hex = createHash("sha256").update(key).digest("hex");
|
|
6
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-5${hex.slice(13, 16)}-${((Number.parseInt(hex[16] ?? "0", 16) & 3) | 8).toString(16)}${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
|
|
7
|
+
}
|
|
8
|
+
/** Provider APIs restrict tool ids; hashing keeps call/result pairs linked. */
|
|
9
|
+
export function projectionToolId(id) {
|
|
10
|
+
return /^[A-Za-z0-9_-]{1,64}$/.test(id) ? id : `call_${createHash("sha256").update(id).digest("hex").slice(0, 32)}`;
|
|
11
|
+
}
|
|
12
|
+
const nonEmpty = (block) => block.type !== "text" || block.text.length > 0;
|
|
13
|
+
/**
|
|
14
|
+
* Splits Cohub messages into alternating native records. A tool call is kept only with its result,
|
|
15
|
+
* because provider APIs reject unpaired calls; dropped content is reported as a projection warning.
|
|
16
|
+
*/
|
|
17
|
+
function segments(message, warnings) {
|
|
18
|
+
const warn = (reason) => warnings.push({ sourceMessageId: message.id, sourceTurnId: message.turnId, reason });
|
|
19
|
+
if (message.content.some((block) => block.type === "image" && block.source.type === "url"))
|
|
20
|
+
warn("external image URL omitted from native projection");
|
|
21
|
+
const visible = message.content.filter((block) => nonEmpty(block) && !(block.type === "image" && block.source.type === "url"));
|
|
22
|
+
if (message.role === "user") {
|
|
23
|
+
const blocks = visible.filter((block) => block.type === "text" || block.type === "image");
|
|
24
|
+
return blocks.length ? [{ role: "user", blocks }] : [];
|
|
25
|
+
}
|
|
26
|
+
const raw = [];
|
|
27
|
+
for (const block of visible) {
|
|
28
|
+
const role = block.type === "tool_result" ? "user" : "assistant";
|
|
29
|
+
if (role === "assistant" && !["text", "tool_use"].includes(block.type))
|
|
30
|
+
continue;
|
|
31
|
+
const last = raw.at(-1);
|
|
32
|
+
if (last?.role === role)
|
|
33
|
+
last.blocks.push(block);
|
|
34
|
+
else
|
|
35
|
+
raw.push({ role, blocks: [block] });
|
|
36
|
+
}
|
|
37
|
+
const paired = [];
|
|
38
|
+
raw.forEach((segment, index) => {
|
|
39
|
+
if (segment.role === "assistant") {
|
|
40
|
+
const results = new Set(raw[index + 1]?.role === "user" ? raw[index + 1]?.blocks.flatMap((block) => block.type === "tool_result" ? [block.tool_use_id] : []) : []);
|
|
41
|
+
const blocks = segment.blocks.filter((block) => block.type !== "tool_use" || results.has(block.id));
|
|
42
|
+
if (blocks.length !== segment.blocks.length)
|
|
43
|
+
warn("tool call without a result omitted from native projection");
|
|
44
|
+
if (blocks.length)
|
|
45
|
+
paired.push({ role: "assistant", blocks });
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
const calls = new Set(raw[index - 1]?.role === "assistant" ? raw[index - 1]?.blocks.flatMap((block) => block.type === "tool_use" ? [block.id] : []) : []);
|
|
49
|
+
const blocks = segment.blocks.filter((block) => block.type === "tool_result" && calls.has(block.tool_use_id));
|
|
50
|
+
if (blocks.length !== segment.blocks.length)
|
|
51
|
+
warn("tool result without a call omitted from native projection");
|
|
52
|
+
if (blocks.length)
|
|
53
|
+
paired.push({ role: "user", blocks });
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
return paired;
|
|
57
|
+
}
|
|
58
|
+
const compactionText = (message) => message.content.flatMap((block) => block.type === "system_note" ? [block.text] : []).join("\n");
|
|
59
|
+
/**
|
|
60
|
+
* Shared walk for transcript formats whose records form a parent-linked chain. `write` maps one
|
|
61
|
+
* user/assistant segment to native records; ids and parent links are assigned here.
|
|
62
|
+
*/
|
|
63
|
+
export function projectChainedSession(input, target, fields, write) {
|
|
64
|
+
const warnings = [];
|
|
65
|
+
const records = [];
|
|
66
|
+
let parentId = null;
|
|
67
|
+
for (const turn of trimProjectionTurnsToCompaction(input.turns)) {
|
|
68
|
+
for (const message of turn.messages) {
|
|
69
|
+
if (isProjectionPendingGeneration(message))
|
|
70
|
+
continue;
|
|
71
|
+
const parts = isProjectionCompaction(message)
|
|
72
|
+
? compactionText(message) ? [{ role: "user", blocks: [{ type: "text", text: compactionText(message) }], compactSummary: true }] : []
|
|
73
|
+
: message.role === "system" ? [] : segments(message, warnings).map((segment) => ({ ...segment, compactSummary: false }));
|
|
74
|
+
let ordinal = 0;
|
|
75
|
+
for (const part of parts) {
|
|
76
|
+
for (const native of write({ ...part, message })) {
|
|
77
|
+
const key = `${message.id}:${message.turnId}:${ordinal++}`;
|
|
78
|
+
const id = projectionUuid(`${input.sessionId}:${key}`);
|
|
79
|
+
records.push({ key, sourceTurnId: message.turnId, sourceMessageId: message.id, record: { [fields.parent]: parentId, [fields.id]: id, ...native } });
|
|
80
|
+
parentId = id;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
const last = input.turns.at(-1);
|
|
86
|
+
return { target, records, cursor: { sourceSequence: last?.sequence ?? null, sourceTurnId: last?.sourceTurnId ?? null, sourceFingerprint: fingerprintProjectionTurns(input.turns) }, warnings };
|
|
87
|
+
}
|
|
88
|
+
export const projectionMeta = (input, message) => ({
|
|
89
|
+
schema: "cohub.projection.v2", spaceId: input.spaceId, sessionId: input.sessionId, ...projectNativeMessageMeta(message),
|
|
90
|
+
});
|
|
91
|
+
export const toolResultText = (block) => typeof block.content === "string"
|
|
92
|
+
? block.content
|
|
93
|
+
: block.content.flatMap((item) => item.type === "text" ? [item.text] : []).join("\n");
|
|
94
|
+
/** Session id is stored on every record of these formats. */
|
|
95
|
+
export const rebindSessionId = (records, nativeSessionId) => records.map((entry) => ({ ...entry, record: { ...entry.record, sessionId: nativeSessionId } }));
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { LocalHarnessAdapter } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Claude Code names a project directory by replacing every non-alphanumeric UTF-16 unit; a longer
|
|
4
|
+
* name keeps its first 200 units and appends the base-36 Java string hash of the path.
|
|
5
|
+
*/
|
|
6
|
+
export declare function claudeProjectName(cwd: string): string;
|
|
7
|
+
export declare const claudeProjectDirectory: (cwd: string) => string;
|
|
8
|
+
export declare const claudeHarness: LocalHarnessAdapter;
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { copyNativeArchive } from "../native/archive.js";
|
|
4
|
+
import { projectChainedSession, projectionMeta, projectionToolId, rebindSessionId } from "./chained-projection.js";
|
|
5
|
+
import { DEFAULT_MODEL, runStreamJson, streamJsonHelp, streamJsonModel } from "./stream-json.js";
|
|
6
|
+
const MAX_PROJECT_NAME = 200;
|
|
7
|
+
const dataRoot = () => process.env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), ".claude");
|
|
8
|
+
/**
|
|
9
|
+
* Claude Code names a project directory by replacing every non-alphanumeric UTF-16 unit; a longer
|
|
10
|
+
* name keeps its first 200 units and appends the base-36 Java string hash of the path.
|
|
11
|
+
*/
|
|
12
|
+
export function claudeProjectName(cwd) {
|
|
13
|
+
const name = cwd.replace(/[^a-zA-Z0-9]/g, "-");
|
|
14
|
+
if (name.length <= MAX_PROJECT_NAME)
|
|
15
|
+
return name;
|
|
16
|
+
let hash = 0;
|
|
17
|
+
for (let index = 0; index < cwd.length; index++)
|
|
18
|
+
hash = (hash * 31 + cwd.charCodeAt(index)) | 0;
|
|
19
|
+
return `${name.slice(0, MAX_PROJECT_NAME)}-${Math.abs(hash).toString(36)}`;
|
|
20
|
+
}
|
|
21
|
+
export const claudeProjectDirectory = (cwd) => join(dataRoot(), "projects", claudeProjectName(cwd));
|
|
22
|
+
const profile = {
|
|
23
|
+
harness: "claude",
|
|
24
|
+
label: "Claude Code",
|
|
25
|
+
binary: "claude",
|
|
26
|
+
provider: "anthropic",
|
|
27
|
+
dataRoot,
|
|
28
|
+
projectDirectory: claudeProjectDirectory,
|
|
29
|
+
effortLevels: ["low", "medium", "high", "xhigh", "max"],
|
|
30
|
+
};
|
|
31
|
+
function anthropicBlock(block) {
|
|
32
|
+
if (block.type === "text")
|
|
33
|
+
return { type: "text", text: block.text };
|
|
34
|
+
if (block.type === "image" && block.source.type === "base64")
|
|
35
|
+
return { type: "image", source: { type: "base64", media_type: block.source.media_type, data: block.source.data } };
|
|
36
|
+
if (block.type === "tool_use")
|
|
37
|
+
return { type: "tool_use", id: projectionToolId(block.id), name: block.name.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 128) || "tool", input: block.input };
|
|
38
|
+
if (block.type === "tool_result") {
|
|
39
|
+
const content = typeof block.content === "string" ? block.content : block.content.map(anthropicBlock).filter((item) => item !== null);
|
|
40
|
+
return { type: "tool_result", tool_use_id: projectionToolId(block.tool_use_id), content, is_error: block.is_error ?? false };
|
|
41
|
+
}
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
/** Claude Code merges consecutive assistant records sharing a message id; each projected call gets its own. */
|
|
45
|
+
function withAssistantIds(projection) {
|
|
46
|
+
return { ...projection, records: projection.records.map((entry) => entry.record.type !== "assistant" ? entry : {
|
|
47
|
+
...entry, record: { ...entry.record, message: { id: `msg_${String(entry.record.uuid).replaceAll("-", "")}`, ...entry.record.message } },
|
|
48
|
+
}) };
|
|
49
|
+
}
|
|
50
|
+
export const claudeHarness = {
|
|
51
|
+
id: "claude",
|
|
52
|
+
binary: profile.binary,
|
|
53
|
+
async models(executable, cwd) {
|
|
54
|
+
await streamJsonHelp(profile, executable, cwd);
|
|
55
|
+
// Aliases follow the signed-in account; Haiku takes no effort level.
|
|
56
|
+
return [
|
|
57
|
+
streamJsonModel(profile, DEFAULT_MODEL, "Default", { reasoning: true, isDefault: true }),
|
|
58
|
+
streamJsonModel(profile, "opus", "Claude Opus", { reasoning: true }),
|
|
59
|
+
streamJsonModel(profile, "sonnet", "Claude Sonnet", { reasoning: true }),
|
|
60
|
+
streamJsonModel(profile, "haiku", "Claude Haiku", { reasoning: false }),
|
|
61
|
+
];
|
|
62
|
+
},
|
|
63
|
+
run: (executor, turn) => runStreamJson(profile, executor, turn),
|
|
64
|
+
session: {
|
|
65
|
+
path: (nativeSessionId, cwd) => join(claudeProjectDirectory(cwd), `${nativeSessionId}.jsonl`),
|
|
66
|
+
startsWithoutFile: true,
|
|
67
|
+
project: (input) => withAssistantIds(projectChainedSession(input, "claude", { id: "uuid", parent: "parentUuid" }, (segment) => {
|
|
68
|
+
const content = segment.blocks.map(anthropicBlock).filter((block) => block !== null);
|
|
69
|
+
return [{
|
|
70
|
+
isSidechain: false, userType: "external", cwd: input.cwd, sessionId: input.nativeSessionId, version: "cohub",
|
|
71
|
+
type: segment.role, timestamp: segment.message.createdAt || input.timestamp || new Date(0).toISOString(),
|
|
72
|
+
...(segment.compactSummary ? { isCompactSummary: true } : {}),
|
|
73
|
+
message: segment.role === "user"
|
|
74
|
+
? { role: "user", content }
|
|
75
|
+
: {
|
|
76
|
+
type: "message", role: "assistant", model: segment.message.model || "cohub", content,
|
|
77
|
+
stop_reason: segment.blocks.some((block) => block.type === "tool_use") ? "tool_use" : "end_turn", stop_sequence: null,
|
|
78
|
+
usage: { input_tokens: 0, output_tokens: 0 },
|
|
79
|
+
},
|
|
80
|
+
cohub: projectionMeta(input, segment.message),
|
|
81
|
+
}];
|
|
82
|
+
})),
|
|
83
|
+
rebind: rebindSessionId,
|
|
84
|
+
archive: {
|
|
85
|
+
// The copy takes a fresh id: the archived one may already exist here, and is never replaced.
|
|
86
|
+
target: ({ id, cwd }) => join(claudeProjectDirectory(cwd), `${id}.jsonl`),
|
|
87
|
+
async import(input) {
|
|
88
|
+
const { checksum } = await copyNativeArchive({ ...input, sessionId: input.id });
|
|
89
|
+
return { checksum, nativeSessionId: input.id };
|
|
90
|
+
},
|
|
91
|
+
},
|
|
92
|
+
},
|
|
93
|
+
nativeSync: false,
|
|
94
|
+
};
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { LocalHarnessAdapter, ThreadKind } from "./types.js";
|
|
2
|
+
/** Codex's first line is the only place a thread's purpose is recorded. */
|
|
3
|
+
export declare function codexThreadKind(payload: Record<string, unknown>): ThreadKind;
|
|
4
|
+
export declare const codexHarness: LocalHarnessAdapter;
|