@hncode/hncode 0.6.7 → 0.7.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hncode/hncode",
3
- "version": "0.6.7",
3
+ "version": "0.7.0",
4
4
  "description": "hncode — A cyan-blue TUI AI coding agent with zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -0,0 +1,120 @@
1
+ // The PTC executor's WORKER SIDE — what actually runs the model's code.
2
+ //
3
+ // This file is loaded as a `worker_threads` entry, never imported by the main process. Everything it can reach is
4
+ // what `parentPort` hands it and the globals below: no `require`, no `process` access beyond what is passed in,
5
+ // and no filesystem. The model's code is compiled inside a `vm` context whose only interesting binding is
6
+ // `callTool`, which messages the main thread and waits.
7
+ //
8
+ // WHY A WORKER AND NOT vm ALONE: `vm` is not a security boundary — code in a context can still reach the host
9
+ // through a prototype it was handed. The thread is what makes a runaway loop killable: `worker.terminate()` stops
10
+ // it without the main process ever yielding, which a `while(true)` in `vm.runInContext` would not.
11
+ //
12
+ // The code runs as an ASYNC body, so `await callTool(...)` works exactly as it reads.
13
+ import { parentPort, workerData } from 'node:worker_threads';
14
+ import vm from 'node:vm';
15
+
16
+ const TOOL_NAMES = Array.isArray(workerData && workerData.toolNames) ? workerData.toolNames : [];
17
+ const TIMEOUT_MS = Number(workerData && workerData.timeoutMs) > 0 ? workerData.timeoutMs : 120000;
18
+
19
+ let seq = 0;
20
+ const pending = new Map();
21
+
22
+ /** Ask the main thread to run a tool, and wait for its answer. */
23
+ function callTool(name, args) {
24
+ const id = ++seq;
25
+ parentPort.postMessage({ type: 'tool', id, name, args: args == null ? {} : args });
26
+ return new Promise((resolve, reject) => {
27
+ pending.set(id, { resolve, reject });
28
+ });
29
+ }
30
+
31
+ parentPort.on('message', (m) => {
32
+ if (!m || m.type !== 'tool_result') return;
33
+ const p = pending.get(m.id);
34
+ if (!p) return;
35
+ pending.delete(m.id);
36
+ if (m.ok) p.resolve(m.result);
37
+ else p.reject(new Error(String(m.error || 'tool failed')));
38
+ });
39
+
40
+ // ---- the sandbox ---------------------------------------------------------------------------------------------
41
+
42
+ /** Collect printed lines. `print` is what the model reaches for. */
43
+ const out = [];
44
+ const write = (...parts) => {
45
+ const line = parts.map((p) => {
46
+ if (typeof p === 'string') return p;
47
+ try { return JSON.stringify(p); } catch { return String(p); }
48
+ }).join(' ');
49
+ // A single line cap keeps a runaway from filling memory before the byte cap is checked.
50
+ out.push(line.length > 8000 ? line.slice(0, 8000) + '…' : line);
51
+ };
52
+
53
+ const sandbox = {
54
+ callTool,
55
+ print: write,
56
+ console: { log: write, error: write, warn: write, info: write },
57
+ JSON,
58
+ Math,
59
+ Date,
60
+ Promise,
61
+ Array,
62
+ Object,
63
+ String,
64
+ Number,
65
+ Boolean,
66
+ Map,
67
+ Set,
68
+ RegExp,
69
+ Error,
70
+ TypeError,
71
+ RangeError,
72
+ isNaN,
73
+ isFinite,
74
+ parseInt,
75
+ parseFloat,
76
+ // `sleep` is the one timer worth exposing: pacing between calls is a real need, and `setTimeout` would let the
77
+ // code keep the thread alive past the point where the caller wants an answer.
78
+ sleep: (ms) => new Promise((r) => setTimeout(r, Math.max(0, Math.min(Number(ms) || 0, 10000)))),
79
+ };
80
+
81
+ const context = vm.createContext(sandbox, {
82
+ // No `codeGeneration` from strings inside the sandbox: a `new Function` there would be a second, unreviewed way
83
+ // in — and the body the model writes is already compiled below.
84
+ codeGeneration: { strings: false, wasm: false },
85
+ });
86
+
87
+ async function run(code) {
88
+ let script;
89
+ try {
90
+ script = new vm.Script(`(async () => {\n${code}\n})()`, { filename: 'ptc-sandbox.js' });
91
+ } catch (e) {
92
+ return { ok: false, error: `Syntax error: ${e.message}`, output: '' };
93
+ }
94
+
95
+ const timer = setTimeout(() => {
96
+ parentPort.postMessage({ type: 'timeout', ms: TIMEOUT_MS });
97
+ process.exit(0);
98
+ }, TIMEOUT_MS);
99
+ if (timer.unref) timer.unref();
100
+
101
+ try {
102
+ const value = await script.runInContext(context, { timeout: TIMEOUT_MS });
103
+ clearTimeout(timer);
104
+ // The returned value is what `return` produced, if anything; `print` already captured stdout.
105
+ let returned;
106
+ if (value !== undefined) {
107
+ try { returned = typeof value === 'string' ? value : JSON.stringify(value); } catch { returned = String(value); }
108
+ }
109
+ return { ok: true, output: out.join('\n'), returned };
110
+ } catch (e) {
111
+ clearTimeout(timer);
112
+ return { ok: false, error: `${e && e.name ? e.name + ': ' : ''}${e && e.message || e}`, output: out.join('\n') };
113
+ }
114
+ }
115
+
116
+ parentPort.on('message', async (m) => {
117
+ if (!m || m.type !== 'run') return;
118
+ const result = await run(String(m.code || ''));
119
+ parentPort.postMessage({ type: 'done', result });
120
+ });
package/src/ptc.js ADDED
@@ -0,0 +1,141 @@
1
+ // The PTC executor's MAIN side.
2
+ //
3
+ // Owns a worker, forwards the tool calls it makes to the real tool layer, and enforces the limits the sandbox
4
+ // cannot enforce about itself: output size, tool count, and a wall-clock deadline that survives a wedged await.
5
+ //
6
+ // WHY THE TOOL CALLS COME BACK HERE AT ALL: the tools need `ctx` — the workspace, the approval hook, the session
7
+ // — none of which may exist inside the sandbox. The worker sends `{type:'tool', name, args}`, this side runs the
8
+ // real tool through `getTool`, and the result crosses back as data. The model's code never holds a function that
9
+ // can reach the filesystem; it holds a promise that the host fulfils.
10
+ import { Worker } from 'node:worker_threads';
11
+ import path from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+
14
+ const here = path.dirname(fileURLToPath(import.meta.url));
15
+
16
+ /** Tools whose results are safe and useful to hand to code, and whose invocation needs no UI. */
17
+ const CALLABLE = new Set([
18
+ 'Read', 'FileLines', 'Glob', 'Grep', 'Git', 'FetchURL', 'WebSearch',
19
+ 'TodoList', 'TaskList', 'TaskOutput', 'Memory', 'ListTeammates', 'TeamTaskList',
20
+ 'ActivateSkill', 'Goal', 'Diagnostics',
21
+ ]);
22
+
23
+ export const DEFAULT_LIMITS = {
24
+ // A code body that orchestrates twenty calls is already unusual; five hundred is a loop that has gone wrong.
25
+ maxToolCalls: 500,
26
+ // What comes back is the whole point of PTC — a cap keeps a runaway `print` from eating the context it saved.
27
+ maxOutputBytes: 32000,
28
+ timeoutMs: 120000,
29
+ };
30
+
31
+ export const CALLABLE_TOOLS = [...CALLABLE];
32
+
33
+ /**
34
+ * Run `code` in a sandbox, letting it call the tools in `CALLABLE`.
35
+ *
36
+ * @param {string} code An async function BODY. `await callTool(name, args)` is available.
37
+ * @param {object} ctx The tool context, passed straight through to each tool.
38
+ * @param {object} [limits] Overrides for `DEFAULT_LIMITS`.
39
+ * @returns {Promise<{ok: boolean, output: string, returned?: string, error?: string, calls: string[], truncated?: boolean}>}
40
+ */
41
+ export function runProgrammatic(code, ctx, limits = {}) {
42
+ const lim = { ...DEFAULT_LIMITS, ...limits };
43
+ return new Promise((resolve) => {
44
+ let settled = false;
45
+ const calls = [];
46
+ const lines = [];
47
+ let bytes = 0;
48
+ let truncated = false;
49
+
50
+ const finish = (result) => {
51
+ if (settled) return;
52
+ settled = true;
53
+ clearTimeout(wall);
54
+ try { worker.terminate(); } catch { /* already gone */ }
55
+ resolve(result);
56
+ };
57
+
58
+ const worker = new Worker(path.join(here, 'ptc-worker.js'), {
59
+ workerData: { toolNames: [...CALLABLE], timeoutMs: lim.timeoutMs },
60
+ // The sandbox needs no stdio and no shared memory.
61
+ stdout: true,
62
+ stderr: true,
63
+ });
64
+
65
+ // The wall clock is the OUTER guarantee: if the worker is stuck in a `while(true)` the inner vm timeout can
66
+ // still fire, but if the main thread is waiting on a tool that never answers, only this one saves us.
67
+ const wall = setTimeout(() => {
68
+ finish({ ok: false, error: `timed out after ${lim.timeoutMs}ms`, output: lines.join('\n'), calls });
69
+ }, lim.timeoutMs + 5000);
70
+
71
+ worker.on('message', async (m) => {
72
+ if (!m) return;
73
+
74
+ if (m.type === 'tool') {
75
+ if (calls.length >= lim.maxToolCalls) {
76
+ worker.postMessage({ type: 'tool_result', id: m.id, ok: false, error: `tool-call limit reached (${lim.maxToolCalls})` });
77
+ return;
78
+ }
79
+ const name = String(m.name || '');
80
+ if (!CALLABLE.has(name)) {
81
+ worker.postMessage({ type: 'tool_result', id: m.id, ok: false, error: `${name} is not callable from code` });
82
+ return;
83
+ }
84
+ // Imported here, not at the top: tools/index.js imports the PTC TOOL, which imports this module — a static
85
+ // import would close that cycle and read `spec` before it exists.
86
+ const { getTool } = await import('./tools/index.js');
87
+ const tool = getTool(name);
88
+ if (!tool || typeof tool.execute !== 'function') {
89
+ worker.postMessage({ type: 'tool_result', id: m.id, ok: false, error: `no such tool: ${name}` });
90
+ return;
91
+ }
92
+ calls.push(name);
93
+ try {
94
+ const raw = await tool.execute(m.args || {}, ctx);
95
+ // A media result is structured blocks, not text; code cannot do anything useful with it.
96
+ const value = (raw && typeof raw === 'object' && Array.isArray(raw.media))
97
+ ? '[media result omitted]'
98
+ : (typeof raw === 'string' ? raw : JSON.stringify(raw));
99
+ worker.postMessage({ type: 'tool_result', id: m.id, ok: true, result: value });
100
+ } catch (e) {
101
+ worker.postMessage({ type: 'tool_result', id: m.id, ok: false, error: String((e && e.message) || e) });
102
+ }
103
+ return;
104
+ }
105
+
106
+ if (m.type === 'timeout') {
107
+ finish({ ok: false, error: `timed out after ${lim.timeoutMs}ms`, output: lines.join('\n'), calls });
108
+ return;
109
+ }
110
+
111
+ if (m.type === 'done') {
112
+ const r = m.result || {};
113
+ let output = String(r.output == null ? '' : r.output);
114
+ // Cap by BYTES, not characters: the model pays for tokens, and a megabyte of ASCII is the worst case.
115
+ if (Buffer.byteLength(output, 'utf8') > lim.maxOutputBytes) {
116
+ output = output.slice(0, lim.maxOutputBytes);
117
+ truncated = true;
118
+ }
119
+ finish({
120
+ ok: !!r.ok,
121
+ output,
122
+ returned: r.returned,
123
+ error: r.error,
124
+ calls,
125
+ truncated: truncated || undefined,
126
+ });
127
+ }
128
+ });
129
+
130
+ worker.on('error', (e) => {
131
+ finish({ ok: false, error: String((e && e.message) || e), output: lines.join('\n'), calls });
132
+ });
133
+ worker.on('exit', (code) => {
134
+ // An exit without a `done` is the worker dying: report it rather than hanging the caller for ever.
135
+ if (!settled) finish({ ok: false, error: `sandbox exited with code ${code}`, output: lines.join('\n'), calls });
136
+ });
137
+
138
+ worker.postMessage({ type: 'run', code: String(code || '') });
139
+ void bytes;
140
+ });
141
+ }
@@ -24,6 +24,7 @@ import { spec as diagnosticsSpec } from './diagnostics.js';
24
24
  import * as memoryMod from './memory.js';
