@humain/humain-code 0.4.6 → 0.4.7
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 +15 -0
- package/dist/bun/sandbox-env-setup.js +8 -0
- package/dist/bun/sandbox-env-setup.js.map +1 -1
- package/dist/bundle/agent-monitor.js +1 -1
- package/dist/bundle/chunks/{anthropic-messages-OHNAMPAM.js → anthropic-messages-YMPB2HJ7.js} +14 -13
- package/dist/bundle/chunks/{azure-openai-responses-FREWTLSS.js → azure-openai-responses-PDHOT7UC.js} +2 -2
- package/dist/bundle/chunks/bedrock-converse-stream.js +35 -35
- package/dist/bundle/chunks/{chunk-UTMYL2YO.js → chunk-2W5PWUPO.js} +10 -10
- package/dist/bundle/chunks/{chunk-DUZY4PDA.js → chunk-3E4SMILM.js} +33 -29
- package/dist/bundle/chunks/{chunk-UU4WS4BQ.js → chunk-3TYF6GG6.js} +319 -321
- package/dist/bundle/chunks/{chunk-FP2SXW5M.js → chunk-DAJJK7AP.js} +472 -458
- package/dist/bundle/chunks/{chunk-JQZ7BIAI.js → chunk-F7UMX5BV.js} +25 -22
- package/dist/bundle/chunks/{chunk-E7WGCXWK.js → chunk-GUUAEK6G.js} +1 -1
- package/dist/bundle/chunks/{chunk-4X774RBJ.js → chunk-GVVRXZHN.js} +4 -4
- package/dist/bundle/chunks/{chunk-H5CZL7M5.js → chunk-KRMTBTWU.js} +1 -1
- package/dist/bundle/chunks/{chunk-ICLZNV4V.js → chunk-LQ4S7CRR.js} +79 -67
- package/dist/bundle/chunks/{chunk-KLIRQQH5.js → chunk-OTXURGIO.js} +1 -1
- package/dist/bundle/chunks/{chunk-OXJXKCLB.js → chunk-PMISFIBM.js} +1 -1
- package/dist/bundle/chunks/{chunk-LFXFQLII.js → chunk-ROSZII6E.js} +1 -1
- package/dist/bundle/chunks/{chunk-E22S6D55.js → chunk-SWRU4BOC.js} +1 -1
- package/dist/bundle/chunks/{chunk-VQTXF23B.js → chunk-TIAXGIMN.js} +1 -1
- package/dist/bundle/chunks/{chunk-3ZI2TEVB.js → chunk-UZ5FVVCP.js} +1 -1
- package/dist/bundle/chunks/{chunk-BBBBZ5HY.js → chunk-XRMWWXLF.js} +3 -3
- package/dist/bundle/chunks/{chunk-2NX3BVH6.js → chunk-Z5LYSSTY.js} +2 -2
- package/dist/bundle/chunks/{cli-5YRA5PFB.js → cli-ZKT34WPW.js} +2 -2
- package/dist/bundle/chunks/{compat-LJ4ZIVJZ.js → compat-VPRCBNVL.js} +8 -8
- package/dist/bundle/chunks/{dist-UAQRGPZO.js → dist-4KCNJLEA.js} +153 -143
- package/dist/bundle/chunks/{dist-QHFJK4TH.js → dist-N7XDUAAO.js} +4 -4
- package/dist/bundle/chunks/{easter-egg-3d-ARXMB2RN.js → easter-egg-3d-5KKDWEIA.js} +1 -1
- package/dist/bundle/chunks/{execute-MFIDTEMB.js → execute-OSBDNQU5.js} +1 -1
- package/dist/bundle/chunks/{extract-EWN2GRAC.js → extract-56PXVZVW.js} +2 -2
- package/dist/bundle/chunks/{host-3OGMFGBY.js → host-2ARI7PQ5.js} +1 -1
- package/dist/bundle/chunks/mistral-conversations-XA2ZGSAH.js +43 -0
- package/dist/bundle/chunks/{openai-codex-responses-5AJAJHTK.js → openai-codex-responses-Y6NRWMOI.js} +2 -2
- package/dist/bundle/chunks/{openai-completions-65RRYKEQ.js → openai-completions-FY77MIZH.js} +6 -6
- package/dist/bundle/chunks/{openai-responses-72W3PGZ7.js → openai-responses-LNSCERKH.js} +2 -2
- package/dist/bundle/chunks/{pi-messages-RLLYRBDT.js → pi-messages-LYJZPRST.js} +7 -6
- package/dist/bundle/chunks/{runtime-HBWXEJT3.js → runtime-JFLZUNYP.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-LWYOTTHQ.js → virtual-modules-F76HZAGG.js} +2 -2
- package/dist/bundle/cli-runtime.js +2 -2
- package/dist/bundle/flow/package.json +1 -1
- package/dist/bundle/index.js +5 -5
- package/dist/bundle/rpc-entry.js +2 -2
- package/dist/core/tools/renderers/write.d.ts +2 -2
- package/dist/core/tools/renderers/write.d.ts.map +1 -1
- package/dist/core/tools/renderers/write.js +120 -15
- package/dist/core/tools/renderers/write.js.map +1 -1
- package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +27 -28
- package/dist/humain/flow-loader.d.ts.map +1 -1
- package/dist/humain/flow-loader.js +30 -2
- package/dist/humain/flow-loader.js.map +1 -1
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +2 -0
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/mermaid.d.ts.map +1 -1
- package/dist/modes/interactive/components/mermaid.js +4 -0
- package/dist/modes/interactive/components/mermaid.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +4 -0
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +5 -0
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/utils/child-process.d.ts +8 -0
- package/dist/utils/child-process.d.ts.map +1 -1
- package/dist/utils/child-process.js +65 -4
- package/dist/utils/child-process.js.map +1 -1
- package/dist/utils/windows-path.d.ts +9 -0
- package/dist/utils/windows-path.d.ts.map +1 -0
- package/dist/utils/windows-path.js +31 -0
- package/dist/utils/windows-path.js.map +1 -0
- package/docs/tui.md +1 -1
- package/npm-shrinkwrap.json +6 -6
- package/package.json +2 -2
- package/dist/bundle/chunks/mistral-conversations-5HCMHK6E.js +0 -43
|
@@ -3,6 +3,14 @@ import type { Readable } from "node:stream";
|
|
|
3
3
|
export declare function spawnProcess(command: string, args: string[], options: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioPipe>): ChildProcessByStdio<null, Readable, Readable>;
|
|
4
4
|
export declare function spawnProcess(command: string, args: string[], options: SpawnOptions): ChildProcess;
|
|
5
5
|
export declare function spawnProcessSync(command: string, args: string[], options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns<string>;
|
|
6
|
+
/**
|
|
7
|
+
* The file a command named without a path is on Windows, from PATH's absolute directories only. cross-spawn finds one with
|
|
8
|
+
* `which`, which looks in the working directory first: a repository could put an npm.cmd or git.exe of its own there, for
|
|
9
|
+
* the package update check to run before any trust decision. Found nowhere, a path that does not exist, so that spawning it
|
|
10
|
+
* fails as a missing command does. (cross-spawn still runs a .cmd through cmd.exe with its arguments escaped.)
|
|
11
|
+
* Exported for tests; spawnProcess and spawnProcessSync call it on Windows only.
|
|
12
|
+
*/
|
|
13
|
+
export declare function resolveWindowsCommand(command: string, env: NodeJS.ProcessEnv | undefined): string;
|
|
6
14
|
/**
|
|
7
15
|
* Wait for a child process to terminate without hanging on inherited stdio handles.
|
|
8
16
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"child-process.d.ts","sourceRoot":"","sources":["../../src/utils/child-process.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,YAAY,EACjB,KAAK,mBAAmB,EAGxB,KAAK,YAAY,EACjB,KAAK,0BAA0B,EAC/B,KAAK,kCAAkC,EACvC,KAAK,gBAAgB,EACrB,KAAK,SAAS,EACd,KAAK,SAAS,EACd,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"child-process.d.ts","sourceRoot":"","sources":["../../src/utils/child-process.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,YAAY,EACjB,KAAK,mBAAmB,EAGxB,KAAK,YAAY,EACjB,KAAK,0BAA0B,EAC/B,KAAK,kCAAkC,EACvC,KAAK,gBAAgB,EACrB,KAAK,SAAS,EACd,KAAK,SAAS,EACd,MAAM,oBAAoB,CAAC;AAE5B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAS5C,wBAAgB,YAAY,CAC3B,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EAAE,EACd,OAAO,EAAE,0BAA0B,CAAC,SAAS,EAAE,SAAS,EAAE,SAAS,CAAC,GAClE,mBAAmB,CAAC,IAAI,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC;AACjD,wBAAgB,YAAY,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,EAAE,YAAY,GAAG,YAAY,CAAC;AAOnG,wBAAgB,gBAAgB,CAC/B,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,MAAM,EAAE,EACd,OAAO,EAAE,kCAAkC,GACzC,gBAAgB,CAAC,MAAM,CAAC,CAI1B;AA8BD;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,CAAC,UAAU,GAAG,SAAS,GAAG,MAAM,CAiBjG;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,YAAY,EAAE,WAAW,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CA8F1G"}
|
|
@@ -1,13 +1,74 @@
|
|
|
1
1
|
import { spawn as nodeSpawn, spawnSync as nodeSpawnSync, } from "node:child_process";
|
|
2
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
2
4
|
import crossSpawn from "cross-spawn";
|
|
5
|
+
import readShebang from "cross-spawn/lib/util/readShebang.js";
|
|
6
|
+
import resolveCommand from "cross-spawn/lib/util/resolveCommand.js";
|
|
7
|
+
import { isProgramFile, windowsPathDirectories } from "./windows-path.js";
|
|
3
8
|
const EXIT_STDIO_GRACE_MS = 100;
|
|
4
9
|
export function spawnProcess(command, args, options) {
|
|
5
|
-
|
|
10
|
+
if (process.platform !== "win32")
|
|
11
|
+
return nodeSpawn(command, args, options);
|
|
12
|
+
const invocation = resolveWindowsInvocation(command, args, options);
|
|
13
|
+
return crossSpawn(invocation.command, invocation.args, options);
|
|
6
14
|
}
|
|
7
15
|
export function spawnProcessSync(command, args, options) {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
16
|
+
if (process.platform !== "win32")
|
|
17
|
+
return nodeSpawnSync(command, args, options);
|
|
18
|
+
const invocation = resolveWindowsInvocation(command, args, options);
|
|
19
|
+
return crossSpawn.sync(invocation.command, invocation.args, options);
|
|
20
|
+
}
|
|
21
|
+
function resolveWindowsInvocation(command, args, options) {
|
|
22
|
+
let file = resolveWindowsCommand(command, options.env);
|
|
23
|
+
if (options.shell)
|
|
24
|
+
return { command: file, args };
|
|
25
|
+
const cwd = typeof options.cwd === "object" ? fileURLToPath(options.cwd) : options.cwd;
|
|
26
|
+
const visited = new Set();
|
|
27
|
+
while (true) {
|
|
28
|
+
file = resolve(cwd ?? "", file);
|
|
29
|
+
// Match cross-spawn's actual file (including explicit PATHEXT paths) before reading its shebang.
|
|
30
|
+
const script = resolveCommand({ command: file, options: { env: options.env } }) ?? file;
|
|
31
|
+
const key = script.toLowerCase();
|
|
32
|
+
if (visited.has(key) || visited.size === 32) {
|
|
33
|
+
return { command: resolveWindowsCommand("shebang-chain", { PATH: "" }), args };
|
|
34
|
+
}
|
|
35
|
+
visited.add(key);
|
|
36
|
+
// cross-spawn otherwise resolves the shebang interpreter cwd-first and passes its bare name to native spawn.
|
|
37
|
+
// Unwrap the entire bounded chain so its final pass sees only a file without a shebang.
|
|
38
|
+
const interpreter = readShebang(script);
|
|
39
|
+
if (!interpreter)
|
|
40
|
+
return { command: script, args };
|
|
41
|
+
file = resolveWindowsCommand(interpreter, options.env);
|
|
42
|
+
args = [script, ...args];
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
// Derived from Pi-Bolt (MIT, Copyright (c) 2026 OpenSec (Pi-Bolt)), commit 36a2080f; modified for HUMAIN Code CLI.
|
|
46
|
+
/**
|
|
47
|
+
* The file a command named without a path is on Windows, from PATH's absolute directories only. cross-spawn finds one with
|
|
48
|
+
* `which`, which looks in the working directory first: a repository could put an npm.cmd or git.exe of its own there, for
|
|
49
|
+
* the package update check to run before any trust decision. Found nowhere, a path that does not exist, so that spawning it
|
|
50
|
+
* fails as a missing command does. (cross-spawn still runs a .cmd through cmd.exe with its arguments escaped.)
|
|
51
|
+
* Exported for tests; spawnProcess and spawnProcessSync call it on Windows only.
|
|
52
|
+
*/
|
|
53
|
+
export function resolveWindowsCommand(command, env) {
|
|
54
|
+
if (/[\\/]/.test(command))
|
|
55
|
+
return command;
|
|
56
|
+
const source = env ?? process.env;
|
|
57
|
+
// (An environment merged from two may have both PATH and Path: PATH, as cross-spawn takes it.)
|
|
58
|
+
const pathKey = "PATH" in source ? "PATH" : Object.keys(source).find((key) => key.toLowerCase() === "path");
|
|
59
|
+
const dirs = windowsPathDirectories(pathKey ? (source[pathKey] ?? "") : "").filter((dir) => isAbsolute(dir));
|
|
60
|
+
const pathExtensions = (source.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
|
|
61
|
+
// (As `which` has it: a name with a dot is also tried as it is.)
|
|
62
|
+
const extensions = command.includes(".") ? ["", ...pathExtensions] : pathExtensions;
|
|
63
|
+
for (const dir of dirs) {
|
|
64
|
+
for (const extension of extensions) {
|
|
65
|
+
const file = join(dir, command + extension);
|
|
66
|
+
if (isProgramFile(file))
|
|
67
|
+
return file;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
// (In a folder that cannot exist: not one of Windows's own programs of that name, were PATH empty.)
|
|
71
|
+
return join(process.env.SystemRoot ?? "C:\\Windows", "humain-code-no-such-command", `${command}.exe`);
|
|
11
72
|
}
|
|
12
73
|
/**
|
|
13
74
|
* Wait for a child process to terminate without hanging on inherited stdio handles.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"child-process.js","sourceRoot":"","sources":["../../src/utils/child-process.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,KAAK,IAAI,SAAS,EAClB,SAAS,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,CAAC,CAAC;QACjC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC7B,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAC3B,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC7B,WAAW,EAAE,gBAAgB,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;QACrE,IAAI,WAAW,EAAE,OAAO;YAAE,YAAY,EAAE,CAAC;IAC1C,CAAC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n\ttype ChildProcess,\n\ttype ChildProcessByStdio,\n\tspawn as nodeSpawn,\n\tspawnSync as nodeSpawnSync,\n\ttype SpawnOptions,\n\ttype SpawnOptionsWithStdioTuple,\n\ttype SpawnSyncOptionsWithStringEncoding,\n\ttype SpawnSyncReturns,\n\ttype StdioNull,\n\ttype StdioPipe,\n} from \"node:child_process\";\nimport type { Readable } from \"node:stream\";\nimport crossSpawn from \"cross-spawn\";\n\nconst EXIT_STDIO_GRACE_MS = 100;\n\nexport function spawnProcess(\n\tcommand: string,\n\targs: string[],\n\toptions: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioPipe>,\n): ChildProcessByStdio<null, Readable, Readable>;\nexport function spawnProcess(command: string, args: string[], options: SpawnOptions): ChildProcess;\nexport function spawnProcess(command: string, args: string[], options: SpawnOptions): ChildProcess {\n\treturn process.platform === \"win32\" ? crossSpawn(command, args, options) : nodeSpawn(command, args, options);\n}\n\nexport function spawnProcessSync(\n\tcommand: string,\n\targs: string[],\n\toptions: SpawnSyncOptionsWithStringEncoding,\n): SpawnSyncReturns<string> {\n\treturn process.platform === \"win32\"\n\t\t? crossSpawn.sync(command, args, options)\n\t\t: nodeSpawnSync(command, args, options);\n}\n\n/**\n * Wait for a child process to terminate without hanging on inherited stdio handles.\n *\n * A short-lived child can `exit` while a detached descendant keeps its stdout/stderr\n * pipe open. We must not resolve and destroy the streams on a fixed deadline measured\n * from `exit`, or output still being written past that deadline is silently lost\n * (earendil-works/pi#5303). Instead, after `exit` we wait for the pipes to fall idle:\n * the grace timer is re-armed on every chunk, so an actively writing descendant keeps\n * us reading, while a quiet inherited handle (e.g. a Windows daemonized descendant\n * that never lets `close` fire) still releases us after the grace elapses.\n */\nexport function waitForChildProcess(child: ChildProcess, drainSignal?: AbortSignal): Promise<number | null> {\n\treturn new Promise((resolve, reject) => {\n\t\tlet settled = false;\n\t\tlet exited = false;\n\t\tlet exitCode: number | null = null;\n\t\tlet postExitTimer: NodeJS.Timeout | undefined;\n\t\tlet stdoutEnded = child.stdout === null;\n\t\tlet stderrEnded = child.stderr === null;\n\n\t\tconst cleanup = () => {\n\t\t\tdrainSignal?.removeEventListener(\"abort\", onDrainAbort);\n\t\t\tif (postExitTimer) {\n\t\t\t\tclearTimeout(postExitTimer);\n\t\t\t\tpostExitTimer = undefined;\n\t\t\t}\n\t\t\tchild.removeListener(\"error\", onError);\n\t\t\tchild.removeListener(\"exit\", onExit);\n\t\t\tchild.removeListener(\"close\", onClose);\n\t\t\tchild.stdout?.removeListener(\"end\", onStdoutEnd);\n\t\t\tchild.stderr?.removeListener(\"end\", onStderrEnd);\n\t\t\tchild.stdout?.removeListener(\"data\", onData);\n\t\t\tchild.stderr?.removeListener(\"data\", onData);\n\t\t};\n\n\t\tconst finalize = (code: number | null) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tchild.stdout?.destroy();\n\t\t\tchild.stderr?.destroy();\n\t\t\tresolve(code);\n\t\t};\n\n\t\t// Cancellation bounds draining even if termination failed or an escaped descendant keeps writing.\n\t\tconst onDrainAbort = () => finalize(child.exitCode);\n\n\t\tconst maybeFinalizeAfterExit = () => {\n\t\t\tif (!exited || settled) return;\n\t\t\tif (stdoutEnded && stderrEnded) {\n\t\t\t\tfinalize(exitCode);\n\t\t\t}\n\t\t};\n\n\t\tconst armIdleTimer = () => {\n\t\t\tif (postExitTimer) clearTimeout(postExitTimer);\n\t\t\tpostExitTimer = setTimeout(() => finalize(exitCode), EXIT_STDIO_GRACE_MS);\n\t\t};\n\n\t\tconst onData = () => {\n\t\t\t// Output is still arriving after exit; defer finalizing so we don't\n\t\t\t// destroy the stream mid-write and truncate the tail.\n\t\t\tif (exited && !settled) armIdleTimer();\n\t\t};\n\n\t\tconst onStdoutEnd = () => {\n\t\t\tstdoutEnded = true;\n\t\t\tmaybeFinalizeAfterExit();\n\t\t};\n\n\t\tconst onStderrEnd = () => {\n\t\t\tstderrEnded = true;\n\t\t\tmaybeFinalizeAfterExit();\n\t\t};\n\n\t\tconst onError = (err: Error) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\treject(err);\n\t\t};\n\n\t\tconst onExit = (code: number | null) => {\n\t\t\texited = true;\n\t\t\texitCode = code;\n\t\t\tmaybeFinalizeAfterExit();\n\t\t\tif (!settled) {\n\t\t\t\tarmIdleTimer();\n\t\t\t}\n\t\t};\n\n\t\tconst onClose = (code: number | null) => {\n\t\t\tfinalize(code);\n\t\t};\n\n\t\tchild.stdout?.once(\"end\", onStdoutEnd);\n\t\tchild.stderr?.once(\"end\", onStderrEnd);\n\t\tchild.stdout?.on(\"data\", onData);\n\t\tchild.stderr?.on(\"data\", onData);\n\t\tchild.once(\"error\", onError);\n\t\tchild.once(\"exit\", onExit);\n\t\tchild.once(\"close\", onClose);\n\t\tdrainSignal?.addEventListener(\"abort\", onDrainAbort, { once: true });\n\t\tif (drainSignal?.aborted) onDrainAbort();\n\t});\n}\n"]}
|
|
1
|
+
{"version":3,"file":"child-process.js","sourceRoot":"","sources":["../../src/utils/child-process.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,KAAK,IAAI,SAAS,EAClB,SAAS,IAAI,aAAa,GAO1B,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,OAAO,EAA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AC,CAAC;QACb,CAAC,CAAC;QAEF,MAAM,MAAM,GAAG,CAAC,IAAmB,EAAE,EAAE;YACtC,MAAM,GAAG,IAAI,CAAC;YACd,QAAQ,GAAG,IAAI,CAAC;YAChB,sBAAsB,EAAE,CAAC;YACzB,IAAI,CAAC,OAAO,EAAE,CAAC;gBACd,YAAY,EAAE,CAAC;YAChB,CAAC;QACF,CAAC,CAAC;QAEF,MAAM,OAAO,GAAG,CAAC,IAAmB,EAAE,EAAE;YACvC,QAAQ,CAAC,IAAI,CAAC,CAAC;QAChB,CAAC,CAAC;QAEF,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;QACvC,KAAK,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;QACvC,KAAK,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACjC,KAAK,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACjC,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC7B,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QAC3B,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC7B,WAAW,EAAE,gBAAgB,CAAC,OAAO,EAAE,YAAY,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC,CAAC;QACrE,IAAI,WAAW,EAAE,OAAO;YAAE,YAAY,EAAE,CAAC;IAC1C,CAAC,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n\ttype ChildProcess,\n\ttype ChildProcessByStdio,\n\tspawn as nodeSpawn,\n\tspawnSync as nodeSpawnSync,\n\ttype SpawnOptions,\n\ttype SpawnOptionsWithStdioTuple,\n\ttype SpawnSyncOptionsWithStringEncoding,\n\ttype SpawnSyncReturns,\n\ttype StdioNull,\n\ttype StdioPipe,\n} from \"node:child_process\";\nimport { isAbsolute, join, resolve } from \"node:path\";\nimport type { Readable } from \"node:stream\";\nimport { fileURLToPath } from \"node:url\";\nimport crossSpawn from \"cross-spawn\";\nimport readShebang from \"cross-spawn/lib/util/readShebang.js\";\nimport resolveCommand from \"cross-spawn/lib/util/resolveCommand.js\";\nimport { isProgramFile, windowsPathDirectories } from \"./windows-path.ts\";\n\nconst EXIT_STDIO_GRACE_MS = 100;\n\nexport function spawnProcess(\n\tcommand: string,\n\targs: string[],\n\toptions: SpawnOptionsWithStdioTuple<StdioNull, StdioPipe, StdioPipe>,\n): ChildProcessByStdio<null, Readable, Readable>;\nexport function spawnProcess(command: string, args: string[], options: SpawnOptions): ChildProcess;\nexport function spawnProcess(command: string, args: string[], options: SpawnOptions): ChildProcess {\n\tif (process.platform !== \"win32\") return nodeSpawn(command, args, options);\n\tconst invocation = resolveWindowsInvocation(command, args, options);\n\treturn crossSpawn(invocation.command, invocation.args, options);\n}\n\nexport function spawnProcessSync(\n\tcommand: string,\n\targs: string[],\n\toptions: SpawnSyncOptionsWithStringEncoding,\n): SpawnSyncReturns<string> {\n\tif (process.platform !== \"win32\") return nodeSpawnSync(command, args, options);\n\tconst invocation = resolveWindowsInvocation(command, args, options);\n\treturn crossSpawn.sync(invocation.command, invocation.args, options);\n}\n\nfunction resolveWindowsInvocation(\n\tcommand: string,\n\targs: string[],\n\toptions: Pick<SpawnOptions, \"env\" | \"shell\" | \"cwd\">,\n): { command: string; args: string[] } {\n\tlet file = resolveWindowsCommand(command, options.env);\n\tif (options.shell) return { command: file, args };\n\tconst cwd = typeof options.cwd === \"object\" ? fileURLToPath(options.cwd) : options.cwd;\n\tconst visited = new Set<string>();\n\twhile (true) {\n\t\tfile = resolve(cwd ?? \"\", file);\n\t\t// Match cross-spawn's actual file (including explicit PATHEXT paths) before reading its shebang.\n\t\tconst script = resolveCommand({ command: file, options: { env: options.env } }) ?? file;\n\t\tconst key = script.toLowerCase();\n\t\tif (visited.has(key) || visited.size === 32) {\n\t\t\treturn { command: resolveWindowsCommand(\"shebang-chain\", { PATH: \"\" }), args };\n\t\t}\n\t\tvisited.add(key);\n\t\t// cross-spawn otherwise resolves the shebang interpreter cwd-first and passes its bare name to native spawn.\n\t\t// Unwrap the entire bounded chain so its final pass sees only a file without a shebang.\n\t\tconst interpreter = readShebang(script);\n\t\tif (!interpreter) return { command: script, args };\n\t\tfile = resolveWindowsCommand(interpreter, options.env);\n\t\targs = [script, ...args];\n\t}\n}\n\n// Derived from Pi-Bolt (MIT, Copyright (c) 2026 OpenSec (Pi-Bolt)), commit 36a2080f; modified for HUMAIN Code CLI.\n/**\n * The file a command named without a path is on Windows, from PATH's absolute directories only. cross-spawn finds one with\n * `which`, which looks in the working directory first: a repository could put an npm.cmd or git.exe of its own there, for\n * the package update check to run before any trust decision. Found nowhere, a path that does not exist, so that spawning it\n * fails as a missing command does. (cross-spawn still runs a .cmd through cmd.exe with its arguments escaped.)\n * Exported for tests; spawnProcess and spawnProcessSync call it on Windows only.\n */\nexport function resolveWindowsCommand(command: string, env: NodeJS.ProcessEnv | undefined): string {\n\tif (/[\\\\/]/.test(command)) return command;\n\tconst source = env ?? process.env;\n\t// (An environment merged from two may have both PATH and Path: PATH, as cross-spawn takes it.)\n\tconst pathKey = \"PATH\" in source ? \"PATH\" : Object.keys(source).find((key) => key.toLowerCase() === \"path\");\n\tconst dirs = windowsPathDirectories(pathKey ? (source[pathKey] ?? \"\") : \"\").filter((dir) => isAbsolute(dir));\n\tconst pathExtensions = (source.PATHEXT ?? \".COM;.EXE;.BAT;.CMD\").split(\";\").filter(Boolean);\n\t// (As `which` has it: a name with a dot is also tried as it is.)\n\tconst extensions = command.includes(\".\") ? [\"\", ...pathExtensions] : pathExtensions;\n\tfor (const dir of dirs) {\n\t\tfor (const extension of extensions) {\n\t\t\tconst file = join(dir, command + extension);\n\t\t\tif (isProgramFile(file)) return file;\n\t\t}\n\t}\n\t// (In a folder that cannot exist: not one of Windows's own programs of that name, were PATH empty.)\n\treturn join(process.env.SystemRoot ?? \"C:\\\\Windows\", \"humain-code-no-such-command\", `${command}.exe`);\n}\n\n/**\n * Wait for a child process to terminate without hanging on inherited stdio handles.\n *\n * A short-lived child can `exit` while a detached descendant keeps its stdout/stderr\n * pipe open. We must not resolve and destroy the streams on a fixed deadline measured\n * from `exit`, or output still being written past that deadline is silently lost\n * (earendil-works/pi#5303). Instead, after `exit` we wait for the pipes to fall idle:\n * the grace timer is re-armed on every chunk, so an actively writing descendant keeps\n * us reading, while a quiet inherited handle (e.g. a Windows daemonized descendant\n * that never lets `close` fire) still releases us after the grace elapses.\n */\nexport function waitForChildProcess(child: ChildProcess, drainSignal?: AbortSignal): Promise<number | null> {\n\treturn new Promise((resolve, reject) => {\n\t\tlet settled = false;\n\t\tlet exited = false;\n\t\tlet exitCode: number | null = null;\n\t\tlet postExitTimer: NodeJS.Timeout | undefined;\n\t\tlet stdoutEnded = child.stdout === null;\n\t\tlet stderrEnded = child.stderr === null;\n\n\t\tconst cleanup = () => {\n\t\t\tdrainSignal?.removeEventListener(\"abort\", onDrainAbort);\n\t\t\tif (postExitTimer) {\n\t\t\t\tclearTimeout(postExitTimer);\n\t\t\t\tpostExitTimer = undefined;\n\t\t\t}\n\t\t\tchild.removeListener(\"error\", onError);\n\t\t\tchild.removeListener(\"exit\", onExit);\n\t\t\tchild.removeListener(\"close\", onClose);\n\t\t\tchild.stdout?.removeListener(\"end\", onStdoutEnd);\n\t\t\tchild.stderr?.removeListener(\"end\", onStderrEnd);\n\t\t\tchild.stdout?.removeListener(\"data\", onData);\n\t\t\tchild.stderr?.removeListener(\"data\", onData);\n\t\t};\n\n\t\tconst finalize = (code: number | null) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\tchild.stdout?.destroy();\n\t\t\tchild.stderr?.destroy();\n\t\t\tresolve(code);\n\t\t};\n\n\t\t// Cancellation bounds draining even if termination failed or an escaped descendant keeps writing.\n\t\tconst onDrainAbort = () => finalize(child.exitCode);\n\n\t\tconst maybeFinalizeAfterExit = () => {\n\t\t\tif (!exited || settled) return;\n\t\t\tif (stdoutEnded && stderrEnded) {\n\t\t\t\tfinalize(exitCode);\n\t\t\t}\n\t\t};\n\n\t\tconst armIdleTimer = () => {\n\t\t\tif (postExitTimer) clearTimeout(postExitTimer);\n\t\t\tpostExitTimer = setTimeout(() => finalize(exitCode), EXIT_STDIO_GRACE_MS);\n\t\t};\n\n\t\tconst onData = () => {\n\t\t\t// Output is still arriving after exit; defer finalizing so we don't\n\t\t\t// destroy the stream mid-write and truncate the tail.\n\t\t\tif (exited && !settled) armIdleTimer();\n\t\t};\n\n\t\tconst onStdoutEnd = () => {\n\t\t\tstdoutEnded = true;\n\t\t\tmaybeFinalizeAfterExit();\n\t\t};\n\n\t\tconst onStderrEnd = () => {\n\t\t\tstderrEnded = true;\n\t\t\tmaybeFinalizeAfterExit();\n\t\t};\n\n\t\tconst onError = (err: Error) => {\n\t\t\tif (settled) return;\n\t\t\tsettled = true;\n\t\t\tcleanup();\n\t\t\treject(err);\n\t\t};\n\n\t\tconst onExit = (code: number | null) => {\n\t\t\texited = true;\n\t\t\texitCode = code;\n\t\t\tmaybeFinalizeAfterExit();\n\t\t\tif (!settled) {\n\t\t\t\tarmIdleTimer();\n\t\t\t}\n\t\t};\n\n\t\tconst onClose = (code: number | null) => {\n\t\t\tfinalize(code);\n\t\t};\n\n\t\tchild.stdout?.once(\"end\", onStdoutEnd);\n\t\tchild.stderr?.once(\"end\", onStderrEnd);\n\t\tchild.stdout?.on(\"data\", onData);\n\t\tchild.stderr?.on(\"data\", onData);\n\t\tchild.once(\"error\", onError);\n\t\tchild.once(\"exit\", onExit);\n\t\tchild.once(\"close\", onClose);\n\t\tdrainSignal?.addEventListener(\"abort\", onDrainAbort, { once: true });\n\t\tif (drainSignal?.aborted) onDrainAbort();\n\t});\n}\n"]}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** PATH's directories as Windows reads them: an entry may be in quotes ("C:\Program Files\x"), which are not part of it. */
|
|
2
|
+
export declare function windowsPathDirectories(path: string): string[];
|
|
3
|
+
/**
|
|
4
|
+
* A file there to run. An app execution alias (a Store app's pwsh.exe, python.exe or winget.exe in WindowsApps) is a reparse
|
|
5
|
+
* point that stat may refuse to follow, or say is not there; Windows starts it all the same, and `where` lists it: it counts
|
|
6
|
+
* when the link itself is there and is not a folder.
|
|
7
|
+
*/
|
|
8
|
+
export declare function isProgramFile(file: string): boolean;
|
|
9
|
+
//# sourceMappingURL=windows-path.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"windows-path.d.ts","sourceRoot":"","sources":["../../src/utils/windows-path.ts"],"names":[],"mappings":"AAIA,4HAA4H;AAC5H,wBAAgB,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAK7D;AAED;;;;GAIG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAWnD"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Derived from Pi-Bolt (MIT, Copyright (c) 2026 OpenSec (Pi-Bolt)), commit 36a2080f; modified for HUMAIN Code CLI.
|
|
2
|
+
import { lstatSync, statSync } from "node:fs";
|
|
3
|
+
import { delimiter } from "node:path";
|
|
4
|
+
/** PATH's directories as Windows reads them: an entry may be in quotes ("C:\Program Files\x"), which are not part of it. */
|
|
5
|
+
export function windowsPathDirectories(path) {
|
|
6
|
+
return path
|
|
7
|
+
.split(delimiter)
|
|
8
|
+
.map((dir) => dir.trim().replace(/^"(.*)"$/, "$1"))
|
|
9
|
+
.filter(Boolean);
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* A file there to run. An app execution alias (a Store app's pwsh.exe, python.exe or winget.exe in WindowsApps) is a reparse
|
|
13
|
+
* point that stat may refuse to follow, or say is not there; Windows starts it all the same, and `where` lists it: it counts
|
|
14
|
+
* when the link itself is there and is not a folder.
|
|
15
|
+
*/
|
|
16
|
+
export function isProgramFile(file) {
|
|
17
|
+
try {
|
|
18
|
+
const stats = statSync(file, { throwIfNoEntry: false });
|
|
19
|
+
if (stats)
|
|
20
|
+
return stats.isFile();
|
|
21
|
+
}
|
|
22
|
+
catch { }
|
|
23
|
+
try {
|
|
24
|
+
const link = lstatSync(file, { throwIfNoEntry: false });
|
|
25
|
+
return link !== undefined && !link.isDirectory();
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return false;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=windows-path.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"windows-path.js","sourceRoot":"","sources":["../../src/utils/windows-path.ts"],"names":[],"mappings":"AAAA,mHAAmH;AACnH,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC9C,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC,4HAA4H;AAC5H,MAAM,UAAU,sBAAsB,CAAC,IAAY;IAClD,OAAO,IAAI;SACT,KAAK,CAAC,SAAS,CAAC;SAChB,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,OAAO,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;SAClD,MAAM,CAAC,OAAO,CAAC,CAAC;AACnB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAAC,IAAY;IACzC,IAAI,CAAC;QACJ,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,EAAE,EAAE,cAAc,EAAE,KAAK,EAAE,CAAC,CAAC;QACxD,IAAI,KAAK;YAAE,OAAO,KAAK,CAAC,MAAM,EAAE,CAAC;IAClC,CAAC;IAAC,MAAM,CAAC,CAAA,CAAC;IACV,IAAI,CAAC;QACJ,MAAM,IAAI,GAAG,SAAS,CAAC,IAAI,EAAE,EAAE,cAAc,EAAE,KAAK,EAAE,CAAC,CAAC;QACxD,OAAO,IAAI,KAAK,SAAS,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC;IAClD,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,KAAK,CAAC;IACd,CAAC;AACF,CAAC","sourcesContent":["// Derived from Pi-Bolt (MIT, Copyright (c) 2026 OpenSec (Pi-Bolt)), commit 36a2080f; modified for HUMAIN Code CLI.\nimport { lstatSync, statSync } from \"node:fs\";\nimport { delimiter } from \"node:path\";\n\n/** PATH's directories as Windows reads them: an entry may be in quotes (\"C:\\Program Files\\x\"), which are not part of it. */\nexport function windowsPathDirectories(path: string): string[] {\n\treturn path\n\t\t.split(delimiter)\n\t\t.map((dir) => dir.trim().replace(/^\"(.*)\"$/, \"$1\"))\n\t\t.filter(Boolean);\n}\n\n/**\n * A file there to run. An app execution alias (a Store app's pwsh.exe, python.exe or winget.exe in WindowsApps) is a reparse\n * point that stat may refuse to follow, or say is not there; Windows starts it all the same, and `where` lists it: it counts\n * when the link itself is there and is not a folder.\n */\nexport function isProgramFile(file: string): boolean {\n\ttry {\n\t\tconst stats = statSync(file, { throwIfNoEntry: false });\n\t\tif (stats) return stats.isFile();\n\t} catch {}\n\ttry {\n\t\tconst link = lstatSync(file, { throwIfNoEntry: false });\n\t\treturn link !== undefined && !link.isDirectory();\n\t} catch {\n\t\treturn false;\n\t}\n}\n"]}
|
package/docs/tui.md
CHANGED
|
@@ -109,7 +109,7 @@ Rendering runs on the interactive path. Cache expensive layout and highlighting
|
|
|
109
109
|
|
|
110
110
|
Keep the default view compact and reveal detail through expansion or a dedicated screen. For custom tool rendering, handle partial results and reuse the previous component when it can be updated safely.
|
|
111
111
|
|
|
112
|
-
Use `HUMAIN_TERMINAL_TUI_WRITE_LOG` to capture the raw ANSI stream when diagnosing rendering problems. Test narrow widths, wide characters, resize events, theme changes, focus transitions, and both regular and fullscreen modes.
|
|
112
|
+
Use `HUMAIN_TERMINAL_TUI_WRITE_LOG` to capture the raw ANSI stream when diagnosing rendering problems. Set `HUMAIN_TERMINAL_TUI_SCROLL_ROWS=0` to turn off fullscreen moved-row scrolling and redraw changed rows one by one, for terminals that mishandle scroll regions. Test narrow widths, wide characters, resize events, theme changes, focus transitions, and both regular and fullscreen modes.
|
|
113
113
|
|
|
114
114
|
## Examples and source
|
|
115
115
|
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@humain/humain-code",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.7",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@humain/humain-code",
|
|
9
|
-
"version": "0.4.
|
|
9
|
+
"version": "0.4.7",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
|
-
"@humain/humain-code-contracts": "0.4.
|
|
12
|
+
"@humain/humain-code-contracts": "0.4.7",
|
|
13
13
|
"@aws-sdk/client-bedrock-runtime": "3.1146.0",
|
|
14
14
|
"@earendil-works/pi-agent-core": "1.1.0",
|
|
15
15
|
"@earendil-works/pi-ai": "1.1.0",
|
|
@@ -1024,9 +1024,9 @@
|
|
|
1024
1024
|
"hasInstallScript": true
|
|
1025
1025
|
},
|
|
1026
1026
|
"node_modules/@humain/humain-code-contracts": {
|
|
1027
|
-
"version": "0.4.
|
|
1028
|
-
"resolved": "https://registry.npmjs.org/@humain/humain-code-contracts/-/humain-code-contracts-0.4.
|
|
1029
|
-
"integrity": "sha512-
|
|
1027
|
+
"version": "0.4.7",
|
|
1028
|
+
"resolved": "https://registry.npmjs.org/@humain/humain-code-contracts/-/humain-code-contracts-0.4.7.tgz",
|
|
1029
|
+
"integrity": "sha512-8YNM/NxTg1x+7Ap7CSymPFLcM2uOKA1qFrlBxYSLu6UAzt6n4h+1VmmwizELS8nA+1BgAVlb1KIpcHMaUYkbTw==",
|
|
1030
1030
|
"license": "MIT",
|
|
1031
1031
|
"dependencies": {
|
|
1032
1032
|
"typebox": "1.3.35"
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@humain/humain-code",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.7",
|
|
4
4
|
"description": "Coding agent CLI with read, bash, edit, write tools and session management",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"humainTerminalConfig": {
|
|
@@ -86,7 +86,7 @@
|
|
|
86
86
|
"prepublishOnly": "npm run clean && npm run build && npm run shrinkwrap"
|
|
87
87
|
},
|
|
88
88
|
"dependencies": {
|
|
89
|
-
"@humain/humain-code-contracts": "0.4.
|
|
89
|
+
"@humain/humain-code-contracts": "0.4.7",
|
|
90
90
|
"@aws-sdk/client-bedrock-runtime": "3.1146.0",
|
|
91
91
|
"@earendil-works/pi-agent-core": "1.1.0",
|
|
92
92
|
"@earendil-works/pi-ai": "1.1.0",
|
|
@@ -1,43 +0,0 @@
|
|
|
1
|
-
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
-
import{shortHash}from"./chunk-PJACZCIR.js";import{buildBaseOptions,getJsonSchemaToolParameters,getPiUserAgent,resolveJsonSchemaStrictSampling,transformMessages}from"./chunk-IMR3ZJM5.js";import{hasIncompleteUsage}from"./chunk-YTVFIA3A.js";import{sanitizeSurrogates}from"./chunk-L2ZPNLYD.js";import{createRequestObserver,headersToRecord}from"./chunk-II2442A2.js";import{parseStreamingJson}from"./chunk-4X774RBJ.js";import{calculateCost,clampThinkingLevel,getCurrentTools,
|
|
3
|
-
getSystemMessageText,renderSystemMessageUpdate,resolveTranscript}from"./chunk-WPLW452J.js";import{AssistantMessageEventStream}from"./chunk-YURQPD6Y.js";import"./chunk-AKA7HNO3.js";import"./chunk-JXWJOIH4.js";var MISTRAL_TOOL_CALL_ID_LENGTH=9,MAX_MISTRAL_ERROR_BODY_CHARS=4e3,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,model.compat?.supportsMidConvoSystemMessages);return(async()=>{let output=createOutput(model);try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let normalizeMistralToolCallId=createMistralToolCallIdNormalizer(),transformedMessages=transformMessages(normalizedContext.
|
|
4
|
-
messages,model,id=>normalizeMistralToolCallId(id)),payload=buildChatPayload(model,normalizedContext,transformedMessages,options),nextPayload=await options?.onPayload?.(payload,model);nextPayload!==void 0&&(payload=nextPayload);let mistralStream=await requestMistralStream(model,payload,apiKey,options);if(stream2.push({type:"start",partial:output}),await consumeChatStream(model,output,stream2,mistralStream,options?.onProviderStreamEvent),options?.signal?.aborted)throw new Error("Request was aborte\
|
|
5
|
-
d");if(output.stopReason==="pending")throw new Error("Mistral stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.partialArgs;output.usage.usageIncomplete=!0,output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatMistralError(
|
|
6
|
-
error),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0,reasoning=clampedReasoning==="off"?void 0:clampedReasoning,effortMap=model.reasoning?
|
|
7
|
-
model.thinkingLevelMap:void 0,reasoningEffort=effortMap?reasoning?effortMap[reasoning]??"high":effortMap.off??void 0:void 0;return stream(model,context,{...base,promptMode:model.reasoning&&!effortMap&&reasoning?"reasoning":void 0,reasoningEffort})};function createOutput(model){return{role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:{usageIncomplete:!0,input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},
|
|
8
|
-
stopReason:"pending",timestamp:Date.now()}}function createMistralToolCallIdNormalizer(){let idMap=new Map,reverseMap=new Map;return id=>{let existing=idMap.get(id);if(existing)return existing;let attempt=0;for(;;){let candidate=deriveMistralToolCallId(id,attempt),owner=reverseMap.get(candidate);if(!owner||owner===id)return idMap.set(id,candidate),reverseMap.set(candidate,id),candidate;attempt++}}}function deriveMistralToolCallId(id,attempt){let normalized=id.replace(/[^a-zA-Z0-9]/g,"");if(attempt===
|
|
9
|
-
0&&normalized.length===MISTRAL_TOOL_CALL_ID_LENGTH)return normalized;let seedBase=normalized||id,seed=attempt===0?seedBase:`${seedBase}:${attempt}`;return shortHash(seed).replace(/[^a-zA-Z0-9]/g,"").slice(0,MISTRAL_TOOL_CALL_ID_LENGTH)}function formatMistralError(error){if(error instanceof Error){let httpError=error,statusCode=typeof httpError.statusCode=="number"?httpError.statusCode:void 0,bodyText=typeof httpError.body=="string"?httpError.body.trim():void 0;return statusCode!==void 0&&bodyText?
|
|
10
|
-
`Mistral API error (${statusCode}): ${truncateErrorText(bodyText,MAX_MISTRAL_ERROR_BODY_CHARS)}`:statusCode!==void 0?`Mistral API error (${statusCode}): ${error.message}`:error.message}return safeJsonStringify(error)}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${text.slice(0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(
|
|
11
|
-
value)}}async function requestMistralStream(model,payload,apiKey,options){let baseUrl=new URL(model.baseUrl);baseUrl.pathname=`${baseUrl.pathname.replace(/\/+$/u,"")}/`;let url=new URL("v1/chat/completions",baseUrl),headers=buildMistralHeaders(model,apiKey,options),timeoutSignal=AbortSignal.timeout(options?.timeoutMs??6e4),signal=options?.signal?AbortSignal.any([options.signal,timeoutSignal]):timeoutSignal,body=JSON.stringify(toMistralWirePayload(payload));await createRequestObserver(options,{api:model.
|
|
12
|
-
api,provider:model.provider,model:model.id,operation:"chat"})(body);let response=await(options?.fetch??globalThis.fetch)(url,{method:"POST",headers,body,signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),!response.ok){let body2=await response.text();throw new MistralHttpError(response.status,body2,response.statusText)}if(!response.body)throw new Error("Mistral response has no body");return readMistralEvents(response.body,signal)}var MistralHttpError=class extends Error{statusCode;body;constructor(statusCode,body,statusText){
|
|
13
|
-
super(statusText||`Request failed with status ${statusCode}`),this.name="MistralHttpError",this.statusCode=statusCode,this.body=body}};function buildMistralHeaders(model,apiKey,options){let headers=new Headers({"User-Agent":getPiUserAgent(),accept:"text/event-stream",authorization:`Bearer ${apiKey}`,"content-type":"application/json"});applyMistralHeaderOverrides(headers,model.headers),applyMistralHeaderOverrides(headers,options?.headers);let hasExplicitAffinity=hasMistralHeaderOverride(model.headers,
|
|
14
|
-
"x-affinity")||hasMistralHeaderOverride(options?.headers,"x-affinity");return shouldUsePromptCaching(options)&&!hasExplicitAffinity&&headers.set("x-affinity",options.sessionId),headers}function applyMistralHeaderOverrides(headers,overrides){if(overrides)for(let[name,value]of Object.entries(overrides))value===null?headers.delete(name):headers.set(name,value)}function hasMistralHeaderOverride(overrides,target){return!!overrides&&Object.keys(overrides).some(name=>name.toLowerCase()===target)}function toMistralWirePayload(payload){
|
|
15
|
-
let wirePayload={...payload};for(let[source,target]of[["topP","top_p"],["maxTokens","max_tokens"],["randomSeed","random_seed"],["responseFormat","response_format"],["toolChoice","tool_choice"],["presencePenalty","presence_penalty"],["frequencyPenalty","frequency_penalty"],["parallelToolCalls","parallel_tool_calls"],["reasoningEffort","reasoning_effort"],["promptMode","prompt_mode"],["promptCacheKey","prompt_cache_key"],["safePrompt","safe_prompt"]])remapMistralProperty(wirePayload,source,target);
|
|
16
|
-
wirePayload.messages=payload.messages.map(message=>toMistralWireMessage(message));let responseFormat=wirePayload.response_format;if(isMistralRecord(responseFormat)){let wireResponseFormat={...responseFormat};remapMistralProperty(wireResponseFormat,"jsonSchema","json_schema");let jsonSchema=wireResponseFormat.json_schema;if(isMistralRecord(jsonSchema)){let wireJsonSchema={...jsonSchema};remapMistralProperty(wireJsonSchema,"schemaDefinition","schema"),wireResponseFormat.json_schema=wireJsonSchema}
|
|
17
|
-
wirePayload.response_format=wireResponseFormat}return wirePayload}function toMistralWireMessage(message){let wireMessage={...message};return remapMistralProperty(wireMessage,"toolCalls","tool_calls"),remapMistralProperty(wireMessage,"toolCallId","tool_call_id"),Array.isArray(message.content)&&(wireMessage.content=message.content.map(chunk=>toMistralWireContentChunk(chunk))),wireMessage}function toMistralWireContentChunk(chunk){let wireChunk={...chunk};for(let[source,target]of[["imageUrl","image_\
|
|
18
|
-
url"],["documentUrl","document_url"],["documentName","document_name"],["fileId","file_id"],["referenceIds","reference_ids"],["inputAudio","input_audio"]])remapMistralProperty(wireChunk,source,target);return wireChunk}function remapMistralProperty(record,source,target){source in record&&(record[target]=record[source],delete record[source])}function isMistralRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var MISTRAL_STREAM_DONE=Symbol("mistral-stream-done");async function*readMistralEvents(body,signal){
|
|
19
|
-
let reader=body.getReader(),decoder=new TextDecoder,buffer="",onAbort=()=>{reader.cancel().catch(()=>{})};signal.addEventListener("abort",onAbort,{once:!0});try{for(;;){if(signal.aborted)throw signal.reason;let{done,value}=await reader.read();if(signal.aborted)throw signal.reason;buffer+=done?decoder.decode():decoder.decode(value,{stream:!0});let boundary=findMistralEventBoundary(buffer);for(;boundary;){let event=parseMistralEvent(buffer.slice(0,boundary.index));if(buffer=buffer.slice(boundary.index+
|
|
20
|
-
boundary.length),event===MISTRAL_STREAM_DONE)return;event&&(yield event),boundary=findMistralEventBoundary(buffer)}if(done)break}if(buffer.trim()){let event=parseMistralEvent(buffer);event!==MISTRAL_STREAM_DONE&&event&&(yield event)}}finally{signal.removeEventListener("abort",onAbort);try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}}function findMistralEventBoundary(buffer){let match=/\r\n\r\n|\r\n\r|\r\n\n|\r\r\n|\n\r\n|\r\r|\n\r|\n\n/u.exec(buffer);return match?.index===void 0?
|
|
21
|
-
void 0:{index:match.index,length:match[0].length}}function parseMistralEvent(raw){let data=raw.split(/\r\n|\r|\n/u).filter(line=>line.startsWith("data:")).map(line=>line.slice(5).trimStart()).join(`
|
|
22
|
-
`).trim();if(!data)return;if(data==="[DONE]")return MISTRAL_STREAM_DONE;let parsed=JSON.parse(data);if(!isMistralRecord(parsed)||!Array.isArray(parsed.choices))throw new Error("Invalid Mistral streaming event");return{data:parsed}}function buildChatPayload(model,context,messages,options){let payload={model:model.id,stream:!0,messages:toChatMessages(messages,model.input.includes("image"))},currentTools=getCurrentTools(context.messages);return currentTools.length>0&&(payload.tools=toFunctionTools(
|
|
23
|
-
currentTools)),options?.temperature!==void 0&&(payload.temperature=options.temperature),options?.maxTokens!==void 0&&(payload.maxTokens=options.maxTokens),options?.toolChoice&&(payload.toolChoice=mapToolChoice(options.toolChoice)),options?.promptMode&&(payload.promptMode=options.promptMode),options?.reasoningEffort&&(payload.reasoningEffort=options.reasoningEffort),shouldUsePromptCaching(options)&&(payload.promptCacheKey=options.sessionId),payload}function shouldUsePromptCaching(options){return options?.
|
|
24
|
-
cacheRetention!=="none"&&!!options?.sessionId}function getMistralCachedPromptTokens(usage,promptTokens){let rawUsage=usage,cacheCounters=[rawUsage.promptTokensDetails?.cachedTokens,rawUsage.prompt_tokens_details?.cached_tokens,rawUsage.promptTokenDetails?.cachedTokens,rawUsage.prompt_token_details?.cached_tokens,rawUsage.numCachedTokens,rawUsage.num_cached_tokens],rawCachedTokens=cacheCounters.find(value=>value!=null),cachedTokens=typeof rawCachedTokens=="number"&&Number.isFinite(rawCachedTokens)?
|
|
25
|
-
rawCachedTokens:0;return{count:Math.min(promptTokens,Math.max(0,cachedTokens)),incomplete:hasIncompleteUsage([promptTokens-cachedTokens],cacheCounters)}}async function consumeChatStream(model,output,stream2,mistralStream,onProviderStreamEvent){let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1,toolBlocksByKey=new Map,finishCurrentBlock=block=>{if(block){if(block.type==="text"){stream2.push({type:"text_end",contentIndex:blockIndex(),content:block.text,partial:output});return}
|
|
26
|
-
block.type==="thinking"&&stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:block.thinking,partial:output})}};for await(let event of mistralStream){let chunk=event.data;if(await onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.id,chunk.usage){let promptTokens=chunk.usage.prompt_tokens||0,cached=getMistralCachedPromptTokens(chunk.usage,promptTokens),cachedPromptTokens=cached.count;output.usage.usageIncomplete=cached.incomplete||hasIncompleteUsage([chunk.usage.prompt_tokens,
|
|
27
|
-
chunk.usage.completion_tokens],[chunk.usage.total_tokens]),output.usage.input=Math.max(0,promptTokens-cachedPromptTokens),output.usage.output=chunk.usage.completion_tokens||0,output.usage.cacheRead=cachedPromptTokens,output.usage.cacheWrite=0,output.usage.totalTokens=chunk.usage.total_tokens||output.usage.input+output.usage.output+output.usage.cacheRead+output.usage.cacheWrite,output.usage.usageIncomplete||=hasIncompleteUsage([output.usage.totalTokens]),calculateCost(model,output.usage)}let choice=chunk.
|
|
28
|
-
choices[0];if(!choice)continue;if(choice.finish_reason){output.rawStopReason=choice.finish_reason;let stopReasonResult=mapChatStopReason(choice.finish_reason);output.stopReason=stopReasonResult.stopReason,stopReasonResult.errorMessage&&(output.errorMessage=stopReasonResult.errorMessage)}let delta=choice.delta;if(delta.content!==null&&delta.content!==void 0){let contentItems=typeof delta.content=="string"?[delta.content]:delta.content;for(let item of contentItems){if(typeof item=="string"){let textDelta=sanitizeSurrogates(
|
|
29
|
-
item);if(!textDelta)continue;currentBlock?.type!=="text"&&(finishCurrentBlock(currentBlock),currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output})),currentBlock.text+=textDelta,stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:textDelta,partial:output});continue}if(item.type==="thinking"){let deltaText=(item.thinking??[]).map(part=>part.text??"").filter(text=>text.length>0).join(""),thinkingDelta=sanitizeSurrogates(
|
|
30
|
-
deltaText);if(!thinkingDelta)continue;currentBlock?.type!=="thinking"&&(finishCurrentBlock(currentBlock),currentBlock={type:"thinking",thinking:""},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})),currentBlock.thinking+=thinkingDelta,stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:thinkingDelta,partial:output});continue}if(item.type==="text"){let textDelta=sanitizeSurrogates(item.text??"");if(!textDelta)continue;
|
|
31
|
-
currentBlock?.type!=="text"&&(finishCurrentBlock(currentBlock),currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output})),currentBlock.text+=textDelta,stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:textDelta,partial:output})}}}let toolCalls=delta.tool_calls||[];for(let toolCall of toolCalls){currentBlock&&(finishCurrentBlock(currentBlock),currentBlock=null);let callId=toolCall.id&&toolCall.id!==
|
|
32
|
-
"null"?toolCall.id:deriveMistralToolCallId(`toolcall:${toolCall.index??0}`,0),key=toolCall.index??callId,existingIndex=toolBlocksByKey.get(key),block;if(existingIndex!==void 0){let existing=output.content[existingIndex];existing?.type==="toolCall"&&(block=existing)}block||(block={type:"toolCall",id:callId,name:toolCall.function.name,arguments:{},partialArgs:""},output.content.push(block),toolBlocksByKey.set(key,output.content.length-1),stream2.push({type:"toolcall_start",contentIndex:output.content.
|
|
33
|
-
length-1,partial:output}));let argsDelta=typeof toolCall.function.arguments=="string"?toolCall.function.arguments:JSON.stringify(toolCall.function.arguments||{});block.partialArgs=(block.partialArgs||"")+argsDelta,block.arguments=parseStreamingJson(block.partialArgs),stream2.push({type:"toolcall_delta",contentIndex:toolBlocksByKey.get(key),delta:argsDelta,partial:output})}}finishCurrentBlock(currentBlock);for(let index of toolBlocksByKey.values()){let block=output.content[index];if(block.type!==
|
|
34
|
-
"toolCall")continue;let toolBlock=block;toolBlock.arguments=parseStreamingJson(toolBlock.partialArgs),delete toolBlock.partialArgs,stream2.push({type:"toolcall_end",contentIndex:index,toolCall:toolBlock,partial:output})}}function toFunctionTools(tools){return tools.map(tool=>{let strict=resolveJsonSchemaStrictSampling(tool,!0);return{type:"function",function:{name:tool.name,description:tool.description,parameters:stripSymbolKeys(getJsonSchemaToolParameters(tool,strict)),strict:strict??!1}}})}function stripSymbolKeys(value){
|
|
35
|
-
if(Array.isArray(value))return value.map(item=>stripSymbolKeys(item));if(value&&typeof value=="object"){let result={};for(let[key,entry]of Object.entries(value))result[key]=stripSymbolKeys(entry);return result}return value}function toChatMessages(messages,supportsImages){let result=[];for(let[index,msg]of messages.entries()){if(msg.role==="system"){let text=index===0?getSystemMessageText(msg):renderSystemMessageUpdate(msg);text.length>0&&result.push({role:"system",content:sanitizeSurrogates(text)});
|
|
36
|
-
continue}if(msg.role==="user"){if(typeof msg.content=="string"){result.push({role:"user",content:sanitizeSurrogates(msg.content)});continue}let hadImages=msg.content.some(item=>item.type==="image"),content=msg.content.filter(item=>item.type==="text"||supportsImages).map(item=>item.type==="text"?{type:"text",text:sanitizeSurrogates(item.text)}:{type:"image_url",imageUrl:`data:${item.mimeType};base64,${item.data}`});if(content.length>0){result.push({role:"user",content});continue}hadImages&&!supportsImages&&
|
|
37
|
-
result.push({role:"user",content:"(image omitted: model does not support images)"});continue}if(msg.role==="assistant"){let contentParts=[],toolCalls=[];for(let block of msg.content){if(block.type==="text"){block.text.trim().length>0&&contentParts.push({type:"text",text:sanitizeSurrogates(block.text)});continue}if(block.type==="thinking"){block.thinking.trim().length>0&&contentParts.push({type:"thinking",thinking:[{type:"text",text:sanitizeSurrogates(block.thinking)}]});continue}toolCalls.push({
|
|
38
|
-
id:block.id,type:"function",function:{name:block.name,arguments:JSON.stringify(block.arguments||{})},index:0})}let assistantMessage={role:"assistant",prefix:!1};contentParts.length>0&&(assistantMessage.content=contentParts),toolCalls.length>0&&(assistantMessage.toolCalls=toolCalls),(contentParts.length>0||toolCalls.length>0)&&result.push(assistantMessage);continue}let toolContent=[],textResult=msg.content.filter(part=>part.type==="text").map(part=>part.type==="text"?sanitizeSurrogates(part.text):
|
|
39
|
-
"").join(`
|
|
40
|
-
`),hasImages=msg.content.some(part=>part.type==="image"),toolText=buildToolResultText(textResult,hasImages,supportsImages,msg.isError);toolContent.push({type:"text",text:toolText});for(let part of msg.content)supportsImages&&part.type==="image"&&toolContent.push({type:"image_url",imageUrl:`data:${part.mimeType};base64,${part.data}`});result.push({role:"tool",toolCallId:msg.toolCallId,name:msg.toolName,content:toolContent})}return result}function buildToolResultText(text,hasImages,supportsImages,isError){
|
|
41
|
-
let trimmed=text.trim(),errorPrefix=isError?"[tool error] ":"";return trimmed.length>0?`${errorPrefix}${trimmed}${hasImages&&!supportsImages?`
|
|
42
|
-
[tool image omitted: model does not support images]`:""}`:hasImages?supportsImages?isError?"[tool error] (see attached image)":"(see attached image)":isError?"[tool error] (image omitted: model does not support images)":"(image omitted: model does not support images)":isError?"[tool error] (no tool output)":"(no tool output)"}function mapToolChoice(choice){if(choice)return choice==="auto"||choice==="none"||choice==="any"||choice==="required"?choice:{type:"function",function:{name:choice.function.
|
|
43
|
-
name}}}function mapChatStopReason(reason){if(reason===null)return{stopReason:"stop"};switch(reason){case"stop":return{stopReason:"stop"};case"length":case"model_length":return{stopReason:"length"};case"tool_calls":return{stopReason:"toolUse"};case"error":return{stopReason:"error",errorMessage:"Provider stopped with: error (server error)"};default:return{stopReason:"error",errorMessage:`Provider stopped with: ${reason}`}}}export{stream,streamSimple};
|