@skaile/workspaces 3.0.0 → 3.2.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/CHANGELOG.md +51 -0
- package/README.md +5 -1
- package/dist/{asset-feeds-XKPJZ6QT.js → asset-feeds-25DVAGVD.js} +4 -4
- package/dist/{asset-feeds-XKPJZ6QT.js.map → asset-feeds-25DVAGVD.js.map} +1 -1
- package/dist/asset-manager/index.js +1 -1
- package/dist/bridge/drivers/claude-sdk.js +5 -205
- package/dist/bridge/drivers/claude-sdk.js.map +1 -1
- package/dist/bridge/drivers/codex.js +1 -1
- package/dist/bridge/drivers/continue.js +2 -2
- package/dist/bridge/drivers/echo.js +1 -1
- package/dist/bridge/drivers/gemini.js +3 -3
- package/dist/bridge/drivers/goose.js +2 -2
- package/dist/bridge/drivers/omp.js +1 -1
- package/dist/bridge/drivers/opencode.js +2 -2
- package/dist/bridge/drivers/qwen.js +3 -3
- package/dist/bridge/index.js +13 -3
- package/dist/bridge/src/drivers/claude-sdk.d.ts.map +1 -1
- package/dist/bridge/src/drivers/resume-probe.d.ts +54 -0
- package/dist/bridge/src/drivers/resume-probe.d.ts.map +1 -0
- package/dist/bridge/src/drivers/scrub-transcript.d.ts +17 -0
- package/dist/bridge/src/drivers/scrub-transcript.d.ts.map +1 -1
- package/dist/bridge/src/index.d.ts +1 -0
- package/dist/bridge/src/index.d.ts.map +1 -1
- package/dist/{chunk-KXWUCKP5.js → chunk-2U4ISGE2.js} +4 -4
- package/dist/{chunk-KXWUCKP5.js.map → chunk-2U4ISGE2.js.map} +1 -1
- package/dist/{chunk-P2J3MLTW.js → chunk-3IGXVTOS.js} +3 -3
- package/dist/{chunk-P2J3MLTW.js.map → chunk-3IGXVTOS.js.map} +1 -1
- package/dist/chunk-46LE3GNY.js +296 -0
- package/dist/chunk-46LE3GNY.js.map +1 -0
- package/dist/{chunk-5QGMEPUX.js → chunk-B4J6TV4G.js} +21 -5
- package/dist/chunk-B4J6TV4G.js.map +1 -0
- package/dist/{chunk-Q6O53D5Q.js → chunk-CO4DNTIL.js} +2 -2
- package/dist/{chunk-Q6O53D5Q.js.map → chunk-CO4DNTIL.js.map} +1 -1
- package/dist/{chunk-WECBTWWZ.js → chunk-CTCCFKZV.js} +3 -3
- package/dist/{chunk-WECBTWWZ.js.map → chunk-CTCCFKZV.js.map} +1 -1
- package/dist/{chunk-JQMULHO6.js → chunk-DEW2G3QZ.js} +14 -12
- package/dist/chunk-DEW2G3QZ.js.map +1 -0
- package/dist/{chunk-QGDQHNYC.js → chunk-DPFSO4T2.js} +4 -4
- package/dist/{chunk-QGDQHNYC.js.map → chunk-DPFSO4T2.js.map} +1 -1
- package/dist/{chunk-S5FV6ISY.js → chunk-EYBGQJNF.js} +26 -6
- package/dist/chunk-EYBGQJNF.js.map +1 -0
- package/dist/{chunk-NMKTM55X.js → chunk-F5YPDCN6.js} +2 -2
- package/dist/{chunk-NMKTM55X.js.map → chunk-F5YPDCN6.js.map} +1 -1
- package/dist/{chunk-7KFN2EPR.js → chunk-FLBDLF3I.js} +4 -4
- package/dist/{chunk-7KFN2EPR.js.map → chunk-FLBDLF3I.js.map} +1 -1
- package/dist/{chunk-BJDACPWZ.js → chunk-FP7DNGX6.js} +3 -3
- package/dist/{chunk-BJDACPWZ.js.map → chunk-FP7DNGX6.js.map} +1 -1
- package/dist/{chunk-P5W6JVD4.js → chunk-HA2H3FLE.js} +3 -3
- package/dist/{chunk-P5W6JVD4.js.map → chunk-HA2H3FLE.js.map} +1 -1
- package/dist/{chunk-N4GFUWWC.js → chunk-HNBWU5RA.js} +3 -3
- package/dist/{chunk-N4GFUWWC.js.map → chunk-HNBWU5RA.js.map} +1 -1
- package/dist/{chunk-TXTCW7V6.js → chunk-IMA5H7AG.js} +6 -6
- package/dist/{chunk-TXTCW7V6.js.map → chunk-IMA5H7AG.js.map} +1 -1
- package/dist/{chunk-EH7BCJF4.js → chunk-K5OKE4G2.js} +6 -6
- package/dist/{chunk-EH7BCJF4.js.map → chunk-K5OKE4G2.js.map} +1 -1
- package/dist/{chunk-SR6NBBWT.js → chunk-QFO4IYBZ.js} +2 -2
- package/dist/{chunk-SR6NBBWT.js.map → chunk-QFO4IYBZ.js.map} +1 -1
- package/dist/{chunk-ZO7KL7GN.js → chunk-RW4I42MW.js} +73 -36
- package/dist/chunk-RW4I42MW.js.map +1 -0
- package/dist/{chunk-7HXS7WZF.js → chunk-ST4RC2JF.js} +2 -2
- package/dist/{chunk-7HXS7WZF.js.map → chunk-ST4RC2JF.js.map} +1 -1
- package/dist/{chunk-XJECOBCO.js → chunk-XL7ZDZ4O.js} +5 -5
- package/dist/{chunk-XJECOBCO.js.map → chunk-XL7ZDZ4O.js.map} +1 -1
- package/dist/cli/index.js +34 -34
- package/dist/connectors/index.js +7 -7
- package/dist/{ensure-sources-D6R57GAP.js → ensure-sources-YOJ5HOCL.js} +4 -4
- package/dist/{ensure-sources-D6R57GAP.js.map → ensure-sources-YOJ5HOCL.js.map} +1 -1
- package/dist/factory-assets/connectors/box.js +7 -7
- package/dist/factory-assets/connectors/deploy.js +7 -7
- package/dist/factory-assets/connectors/devserver.js +7 -7
- package/dist/factory-assets/connectors/flow/CONNECTOR.md +26 -9
- package/dist/factory-assets/connectors/flow/adapter.d.ts +15 -7
- package/dist/factory-assets/connectors/flow/adapter.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/adapter.js +7 -7
- package/dist/factory-assets/connectors/flow/contract/expression.d.ts +3 -1
- package/dist/factory-assets/connectors/flow/contract/expression.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/contract/schema.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/contract.js +2 -2
- package/dist/factory-assets/connectors/flow/engine/bindings.d.ts +12 -0
- package/dist/factory-assets/connectors/flow/engine/bindings.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/engine/check-provenance.d.ts +13 -2
- package/dist/factory-assets/connectors/flow/engine/check-provenance.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/engine/engine.d.ts +5 -1
- package/dist/factory-assets/connectors/flow/engine/engine.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/engine/index.d.ts +1 -0
- package/dist/factory-assets/connectors/flow/engine/index.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/engine/optional-failure.d.ts +24 -0
- package/dist/factory-assets/connectors/flow/engine/optional-failure.d.ts.map +1 -0
- package/dist/factory-assets/connectors/flow/engine/router-settlement.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/engine/types.d.ts +3 -1
- package/dist/factory-assets/connectors/flow/engine/types.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/engine.js +2 -2
- package/dist/factory-assets/connectors/flow/prompt-fragments.js +1 -1
- package/dist/factory-assets/connectors/flow/run-flow.js +8 -8
- package/dist/factory-assets/connectors/flow/sub-flow-runner.d.ts +9 -1
- package/dist/factory-assets/connectors/flow/sub-flow-runner.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow.js +7 -7
- package/dist/factory-assets/connectors/git.js +7 -7
- package/dist/factory-assets/connectors/gmail.js +7 -7
- package/dist/factory-assets/connectors/googledrive.js +7 -7
- package/dist/factory-assets/connectors/local.js +7 -7
- package/dist/factory-assets/connectors/mattermost.js +7 -7
- package/dist/factory-assets/connectors/memory.js +7 -7
- package/dist/factory-assets/connectors/minio.js +7 -7
- package/dist/factory-assets/connectors/postgres.js +7 -7
- package/dist/factory-assets/connectors/s3.js +7 -7
- package/dist/factory-assets/connectors/sharepoint.js +7 -7
- package/dist/factory-assets/connectors/sqlite.js +7 -7
- package/dist/factory-assets/connectors/static-server.js +7 -7
- package/dist/factory-assets/connectors/tunnel.js +7 -7
- package/dist/factory-assets/connectors/webdav.js +7 -7
- package/dist/factory-assets/connectors/xstate-store.js +7 -7
- package/dist/factory-assets/connectors/xstate.js +7 -7
- package/dist/{flows-LQSVM45J.js → flows-7KUZGZ77.js} +3 -3
- package/dist/{flows-LQSVM45J.js.map → flows-7KUZGZ77.js.map} +1 -1
- package/dist/{helpers-IS4MSEOQ.js → helpers-YNZ5SWNX.js} +4 -4
- package/dist/{helpers-IS4MSEOQ.js.map → helpers-YNZ5SWNX.js.map} +1 -1
- package/dist/{library-publish-QJACP6FW.js → library-publish-JBZ2TEQI.js} +8 -8
- package/dist/{library-publish-QJACP6FW.js.map → library-publish-JBZ2TEQI.js.map} +1 -1
- package/dist/{open-library-3FMLAU3F.js → open-library-H2LAGVTM.js} +7 -7
- package/dist/{open-library-3FMLAU3F.js.map → open-library-H2LAGVTM.js.map} +1 -1
- package/dist/{project-KEAAGHSX.js → project-WBIYBTN3.js} +5 -5
- package/dist/{project-KEAAGHSX.js.map → project-WBIYBTN3.js.map} +1 -1
- package/dist/runner/index.js +11 -11
- package/dist/runner/src/serve.d.ts.map +1 -1
- package/dist/sdk/asset-manager.js +1 -1
- package/dist/sdk/bridge.js +13 -3
- package/dist/sdk/flow.js +2 -2
- package/dist/sdk/index.js +11 -11
- package/dist/sdk/runner.js +11 -11
- package/dist/{setup-VX6EPF5P.js → setup-I5SLLHRA.js} +5 -5
- package/dist/{setup-VX6EPF5P.js.map → setup-I5SLLHRA.js.map} +1 -1
- package/dist/{source-45XHQSBF.js → source-UCMNKSA2.js} +8 -8
- package/dist/{source-45XHQSBF.js.map → source-UCMNKSA2.js.map} +1 -1
- package/dist/{source-manifest-publish-M34SKD46.js → source-manifest-publish-BZ777MH5.js} +9 -9
- package/dist/{source-manifest-publish-M34SKD46.js.map → source-manifest-publish-BZ777MH5.js.map} +1 -1
- package/dist/tui/index.js +11 -11
- package/dist/types/src/flow.d.ts +38 -12
- package/dist/types/src/flow.d.ts.map +1 -1
- package/dist/types/src/lifecycle.d.ts +12 -0
- package/dist/types/src/lifecycle.d.ts.map +1 -1
- package/dist/workspace-plugin/adapters/mcp.js +1 -1
- package/dist/workspace-plugin/adapters/omp.js +3 -3
- package/dist/workspace-plugin/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-5QGMEPUX.js.map +0 -1
- package/dist/chunk-ISQWMBKD.js +0 -74
- package/dist/chunk-ISQWMBKD.js.map +0 -1
- package/dist/chunk-JQMULHO6.js.map +0 -1
- package/dist/chunk-S5FV6ISY.js.map +0 -1
- package/dist/chunk-ZO7KL7GN.js.map +0 -1
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
import { fsDeadlineMs, withFsDeadline, tryWithFsDeadline } from './chunk-DYMWJAL4.js';
|
|
2
|
+
import { createReadStream, createWriteStream } from 'fs';
|
|
3
|
+
import { readdir, stat, rename, unlink } from 'fs/promises';
|
|
4
|
+
import { join } from 'path';
|
|
5
|
+
import { pipeline } from 'stream/promises';
|
|
6
|
+
import { homedir } from 'os';
|
|
7
|
+
|
|
8
|
+
// bridge/src/cloud.ts
|
|
9
|
+
var SUPPORTED_CLOUDS = ["default", "bedrock", "vertex", "azure", "gateway"];
|
|
10
|
+
var CLOUD_SECRET_ENV_KEYS = {
|
|
11
|
+
bedrock: [
|
|
12
|
+
"AWS_ACCESS_KEY_ID",
|
|
13
|
+
"AWS_SECRET_ACCESS_KEY",
|
|
14
|
+
"AWS_SESSION_TOKEN",
|
|
15
|
+
"AWS_BEARER_TOKEN_BEDROCK"
|
|
16
|
+
],
|
|
17
|
+
vertex: ["GOOGLE_APPLICATION_CREDENTIALS_JSON"],
|
|
18
|
+
azure: ["ANTHROPIC_FOUNDRY_API_KEY"],
|
|
19
|
+
gateway: ["ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_API_KEY"]
|
|
20
|
+
};
|
|
21
|
+
var SCRUBBED_ENV_KEYS = ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL"];
|
|
22
|
+
function buildClaudeCloudEnv(args) {
|
|
23
|
+
const { cloud, cloudConfig, cloudSecrets, baseEnv, configEnv, fallbackApiKey } = args;
|
|
24
|
+
const env = { ...baseEnv, ...configEnv ?? {} };
|
|
25
|
+
const ambient = {
|
|
26
|
+
authToken: env.ANTHROPIC_AUTH_TOKEN,
|
|
27
|
+
apiKey: env.ANTHROPIC_API_KEY,
|
|
28
|
+
baseUrl: env.ANTHROPIC_BASE_URL
|
|
29
|
+
};
|
|
30
|
+
for (const key of Object.keys(env)) {
|
|
31
|
+
if (SCRUBBED_ENV_KEYS.includes(key) || key.startsWith("CLAUDE_CODE_USE_")) {
|
|
32
|
+
delete env[key];
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
const set = (key, value) => {
|
|
36
|
+
if (value) env[key] = value;
|
|
37
|
+
};
|
|
38
|
+
switch (cloud) {
|
|
39
|
+
case "bedrock": {
|
|
40
|
+
env.CLAUDE_CODE_USE_BEDROCK = "1";
|
|
41
|
+
for (const key of CLOUD_SECRET_ENV_KEYS.bedrock) set(key, cloudSecrets?.[key]);
|
|
42
|
+
set("AWS_REGION", cloudConfig?.region);
|
|
43
|
+
break;
|
|
44
|
+
}
|
|
45
|
+
case "vertex": {
|
|
46
|
+
env.CLAUDE_CODE_USE_VERTEX = "1";
|
|
47
|
+
set("GOOGLE_APPLICATION_CREDENTIALS", cloudSecrets?.GOOGLE_APPLICATION_CREDENTIALS);
|
|
48
|
+
set("ANTHROPIC_VERTEX_PROJECT_ID", cloudConfig?.projectId);
|
|
49
|
+
set("CLOUD_ML_REGION", cloudConfig?.region);
|
|
50
|
+
break;
|
|
51
|
+
}
|
|
52
|
+
case "azure": {
|
|
53
|
+
env.CLAUDE_CODE_USE_FOUNDRY = "1";
|
|
54
|
+
set("ANTHROPIC_FOUNDRY_API_KEY", cloudSecrets?.ANTHROPIC_FOUNDRY_API_KEY);
|
|
55
|
+
if (cloudConfig?.resource) {
|
|
56
|
+
env.ANTHROPIC_FOUNDRY_RESOURCE = cloudConfig.resource;
|
|
57
|
+
} else {
|
|
58
|
+
set("ANTHROPIC_FOUNDRY_BASE_URL", cloudConfig?.baseUrl);
|
|
59
|
+
}
|
|
60
|
+
break;
|
|
61
|
+
}
|
|
62
|
+
case "gateway": {
|
|
63
|
+
set("ANTHROPIC_BASE_URL", cloudConfig?.baseUrl ?? ambient.baseUrl);
|
|
64
|
+
const authToken = cloudSecrets?.ANTHROPIC_AUTH_TOKEN ?? ambient.authToken;
|
|
65
|
+
if (authToken) {
|
|
66
|
+
env.ANTHROPIC_AUTH_TOKEN = authToken;
|
|
67
|
+
} else {
|
|
68
|
+
set(
|
|
69
|
+
"ANTHROPIC_API_KEY",
|
|
70
|
+
cloudSecrets?.ANTHROPIC_API_KEY ?? fallbackApiKey ?? ambient.apiKey
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
break;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return env;
|
|
77
|
+
}
|
|
78
|
+
var STUB_TEXT = "[image removed: unprocessable image data]";
|
|
79
|
+
var STUB_TEXT_OVERSIZED = "[image removed: image too large]";
|
|
80
|
+
var MAX_IMAGE_BYTES = 5 * 1024 * 1024;
|
|
81
|
+
function sniffImageMediaType(base64) {
|
|
82
|
+
let buf;
|
|
83
|
+
try {
|
|
84
|
+
buf = Buffer.from(base64.slice(0, 32), "base64");
|
|
85
|
+
} catch {
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
if (buf.length < 4) {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
if (buf[0] === 255 && buf[1] === 216) {
|
|
92
|
+
return "image/jpeg";
|
|
93
|
+
}
|
|
94
|
+
if (buf[0] === 137 && buf[1] === 80 && buf[2] === 78 && buf[3] === 71) {
|
|
95
|
+
return "image/png";
|
|
96
|
+
}
|
|
97
|
+
if (buf[0] === 71 && buf[1] === 73 && buf[2] === 70 && buf[3] === 56) {
|
|
98
|
+
return "image/gif";
|
|
99
|
+
}
|
|
100
|
+
if (buf.length >= 12 && buf[0] === 82 && buf[1] === 73 && buf[2] === 70 && buf[3] === 70 && buf[8] === 87 && buf[9] === 69 && buf[10] === 66 && buf[11] === 80) {
|
|
101
|
+
return "image/webp";
|
|
102
|
+
}
|
|
103
|
+
return null;
|
|
104
|
+
}
|
|
105
|
+
function totalChanges(c) {
|
|
106
|
+
return c.corrected + c.stubbed + c.cacheStripped;
|
|
107
|
+
}
|
|
108
|
+
function scrubBlock(block, counters) {
|
|
109
|
+
if (block.type === "tool_result" && Array.isArray(block.content)) {
|
|
110
|
+
return {
|
|
111
|
+
...block,
|
|
112
|
+
content: block.content.map((inner) => scrubBlock(inner, counters))
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
if (block.type === "text" && block.cache_control != null) {
|
|
116
|
+
const text = typeof block.text === "string" ? block.text : "";
|
|
117
|
+
if (text.trim() === "") {
|
|
118
|
+
counters.cacheStripped++;
|
|
119
|
+
const clone = { ...block };
|
|
120
|
+
delete clone.cache_control;
|
|
121
|
+
return clone;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (block.type === "image" && block.source?.type === "base64" && typeof block.source.data === "string") {
|
|
125
|
+
const data = block.source.data;
|
|
126
|
+
if (Math.floor(data.length * 3 / 4) > MAX_IMAGE_BYTES) {
|
|
127
|
+
counters.stubbed++;
|
|
128
|
+
return { type: "text", text: STUB_TEXT_OVERSIZED };
|
|
129
|
+
}
|
|
130
|
+
const sniffed = sniffImageMediaType(data);
|
|
131
|
+
if (sniffed === null) {
|
|
132
|
+
counters.stubbed++;
|
|
133
|
+
return { type: "text", text: STUB_TEXT };
|
|
134
|
+
}
|
|
135
|
+
if (sniffed !== block.source.media_type) {
|
|
136
|
+
counters.corrected++;
|
|
137
|
+
return { ...block, source: { ...block.source, media_type: sniffed } };
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return block;
|
|
141
|
+
}
|
|
142
|
+
async function locateTranscriptPath(configDir, sessionId, timeoutMs = fsDeadlineMs()) {
|
|
143
|
+
const projectsDir = join(configDir, "projects");
|
|
144
|
+
const entries = await tryWithFsDeadline(
|
|
145
|
+
`readdir ${projectsDir}`,
|
|
146
|
+
() => readdir(projectsDir),
|
|
147
|
+
null,
|
|
148
|
+
timeoutMs
|
|
149
|
+
);
|
|
150
|
+
if (!entries) return null;
|
|
151
|
+
for (const entry of entries) {
|
|
152
|
+
const candidate = join(projectsDir, entry, `${sessionId}.jsonl`);
|
|
153
|
+
const found = await tryWithFsDeadline(
|
|
154
|
+
`stat ${candidate}`,
|
|
155
|
+
async () => (await stat(candidate)).isFile(),
|
|
156
|
+
false,
|
|
157
|
+
timeoutMs
|
|
158
|
+
);
|
|
159
|
+
if (found) return candidate;
|
|
160
|
+
}
|
|
161
|
+
return null;
|
|
162
|
+
}
|
|
163
|
+
async function* streamLines(filePath) {
|
|
164
|
+
const stream = createReadStream(filePath, { encoding: "utf8" });
|
|
165
|
+
let pending = "";
|
|
166
|
+
try {
|
|
167
|
+
for await (const chunk of stream) {
|
|
168
|
+
pending += chunk;
|
|
169
|
+
let idx = pending.indexOf("\n");
|
|
170
|
+
while (idx !== -1) {
|
|
171
|
+
yield pending.slice(0, idx);
|
|
172
|
+
pending = pending.slice(idx + 1);
|
|
173
|
+
idx = pending.indexOf("\n");
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
yield pending;
|
|
177
|
+
} finally {
|
|
178
|
+
stream.destroy();
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
function repairLine(line, counters) {
|
|
182
|
+
if (line.trim() === "") return line;
|
|
183
|
+
const eol = line.endsWith("\r") ? "\r" : "";
|
|
184
|
+
const body = eol === "" ? line : line.slice(0, -1);
|
|
185
|
+
let entry;
|
|
186
|
+
try {
|
|
187
|
+
entry = JSON.parse(body);
|
|
188
|
+
} catch {
|
|
189
|
+
return line;
|
|
190
|
+
}
|
|
191
|
+
const content = entry.message?.content;
|
|
192
|
+
if (!Array.isArray(content)) return line;
|
|
193
|
+
const before = totalChanges(counters);
|
|
194
|
+
const scrubbed = content.map((block) => scrubBlock(block, counters));
|
|
195
|
+
if (totalChanges(counters) === before) return line;
|
|
196
|
+
return `${JSON.stringify({ ...entry, message: { ...entry.message, content: scrubbed } })}${eol}`;
|
|
197
|
+
}
|
|
198
|
+
async function scrubPoisonedTranscript(opts) {
|
|
199
|
+
const { configDir, sessionId, log } = opts;
|
|
200
|
+
const timeoutMs = fsDeadlineMs();
|
|
201
|
+
const result = {
|
|
202
|
+
filePath: null,
|
|
203
|
+
corrected: 0,
|
|
204
|
+
stubbed: 0,
|
|
205
|
+
cacheStripped: 0,
|
|
206
|
+
changed: false
|
|
207
|
+
};
|
|
208
|
+
const filePath = await locateTranscriptPath(configDir, sessionId, timeoutMs);
|
|
209
|
+
if (!filePath) {
|
|
210
|
+
log?.warn("scrub-transcript: no transcript found", { configDir, sessionId });
|
|
211
|
+
return result;
|
|
212
|
+
}
|
|
213
|
+
result.filePath = filePath;
|
|
214
|
+
const counters = { corrected: 0, stubbed: 0, cacheStripped: 0 };
|
|
215
|
+
try {
|
|
216
|
+
await withFsDeadline(
|
|
217
|
+
`scan transcript ${filePath}`,
|
|
218
|
+
async () => {
|
|
219
|
+
for await (const line of streamLines(filePath)) repairLine(line, counters);
|
|
220
|
+
},
|
|
221
|
+
timeoutMs
|
|
222
|
+
);
|
|
223
|
+
} catch (err) {
|
|
224
|
+
log?.warn("scrub-transcript: failed to read transcript", {
|
|
225
|
+
filePath,
|
|
226
|
+
error: err instanceof Error ? err.message : String(err)
|
|
227
|
+
});
|
|
228
|
+
return result;
|
|
229
|
+
}
|
|
230
|
+
result.corrected = counters.corrected;
|
|
231
|
+
result.stubbed = counters.stubbed;
|
|
232
|
+
result.cacheStripped = counters.cacheStripped;
|
|
233
|
+
if (totalChanges(counters) === 0) {
|
|
234
|
+
return result;
|
|
235
|
+
}
|
|
236
|
+
const tmpPath = `${filePath}.scrub-tmp`;
|
|
237
|
+
try {
|
|
238
|
+
await withFsDeadline(
|
|
239
|
+
`rewrite transcript ${filePath}`,
|
|
240
|
+
async () => {
|
|
241
|
+
const discard = { corrected: 0, stubbed: 0, cacheStripped: 0 };
|
|
242
|
+
await pipeline(
|
|
243
|
+
(async function* () {
|
|
244
|
+
let first = true;
|
|
245
|
+
for await (const line of streamLines(filePath)) {
|
|
246
|
+
yield first ? repairLine(line, discard) : `
|
|
247
|
+
${repairLine(line, discard)}`;
|
|
248
|
+
first = false;
|
|
249
|
+
}
|
|
250
|
+
})(),
|
|
251
|
+
createWriteStream(tmpPath, { encoding: "utf8" })
|
|
252
|
+
);
|
|
253
|
+
await rename(tmpPath, filePath);
|
|
254
|
+
},
|
|
255
|
+
timeoutMs
|
|
256
|
+
);
|
|
257
|
+
} catch (err) {
|
|
258
|
+
log?.warn("scrub-transcript: failed to rewrite transcript", {
|
|
259
|
+
filePath,
|
|
260
|
+
error: err instanceof Error ? err.message : String(err)
|
|
261
|
+
});
|
|
262
|
+
await tryWithFsDeadline(`unlink ${tmpPath}`, () => unlink(tmpPath), void 0, timeoutMs);
|
|
263
|
+
return result;
|
|
264
|
+
}
|
|
265
|
+
result.changed = true;
|
|
266
|
+
log?.info("scrub-transcript: repaired poisoned transcript", {
|
|
267
|
+
filePath,
|
|
268
|
+
corrected: result.corrected,
|
|
269
|
+
stubbed: result.stubbed,
|
|
270
|
+
cacheStripped: result.cacheStripped
|
|
271
|
+
});
|
|
272
|
+
return result;
|
|
273
|
+
}
|
|
274
|
+
var RESUME_PROBE_TIMEOUT_MS = 2e3;
|
|
275
|
+
function resolveClaudeConfigDir(env) {
|
|
276
|
+
return env?.CLAUDE_CONFIG_DIR || process.env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude");
|
|
277
|
+
}
|
|
278
|
+
async function probeResumeTranscript(sessionId, opts) {
|
|
279
|
+
const configDir = resolveClaudeConfigDir(opts?.env);
|
|
280
|
+
const timeoutMs = opts?.timeoutMs ?? RESUME_PROBE_TIMEOUT_MS;
|
|
281
|
+
const locate = opts?.locate ?? locateTranscriptPath;
|
|
282
|
+
try {
|
|
283
|
+
const filePath = await withFsDeadline(
|
|
284
|
+
`resume-probe ${sessionId}`,
|
|
285
|
+
() => locate(configDir, sessionId),
|
|
286
|
+
timeoutMs
|
|
287
|
+
);
|
|
288
|
+
return filePath ? "transcript_found" : "jsonl_lost";
|
|
289
|
+
} catch {
|
|
290
|
+
return void 0;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
export { CLOUD_SECRET_ENV_KEYS, SUPPORTED_CLOUDS, buildClaudeCloudEnv, probeResumeTranscript, resolveClaudeConfigDir, scrubPoisonedTranscript };
|
|
295
|
+
//# sourceMappingURL=chunk-46LE3GNY.js.map
|
|
296
|
+
//# sourceMappingURL=chunk-46LE3GNY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../bridge/src/cloud.ts","../bridge/src/drivers/scrub-transcript.ts","../bridge/src/drivers/resume-probe.ts"],"names":["join"],"mappings":";;;;;;;;AAsBO,IAAM,mBAAmB,CAAC,SAAA,EAAW,SAAA,EAAW,QAAA,EAAU,SAAS,SAAS;AAuC5E,IAAM,qBAAA,GAAgF;AAAA,EAC3F,OAAA,EAAS;AAAA,IACP,mBAAA;AAAA,IACA,uBAAA;AAAA,IACA,mBAAA;AAAA,IACA;AAAA,GACF;AAAA,EACA,MAAA,EAAQ,CAAC,qCAAqC,CAAA;AAAA,EAC9C,KAAA,EAAO,CAAC,2BAA2B,CAAA;AAAA,EACnC,OAAA,EAAS,CAAC,sBAAA,EAAwB,mBAAmB;AACvD;AAaA,IAAM,iBAAA,GAAoB,CAAC,mBAAA,EAAqB,sBAAA,EAAwB,oBAAoB,CAAA;AAuBrF,SAAS,oBAAoB,IAAA,EAQT;AACzB,EAAA,MAAM,EAAE,KAAA,EAAO,WAAA,EAAa,cAAc,OAAA,EAAS,SAAA,EAAW,gBAAe,GAAI,IAAA;AACjF,EAAA,MAAM,MAA8B,EAAE,GAAG,SAAS,GAAI,SAAA,IAAa,EAAC,EAAG;AAGvE,EAAA,MAAM,OAAA,GAAU;AAAA,IACd,WAAW,GAAA,CAAI,oBAAA;AAAA,IACf,QAAQ,GAAA,CAAI,iBAAA;AAAA,IACZ,SAAS,GAAA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,GAAU,IAAA;AACjB,EAAA,GAAA,EAAK,KAAK,gDAAA,EAAkD;AAAA,IAC1D,QAAA;AAAA,IACA,WAAW,MAAA,CAAO,SAAA;AAAA,IAClB,SAAS,MAAA,CAAO,OAAA;AAAA,IAChB,eAAe,MAAA,CAAO;AAAA,GACvB,CAAA;AACD,EAAA,OAAO,MAAA;AACT;ACtcA,IAAM,uBAAA,GAA0B,GAAA;AAwBzB,SAAS,uBAAuB,GAAA,EAAkD;AACvF,EAAA,OAAO,GAAA,EAAK,qBAAqB,OAAA,CAAQ,GAAA,CAAI,qBAAqBA,IAAAA,CAAK,OAAA,IAAW,SAAS,CAAA;AAC7F;AAgBA,eAAsB,qBAAA,CACpB,WACA,IAAA,EAKyC;AACzC,EAAA,MAAM,SAAA,GAAY,sBAAA,CAAuB,IAAA,EAAM,GAAG,CAAA;AAClD,EAAA,MAAM,SAAA,GAAY,MAAM,SAAA,IAAa,uBAAA;AACrC,EAAA,MAAM,MAAA,GAAS,MAAM,MAAA,IAAU,oBAAA;AAC/B,EAAA,IAAI;AAIF,IAAA,MAAM,WAAW,MAAM,cAAA;AAAA,MACrB,gBAAgB,SAAS,CAAA,CAAA;AAAA,MACzB,MAAM,MAAA,CAAO,SAAA,EAAW,SAAS,CAAA;AAAA,MACjC;AAAA,KACF;AACA,IAAA,OAAO,WAAW,kBAAA,GAAqB,YAAA;AAAA,EACzC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF","file":"chunk-46LE3GNY.js","sourcesContent":["/**\n * AI cloud-provider transport dimension for the `claude-sdk` driver.\n *\n * `cloud` is a config axis orthogonal to `provider` (model vendor) and\n * `driver` (agent runtime). Under `driver: claude-sdk` each non-default value\n * maps to one of the Claude Agent SDK's native env-var transports:\n * Amazon Bedrock, Google Vertex AI, Azure AI Foundry, or a generic\n * `ANTHROPIC_BASE_URL` gateway (LiteLLM / corporate proxy).\n *\n * Cross-repo contract: env key names and semantics here are load-bearing —\n * the platform resolves credential bundles against the same key set.\n */\n\n/**\n * Canonical list of supported cloud transports. `\"default\"` (or an absent\n * `cloud` field) means the provider's native API — today's behavior, unchanged.\n *\n * The codec in `core/workspace-config.ts` keeps a local copy (`KNOWN_CLOUDS`)\n * to avoid an import cycle; a drift test asserts parity.\n *\n * @since 1.3.0\n */\nexport const SUPPORTED_CLOUDS = [\"default\", \"bedrock\", \"vertex\", \"azure\", \"gateway\"] as const;\n\n/** One of the supported cloud transport identifiers. */\nexport type CloudId = (typeof SUPPORTED_CLOUDS)[number];\n\n/**\n * Non-secret transport settings for a cloud. Sourced from skaile.yaml\n * `cloud_config` (snake_case on the wire, camelCase in-process — converted\n * exactly once at the settings/serve boundary).\n *\n * Must stay field-identical with core's `CloudTransportConfig` and the inline\n * `AgentSessionConfig.cloudConfig` shape (kept separate to avoid a core↔bridge\n * import cycle) — a field added here must be added there too.\n *\n * @since 1.3.0\n */\nexport interface CloudConfig {\n /** bedrock: AWS region (`AWS_REGION`); vertex: `CLOUD_ML_REGION`. */\n region?: string;\n /** vertex only: GCP project (`ANTHROPIC_VERTEX_PROJECT_ID`). */\n projectId?: string;\n /** azure only: Foundry resource name (`ANTHROPIC_FOUNDRY_RESOURCE`). */\n resource?: string;\n /** azure (alternative to `resource`) / gateway (required): endpoint base URL. */\n baseUrl?: string;\n}\n\n/**\n * Secret env keys that make up the credential bundle for each non-default\n * cloud. The platform delivers these env-keyed in the `session_init` secrets\n * map; the runner picks them out via `resolveCloudSecretBundle`.\n *\n * Vertex note: `GOOGLE_APPLICATION_CREDENTIALS_JSON` is our convention for the\n * raw service-account JSON blob. The runner materializes it to a 0600 file and\n * hands the driver `GOOGLE_APPLICATION_CREDENTIALS` (a path) instead — the\n * driver never sees the raw JSON.\n *\n * @since 1.3.0\n */\nexport const CLOUD_SECRET_ENV_KEYS: Record<Exclude<CloudId, \"default\">, readonly string[]> = {\n bedrock: [\n \"AWS_ACCESS_KEY_ID\",\n \"AWS_SECRET_ACCESS_KEY\",\n \"AWS_SESSION_TOKEN\",\n \"AWS_BEARER_TOKEN_BEDROCK\",\n ],\n vertex: [\"GOOGLE_APPLICATION_CREDENTIALS_JSON\"],\n azure: [\"ANTHROPIC_FOUNDRY_API_KEY\"],\n gateway: [\"ANTHROPIC_AUTH_TOKEN\", \"ANTHROPIC_API_KEY\"],\n};\n\n/**\n * Env vars scrubbed from the inherited environment before a non-default cloud\n * transport is assembled. Ambient first-party credentials or a stale\n * `CLAUDE_CODE_USE_*` flag must never leak into a Bedrock/Vertex/Foundry/\n * gateway session (the gateway branch re-adds its own carriers explicitly).\n *\n * Deliberately NOT exhaustive across clouds: ambient cloud-specific vars\n * (AWS_*, GOOGLE_*, ANTHROPIC_VERTEX_PROJECT_ID, ANTHROPIC_FOUNDRY_*) survive\n * so a standalone CLI inherits its own cloud's environment; the SDK ignores\n * vars whose transport flag is unset.\n */\nconst SCRUBBED_ENV_KEYS = [\"ANTHROPIC_API_KEY\", \"ANTHROPIC_AUTH_TOKEN\", \"ANTHROPIC_BASE_URL\"];\n\n/**\n * Assemble the Claude Agent SDK child env for a non-default cloud transport.\n *\n * Pure function (no external state touched; the returned `env` is a fresh\n * object — inputs are never mutated): starts from `baseEnv` (caller passes a\n * copy of `process.env` with undefined stripped) merged with `configEnv`,\n * scrubs inherited Anthropic\n * credential/routing vars and every `CLAUDE_CODE_USE_*` flag, then sets exactly\n * one `CLAUDE_CODE_USE_*` flag (none for gateway) plus the cloud's credential\n * bundle and derived non-secret vars. AWS_* / GOOGLE_* ambient values are NOT\n * scrubbed, so a standalone CLI inherits ambient cloud credentials when no\n * explicit `cloudSecrets` bundle is provided. Gateway is the mirror case: its\n * carriers ARE the scrubbed Anthropic vars, so the gateway branch restores\n * them from `cloudSecrets` → `fallbackApiKey` (resolved `apiKeys.anthropic`)\n * → the pre-scrub config/ambient value — otherwise a standalone gateway\n * session would have no reachable auth carrier at all.\n *\n * Never returns `undefined` values; absent settings are simply omitted.\n *\n * @since 1.3.0\n */\nexport function buildClaudeCloudEnv(args: {\n cloud: Exclude<CloudId, \"default\">;\n cloudConfig?: CloudConfig;\n cloudSecrets?: Record<string, string>;\n baseEnv: Record<string, string>;\n configEnv?: Record<string, string>;\n /** Resolved API key (e.g. `apiKeys.anthropic`) — gateway auth fallback only. */\n fallbackApiKey?: string;\n}): Record<string, string> {\n const { cloud, cloudConfig, cloudSecrets, baseEnv, configEnv, fallbackApiKey } = args;\n const env: Record<string, string> = { ...baseEnv, ...(configEnv ?? {}) };\n\n // Captured before the scrub — gateway falls back to these carriers.\n const ambient = {\n authToken: env.ANTHROPIC_AUTH_TOKEN,\n apiKey: env.ANTHROPIC_API_KEY,\n baseUrl: env.ANTHROPIC_BASE_URL,\n };\n\n for (const key of Object.keys(env)) {\n if (SCRUBBED_ENV_KEYS.includes(key) || key.startsWith(\"CLAUDE_CODE_USE_\")) {\n delete env[key];\n }\n }\n\n const set = (key: string, value: string | undefined) => {\n // Falsy check is deliberate: an empty-string credential/setting is never\n // valid env — dropping it beats shipping a key the SDK treats as set.\n if (value) env[key] = value;\n };\n\n switch (cloud) {\n case \"bedrock\": {\n env.CLAUDE_CODE_USE_BEDROCK = \"1\";\n // Explicit bundle values override ambient AWS_* (which survive the scrub\n // so a standalone CLI keeps its ambient credentials).\n for (const key of CLOUD_SECRET_ENV_KEYS.bedrock) set(key, cloudSecrets?.[key]);\n set(\"AWS_REGION\", cloudConfig?.region);\n break;\n }\n case \"vertex\": {\n env.CLAUDE_CODE_USE_VERTEX = \"1\";\n // Runner-materialized SA file path; ambient GOOGLE_APPLICATION_CREDENTIALS\n // is kept when no bundle value is provided.\n set(\"GOOGLE_APPLICATION_CREDENTIALS\", cloudSecrets?.GOOGLE_APPLICATION_CREDENTIALS);\n set(\"ANTHROPIC_VERTEX_PROJECT_ID\", cloudConfig?.projectId);\n set(\"CLOUD_ML_REGION\", cloudConfig?.region);\n break;\n }\n case \"azure\": {\n env.CLAUDE_CODE_USE_FOUNDRY = \"1\";\n set(\"ANTHROPIC_FOUNDRY_API_KEY\", cloudSecrets?.ANTHROPIC_FOUNDRY_API_KEY);\n // Resource wins over base_url when both are configured.\n if (cloudConfig?.resource) {\n env.ANTHROPIC_FOUNDRY_RESOURCE = cloudConfig.resource;\n } else {\n set(\"ANTHROPIC_FOUNDRY_BASE_URL\", cloudConfig?.baseUrl);\n }\n break;\n }\n case \"gateway\": {\n // No CLAUDE_CODE_USE_* flag — the gateway is addressed purely via\n // ANTHROPIC_BASE_URL plus an auth carrier. Explicit bundle wins;\n // standalone sessions fall back to the resolved key / ambient carriers.\n set(\"ANTHROPIC_BASE_URL\", cloudConfig?.baseUrl ?? ambient.baseUrl);\n const authToken = cloudSecrets?.ANTHROPIC_AUTH_TOKEN ?? ambient.authToken;\n if (authToken) {\n env.ANTHROPIC_AUTH_TOKEN = authToken;\n } else {\n set(\n \"ANTHROPIC_API_KEY\",\n cloudSecrets?.ANTHROPIC_API_KEY ?? fallbackApiKey ?? ambient.apiKey,\n );\n }\n break;\n }\n }\n\n return env;\n}\n","/**\n * Poisoned-transcript repair for the Claude Agent SDK driver.\n *\n * The Anthropic Messages API can permanently reject a conversation once its\n * persisted history contains a malformed content block. Because the bad block\n * lives in the SDK's on-disk JSONL transcript, every replayed turn fails with\n * the same `400 invalid_request_error` and the session is bricked with no\n * in-band recovery.\n *\n * This module repairs the transcript in place, covering three known poison\n * classes:\n *\n * 1. **Image `media_type` mismatch / omission.** An image block whose declared\n * `media_type` does not match — or is missing for — the actual bytes:\n * `... The image was specified using the image/png media type, but the\n * image appears to be a image/jpeg image`. Produced by the Claude Code\n * `Read` tool's format fallback (anthropics/claude-code#55338, #30124,\n * #33179). Repaired by sniffing the base64 magic bytes and correcting\n * `media_type`.\n * 2. **Oversized image.** An image whose decoded payload exceeds the API's\n * 5 MB per-image limit (anthropics/claude-code#34566). Replaced with a\n * text stub — the byte budget cannot be recovered any other way.\n * 3. **`cache_control` on an empty text block.** A text block carrying a\n * `cache_control` marker with empty/whitespace `text`\n * (anthropics/claude-code#59626). The `cache_control` field is stripped.\n *\n * Genuinely unidentifiable image blocks are also replaced with a text stub.\n *\n * Recovering by content scan (rather than parsing the API's `messages.N`\n * index) is deliberate: the index addresses the assembled API request, not a\n * JSONL line, and reproducing the SDK's message-assembly is fragile. A full\n * scan is index-free and repairs every poisoned block in one pass.\n *\n * **Async and line-streaming since #454.** A Claude Code transcript is routinely\n * multi-megabyte (base64 images inline in `tool_result` blocks), and this runs on\n * a failed turn *and before every resume* — inside the single-threaded `skaile\n * serve` loop. The previous `readFileSync` + `writeFileSync` + `renameSync` held\n * the loop for the whole file and materialised it twice over as one string. Both\n * passes now stream line by line off a `createReadStream`, so the loop is yielded\n * between lines and peak memory is one JSONL line rather than the whole file, and\n * every I/O phase is deadline-bounded.\n *\n * Streaming was chosen over a worker thread: the work is I/O-bound rather than\n * CPU-bound (per-line `JSON.parse` on a yielded loop is not what stalls a turn),\n * and a worker would add a structured-clone of the same multi-MB payload plus a\n * thread lifecycle to a path that must never block a turn.\n *\n * @module\n */\n\nimport { createReadStream, createWriteStream } from \"node:fs\";\nimport { readdir, rename, stat, unlink } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport { fsDeadlineMs, tryWithFsDeadline, withFsDeadline } from \"@skaile/workspaces/core\";\n\n/**\n * Minimal logger shape accepted by {@link scrubPoisonedTranscript}. Compatible\n * with the bridge `Logger`, but narrowed so the helper stays unit-testable\n * without a real logger instance.\n *\n * @category Transcript repair\n */\nexport interface ScrubLogger {\n info(message: string, data?: Record<string, unknown>): void;\n warn(message: string, data?: Record<string, unknown>): void;\n}\n\n/**\n * Options for {@link scrubPoisonedTranscript}.\n *\n * @category Transcript repair\n */\nexport interface ScrubTranscriptOptions {\n /**\n * Claude Code config directory — the parent of `projects/`. Resolve from\n * `CLAUDE_CONFIG_DIR`, falling back to `~/.claude`.\n */\n configDir: string;\n /** SDK session id whose transcript JSONL should be repaired. */\n sessionId: string;\n /** Optional logger for diagnostics. */\n log?: ScrubLogger;\n}\n\n/**\n * Outcome of a {@link scrubPoisonedTranscript} pass.\n *\n * @category Transcript repair\n */\nexport interface ScrubTranscriptResult {\n /** The located JSONL transcript path, or `null` when not found. */\n filePath: string | null;\n /** Image blocks whose `media_type` was corrected (or filled in) to match the bytes. */\n corrected: number;\n /**\n * Image blocks replaced with a text stub — either unidentifiable bytes or a\n * payload over the API's 5 MB per-image limit.\n */\n stubbed: number;\n /** Empty text blocks from which a rejected `cache_control` marker was stripped. */\n cacheStripped: number;\n /**\n * `true` when the transcript was located, contained at least one poisoned\n * block, and was rewritten. `false` means nothing needed repair (or the\n * file was not found) — the caller should not retry the resume.\n */\n changed: boolean;\n}\n\n/** Text inserted in place of an image block whose format cannot be identified. */\nconst STUB_TEXT = \"[image removed: unprocessable image data]\";\n\n/** Text inserted in place of an image block that exceeds the API size limit. */\nconst STUB_TEXT_OVERSIZED = \"[image removed: image too large]\";\n\n/**\n * The Anthropic Messages API rejects any single image whose decoded payload\n * exceeds 5 MB. An image at or under this is left alone; a larger one is\n * stubbed (its byte budget cannot be recovered).\n */\nconst MAX_IMAGE_BYTES = 5 * 1024 * 1024;\n\n/**\n * Identify an image's media type from the leading bytes of its base64 payload.\n *\n * Recognises the four formats the Anthropic API accepts. Returns `null` when\n * the magic bytes match no known format — the caller treats that as a\n * genuinely corrupt block and stubs it.\n *\n * @param base64 - Base64-encoded image data (only the prefix is inspected).\n * @returns An `image/*` media type, or `null` when unrecognised.\n * @category Transcript repair\n */\nexport function sniffImageMediaType(base64: string): string | null {\n let buf: Buffer;\n try {\n // 32 base64 chars decode to 24 bytes — enough for the WebP check at 12.\n buf = Buffer.from(base64.slice(0, 32), \"base64\");\n } catch {\n return null;\n }\n if (buf.length < 4) {\n return null;\n }\n // JPEG — SOI marker `FF D8`. Third byte varies (and may be corrupt), so a\n // two-byte check is intentional: it still matches malformed JPEGs, which is\n // exactly the poison case the API flags as \"appears to be image/jpeg\".\n if (buf[0] === 0xff && buf[1] === 0xd8) {\n return \"image/jpeg\";\n }\n // PNG — `89 50 4E 47`.\n if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) {\n return \"image/png\";\n }\n // GIF — `47 49 46 38` (\"GIF8\").\n if (buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x38) {\n return \"image/gif\";\n }\n // WebP — `RIFF` at 0..3 and `WEBP` at 8..11.\n if (\n buf.length >= 12 &&\n buf[0] === 0x52 &&\n buf[1] === 0x49 &&\n buf[2] === 0x46 &&\n buf[3] === 0x46 &&\n buf[8] === 0x57 &&\n buf[9] === 0x45 &&\n buf[10] === 0x42 &&\n buf[11] === 0x50\n ) {\n return \"image/webp\";\n }\n return null;\n}\n\n/** A base64 image source on a content block (shape is SDK-defined). */\ninterface Base64ImageSource {\n type?: string;\n media_type?: string;\n data?: string;\n}\n\n/** Loosely-typed content block from a transcript message. */\ninterface ContentBlockLike {\n type?: string;\n source?: Base64ImageSource;\n content?: unknown;\n [k: string]: unknown;\n}\n\n/** Mutable counters threaded through one scrub pass. */\ninterface ScrubCounters {\n corrected: number;\n stubbed: number;\n cacheStripped: number;\n}\n\n/** Total repairs recorded in a counter set — used to detect per-line changes. */\nfunction totalChanges(c: ScrubCounters): number {\n return c.corrected + c.stubbed + c.cacheStripped;\n}\n\n/**\n * Repair a single content block. Returns the (possibly replaced) block.\n *\n * - A `tool_result` block recurses into its `content` array.\n * - A text block carrying a `cache_control` marker whose `text` is empty or\n * whitespace has the marker stripped (the API rejects `cache_control` on\n * empty text blocks).\n * - An image block whose decoded payload exceeds the API's 5 MB limit is\n * replaced with a text stub.\n * - An image block whose bytes match no known format is replaced with a text\n * stub (an image cannot simply be dropped — a `tool_result` must keep at\n * least one content entry, and a bare `image` block is replaced 1:1).\n * - An image block whose declared `media_type` mismatches (or is missing for)\n * the sniffed type is corrected in place.\n * - Every other block is returned untouched.\n */\nfunction scrubBlock(block: ContentBlockLike, counters: ScrubCounters): ContentBlockLike {\n if (block.type === \"tool_result\" && Array.isArray(block.content)) {\n return {\n ...block,\n content: (block.content as ContentBlockLike[]).map((inner) => scrubBlock(inner, counters)),\n };\n }\n\n // A `cache_control` marker on a text block whose text is empty or whitespace\n // is rejected by the API (\"cache_control cannot be set for empty text\n // blocks\"). Strip the marker — the empty block itself is harmless.\n if (block.type === \"text\" && block.cache_control != null) {\n const text = typeof block.text === \"string\" ? block.text : \"\";\n if (text.trim() === \"\") {\n counters.cacheStripped++;\n const clone = { ...block };\n delete clone.cache_control;\n return clone;\n }\n }\n\n if (\n block.type === \"image\" &&\n block.source?.type === \"base64\" &&\n typeof block.source.data === \"string\"\n ) {\n const data = block.source.data;\n // The API rejects any image whose decoded payload exceeds 5 MB. The byte\n // budget cannot be salvaged, so the whole block becomes a text stub.\n // base64 encodes 3 bytes per 4 chars, so decoded length ≈ len * 3 / 4.\n if (Math.floor((data.length * 3) / 4) > MAX_IMAGE_BYTES) {\n counters.stubbed++;\n return { type: \"text\", text: STUB_TEXT_OVERSIZED };\n }\n const sniffed = sniffImageMediaType(data);\n if (sniffed === null) {\n counters.stubbed++;\n return { type: \"text\", text: STUB_TEXT };\n }\n if (sniffed !== block.source.media_type) {\n counters.corrected++;\n return { ...block, source: { ...block.source, media_type: sniffed } };\n }\n }\n\n return block;\n}\n\n/**\n * Locate the JSONL transcript for `sessionId` under `<configDir>/projects/`.\n *\n * Claude Code encodes the project directory into the `projects/` subfolder\n * name; rather than reproduce that encoding, this scans every subfolder for\n * `<sessionId>.jsonl` (the session id is a UUID — globally unique).\n *\n * Async and deadline-bounded since #454. The `existsSync(projectsDir)` probe is\n * gone: `readdir` already fails on a missing directory, so the probe was a\n * second stat on the same path for no information.\n *\n * `timeoutMs` defaults to {@link fsDeadlineMs} so callers that only need the\n * path (the resume probe) can omit it.\n *\n * @category Transcript repair\n */\nexport async function locateTranscriptPath(\n configDir: string,\n sessionId: string,\n timeoutMs: number = fsDeadlineMs(),\n): Promise<string | null> {\n const projectsDir = join(configDir, \"projects\");\n const entries = await tryWithFsDeadline(\n `readdir ${projectsDir}`,\n () => readdir(projectsDir),\n null,\n timeoutMs,\n );\n if (!entries) return null;\n for (const entry of entries) {\n const candidate = join(projectsDir, entry, `${sessionId}.jsonl`);\n const found = await tryWithFsDeadline(\n `stat ${candidate}`,\n async () => (await stat(candidate)).isFile(),\n false,\n timeoutMs,\n );\n if (found) return candidate;\n }\n return null;\n}\n\n/**\n * Yield a file's contents line by line, reproducing `readFileSync(...).split(\"\\n\")`\n * exactly — including the final (possibly empty) segment, so a trailing newline\n * survives a rewrite byte for byte.\n *\n * Splits on `\\n` alone, so a line out of a CRLF transcript arrives with its\n * `\\r` still attached. That carrier byte is part of the line here, and\n * {@link repairLine} re-attaches it to a line it rewrites — the file keeps the\n * terminator style it arrived with. Deliberately not `node:readline`:\n * `crlfDelay` strips the `\\r` outright (rewriting a CRLF transcript to LF) and\n * the interface swallows the trailing-newline distinction, either of which\n * would make the \"clean transcript is left byte-for-byte untouched\" guarantee\n * false. Only one line is held in memory at a time, so a multi-MB transcript\n * never materialises as a single string.\n */\nasync function* streamLines(filePath: string): AsyncGenerator<string> {\n const stream = createReadStream(filePath, { encoding: \"utf8\" });\n let pending = \"\";\n try {\n for await (const chunk of stream) {\n pending += chunk as string;\n let idx = pending.indexOf(\"\\n\");\n while (idx !== -1) {\n yield pending.slice(0, idx);\n pending = pending.slice(idx + 1);\n idx = pending.indexOf(\"\\n\");\n }\n }\n yield pending;\n } finally {\n stream.destroy();\n }\n}\n\n/**\n * Repair one JSONL line, returning the (possibly rewritten) line and mutating\n * `counters`. A non-JSON, blank, or content-less line is returned untouched.\n *\n * The reader splits on `\\n` only, so a line from a CRLF transcript still carries\n * its trailing `\\r`. An untouched line is returned verbatim and keeps it; a\n * rewritten one is rebuilt by `JSON.stringify`, which would drop it — leaving a\n * repaired CRLF transcript with mixed line endings. So the terminator is split\n * off before the parse and re-appended to the rewritten line.\n */\nfunction repairLine(line: string, counters: ScrubCounters): string {\n if (line.trim() === \"\") return line;\n const eol = line.endsWith(\"\\r\") ? \"\\r\" : \"\";\n const body = eol === \"\" ? line : line.slice(0, -1);\n let entry: { message?: { content?: unknown } };\n try {\n entry = JSON.parse(body);\n } catch {\n return line; // Not JSON — leave untouched.\n }\n const content = entry.message?.content;\n if (!Array.isArray(content)) return line;\n const before = totalChanges(counters);\n const scrubbed = (content as ContentBlockLike[]).map((block) => scrubBlock(block, counters));\n if (totalChanges(counters) === before) return line; // Nothing changed on this line.\n return `${JSON.stringify({ ...entry, message: { ...entry.message, content: scrubbed } })}${eol}`;\n}\n\n/**\n * Scan a Claude Code SDK transcript for image content blocks whose declared\n * `media_type` does not match the actual bytes, repair them, and atomically\n * rewrite the file.\n *\n * Safe to call after a turn has failed: the SDK query is dead at that point,\n * and the next resume re-reads the transcript from disk.\n *\n * **Async since #454.** Two streaming passes rather than one whole-file read:\n * pass 1 counts repairs without writing anything, and pass 2 runs only when\n * pass 1 found something. The common case — the preventive scrub of a clean\n * transcript before every resume — is therefore one streaming read and zero\n * writes, and a clean transcript is still left byte-for-byte untouched.\n *\n * @param opts - Config directory, session id, and an optional logger.\n * @returns A {@link ScrubTranscriptResult}. When `changed` is `true` the\n * caller may retry the resume with the same session id.\n * @category Transcript repair\n */\nexport async function scrubPoisonedTranscript(\n opts: ScrubTranscriptOptions,\n): Promise<ScrubTranscriptResult> {\n const { configDir, sessionId, log } = opts;\n const timeoutMs = fsDeadlineMs();\n const result: ScrubTranscriptResult = {\n filePath: null,\n corrected: 0,\n stubbed: 0,\n cacheStripped: 0,\n changed: false,\n };\n\n const filePath = await locateTranscriptPath(configDir, sessionId, timeoutMs);\n if (!filePath) {\n log?.warn(\"scrub-transcript: no transcript found\", { configDir, sessionId });\n return result;\n }\n result.filePath = filePath;\n\n // ── Pass 1: detect. Streams the transcript, counting repairs, writing nothing.\n const counters: ScrubCounters = { corrected: 0, stubbed: 0, cacheStripped: 0 };\n try {\n await withFsDeadline(\n `scan transcript ${filePath}`,\n async () => {\n for await (const line of streamLines(filePath)) repairLine(line, counters);\n },\n timeoutMs,\n );\n } catch (err) {\n log?.warn(\"scrub-transcript: failed to read transcript\", {\n filePath,\n error: err instanceof Error ? err.message : String(err),\n });\n return result;\n }\n\n result.corrected = counters.corrected;\n result.stubbed = counters.stubbed;\n result.cacheStripped = counters.cacheStripped;\n\n if (totalChanges(counters) === 0) {\n return result;\n }\n\n // ── Pass 2: rewrite. Atomic: stream a sibling temp file, then rename over the\n // original. Line separators are re-emitted exactly as pass 1 split them, so a\n // trailing newline and any blank lines survive verbatim.\n const tmpPath = `${filePath}.scrub-tmp`;\n try {\n await withFsDeadline(\n `rewrite transcript ${filePath}`,\n async () => {\n const discard: ScrubCounters = { corrected: 0, stubbed: 0, cacheStripped: 0 };\n await pipeline(\n (async function* () {\n let first = true;\n for await (const line of streamLines(filePath)) {\n yield first ? repairLine(line, discard) : `\\n${repairLine(line, discard)}`;\n first = false;\n }\n })(),\n createWriteStream(tmpPath, { encoding: \"utf8\" }),\n );\n await rename(tmpPath, filePath);\n },\n timeoutMs,\n );\n } catch (err) {\n log?.warn(\"scrub-transcript: failed to rewrite transcript\", {\n filePath,\n error: err instanceof Error ? err.message : String(err),\n });\n // Never leave a half-written sibling behind — the next scrub would rewrite\n // it anyway, but a stray `.scrub-tmp` in the SDK's projects dir is noise.\n await tryWithFsDeadline(`unlink ${tmpPath}`, () => unlink(tmpPath), undefined, timeoutMs);\n return result;\n }\n\n result.changed = true;\n log?.info(\"scrub-transcript: repaired poisoned transcript\", {\n filePath,\n corrected: result.corrected,\n stubbed: result.stubbed,\n cacheStripped: result.cacheStripped,\n });\n return result;\n}\n","/**\n * Pre-first-turn resume probe for the Claude Agent SDK driver.\n *\n * A tier-1 native resume only hands its session id to the SDK inside the first\n * real turn, so the `jsonl_lost` outcome (\"No conversation found\") is invisible\n * until a turn is consumed. The runner shares the container filesystem with the\n * SDK, so a cheap `stat` of the on-disk JSONL transcript is an authoritative,\n * side-effect-free signal of whether the resume will find its history — no\n * probe query, no spurious model turn.\n *\n * @module\n */\n\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { withFsDeadline } from \"@skaile/workspaces/core\";\nimport { locateTranscriptPath } from \"./scrub-transcript.js\";\n\n/**\n * Overall wall-clock budget for the probe. Deliberately a small fraction of the\n * platform's `session_init_ack` timeout (`DEFAULT_INIT_ACK_TIMEOUT_MS`, 15s):\n * the probe runs synchronously on the pre-ack path, so a wedged\n * `CLAUDE_CONFIG_DIR` mount must never push the ack past its deadline.\n */\nconst RESUME_PROBE_TIMEOUT_MS = 2_000;\n\n/**\n * Outcome of {@link probeResumeTranscript}: whether the SDK transcript for a\n * requested tier-1 resume exists on disk.\n *\n * @category Resume probe\n */\nexport type ResumeProbeOutcome = \"transcript_found\" | \"jsonl_lost\";\n\n/**\n * Resolve the Claude Code config directory — the parent of `projects/` — from\n * an explicit env map, the process environment, or the `~/.claude` default.\n *\n * The runner's probe and the claude-sdk driver share this one resolver, so they\n * agree as long as they see the same `CLAUDE_CONFIG_DIR`. Today they do:\n * `CLAUDE_CONFIG_DIR` is container-scoped and neither side threads a per-session\n * override through `config.env`, so both fall through to `process.env`. If a\n * future change ever set the driver's `config.env.CLAUDE_CONFIG_DIR` to a\n * divergent path, the reactive `resume_failed { jsonl_lost }` turn remains the\n * safety net.\n *\n * @category Resume probe\n */\nexport function resolveClaudeConfigDir(env?: Record<string, string | undefined>): string {\n return env?.CLAUDE_CONFIG_DIR || process.env.CLAUDE_CONFIG_DIR || join(homedir(), \".claude\");\n}\n\n/**\n * Probe whether the SDK JSONL transcript for `sessionId` exists on disk.\n *\n * Non-null locator result → `transcript_found`; null → `jsonl_lost`;\n * `undefined` → outcome unknown (the probe exceeded its budget or errored). The\n * caller leaves the ack field ABSENT on `undefined` so the reactive\n * `resume_failed { jsonl_lost }` turn stays the safety net — a timed-out probe\n * must never masquerade as a genuine `jsonl_lost` and force a needless downgrade.\n *\n * `opts.timeoutMs` overrides {@link RESUME_PROBE_TIMEOUT_MS}; `opts.locate`\n * overrides the transcript locator (used by tests / alternate stores).\n *\n * @category Resume probe\n */\nexport async function probeResumeTranscript(\n sessionId: string,\n opts?: {\n env?: Record<string, string | undefined>;\n timeoutMs?: number;\n locate?: (configDir: string, sessionId: string) => Promise<string | null>;\n },\n): Promise<ResumeProbeOutcome | undefined> {\n const configDir = resolveClaudeConfigDir(opts?.env);\n const timeoutMs = opts?.timeoutMs ?? RESUME_PROBE_TIMEOUT_MS;\n const locate = opts?.locate ?? locateTranscriptPath;\n try {\n // Bound the whole probe on wall-clock and THROW on expiry: the inner per-op\n // deadline swallows a timeout into a null path (a false `jsonl_lost`), so a\n // wedged mount must yield \"unknown\" here rather than a spurious downgrade.\n const filePath = await withFsDeadline(\n `resume-probe ${sessionId}`,\n () => locate(configDir, sessionId),\n timeoutMs,\n );\n return filePath ? \"transcript_found\" : \"jsonl_lost\";\n } catch {\n return undefined;\n }\n}\n"]}
|
|
@@ -22,15 +22,19 @@ var FlowExpressionError = class extends Error {
|
|
|
22
22
|
name = "FlowExpressionError";
|
|
23
23
|
/** Runtime path that was grammar-valid but absent from the supplied context. */
|
|
24
24
|
missingPath;
|
|
25
|
-
|
|
25
|
+
/** Producer node whose `skipped` status is why {@link missingPath} is absent. */
|
|
26
|
+
skippedProducer;
|
|
27
|
+
constructor(message, missingPath, skippedProducer) {
|
|
26
28
|
super(message);
|
|
27
29
|
this.missingPath = missingPath;
|
|
30
|
+
this.skippedProducer = skippedProducer;
|
|
28
31
|
}
|
|
29
32
|
};
|
|
30
|
-
function expressionError(message, position, missingPath) {
|
|
33
|
+
function expressionError(message, position, missingPath, skippedProducer) {
|
|
31
34
|
return new FlowExpressionError(
|
|
32
35
|
position === void 0 ? `Flow expression ${message}` : `Flow expression ${message} at ${position}`,
|
|
33
|
-
missingPath
|
|
36
|
+
missingPath,
|
|
37
|
+
skippedProducer
|
|
34
38
|
);
|
|
35
39
|
}
|
|
36
40
|
function parseString(source, start) {
|
|
@@ -159,6 +163,7 @@ function resolvePath(raw, context, position, traverse) {
|
|
|
159
163
|
if (forbidden) throw expressionError(`contains forbidden path segment ${forbidden}`, position);
|
|
160
164
|
let value;
|
|
161
165
|
let remaining;
|
|
166
|
+
let skippedProducer;
|
|
162
167
|
if (segments[0] === "flow" && segments[1] === "input") {
|
|
163
168
|
if (segments.length === 2) {
|
|
164
169
|
throw expressionError("path requires a JSON property suffix", position);
|
|
@@ -175,12 +180,23 @@ function resolvePath(raw, context, position, traverse) {
|
|
|
175
180
|
if (segments.length === 4) {
|
|
176
181
|
throw expressionError("path requires a JSON property suffix", position);
|
|
177
182
|
}
|
|
183
|
+
if (Object.hasOwn(context.nodes, segments[1]) && context.nodes[segments[1]].status === "skipped") {
|
|
184
|
+
skippedProducer = segments[1];
|
|
185
|
+
}
|
|
178
186
|
value = context.nodes;
|
|
179
187
|
remaining = segments.slice(1);
|
|
180
188
|
} else {
|
|
181
189
|
throw expressionError(`contains unsupported path ${raw}`, position);
|
|
182
190
|
}
|
|
183
191
|
if (!traverse) return void 0;
|
|
192
|
+
if (skippedProducer !== void 0) {
|
|
193
|
+
throw expressionError(
|
|
194
|
+
`cannot read ${raw}: producer node ${skippedProducer} was skipped and produced no output`,
|
|
195
|
+
position,
|
|
196
|
+
raw,
|
|
197
|
+
skippedProducer
|
|
198
|
+
);
|
|
199
|
+
}
|
|
184
200
|
for (const segment of remaining) value = ownValue(value, segment, position, raw);
|
|
185
201
|
return value;
|
|
186
202
|
}
|
|
@@ -1252,5 +1268,5 @@ function parseFlowDefinition(data) {
|
|
|
1252
1268
|
}
|
|
1253
1269
|
|
|
1254
1270
|
export { FLOW_EXPRESSION_LIMITS, FlowDefinitionSchema, FlowExpressionError, collectFlowBindingExpressions, evaluate, evaluateFlowExpression, inspectFlowExpression, normalizeV1, parseFlowDefinition, resolveFlowBindings, stableFlowJson };
|
|
1255
|
-
//# sourceMappingURL=chunk-
|
|
1256
|
-
//# sourceMappingURL=chunk-
|
|
1271
|
+
//# sourceMappingURL=chunk-B4J6TV4G.js.map
|
|
1272
|
+
//# sourceMappingURL=chunk-B4J6TV4G.js.map
|