25
25
  import * as goalMod from './goal.js';
26
26
  import * as activateSkillMod from './activate-skill.js';
27
+ import * as ptcMod from './ptc.js';
27
28
  import { pluginTools, pluginToolGeneration } from '../plugin.js';
28
29
 
29
30
 
@@ -59,6 +60,7 @@ const builtinTools = [
59
60
  memoryMod.spec,
60
61
  goalMod.spec,
61
62
  activateSkillMod.spec,
63
+ ptcMod.spec,
62
64
  ...TEAM_TOOL_SPECS,
63
65
  ];
64
66
 
@@ -0,0 +1,91 @@
1
+ /**
2
+ * ProgrammaticToolCall — let the model orchestrate tools with code instead of one round trip each.
3
+ *
4
+ * THE PROBLEM IT SOLVES: a task like "which of these forty files reference the removed symbol" is forty calls,
5
+ * each with its own inference pass, and every one of those results then sits in the context whether or not it
6
+ * mattered. The reading is mechanical; only the conclusion is worth the tokens.
7
+ *
8
+ * With this tool the model writes the LOOP, and only what it prints comes back. The sandbox holds the forty
9
+ * results, the filtering and the joining; the conversation holds the six files that matched.
10
+ *
11
+ * WHY A SEPARATE TOOL AND NOT `Bash`: a shell would give the model the whole machine and no structure. Here every
12
+ * call goes back through the tool layer — the same approval rules, the same workspace guard, the same tools —
13
+ * and the code can only reach the ones on the allowlist. See src/ptc.js for that list, and ptc-worker.js for the
14
+ * sandbox itself.
15
+ */
16
+ import { runProgrammatic, CALLABLE_TOOLS } from '../ptc.js';
17
+
18
+ const DESCRIPTION = [
19
+ 'Orchestrate tools with JavaScript instead of calling them one at a time.',
20
+ '',
21
+ 'WHEN TO USE IT: work that is a LOOP over tool results, or that needs intermediate data the model should not',
22
+ 'have to read. Reading twenty files to find the three that mention a symbol; checking every changed file for a',
23
+ 'pattern; collecting values from many calls and printing only the ones that matter. The intermediate results',
24
+ 'stay inside the sandbox and never enter the conversation — that is the point.',
25
+ '',
26
+ 'WHEN NOT TO USE IT: one or two calls, or when you need to READ a result and decide what to do next. Then an',
27
+ 'ordinary tool call is shorter and clearer.',
28
+ '',
29
+ 'HOW TO WRITE IT: the body of an async function. `await callTool(name, args)` runs a tool and resolves to its',
30
+ 'text result. `print(...)` writes a line to the output; `console.log` is the same. Whatever you `return` is',
31
+ 'appended. Nothing reaches the conversation except what you print or return.',
32
+ '',
33
+ 'Example:',
34
+ '```',
35
+ "const hits = [];",
36
+ "for (const f of (await callTool('Glob', { pattern: 'src/**/*.js' })).split('\\n').filter(Boolean)) {",
37
+ " const text = await callTool('Grep', { pattern: 'oldSymbol', path: f });",
38
+ " if (text && !/No matches/.test(text)) hits.push(f);",
39
+ '}',
40
+ 'print(`${hits.length} files still reference it`);',
41
+ 'print(hits.join(\'\\n\'));',
42
+ '```',
43
+ '',
44
+ `CALLABLE TOOLS: ${CALLABLE_TOOLS.join(', ')}.`,
45
+ 'Anything else is refused — a shell or a write would escape the sandbox\'s purpose.',
46
+ ].join('\n');
47
+
48
+ export const spec = {
49
+ name: 'ProgrammaticToolCall',
50
+ description: DESCRIPTION,
51
+ parameters: {
52
+ type: 'object',
53
+ properties: {
54
+ code: {
55
+ type: 'string',
56
+ description: [
57
+ 'The body of an async function. `await callTool(name, args)` calls a tool; `print(x)` emits a line.',
58
+ 'Only what is printed or returned reaches the conversation.',
59
+ ].join(' '),
60
+ },
61
+ purpose: {
62
+ type: 'string',
63
+ description: 'One line naming what the code is for, shown in the transcript.',
64
+ },
65
+ },
66
+ required: ['code'],
67
+ },
68
+ async execute(args, ctx) {
69
+ const code = String((args && args.code) || '');
70
+ if (!code.trim()) return 'Error: `code` is empty.';
71
+
72
+ const r = await runProgrammatic(code, ctx);
73
+ const parts = [];
74
+
75
+ if (r.output) parts.push(r.output);
76
+ if (r.returned != null && String(r.returned).trim()) parts.push(String(r.returned));
77
+ if (r.truncated) parts.push('[output truncated]');
78
+
79
+ if (!r.ok) {
80
+ // The error goes LAST, after whatever the code managed to print: a partial result plus the reason it
81
+ // stopped is more useful than the reason alone.
82
+ parts.push(`Error: ${r.error}`);
83
+ }
84
+
85
+ // How many tools ran is worth stating — it is the saving this feature exists for, and a model that sees 0 is
86
+ // being told its code never reached a tool.
87
+ if (r.calls.length) parts.push(`(${r.calls.length} tool call${r.calls.length === 1 ? '' : 's'})`);
88
+
89
+ return parts.join('\n') || '(no output)';
90
+ },
91
+ };
package/src/tui.js CHANGED
@@ -14140,7 +14140,7 @@ const agents = readAgentsMd(state.cwd || state.workspace || cfg.workspace, state
14140
14140
  // Tools that act ONLY inside the session: the roster, the mailbox, the task list, the memories.
14141
14141
  // `isInsideWorkspace` answers `false` for any tool it does not know, so without this they all asked for
14142
14142
  // approval in yolo — the one mode whose point is not asking.
14143
- const safeTools = ['Read', 'Grep', 'Glob', 'FetchURL', 'WebSearch', 'TaskOutput', 'TaskList', 'TaskStop', 'TaskWait', 'TodoList', 'Goal', 'ActivateSkill', 'FileLines', 'AgentList', 'AgentMessage', 'AgentInterrupt', 'AgentClose', 'TaskInput', 'SendMessage', 'TeamTaskCreate', 'TeamTaskUpdate', 'TeamTaskList', 'ListTeammates', 'Memory', 'AskUserQuestion'];
14143
+ const safeTools = ['Read', 'Grep', 'Glob', 'FetchURL', 'WebSearch', 'TaskOutput', 'TaskList', 'TaskStop', 'TaskWait', 'TodoList', 'Goal', 'ActivateSkill', 'ProgrammaticToolCall', 'FileLines', 'AgentList', 'AgentMessage', 'AgentInterrupt', 'AgentClose', 'TaskInput', 'SendMessage', 'TeamTaskCreate', 'TeamTaskUpdate', 'TeamTaskList', 'ListTeammates', 'Memory', 'AskUserQuestion'];
14144
14144
  if (rule !== 'ask' && safeTools.includes(toolName)) return true;
14145
14145
  // A read-only SHELL COMMAND (ls/git status/rg/cat …) is as safe as a
14146
14146
  // read-only TOOL, so it runs without a prompt in Ask mode too — the user