@kenkaiiii/ggcoder 5.93.0 → 5.95.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 +20 -15
- package/dist/app-sidecar/auth-routes.js +42 -45
- package/dist/app-sidecar/auth-routes.js.map +1 -1
- package/dist/app-sidecar/route-context.d.ts +3 -1
- package/dist/app-sidecar/run-control-routes.d.ts +1 -1
- package/dist/app-sidecar/run-control-routes.js +59 -1
- package/dist/app-sidecar/run-control-routes.js.map +1 -1
- package/dist/app-sidecar/usage.js +32 -5
- package/dist/app-sidecar/usage.js.map +1 -1
- package/dist/app-sidecar.js +28 -28
- package/dist/app-sidecar.js.map +1 -1
- package/dist/cli/auth.js +104 -68
- package/dist/cli/auth.js.map +1 -1
- package/dist/cli.js +7 -4
- package/dist/cli.js.map +1 -1
- package/dist/core/agent-session.d.ts +7 -1
- package/dist/core/agent-session.js +195 -70
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/auth/index.d.ts +1 -2
- package/dist/core/auth/index.js +1 -2
- package/dist/core/auth/index.js.map +1 -1
- package/dist/core/claude-code/complete.d.ts +33 -0
- package/dist/core/claude-code/complete.js +113 -0
- package/dist/core/claude-code/complete.js.map +1 -0
- package/dist/core/claude-code/events.d.ts +65 -0
- package/dist/core/claude-code/events.js +434 -0
- package/dist/core/claude-code/events.js.map +1 -0
- package/dist/core/claude-code/loop.d.ts +28 -0
- package/dist/core/claude-code/loop.js +271 -0
- package/dist/core/claude-code/loop.js.map +1 -0
- package/dist/core/claude-code/session-sync.d.ts +28 -0
- package/dist/core/claude-code/session-sync.js +53 -0
- package/dist/core/claude-code/session-sync.js.map +1 -0
- package/dist/core/claude-code/tool-bridge.d.ts +43 -0
- package/dist/core/claude-code/tool-bridge.js +274 -0
- package/dist/core/claude-code/tool-bridge.js.map +1 -0
- package/dist/core/codex-request-shape.d.ts +0 -5
- package/dist/core/codex-request-shape.js +4 -16
- package/dist/core/codex-request-shape.js.map +1 -1
- package/dist/core/compaction/compactor.d.ts +8 -2
- package/dist/core/compaction/compactor.js +13 -5
- package/dist/core/compaction/compactor.js.map +1 -1
- package/dist/core/oauth/openai.d.ts +1 -1
- package/dist/core/oauth/openai.js +1 -1
- package/dist/core/oauth/openai.js.map +1 -1
- package/dist/core/settings-manager.d.ts +0 -5
- package/dist/core/settings-manager.js +0 -5
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/subagent-policy.js +1 -1
- package/dist/core/subagent-policy.js.map +1 -1
- package/dist/system-prompt.js +3 -13
- package/dist/system-prompt.js.map +1 -1
- package/dist/tools/generate-image.d.ts +5 -6
- package/dist/tools/generate-image.js +73 -139
- package/dist/tools/generate-image.js.map +1 -1
- package/dist/tools/side-web-search.d.ts +5 -1
- package/dist/tools/side-web-search.js +61 -1
- package/dist/tools/side-web-search.js.map +1 -1
- package/dist/ui/App.d.ts +0 -2
- package/dist/ui/App.js +4 -4
- package/dist/ui/App.js.map +1 -1
- package/dist/ui/components/Footer.js +2 -0
- package/dist/ui/components/Footer.js.map +1 -1
- package/dist/ui/hooks/useAgentLoop.d.ts +3 -2
- package/dist/ui/hooks/useAgentLoop.js +54 -24
- package/dist/ui/hooks/useAgentLoop.js.map +1 -1
- package/dist/ui/hooks/useContextCompaction.d.ts +1 -2
- package/dist/ui/hooks/useContextCompaction.js +1 -5
- package/dist/ui/hooks/useContextCompaction.js.map +1 -1
- package/dist/ui/render.d.ts +0 -2
- package/dist/ui/render.js +0 -1
- package/dist/ui/render.js.map +1 -1
- package/dist/utils/plan-steps.d.ts +1 -0
- package/dist/utils/plan-steps.js +10 -0
- package/dist/utils/plan-steps.js.map +1 -1
- package/dist/utils/prompt-enhancer.d.ts +3 -3
- package/dist/utils/prompt-enhancer.js +21 -18
- package/dist/utils/prompt-enhancer.js.map +1 -1
- package/package.json +5 -4
- package/dist/core/claude-code-version.d.ts +0 -1
- package/dist/core/claude-code-version.js +0 -3
- package/dist/core/claude-code-version.js.map +0 -1
- package/dist/core/oauth/anthropic.d.ts +0 -1
- package/dist/core/oauth/anthropic.js +0 -3
- package/dist/core/oauth/anthropic.js.map +0 -1
- package/dist/core/oauth/gemini.d.ts +0 -1
- package/dist/core/oauth/gemini.js +0 -3
- package/dist/core/oauth/gemini.js.map +0 -1
- package/dist/core/oauth/kimi.d.ts +0 -1
- package/dist/core/oauth/kimi.js +0 -3
- package/dist/core/oauth/kimi.js.map +0 -1
- package/dist/core/oauth/xai.d.ts +0 -1
- package/dist/core/oauth/xai.js +0 -4
- package/dist/core/oauth/xai.js.map +0 -1
|
@@ -6,7 +6,6 @@
|
|
|
6
6
|
* rather than copy-pasting these files \u2014 every previous fork (gg-editor
|
|
7
7
|
* 0.6.0\u20130.6.6) introduced regressions when small details drifted.
|
|
8
8
|
*/
|
|
9
|
-
export {
|
|
10
|
-
export { loginOpenAI, refreshOpenAIToken } from "../oauth/openai.js";
|
|
9
|
+
export { loginChatGPT, refreshChatGPTToken, revokeChatGPTSignIn } from "../oauth/openai.js";
|
|
11
10
|
export type { OAuthCredentials, OAuthLoginCallbacks } from "../oauth/types.js";
|
|
12
11
|
export { AuthStorage, NotLoggedInError } from "../auth-storage.js";
|
package/dist/core/auth/index.js
CHANGED
|
@@ -6,7 +6,6 @@
|
|
|
6
6
|
* rather than copy-pasting these files \u2014 every previous fork (gg-editor
|
|
7
7
|
* 0.6.0\u20130.6.6) introduced regressions when small details drifted.
|
|
8
8
|
*/
|
|
9
|
-
export {
|
|
10
|
-
export { loginOpenAI, refreshOpenAIToken } from "../oauth/openai.js";
|
|
9
|
+
export { loginChatGPT, refreshChatGPTToken, revokeChatGPTSignIn } from "../oauth/openai.js";
|
|
11
10
|
export { AuthStorage, NotLoggedInError } from "../auth-storage.js";
|
|
12
11
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/auth/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/core/auth/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,YAAY,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAE5F,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC"}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { Message, StreamResponse, ThinkingLevel } from "@kenkaiiii/gg-ai";
|
|
2
|
+
import { type AuthStorage } from "@kenkaiiii/gg-core";
|
|
3
|
+
import type { ClaudeCodeQuery } from "./loop.js";
|
|
4
|
+
/** How to start Claude Code for this session. */
|
|
5
|
+
export interface ClaudeCodeProcess {
|
|
6
|
+
executable: string;
|
|
7
|
+
cwd: string;
|
|
8
|
+
env: Record<string, string | undefined>;
|
|
9
|
+
/** Test seam for the SDK's `query()`. */
|
|
10
|
+
query?: ClaudeCodeQuery;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Claude Code process settings when this session runs on a Claude
|
|
14
|
+
* subscription (Anthropic + the Claude Code sign-in marker), else null.
|
|
15
|
+
*/
|
|
16
|
+
export declare function resolveClaudeCodeProcess(authStorage: Pick<AuthStorage, "hasClaudeCodeLogin">, provider: string, cwd: string): Promise<ClaudeCodeProcess | null>;
|
|
17
|
+
export interface ClaudeCodeCompleteOptions extends ClaudeCodeProcess {
|
|
18
|
+
model: string;
|
|
19
|
+
/** System messages become the system prompt; the rest is sent as one user turn. */
|
|
20
|
+
messages: Message[];
|
|
21
|
+
thinking?: ThinkingLevel;
|
|
22
|
+
signal?: AbortSignal;
|
|
23
|
+
/** Claude Code built-in tools this call may use (e.g. `WebSearch`). Default none. */
|
|
24
|
+
builtinTools?: string[];
|
|
25
|
+
/** Default 1; raise it when `builtinTools` must run before the answer. */
|
|
26
|
+
maxTurns?: number;
|
|
27
|
+
}
|
|
28
|
+
export interface ClaudeCodeCompletion extends StreamResponse {
|
|
29
|
+
/** Structured outputs of the built-in tools that ran, in order. */
|
|
30
|
+
toolOutputs: unknown[];
|
|
31
|
+
}
|
|
32
|
+
/** A single model call through Claude Code: no tools of ours, no saved session. */
|
|
33
|
+
export declare function claudeCodeComplete(opts: ClaudeCodeCompleteOptions): Promise<ClaudeCodeCompletion>;
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { query as sdkQuery, } from "@anthropic-ai/claude-agent-sdk";
|
|
2
|
+
import { claudeCodeEnv, resolveClaudeCodeBinary } from "@kenkaiiii/gg-core";
|
|
3
|
+
import { effortForThinking, fromSdkContentBlock, renderTranscript, toSdkUserContent, toSdkUserMessage, toStopReason, toUsage, } from "./events.js";
|
|
4
|
+
/**
|
|
5
|
+
* Claude Code process settings when this session runs on a Claude
|
|
6
|
+
* subscription (Anthropic + the Claude Code sign-in marker), else null.
|
|
7
|
+
*/
|
|
8
|
+
export async function resolveClaudeCodeProcess(authStorage, provider, cwd) {
|
|
9
|
+
if (provider !== "anthropic" || !(await authStorage.hasClaudeCodeLogin()))
|
|
10
|
+
return null;
|
|
11
|
+
const executable = resolveClaudeCodeBinary();
|
|
12
|
+
if (!executable) {
|
|
13
|
+
throw new Error("Claude Code isn't installed anymore. Sign in with Claude again to restore it.");
|
|
14
|
+
}
|
|
15
|
+
return { executable, cwd, env: claudeCodeEnv() };
|
|
16
|
+
}
|
|
17
|
+
const MAX_CONTEXT_CHARS = 1_000_000;
|
|
18
|
+
function promptContent(messages) {
|
|
19
|
+
const turns = messages.filter((m) => m.role !== "system");
|
|
20
|
+
const last = turns.at(-1);
|
|
21
|
+
const tail = last?.role === "user" ? [last] : [];
|
|
22
|
+
const prior = turns.slice(0, turns.length - tail.length);
|
|
23
|
+
const content = tail.flatMap((m) => toSdkUserContent(m.content));
|
|
24
|
+
if (prior.length > 0) {
|
|
25
|
+
content.unshift({ type: "text", text: renderTranscript(prior, MAX_CONTEXT_CHARS) });
|
|
26
|
+
}
|
|
27
|
+
return content.length > 0 ? content : [{ type: "text", text: "Continue." }];
|
|
28
|
+
}
|
|
29
|
+
/** A single model call through Claude Code: no tools of ours, no saved session. */
|
|
30
|
+
export async function claudeCodeComplete(opts) {
|
|
31
|
+
opts.signal?.throwIfAborted();
|
|
32
|
+
const system = opts.messages
|
|
33
|
+
.filter((m) => m.role === "system")
|
|
34
|
+
.map((m) => m.content)
|
|
35
|
+
.join("\n\n");
|
|
36
|
+
const first = toSdkUserMessage(promptContent(opts.messages));
|
|
37
|
+
const input = (async function* () {
|
|
38
|
+
yield first;
|
|
39
|
+
})();
|
|
40
|
+
const builtins = opts.builtinTools ?? [];
|
|
41
|
+
const abortController = new AbortController();
|
|
42
|
+
const onAbort = () => abortController.abort();
|
|
43
|
+
opts.signal?.addEventListener("abort", onAbort, { once: true });
|
|
44
|
+
const effort = effortForThinking(opts.thinking);
|
|
45
|
+
const sdkOptions = {
|
|
46
|
+
cwd: opts.cwd,
|
|
47
|
+
model: opts.model,
|
|
48
|
+
systemPrompt: { type: "custom", prompt: system },
|
|
49
|
+
tools: builtins,
|
|
50
|
+
allowedTools: builtins,
|
|
51
|
+
canUseTool: async (toolName, toolInput) => builtins.includes(toolName)
|
|
52
|
+
? { behavior: "allow", updatedInput: toolInput }
|
|
53
|
+
: { behavior: "deny", message: `${toolName} is not available here.` },
|
|
54
|
+
settingSources: [],
|
|
55
|
+
strictMcpConfig: true,
|
|
56
|
+
mcpServers: {},
|
|
57
|
+
persistSession: false,
|
|
58
|
+
maxTurns: opts.maxTurns ?? 1,
|
|
59
|
+
pathToClaudeCodeExecutable: opts.executable,
|
|
60
|
+
env: opts.env,
|
|
61
|
+
abortController,
|
|
62
|
+
...(effort
|
|
63
|
+
? { thinking: { type: "adaptive" }, effort }
|
|
64
|
+
: { thinking: { type: "disabled" } }),
|
|
65
|
+
};
|
|
66
|
+
const content = [];
|
|
67
|
+
const toolOutputs = [];
|
|
68
|
+
let syntheticError;
|
|
69
|
+
const q = (opts.query ?? sdkQuery)({ prompt: input, options: sdkOptions });
|
|
70
|
+
try {
|
|
71
|
+
for await (const message of q) {
|
|
72
|
+
if (message.type === "assistant" && !message.parent_tool_use_id) {
|
|
73
|
+
const blocks = message.message.content;
|
|
74
|
+
if (message.message.model === "<synthetic>") {
|
|
75
|
+
syntheticError = blocks.map((b) => (b.type === "text" ? String(b.text) : "")).join("");
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
for (const block of blocks)
|
|
79
|
+
content.push(fromSdkContentBlock(block));
|
|
80
|
+
}
|
|
81
|
+
else if (message.type === "user" && message.tool_use_result !== undefined) {
|
|
82
|
+
toolOutputs.push(message.tool_use_result);
|
|
83
|
+
}
|
|
84
|
+
else if (message.type === "result") {
|
|
85
|
+
if (message.subtype !== "success" && message.subtype !== "error_max_turns") {
|
|
86
|
+
throw new Error(message.errors.join("\n") ||
|
|
87
|
+
syntheticError ||
|
|
88
|
+
`Claude Code stopped: ${message.subtype}`);
|
|
89
|
+
}
|
|
90
|
+
if (message.subtype === "success" && message.is_error) {
|
|
91
|
+
throw new Error(message.result || syntheticError || "Claude Code request failed.");
|
|
92
|
+
}
|
|
93
|
+
return {
|
|
94
|
+
message: { role: "assistant", content },
|
|
95
|
+
stopReason: toStopReason(message.stop_reason),
|
|
96
|
+
usage: toUsage(message.usage),
|
|
97
|
+
toolOutputs,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
catch (error) {
|
|
103
|
+
opts.signal?.throwIfAborted();
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
finally {
|
|
107
|
+
opts.signal?.removeEventListener("abort", onAbort);
|
|
108
|
+
q.close();
|
|
109
|
+
}
|
|
110
|
+
opts.signal?.throwIfAborted();
|
|
111
|
+
throw new Error(syntheticError || "Claude Code ended without a reply.");
|
|
112
|
+
}
|
|
113
|
+
//# sourceMappingURL=complete.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|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Ac;wBACd,wBAAwB,OAAO,CAAC,OAAO,EAAE,CAC5C,CAAC;gBACJ,CAAC;gBACD,IAAI,OAAO,CAAC,OAAO,KAAK,SAAS,IAAI,OAAO,CAAC,QAAQ,EAAE,CAAC;oBACtD,MAAM,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,IAAI,cAAc,IAAI,6BAA6B,CAAC,CAAC;gBACrF,CAAC;gBACD,OAAO;oBACL,OAAO,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,OAAO,EAAE;oBACvC,UAAU,EAAE,YAAY,CAAC,OAAO,CAAC,WAAW,CAAC;oBAC7C,KAAK,EAAE,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC;oBAC7B,WAAW;iBACZ,CAAC;YACJ,CAAC;QACH,CAAC;IACH,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,CAAC,MAAM,EAAE,cAAc,EAAE,CAAC;QAC9B,MAAM,KAAK,CAAC;IACd,CAAC;YAAS,CAAC;QACT,IAAI,CAAC,MAAM,EAAE,mBAAmB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACnD,CAAC,CAAC,KAAK,EAAE,CAAC;IACZ,CAAC;IACD,IAAI,CAAC,MAAM,EAAE,cAAc,EAAE,CAAC;IAC9B,MAAM,IAAI,KAAK,CAAC,cAAc,IAAI,oCAAoC,CAAC,CAAC;AAC1E,CAAC"}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import type { AssistantMessage, ContentPart, Message, StopReason, ThinkingLevel, ToolCall, ToolResult, ToolResultContent, Usage, UserMessage } from "@kenkaiiii/gg-ai";
|
|
2
|
+
import type { AgentEvent } from "@kenkaiiii/gg-agent";
|
|
3
|
+
import type { SDKMessage, SDKRateLimitInfo, SDKUserMessage } from "@anthropic-ai/claude-agent-sdk";
|
|
4
|
+
type EffortLevel = "low" | "medium" | "high" | "xhigh" | "max";
|
|
5
|
+
type Block = Record<string, unknown> & {
|
|
6
|
+
type?: string;
|
|
7
|
+
};
|
|
8
|
+
type UserBlock = Exclude<SDKUserMessage["message"]["content"], string>[number];
|
|
9
|
+
/** Claude Code tops out at `max`; our `ultra` rung means "as much as possible". */
|
|
10
|
+
export declare function effortForThinking(level: ThinkingLevel | undefined): EffortLevel | undefined;
|
|
11
|
+
export declare function toUsage(raw: unknown): Usage;
|
|
12
|
+
export declare function addUsage(total: Usage, usage: Usage): void;
|
|
13
|
+
export declare function toStopReason(raw: unknown): StopReason;
|
|
14
|
+
export declare function fromSdkContentBlock(block: Block): ContentPart;
|
|
15
|
+
/** A tool result Claude Code produced itself (the call never reached our bridge). */
|
|
16
|
+
export declare function fromSdkToolResult(block: Block): ToolResult;
|
|
17
|
+
export declare function resultText(content: ToolResultContent): string;
|
|
18
|
+
/** Text parts of a reply, one per line. */
|
|
19
|
+
export declare function assistantText(content: string | ContentPart[]): string;
|
|
20
|
+
export declare function toSdkUserContent(content: UserMessage["content"]): UserBlock[];
|
|
21
|
+
export declare function toSdkUserMessage(content: UserBlock[]): SDKUserMessage;
|
|
22
|
+
/**
|
|
23
|
+
* Our history as one text block, for a fresh Claude Code session that never
|
|
24
|
+
* saw it. Keeps the newest messages when over `maxChars`.
|
|
25
|
+
*/
|
|
26
|
+
export declare function renderTranscript(messages: readonly Message[], maxChars: number): string;
|
|
27
|
+
export interface SdkMessageMapperOptions {
|
|
28
|
+
/** Live transcript; assistant and tool-result messages are appended to it. */
|
|
29
|
+
messages: Message[];
|
|
30
|
+
/** The bridge's copy of a result (capped exactly as the model saw it). */
|
|
31
|
+
takeResult: (toolCallId: string) => ToolResult | undefined;
|
|
32
|
+
onSessionId?: (sessionId: string) => void;
|
|
33
|
+
onRateLimit?: (info: SDKRateLimitInfo) => void;
|
|
34
|
+
now?: () => number;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Turns the SDK's message stream into our events and transcript. Stateful:
|
|
38
|
+
* one instance per run. `result` messages are left to the loop.
|
|
39
|
+
*/
|
|
40
|
+
export declare class SdkMessageMapper {
|
|
41
|
+
private readonly options;
|
|
42
|
+
turn: number;
|
|
43
|
+
readonly totalUsage: Usage;
|
|
44
|
+
lastAssistant: AssistantMessage | undefined;
|
|
45
|
+
/** Text of Claude Code's own error message (e.g. "API Error: …"), if any. */
|
|
46
|
+
syntheticError: string | undefined;
|
|
47
|
+
private current;
|
|
48
|
+
private turnStartedAt;
|
|
49
|
+
private firstEventAt;
|
|
50
|
+
private stopReason;
|
|
51
|
+
private usage;
|
|
52
|
+
private readonly now;
|
|
53
|
+
constructor(options: SdkMessageMapperOptions);
|
|
54
|
+
/** Tool calls of the latest assistant message that have no result yet. */
|
|
55
|
+
unpairedToolCalls(): ToolCall[];
|
|
56
|
+
handle(msg: SDKMessage): AgentEvent[];
|
|
57
|
+
private handleSystem;
|
|
58
|
+
private handleStreamEvent;
|
|
59
|
+
private endTurn;
|
|
60
|
+
private handleAssistant;
|
|
61
|
+
private handleUser;
|
|
62
|
+
/** Close dangling tool calls (after an abort) so the transcript stays paired. */
|
|
63
|
+
pairDanglingToolCalls(note: string): void;
|
|
64
|
+
}
|
|
65
|
+
export {};
|
|
@@ -0,0 +1,434 @@
|
|
|
1
|
+
import { stripClaudeCodeToolPrefix } from "./tool-bridge.js";
|
|
2
|
+
/** Claude Code tops out at `max`; our `ultra` rung means "as much as possible". */
|
|
3
|
+
export function effortForThinking(level) {
|
|
4
|
+
if (!level)
|
|
5
|
+
return undefined;
|
|
6
|
+
return level === "ultra" ? "max" : level;
|
|
7
|
+
}
|
|
8
|
+
const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : 0);
|
|
9
|
+
export function toUsage(raw) {
|
|
10
|
+
const u = (raw ?? {});
|
|
11
|
+
const usage = { inputTokens: num(u.input_tokens), outputTokens: num(u.output_tokens) };
|
|
12
|
+
const reasoning = num(u.output_tokens_details?.thinking_tokens);
|
|
13
|
+
if (reasoning)
|
|
14
|
+
usage.reasoningTokens = reasoning;
|
|
15
|
+
if (num(u.cache_read_input_tokens))
|
|
16
|
+
usage.cacheRead = num(u.cache_read_input_tokens);
|
|
17
|
+
if (num(u.cache_creation_input_tokens))
|
|
18
|
+
usage.cacheWrite = num(u.cache_creation_input_tokens);
|
|
19
|
+
const server = u.server_tool_use;
|
|
20
|
+
if (num(server?.web_search_requests) || num(server?.web_fetch_requests)) {
|
|
21
|
+
usage.serverToolUse = {
|
|
22
|
+
webSearchRequests: num(server?.web_search_requests),
|
|
23
|
+
webFetchRequests: num(server?.web_fetch_requests),
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
return usage;
|
|
27
|
+
}
|
|
28
|
+
export function addUsage(total, usage) {
|
|
29
|
+
total.inputTokens += usage.inputTokens;
|
|
30
|
+
total.outputTokens += usage.outputTokens;
|
|
31
|
+
if (usage.reasoningTokens)
|
|
32
|
+
total.reasoningTokens = (total.reasoningTokens ?? 0) + usage.reasoningTokens;
|
|
33
|
+
if (usage.cacheRead)
|
|
34
|
+
total.cacheRead = (total.cacheRead ?? 0) + usage.cacheRead;
|
|
35
|
+
if (usage.cacheWrite)
|
|
36
|
+
total.cacheWrite = (total.cacheWrite ?? 0) + usage.cacheWrite;
|
|
37
|
+
if (usage.serverToolUse) {
|
|
38
|
+
const s = (total.serverToolUse ??= {});
|
|
39
|
+
s.webSearchRequests = (s.webSearchRequests ?? 0) + (usage.serverToolUse.webSearchRequests ?? 0);
|
|
40
|
+
s.webFetchRequests = (s.webFetchRequests ?? 0) + (usage.serverToolUse.webFetchRequests ?? 0);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const STOP_REASONS = new Set([
|
|
44
|
+
"end_turn",
|
|
45
|
+
"tool_use",
|
|
46
|
+
"max_tokens",
|
|
47
|
+
"pause_turn",
|
|
48
|
+
"stop_sequence",
|
|
49
|
+
"refusal",
|
|
50
|
+
]);
|
|
51
|
+
export function toStopReason(raw) {
|
|
52
|
+
return typeof raw === "string" && STOP_REASONS.has(raw)
|
|
53
|
+
? raw
|
|
54
|
+
: "end_turn";
|
|
55
|
+
}
|
|
56
|
+
export function fromSdkContentBlock(block) {
|
|
57
|
+
switch (block.type) {
|
|
58
|
+
case "text":
|
|
59
|
+
return { type: "text", text: String(block.text ?? "") };
|
|
60
|
+
case "thinking":
|
|
61
|
+
return {
|
|
62
|
+
type: "thinking",
|
|
63
|
+
text: String(block.thinking ?? ""),
|
|
64
|
+
...(typeof block.signature === "string" ? { signature: block.signature } : {}),
|
|
65
|
+
};
|
|
66
|
+
case "tool_use":
|
|
67
|
+
return {
|
|
68
|
+
type: "tool_call",
|
|
69
|
+
id: String(block.id),
|
|
70
|
+
name: stripClaudeCodeToolPrefix(String(block.name)),
|
|
71
|
+
args: (block.input ?? {}),
|
|
72
|
+
};
|
|
73
|
+
case "server_tool_use":
|
|
74
|
+
return {
|
|
75
|
+
type: "server_tool_call",
|
|
76
|
+
id: String(block.id),
|
|
77
|
+
name: String(block.name),
|
|
78
|
+
input: block.input,
|
|
79
|
+
};
|
|
80
|
+
default:
|
|
81
|
+
if (typeof block.tool_use_id === "string") {
|
|
82
|
+
return {
|
|
83
|
+
type: "server_tool_result",
|
|
84
|
+
toolUseId: block.tool_use_id,
|
|
85
|
+
resultType: String(block.type),
|
|
86
|
+
data: block,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
return { type: "raw", data: block, origin: "claude-code" };
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/** A tool result Claude Code produced itself (the call never reached our bridge). */
|
|
93
|
+
export function fromSdkToolResult(block) {
|
|
94
|
+
const raw = block.content;
|
|
95
|
+
let content;
|
|
96
|
+
if (typeof raw === "string")
|
|
97
|
+
content = raw;
|
|
98
|
+
else if (Array.isArray(raw)) {
|
|
99
|
+
content = raw.map((part) => part.type === "image" && part.source && typeof part.source === "object"
|
|
100
|
+
? {
|
|
101
|
+
type: "image",
|
|
102
|
+
mediaType: String(part.source.media_type ?? "image/png"),
|
|
103
|
+
data: String(part.source.data ?? ""),
|
|
104
|
+
}
|
|
105
|
+
: { type: "text", text: String(part.text ?? "") });
|
|
106
|
+
}
|
|
107
|
+
else
|
|
108
|
+
content = "";
|
|
109
|
+
return {
|
|
110
|
+
type: "tool_result",
|
|
111
|
+
toolCallId: String(block.tool_use_id),
|
|
112
|
+
content,
|
|
113
|
+
...(block.is_error ? { isError: true } : {}),
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
export function resultText(content) {
|
|
117
|
+
if (typeof content === "string")
|
|
118
|
+
return content;
|
|
119
|
+
return content.map((part) => (part.type === "text" ? part.text : `[${part.type}]`)).join("\n");
|
|
120
|
+
}
|
|
121
|
+
/** Text parts of a reply, one per line. */
|
|
122
|
+
export function assistantText(content) {
|
|
123
|
+
if (typeof content === "string")
|
|
124
|
+
return content;
|
|
125
|
+
return content
|
|
126
|
+
.filter((part) => part.type === "text")
|
|
127
|
+
.map((part) => part.text)
|
|
128
|
+
.join("\n");
|
|
129
|
+
}
|
|
130
|
+
export function toSdkUserContent(content) {
|
|
131
|
+
if (typeof content === "string")
|
|
132
|
+
return [{ type: "text", text: content }];
|
|
133
|
+
return content.map((part) => {
|
|
134
|
+
if (part.type === "text")
|
|
135
|
+
return { type: "text", text: part.text };
|
|
136
|
+
if (part.type === "image") {
|
|
137
|
+
return {
|
|
138
|
+
type: "image",
|
|
139
|
+
source: {
|
|
140
|
+
type: "base64",
|
|
141
|
+
media_type: part.mediaType,
|
|
142
|
+
data: part.data,
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
return { type: "text", text: `[${part.type} attachment omitted: not supported here]` };
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
export function toSdkUserMessage(content) {
|
|
150
|
+
return { type: "user", message: { role: "user", content }, parent_tool_use_id: null };
|
|
151
|
+
}
|
|
152
|
+
function messageText(message) {
|
|
153
|
+
if (typeof message.content === "string")
|
|
154
|
+
return message.content;
|
|
155
|
+
const lines = [];
|
|
156
|
+
for (const part of message.content) {
|
|
157
|
+
switch (part.type) {
|
|
158
|
+
case "text":
|
|
159
|
+
lines.push(part.text);
|
|
160
|
+
break;
|
|
161
|
+
case "tool_call":
|
|
162
|
+
lines.push(`[called ${part.name} ${JSON.stringify(part.args)}]`);
|
|
163
|
+
break;
|
|
164
|
+
case "tool_result":
|
|
165
|
+
lines.push(`[${part.isError ? "error" : "result"}] ${resultText(part.content)}`);
|
|
166
|
+
break;
|
|
167
|
+
case "image":
|
|
168
|
+
case "video":
|
|
169
|
+
lines.push(`[${part.type}]`);
|
|
170
|
+
break;
|
|
171
|
+
default:
|
|
172
|
+
break;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return lines.join("\n");
|
|
176
|
+
}
|
|
177
|
+
const ROLE_LABEL = {
|
|
178
|
+
system: "System",
|
|
179
|
+
user: "User",
|
|
180
|
+
assistant: "Assistant",
|
|
181
|
+
tool: "Tool",
|
|
182
|
+
};
|
|
183
|
+
/**
|
|
184
|
+
* Our history as one text block, for a fresh Claude Code session that never
|
|
185
|
+
* saw it. Keeps the newest messages when over `maxChars`.
|
|
186
|
+
*/
|
|
187
|
+
export function renderTranscript(messages, maxChars) {
|
|
188
|
+
const entries = [];
|
|
189
|
+
let used = 0;
|
|
190
|
+
let dropped = 0;
|
|
191
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
192
|
+
const message = messages[i];
|
|
193
|
+
if (message.role === "system")
|
|
194
|
+
continue;
|
|
195
|
+
const text = messageText(message).trim();
|
|
196
|
+
if (!text)
|
|
197
|
+
continue;
|
|
198
|
+
const entry = `${ROLE_LABEL[message.role]}: ${text}`;
|
|
199
|
+
if (used + entry.length > maxChars) {
|
|
200
|
+
dropped = i + 1;
|
|
201
|
+
break;
|
|
202
|
+
}
|
|
203
|
+
entries.unshift(entry);
|
|
204
|
+
used += entry.length + 2;
|
|
205
|
+
}
|
|
206
|
+
const head = dropped > 0 ? `[${dropped} earlier messages omitted]\n\n` : "";
|
|
207
|
+
return ("<conversation_so_far>\nThis conversation started before this session. " +
|
|
208
|
+
"Earlier messages, oldest first:\n\n" +
|
|
209
|
+
head +
|
|
210
|
+
entries.join("\n\n") +
|
|
211
|
+
"\n</conversation_so_far>");
|
|
212
|
+
}
|
|
213
|
+
const SYNTHETIC_MODEL = "<synthetic>";
|
|
214
|
+
/**
|
|
215
|
+
* Turns the SDK's message stream into our events and transcript. Stateful:
|
|
216
|
+
* one instance per run. `result` messages are left to the loop.
|
|
217
|
+
*/
|
|
218
|
+
export class SdkMessageMapper {
|
|
219
|
+
options;
|
|
220
|
+
turn = 0;
|
|
221
|
+
totalUsage = { inputTokens: 0, outputTokens: 0 };
|
|
222
|
+
lastAssistant;
|
|
223
|
+
/** Text of Claude Code's own error message (e.g. "API Error: …"), if any. */
|
|
224
|
+
syntheticError;
|
|
225
|
+
current;
|
|
226
|
+
turnStartedAt;
|
|
227
|
+
firstEventAt;
|
|
228
|
+
stopReason = "end_turn";
|
|
229
|
+
usage = { inputTokens: 0, outputTokens: 0 };
|
|
230
|
+
now;
|
|
231
|
+
constructor(options) {
|
|
232
|
+
this.options = options;
|
|
233
|
+
this.now = options.now ?? Date.now;
|
|
234
|
+
}
|
|
235
|
+
/** Tool calls of the latest assistant message that have no result yet. */
|
|
236
|
+
unpairedToolCalls() {
|
|
237
|
+
const last = this.options.messages.at(-1);
|
|
238
|
+
if (last?.role !== "assistant" || typeof last.content === "string")
|
|
239
|
+
return [];
|
|
240
|
+
return last.content.filter((p) => p.type === "tool_call");
|
|
241
|
+
}
|
|
242
|
+
handle(msg) {
|
|
243
|
+
if ("parent_tool_use_id" in msg && msg.parent_tool_use_id)
|
|
244
|
+
return [];
|
|
245
|
+
switch (msg.type) {
|
|
246
|
+
case "system":
|
|
247
|
+
return this.handleSystem(msg);
|
|
248
|
+
case "stream_event":
|
|
249
|
+
return this.handleStreamEvent(msg.event);
|
|
250
|
+
case "assistant":
|
|
251
|
+
return this.handleAssistant(msg.message);
|
|
252
|
+
case "user":
|
|
253
|
+
return this.handleUser(msg.message.content);
|
|
254
|
+
case "rate_limit_event":
|
|
255
|
+
this.options.onRateLimit?.(msg.rate_limit_info);
|
|
256
|
+
return [];
|
|
257
|
+
default:
|
|
258
|
+
return [];
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
handleSystem(msg) {
|
|
262
|
+
if (msg.subtype === "init" && typeof msg.session_id === "string") {
|
|
263
|
+
this.options.onSessionId?.(msg.session_id);
|
|
264
|
+
}
|
|
265
|
+
else if (msg.subtype === "status" && msg.status === "requesting") {
|
|
266
|
+
this.turnStartedAt ??= this.now();
|
|
267
|
+
}
|
|
268
|
+
else if (msg.subtype === "api_retry") {
|
|
269
|
+
const status = msg.error_status;
|
|
270
|
+
const reason = status === 429 ? "rate_limit" : status === 529 ? "overloaded" : "provider_error";
|
|
271
|
+
return [
|
|
272
|
+
{
|
|
273
|
+
type: "retry",
|
|
274
|
+
reason,
|
|
275
|
+
attempt: num(msg.attempt),
|
|
276
|
+
maxAttempts: num(msg.max_retries),
|
|
277
|
+
delayMs: num(msg.retry_delay_ms),
|
|
278
|
+
},
|
|
279
|
+
];
|
|
280
|
+
}
|
|
281
|
+
return [];
|
|
282
|
+
}
|
|
283
|
+
handleStreamEvent(event) {
|
|
284
|
+
switch (event.type) {
|
|
285
|
+
case "message_start":
|
|
286
|
+
this.turnStartedAt ??= this.now();
|
|
287
|
+
this.firstEventAt = this.now();
|
|
288
|
+
this.stopReason = "end_turn";
|
|
289
|
+
this.usage = toUsage(event.message?.usage);
|
|
290
|
+
return [];
|
|
291
|
+
case "content_block_delta": {
|
|
292
|
+
const delta = (event.delta ?? {});
|
|
293
|
+
if (delta.type === "text_delta")
|
|
294
|
+
return [{ type: "text_delta", text: String(delta.text) }];
|
|
295
|
+
if (delta.type === "thinking_delta") {
|
|
296
|
+
return [{ type: "thinking_delta", text: String(delta.thinking) }];
|
|
297
|
+
}
|
|
298
|
+
if (delta.type === "input_json_delta") {
|
|
299
|
+
const chars = String(delta.partial_json ?? "").length;
|
|
300
|
+
return chars > 0 ? [{ type: "toolcall_delta", chars }] : [];
|
|
301
|
+
}
|
|
302
|
+
return [];
|
|
303
|
+
}
|
|
304
|
+
case "message_delta":
|
|
305
|
+
this.stopReason = toStopReason(event.delta?.stop_reason);
|
|
306
|
+
this.usage = toUsage(event.usage);
|
|
307
|
+
return [];
|
|
308
|
+
case "message_stop":
|
|
309
|
+
return this.endTurn();
|
|
310
|
+
default:
|
|
311
|
+
return [];
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
endTurn() {
|
|
315
|
+
this.turn++;
|
|
316
|
+
const completedAt = this.now();
|
|
317
|
+
const startedAt = this.turnStartedAt ?? completedAt;
|
|
318
|
+
const providerDurationMs = completedAt - startedAt;
|
|
319
|
+
const usage = this.usage;
|
|
320
|
+
addUsage(this.totalUsage, usage);
|
|
321
|
+
this.turnStartedAt = undefined;
|
|
322
|
+
const events = [
|
|
323
|
+
{
|
|
324
|
+
type: "turn_end",
|
|
325
|
+
turn: this.turn,
|
|
326
|
+
stopReason: this.stopReason,
|
|
327
|
+
usage,
|
|
328
|
+
timing: {
|
|
329
|
+
startedAt,
|
|
330
|
+
completedAt,
|
|
331
|
+
providerDurationMs,
|
|
332
|
+
...(this.firstEventAt !== undefined
|
|
333
|
+
? { firstProviderEventAt: this.firstEventAt, ttftMs: this.firstEventAt - startedAt }
|
|
334
|
+
: {}),
|
|
335
|
+
...(providerDurationMs > 0 && usage.outputTokens > 0
|
|
336
|
+
? { outputTokensPerSecond: usage.outputTokens / (providerDurationMs / 1000) }
|
|
337
|
+
: {}),
|
|
338
|
+
},
|
|
339
|
+
},
|
|
340
|
+
];
|
|
341
|
+
if (this.stopReason === "max_tokens" || this.stopReason === "refusal") {
|
|
342
|
+
events.push({ type: "truncated", reason: this.stopReason, continued: false });
|
|
343
|
+
}
|
|
344
|
+
this.firstEventAt = undefined;
|
|
345
|
+
return events;
|
|
346
|
+
}
|
|
347
|
+
handleAssistant(message) {
|
|
348
|
+
const blocks = Array.isArray(message.content) ? message.content : [];
|
|
349
|
+
if (message.model === SYNTHETIC_MODEL) {
|
|
350
|
+
const text = blocks.map((b) => (b.type === "text" ? String(b.text) : "")).join("");
|
|
351
|
+
if (text)
|
|
352
|
+
this.syntheticError = text;
|
|
353
|
+
return [];
|
|
354
|
+
}
|
|
355
|
+
const id = String(message.id ?? "");
|
|
356
|
+
if (!this.current || this.current.id !== id) {
|
|
357
|
+
const fresh = { role: "assistant", content: [] };
|
|
358
|
+
this.current = { id, message: fresh };
|
|
359
|
+
this.options.messages.push(fresh);
|
|
360
|
+
this.lastAssistant = fresh;
|
|
361
|
+
}
|
|
362
|
+
const content = this.current.message.content;
|
|
363
|
+
const events = [];
|
|
364
|
+
for (const block of blocks) {
|
|
365
|
+
const part = fromSdkContentBlock(block);
|
|
366
|
+
content.push(part);
|
|
367
|
+
if (part.type === "server_tool_call") {
|
|
368
|
+
events.push({ type: "server_tool_call", id: part.id, name: part.name, input: part.input });
|
|
369
|
+
}
|
|
370
|
+
else if (part.type === "server_tool_result") {
|
|
371
|
+
events.push({
|
|
372
|
+
type: "server_tool_result",
|
|
373
|
+
toolUseId: part.toolUseId,
|
|
374
|
+
resultType: part.resultType,
|
|
375
|
+
data: part.data,
|
|
376
|
+
});
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
return events;
|
|
380
|
+
}
|
|
381
|
+
handleUser(raw) {
|
|
382
|
+
if (typeof raw === "string")
|
|
383
|
+
return [];
|
|
384
|
+
const blocks = raw.filter((b) => b.type === "tool_result");
|
|
385
|
+
if (blocks.length === 0)
|
|
386
|
+
return [];
|
|
387
|
+
const calls = new Map(this.unpairedToolCalls().map((c) => [c.id, c]));
|
|
388
|
+
const events = [];
|
|
389
|
+
const results = blocks.map((block) => {
|
|
390
|
+
const id = String(block.tool_use_id);
|
|
391
|
+
const bridged = this.options.takeResult(id);
|
|
392
|
+
if (bridged)
|
|
393
|
+
return bridged;
|
|
394
|
+
// Claude Code answered this call itself (e.g. denied it), so no
|
|
395
|
+
// tool events went out yet.
|
|
396
|
+
const result = fromSdkToolResult(block);
|
|
397
|
+
const call = calls.get(id);
|
|
398
|
+
events.push({
|
|
399
|
+
type: "tool_call_start",
|
|
400
|
+
toolCallId: id,
|
|
401
|
+
name: call?.name ?? "tool",
|
|
402
|
+
args: call?.args ?? {},
|
|
403
|
+
}, {
|
|
404
|
+
type: "tool_call_end",
|
|
405
|
+
toolCallId: id,
|
|
406
|
+
result: resultText(result.content),
|
|
407
|
+
isError: !!result.isError,
|
|
408
|
+
durationMs: 0,
|
|
409
|
+
});
|
|
410
|
+
return result;
|
|
411
|
+
});
|
|
412
|
+
this.options.messages.push({ role: "tool", content: results });
|
|
413
|
+
this.current = undefined;
|
|
414
|
+
events.push({ type: "checkpoint", turn: this.turn });
|
|
415
|
+
return events;
|
|
416
|
+
}
|
|
417
|
+
/** Close dangling tool calls (after an abort) so the transcript stays paired. */
|
|
418
|
+
pairDanglingToolCalls(note) {
|
|
419
|
+
const pending = this.unpairedToolCalls();
|
|
420
|
+
if (pending.length === 0)
|
|
421
|
+
return;
|
|
422
|
+
this.options.messages.push({
|
|
423
|
+
role: "tool",
|
|
424
|
+
content: pending.map((call) => this.options.takeResult(call.id) ?? {
|
|
425
|
+
type: "tool_result",
|
|
426
|
+
toolCallId: call.id,
|
|
427
|
+
content: note,
|
|
428
|
+
isError: true,
|
|
429
|
+
}),
|
|
430
|
+
});
|
|
431
|
+
this.current = undefined;
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
//# sourceMappingURL=events.js.map
|