@miphamai/cli 0.85.10 → 0.85.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +1 -1
- package/src/agent/sub-agent.ts +49 -1
- package/src/commands/autoloop-journal.ts +16 -1
- package/src/config/loader.ts +23 -3
- package/src/core/context-microcompact.ts +3 -5
- package/src/core/context.ts +58 -16
- package/src/core/credential-masker/output-scrub.ts +7 -1
- package/src/core/crsi-producer.ts +86 -6
- package/src/core/crsi-sandbox.ts +101 -49
- package/src/core/engine.ts +108 -26
- package/src/core/hooks-executor.ts +165 -16
- package/src/core/instructions.ts +6 -5
- package/src/core/memory/memory-manager.ts +9 -1
- package/src/core/permission-config.ts +28 -0
- package/src/core/permission.ts +51 -5
- package/src/core/rules-loader.ts +96 -5
- package/src/core/task-performance.ts +32 -4
- package/src/i18n-core/locales/en-US.json +2 -0
- package/src/i18n-core/locales/zh-CN.json +2 -0
- package/src/mcp/registry.ts +8 -0
- package/src/plugin/plugin-loader.ts +10 -9
- package/src/providers/anthropic.ts +11 -3
- package/src/providers/fetch-utils.ts +34 -1
- package/src/providers/openai-compat.ts +24 -2
- package/src/shared/package-info.ts +2 -2
- package/src/shared/sanitize.ts +65 -0
- package/src/shared/types.ts +30 -0
- package/src/tools/agent/agent.ts +18 -3
- package/src/tools/agent/exit-plan.ts +49 -9
- package/src/tools/artifact/artifact.ts +0 -1
- package/src/tools/exec/bash.ts +28 -3
- package/src/tools/index.ts +7 -1
- package/src/tools/network/web-fetch.ts +2 -1
- package/src/tools/system/tool-search.ts +1 -1
- package/src/ui/chat.tsx +2 -1
- package/src/ui/commands.ts +28 -11
- package/src/ui/input.tsx +5 -0
- package/src/workflow/event-bus.ts +13 -0
- package/src/workflow/journal.ts +8 -0
- package/src/workflow/runtime.ts +59 -11
package/src/shared/sanitize.ts
CHANGED
|
@@ -213,6 +213,39 @@ export function stripControlCharsForCheck(input: string): string {
|
|
|
213
213
|
return result
|
|
214
214
|
}
|
|
215
215
|
|
|
216
|
+
/**
|
|
217
|
+
* Decode ` ` in assistant text for terminal display.
|
|
218
|
+
*
|
|
219
|
+
* The terminal has no markdown/entity layer, so a reply that uses ` ` to indent
|
|
220
|
+
* — row labels in a table, most often — shows the literal characters. Only this one
|
|
221
|
+
* entity is decoded, deliberately: `<`/`&`/`>` appear in code the assistant
|
|
222
|
+
* is *showing*, where decoding would corrupt the sample, whereas a literal ` `
|
|
223
|
+
* meant to be read as text is rare enough to accept. This is a narrow fix for the
|
|
224
|
+
* common case, not a general entity decoder.
|
|
225
|
+
*/
|
|
226
|
+
export function decodeDisplayEntities(input: string): string {
|
|
227
|
+
if (!input.includes('&')) return input
|
|
228
|
+
return input.replace(/ /gi, ' ')
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Make an untrusted **single-line** value safe to interpolate into terminal output.
|
|
233
|
+
*
|
|
234
|
+
* Config-sourced strings (an MCP server's name, URL, or command line) are rendered
|
|
235
|
+
* straight into the transcript. `stripDangerousUnicode` covers the invisible
|
|
236
|
+
* characters but **not** C0 controls, and ESC (U+001B) is one of those — a name
|
|
237
|
+
* carrying `\x1b[2J` is read by the terminal as a clear-screen sequence, not shown
|
|
238
|
+
* as text. DEL (U+007F) goes too.
|
|
239
|
+
*
|
|
240
|
+
* Newlines are stripped as well, unlike `stripControlCharsForCheck` (which keeps
|
|
241
|
+
* `\n` for multi-line shell commands): these values sit on one output line, so an
|
|
242
|
+
* embedded newline forges an extra row in the listing.
|
|
243
|
+
*/
|
|
244
|
+
export function sanitizeInlineField(input: string): string {
|
|
245
|
+
if (!input) return input
|
|
246
|
+
return stripDangerousUnicode(input).replace(/[\x00-\x1f\x7f]/g, '')
|
|
247
|
+
}
|
|
248
|
+
|
|
216
249
|
/**
|
|
217
250
|
* Full command sanitization pipeline for permission checks.
|
|
218
251
|
* Applies in order:
|
|
@@ -255,3 +288,35 @@ export function sanitizeForDisplay(input: string): string {
|
|
|
255
288
|
result = result.replace(/\f/g, '⟨FF⟩')
|
|
256
289
|
return result
|
|
257
290
|
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Neutralize text that is about to be **injected into the system prompt** inside a
|
|
294
|
+
* tag-delimited block (memory recall, session summaries).
|
|
295
|
+
*
|
|
296
|
+
* Two steps, both load-bearing:
|
|
297
|
+
*
|
|
298
|
+
* 1. `stripDangerousUnicode` — the same invisible set the command path applies.
|
|
299
|
+
* Without it the text can carry an invisible character that hides part of a
|
|
300
|
+
* delimiter from anything scanning the text, while the model still reads it.
|
|
301
|
+
* 2. Drop `<…>`-shaped runs. The injection point wraps the text in
|
|
302
|
+
* `<system-reminder>…</system-reminder>`, so an entry whose own text contains
|
|
303
|
+
* `</system-reminder>` closes that block early and everything after it reads as
|
|
304
|
+
* ordinary prompt text instead of as recalled data. Stripping the brackets is
|
|
305
|
+
* what makes the wrapper unforgeable: the text stays readable, it just stops
|
|
306
|
+
* being able to *end* the block it was pasted into.
|
|
307
|
+
*
|
|
308
|
+
* Same move as `skills/sanitizer.ts` `sanitizeSkillDescription` (which strips
|
|
309
|
+
* `<[^>]*>` for this exact reason); this one additionally strips the invisible set,
|
|
310
|
+
* which the skill path does not. Both are lossy **on purpose** — an injected entry is
|
|
311
|
+
* prose for a model to read, not markup, so no legitimate entry loses meaning.
|
|
312
|
+
*
|
|
313
|
+
* The run is bounded at 200 characters so a stray `<` in prose cannot swallow the
|
|
314
|
+
* rest of the entry, and a letter must follow `<` (or `</`) immediately — so
|
|
315
|
+
* "a < b and c > d" survives while `</system-reminder>` does not. A forged delimiter
|
|
316
|
+
* with a space inside it (`</ system-reminder>`) is not a form this wrapper emits,
|
|
317
|
+
* and buying that case costs every piece of prose containing `< word >`.
|
|
318
|
+
*/
|
|
319
|
+
export function neutralizeInjectedMarkup(input: string): string {
|
|
320
|
+
if (!input) return input
|
|
321
|
+
return stripDangerousUnicode(input).replace(/<\/?[A-Za-z][^<>]{0,200}>/g, '')
|
|
322
|
+
}
|
package/src/shared/types.ts
CHANGED
|
@@ -135,6 +135,14 @@ export interface StreamChunk {
|
|
|
135
135
|
*/
|
|
136
136
|
isError?: boolean
|
|
137
137
|
error?: string
|
|
138
|
+
/**
|
|
139
|
+
* `type: 'error'` only. `false` means the provider knows the failure is
|
|
140
|
+
* deterministic (a content filter, a malformed request, a bad key) and re-sending
|
|
141
|
+
* it will produce the same answer. The engine then skips both its in-place retry
|
|
142
|
+
* and the fallback provider, so a final error is shown once instead of three
|
|
143
|
+
* times. Absent means "unknown" and preserves the retry.
|
|
144
|
+
*/
|
|
145
|
+
retryable?: boolean
|
|
138
146
|
/** DeepSeek reasoning tokens accumulated during this stream. */
|
|
139
147
|
reasoning_content?: string
|
|
140
148
|
/** Anthropic thinking block content (DeepSeek Anthropic endpoint). */
|
|
@@ -565,6 +573,28 @@ export interface ToolContext {
|
|
|
565
573
|
llm?: import('../providers/llm').Llm
|
|
566
574
|
/** Files read this session — used by Write tool to check read-before-write */
|
|
567
575
|
readFiles?: Set<string>
|
|
576
|
+
/**
|
|
577
|
+
* Cancellation for the turn this tool call belongs to.
|
|
578
|
+
*
|
|
579
|
+
* Carried on the context, not on `execute`'s signature, so every tool can reach it
|
|
580
|
+
* without changing the `ToolDefinition.execute` contract. Before this field existed
|
|
581
|
+
* the signal stopped at `permission.resolveApproval` and the LLM stream: a long
|
|
582
|
+
* Bash command could not be cancelled at all, because nothing it received ever
|
|
583
|
+
* changed. Absent means "no cancellation in effect" — tools must treat that as
|
|
584
|
+
* "run to completion", not as "abort".
|
|
585
|
+
*/
|
|
586
|
+
signal?: AbortSignal
|
|
587
|
+
/**
|
|
588
|
+
* True when this tool call is being executed *by a sub-agent*, not by the main
|
|
589
|
+
* loop.
|
|
590
|
+
*
|
|
591
|
+
* Set by `SubAgent.runExecution` on the context it hands its own tools, so a
|
|
592
|
+
* tool whose behaviour must differ one level down can see where it is instead of
|
|
593
|
+
* inferring it (`sessionId` is `'sub-agent'` there, but that is a display string,
|
|
594
|
+
* not a contract). The only reader today is the Agent tool: a nested call cannot
|
|
595
|
+
* consume a background handle, so its default flips to synchronous.
|
|
596
|
+
*/
|
|
597
|
+
isSubAgent?: boolean
|
|
568
598
|
}
|
|
569
599
|
|
|
570
600
|
export interface ToolDefinition {
|
package/src/tools/agent/agent.ts
CHANGED
|
@@ -7,14 +7,28 @@ const VALID_TYPES: SubAgentType[] = ['general', 'explore', 'plan', 'code-review'
|
|
|
7
7
|
|
|
8
8
|
/**
|
|
9
9
|
* Resolve whether a sub-agent should run in the background.
|
|
10
|
-
*
|
|
11
|
-
* `
|
|
10
|
+
*
|
|
11
|
+
* Precedence: explicit `run_in_background` param > nested-call rule > agent
|
|
12
|
+
* frontmatter `background` field > default (background, Claude Code 2.1.232 parity).
|
|
13
|
+
*
|
|
14
|
+
* `nested` is true when the caller is itself a sub-agent. `[background-task:<id>]`
|
|
15
|
+
* is a *handle*, not an answer: the child's result goes to the background registry
|
|
16
|
+
* and the hook/experience logs, and nothing ever hands it back to the agent that
|
|
17
|
+
* asked. So one level down, the ordinary fan-out shape — "ask a child, then use its
|
|
18
|
+
* answer" — cannot work at all: the caller sees a placeholder where its input
|
|
19
|
+
* should be. A *default* of background turns that from an option into a hole, which
|
|
20
|
+
* is why the default flips here. An explicit `run_in_background: true` is still
|
|
21
|
+
* honoured, in both directions: that is a request, not a default chosen on the
|
|
22
|
+
* caller's behalf.
|
|
12
23
|
*/
|
|
13
24
|
export function resolveRunInBackground(
|
|
14
25
|
runInBackground: boolean | undefined,
|
|
15
26
|
agentDef?: { background?: boolean },
|
|
27
|
+
nested = false,
|
|
16
28
|
): boolean {
|
|
17
|
-
|
|
29
|
+
if (runInBackground !== undefined) return runInBackground
|
|
30
|
+
if (nested) return false
|
|
31
|
+
return agentDef?.background ?? true
|
|
18
32
|
}
|
|
19
33
|
|
|
20
34
|
export const agentTool: ToolDefinition = {
|
|
@@ -73,6 +87,7 @@ export const agentTool: ToolDefinition = {
|
|
|
73
87
|
const runInBackground = resolveRunInBackground(
|
|
74
88
|
params.run_in_background as boolean | undefined,
|
|
75
89
|
agentDef,
|
|
90
|
+
ctx.isSubAgent === true,
|
|
76
91
|
)
|
|
77
92
|
|
|
78
93
|
try {
|
|
@@ -1,5 +1,35 @@
|
|
|
1
|
-
import { readFileSync } from 'node:fs'
|
|
1
|
+
import { readFileSync, readdirSync, statSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
2
3
|
import type { ToolDefinition } from '../../shared/index.ts'
|
|
4
|
+
import { MIPHAM_DIR } from '../../shared/constants.ts'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Newest `plan-*.md` under `<cwd>/.mipham/plans/`, or null when there is none.
|
|
8
|
+
*
|
|
9
|
+
* This backs the `planFile` parameter's documented default. Without it the
|
|
10
|
+
* docstring promised a fallback the body never performed (`planFile || ''`), so an
|
|
11
|
+
* omission read as "use the most recent plan" and quietly produced no plan at all.
|
|
12
|
+
*/
|
|
13
|
+
function mostRecentPlanFile(cwd: string): string | null {
|
|
14
|
+
const dir = join(cwd, MIPHAM_DIR, 'plans')
|
|
15
|
+
let names: string[]
|
|
16
|
+
try {
|
|
17
|
+
names = readdirSync(dir).filter((n) => n.startsWith('plan-') && n.endsWith('.md'))
|
|
18
|
+
} catch {
|
|
19
|
+
return null // no plans directory — nothing to fall back to
|
|
20
|
+
}
|
|
21
|
+
let newest: { path: string; mtime: number } | null = null
|
|
22
|
+
for (const name of names) {
|
|
23
|
+
const path = join(dir, name)
|
|
24
|
+
try {
|
|
25
|
+
const mtime = statSync(path).mtimeMs
|
|
26
|
+
if (!newest || mtime > newest.mtime) newest = { path, mtime }
|
|
27
|
+
} catch {
|
|
28
|
+
// Unreadable entry — not a fallback candidate.
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return newest?.path ?? null
|
|
32
|
+
}
|
|
3
33
|
|
|
4
34
|
export const exitPlanModeTool: ToolDefinition = {
|
|
5
35
|
name: 'ExitPlanMode',
|
|
@@ -21,27 +51,37 @@ export const exitPlanModeTool: ToolDefinition = {
|
|
|
21
51
|
},
|
|
22
52
|
required: [],
|
|
23
53
|
},
|
|
24
|
-
async execute(params,
|
|
25
|
-
const planFile = (params.planFile as string) || ''
|
|
54
|
+
async execute(params, ctx) {
|
|
55
|
+
const planFile = (params.planFile as string) || mostRecentPlanFile(ctx.cwd) || ''
|
|
26
56
|
|
|
27
57
|
// Try to read the plan to confirm it exists
|
|
28
58
|
let planContent = ''
|
|
59
|
+
let readError = ''
|
|
29
60
|
try {
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
planContent = readFileSync(planPath, 'utf-8')
|
|
61
|
+
if (planFile) {
|
|
62
|
+
planContent = readFileSync(planFile, 'utf-8')
|
|
33
63
|
}
|
|
34
|
-
} catch {
|
|
35
|
-
|
|
64
|
+
} catch (err) {
|
|
65
|
+
readError = err instanceof Error ? err.message : String(err)
|
|
36
66
|
}
|
|
37
67
|
|
|
68
|
+
// Say which of the three states we are actually in. The old text asserted
|
|
69
|
+
// "Plan file saved" unconditionally, so a missing or unreadable plan still read
|
|
70
|
+
// as success and the model would present a plan it never retrieved.
|
|
71
|
+
const planStatus = planContent
|
|
72
|
+
? '✓ Plan file read. Present your plan to the user now.'
|
|
73
|
+
: planFile
|
|
74
|
+
? `⚠️ Plan file not readable (${planFile}): ${readError}`
|
|
75
|
+
: '⚠️ No plan file found — present the plan from your own context.'
|
|
76
|
+
|
|
38
77
|
return {
|
|
39
78
|
success: true,
|
|
40
79
|
content: [
|
|
41
80
|
'── Plan Ready for Review ──',
|
|
42
81
|
'',
|
|
43
82
|
'✓ Exiting plan mode.',
|
|
44
|
-
|
|
83
|
+
planStatus,
|
|
84
|
+
planFile ? `Plan file: ${planFile}` : '',
|
|
45
85
|
'',
|
|
46
86
|
'⚠️ IMPORTANT: You are still in limited permission mode.',
|
|
47
87
|
' The user must explicitly approve before you can make changes.',
|
package/src/tools/exec/bash.ts
CHANGED
|
@@ -439,8 +439,24 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
439
439
|
timedOut = true
|
|
440
440
|
killProcessGroup(proc.pid)
|
|
441
441
|
}, timeout)
|
|
442
|
+
|
|
443
|
+
// Cancellation. The turn's signal used to stop at the approval prompt and the
|
|
444
|
+
// model stream, so a long-running command had no way to be stopped: nothing
|
|
445
|
+
// it received ever changed. Abort has to reach the process group, or Escape
|
|
446
|
+
// kills the turn while the command keeps writing to the user's disk.
|
|
447
|
+
let aborted = false
|
|
448
|
+
const onAbort = () => {
|
|
449
|
+
aborted = true
|
|
450
|
+
killProcessGroup(proc.pid)
|
|
451
|
+
}
|
|
452
|
+
if (ctx.signal) {
|
|
453
|
+
if (ctx.signal.aborted) onAbort()
|
|
454
|
+
else ctx.signal.addEventListener('abort', onAbort, { once: true })
|
|
455
|
+
}
|
|
456
|
+
|
|
442
457
|
const exitCode = await proc.exited
|
|
443
458
|
clearTimeout(timer)
|
|
459
|
+
ctx.signal?.removeEventListener('abort', onAbort)
|
|
444
460
|
|
|
445
461
|
// The shell is gone, so only a pipe-holding descendant can still be
|
|
446
462
|
// holding these up. Released by the group kill, at most once.
|
|
@@ -493,12 +509,21 @@ export function createBashTool(credentialConfig?: CredentialMaskingConfig): Tool
|
|
|
493
509
|
return {
|
|
494
510
|
success: false,
|
|
495
511
|
content: errorContent,
|
|
496
|
-
error:
|
|
497
|
-
? `Command
|
|
498
|
-
:
|
|
512
|
+
error: aborted
|
|
513
|
+
? `Command cancelled (SIGKILL to its process group)`
|
|
514
|
+
: timedOut
|
|
515
|
+
? `Command timed out after ${timeout}ms (killed): ${stderr.slice(0, 1_000)}`
|
|
516
|
+
: `Exit code ${exitCode}: ${stderr.slice(0, 1_000)}`,
|
|
499
517
|
}
|
|
500
518
|
}
|
|
501
519
|
|
|
520
|
+
// An aborted command may also exit 0 (SIGKILL raced the natural exit). Report
|
|
521
|
+
// the cancellation either way, so a half-finished command is never handed back
|
|
522
|
+
// as a clean success.
|
|
523
|
+
if (aborted) {
|
|
524
|
+
return { success: false, content: output.slice(0, 5_000), error: 'Command cancelled' }
|
|
525
|
+
}
|
|
526
|
+
|
|
502
527
|
let successContent = output.slice(0, 100_000) || '(no output)'
|
|
503
528
|
if (violations.length > 0) {
|
|
504
529
|
successContent += '\n\n── Sandbox Violations ──\n' + violations.join('\n')
|
package/src/tools/index.ts
CHANGED
|
@@ -74,7 +74,13 @@ export function createToolRegistry(
|
|
|
74
74
|
sendMessageTool,
|
|
75
75
|
listAgentsTool,
|
|
76
76
|
// Network tools
|
|
77
|
-
|
|
77
|
+
// `MIPHAM_DISABLE_WEB_FETCH=1` removes WebFetch from the registry entirely, so
|
|
78
|
+
// it is never advertised to the model. A `permissionRules.deny: ["WebFetch"]`
|
|
79
|
+
// reaches the same endpoint by a different mechanism — the tool is still listed
|
|
80
|
+
// in the schema and only rejected when called, which costs a wasted turn (and a
|
|
81
|
+
// perplexed model) before the refusal lands. An env kill-switch has to act at
|
|
82
|
+
// registration, not at call time.
|
|
83
|
+
...(process.env.MIPHAM_DISABLE_WEB_FETCH === '1' ? [] : [webFetchTool]),
|
|
78
84
|
webSearchTool,
|
|
79
85
|
// System tools
|
|
80
86
|
mcpTool,
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { ToolDefinition } from '../../shared/index.ts'
|
|
2
|
+
import { PACKAGE_VERSION } from '../../shared/package-info'
|
|
2
3
|
import { validateUrl } from '../../security/url'
|
|
3
4
|
|
|
4
5
|
// ── In-memory cache (15-min TTL per URL) ──
|
|
@@ -195,7 +196,7 @@ export const webFetchTool: ToolDefinition = {
|
|
|
195
196
|
for (let hop = 0; hop <= 5; hop++) {
|
|
196
197
|
response = await fetch(currentUrl, {
|
|
197
198
|
headers: {
|
|
198
|
-
'User-Agent':
|
|
199
|
+
'User-Agent': `Mipham-Code/${PACKAGE_VERSION}`,
|
|
199
200
|
Accept: 'text/html,application/xhtml+xml,*/*',
|
|
200
201
|
},
|
|
201
202
|
redirect: 'manual',
|
|
@@ -50,7 +50,7 @@ export const toolSearchTool: ToolDefinition = {
|
|
|
50
50
|
content:
|
|
51
51
|
'── MCP Tool Search ──\n\n' +
|
|
52
52
|
'No MCP servers connected.\n\n' +
|
|
53
|
-
'Connect MCP servers in .mcp.json or via /mcp
|
|
53
|
+
'Connect MCP servers in .mcp.json or via /mcp connect <server-name>.',
|
|
54
54
|
}
|
|
55
55
|
}
|
|
56
56
|
|
package/src/ui/chat.tsx
CHANGED
|
@@ -2,6 +2,7 @@ import React, { useMemo } from 'react'
|
|
|
2
2
|
import { Box, Text } from 'ink'
|
|
3
3
|
import { useI18n } from '../i18n-context'
|
|
4
4
|
import type { ChatMessage } from './app'
|
|
5
|
+
import { decodeDisplayEntities } from '../shared/sanitize'
|
|
5
6
|
import { homedir } from 'node:os'
|
|
6
7
|
|
|
7
8
|
interface ChatPanelProps {
|
|
@@ -93,7 +94,7 @@ const MessageRow = React.memo(
|
|
|
93
94
|
⚠ {t('ui.system.role_label')}:
|
|
94
95
|
</Text>
|
|
95
96
|
) : null}
|
|
96
|
-
<Text>{msg.content}</Text>
|
|
97
|
+
<Text>{msg.toolMeta ? msg.content : decodeDisplayEntities(msg.content)}</Text>
|
|
97
98
|
</>
|
|
98
99
|
)}
|
|
99
100
|
</Box>
|
package/src/ui/commands.ts
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import type { QueryEngine } from '../core/engine'
|
|
8
8
|
import type { MiphamConfig } from '../shared/index.ts'
|
|
9
9
|
import { formatContextWindow } from '../shared/format'
|
|
10
|
+
import { sanitizeInlineField } from '../shared/sanitize'
|
|
10
11
|
import type { SkillsLoader } from '../skills/loader'
|
|
11
12
|
import { loadSkillUsage } from '../skills/usage'
|
|
12
13
|
import type { PluginManager } from '../plugin/plugin-manager'
|
|
@@ -3172,6 +3173,23 @@ const loopCmd: CommandHandler = async (ctx, args) => {
|
|
|
3172
3173
|
return { content: lines.join('\n\n') }
|
|
3173
3174
|
}
|
|
3174
3175
|
|
|
3176
|
+
// Shared tail of both autonomous-loop prompts below. It carries two fixes:
|
|
3177
|
+
//
|
|
3178
|
+
// - the journal's per-iteration row is the assistant's **visible text**
|
|
3179
|
+
// (`app.tsx` passes `assistantContent`, which only accumulates
|
|
3180
|
+
// `type === 'text'` chunks), so a loop that never emits text has a
|
|
3181
|
+
// progress log with nothing in it — the prompt now asks for one line;
|
|
3182
|
+
// - the prompts used to say `logAutoloopIteration("<id>", "<summary>")`, a
|
|
3183
|
+
// module export *inside* the CLI that is not a tool and so was never
|
|
3184
|
+
// callable, and to have the model write the journal file itself — which
|
|
3185
|
+
// would clobber the counters the CLI maintains there.
|
|
3186
|
+
const journalNotice = (id: string): string =>
|
|
3187
|
+
`\nEnd each iteration with one line of plain text saying where the loop stands.\n` +
|
|
3188
|
+
`The journal records the text you emit: an iteration that emits none is logged as\n` +
|
|
3189
|
+
`having no visible output, and /loop status shows that instead of progress.\n` +
|
|
3190
|
+
`Do not edit ~/.mipham/autoloop/${id}.json yourself — the CLI writes it (iteration\n` +
|
|
3191
|
+
`count, token totals, status) and a direct write would clobber that accounting.`
|
|
3192
|
+
|
|
3175
3193
|
// ── /loop auto <prompt> — autonomous self-paced loop ──
|
|
3176
3194
|
if (sub === 'auto') {
|
|
3177
3195
|
const prompt = args.slice(1).join(' ')
|
|
@@ -3202,9 +3220,8 @@ const loopCmd: CommandHandler = async (ctx, args) => {
|
|
|
3202
3220
|
` - delaySeconds: your best estimate of how long to wait (60-3600)\n` +
|
|
3203
3221
|
` - reason: one sentence explaining why\n` +
|
|
3204
3222
|
` - prompt: include this full autonomous loop ID: ${sessionId}\n` +
|
|
3205
|
-
`3. When the task is COMPLETE, call ScheduleWakeup with stop:true\n
|
|
3206
|
-
|
|
3207
|
-
`Use the autoloop-journal module: logAutoloopIteration("${sessionId}", "<summary>").`
|
|
3223
|
+
`3. When the task is COMPLETE, call ScheduleWakeup with stop:true\n` +
|
|
3224
|
+
journalNotice(sessionId)
|
|
3208
3225
|
|
|
3209
3226
|
return {
|
|
3210
3227
|
content:
|
|
@@ -3259,8 +3276,8 @@ const loopCmd: CommandHandler = async (ctx, args) => {
|
|
|
3259
3276
|
`You are in an autonomous loop (auto-detected — no interval specified). Each iteration:\n` +
|
|
3260
3277
|
`1. Make progress on the task above\n` +
|
|
3261
3278
|
`2. When you need to wait, call ScheduleWakeup with your chosen delaySeconds and this loop ID: ${sessionId}\n` +
|
|
3262
|
-
`3. When COMPLETE, call ScheduleWakeup with stop:true\n
|
|
3263
|
-
|
|
3279
|
+
`3. When COMPLETE, call ScheduleWakeup with stop:true\n` +
|
|
3280
|
+
journalNotice(sessionId)
|
|
3264
3281
|
|
|
3265
3282
|
return {
|
|
3266
3283
|
content:
|
|
@@ -4932,7 +4949,7 @@ const mcpCmd: CommandHandler = async (ctx, args) => {
|
|
|
4932
4949
|
const config = mcpServers.find((s) => s.name === name)
|
|
4933
4950
|
if (!config) {
|
|
4934
4951
|
return {
|
|
4935
|
-
content: `Server "${name}" not found in config.\n\nConfigured: ${mcpServers.map((s) => s.name).join(', ') || '(none)'}`,
|
|
4952
|
+
content: `Server "${sanitizeInlineField(name)}" not found in config.\n\nConfigured: ${mcpServers.map((s) => sanitizeInlineField(s.name)).join(', ') || '(none)'}`,
|
|
4936
4953
|
}
|
|
4937
4954
|
}
|
|
4938
4955
|
if (config.auth?.type === 'oauth') {
|
|
@@ -4952,7 +4969,7 @@ const mcpCmd: CommandHandler = async (ctx, args) => {
|
|
|
4952
4969
|
const headerKeys = config.headers ? Object.keys(config.headers) : []
|
|
4953
4970
|
const headerLine = headerKeys.length > 0 ? `\nHeaders to send: ${headerKeys.join(', ')}` : ''
|
|
4954
4971
|
return {
|
|
4955
|
-
content: `── MCP Connect: ${name} ──\n\nConnecting via HTTP\nURL: ${config.url}${headerLine}\n\n⚠️ Verify the URL — any configured headers (e.g. Authorization) will be sent to this server.`,
|
|
4972
|
+
content: `── MCP Connect: ${sanitizeInlineField(name)} ──\n\nConnecting via HTTP\nURL: ${sanitizeInlineField(config.url)}${headerLine}\n\n⚠️ Verify the URL — any configured headers (e.g. Authorization) will be sent to this server.`,
|
|
4956
4973
|
forwardToAI: `Connect to MCP server "${name}" using McpClient.getInstance().connect(config), then register its tools. Report the result.`,
|
|
4957
4974
|
}
|
|
4958
4975
|
}
|
|
@@ -5042,15 +5059,15 @@ const mcpCmd: CommandHandler = async (ctx, args) => {
|
|
|
5042
5059
|
: '⚪'
|
|
5043
5060
|
const statusLabel = live ? live.status : 'not started'
|
|
5044
5061
|
const oauthTag = s.auth?.type === 'oauth' ? ' [OAuth]' : ''
|
|
5045
|
-
lines.push(` ${statusIcon} ${s.name}${oauthTag} [${statusLabel}]`)
|
|
5062
|
+
lines.push(` ${statusIcon} ${sanitizeInlineField(s.name)}${oauthTag} [${statusLabel}]`)
|
|
5046
5063
|
const transportInfo = s.url
|
|
5047
|
-
? `URL: ${s.url}`
|
|
5048
|
-
: `Command: ${s.command ?? ''} ${(s.args ?? []).join(' ')}`
|
|
5064
|
+
? `URL: ${sanitizeInlineField(s.url)}`
|
|
5065
|
+
: `Command: ${sanitizeInlineField(s.command ?? '')} ${(s.args ?? []).map(sanitizeInlineField).join(' ')}`
|
|
5049
5066
|
lines.push(` ${transportInfo}`)
|
|
5050
5067
|
if (live?.tools && live.tools.length > 0) {
|
|
5051
5068
|
lines.push(` Tools: ${live.tools.length} registered`)
|
|
5052
5069
|
}
|
|
5053
|
-
if (live?.error) lines.push(` Error: ${live.error}`)
|
|
5070
|
+
if (live?.error) lines.push(` Error: ${sanitizeInlineField(live.error)}`)
|
|
5054
5071
|
lines.push('')
|
|
5055
5072
|
}
|
|
5056
5073
|
} else {
|
package/src/ui/input.tsx
CHANGED
|
@@ -399,6 +399,11 @@ export function InputBar({
|
|
|
399
399
|
useInput((input, key) => {
|
|
400
400
|
// ── Escape: cancel loading → clear draft ──
|
|
401
401
|
if (key.escape) {
|
|
402
|
+
// While the command picker is open, Escape belongs to it. Ink 7 runs every
|
|
403
|
+
// registered `useInput` listener for one keypress (no stopPropagation), so
|
|
404
|
+
// without this the picker closes AND this branch wipes the draft — the exact
|
|
405
|
+
// text the picker's `onClose` is written to preserve.
|
|
406
|
+
if (pickerActive) return
|
|
402
407
|
// Escape while loading → abort
|
|
403
408
|
if (isLoading) {
|
|
404
409
|
onCancel?.()
|
|
@@ -18,6 +18,19 @@ export class WorkflowEventBus extends EventEmitter {
|
|
|
18
18
|
}
|
|
19
19
|
|
|
20
20
|
emitEvent(event: WorkflowEvent): void {
|
|
21
|
+
// `error` here is a **payload type**, not EventEmitter's crash channel — and the
|
|
22
|
+
// two are wired to the same string. Node makes `emit('error', …)` throw
|
|
23
|
+
// ERR_UNHANDLED_ERROR when no listener is attached, so a workflow that failed
|
|
24
|
+
// while nothing was watching the bus replaced its own diagnostic with
|
|
25
|
+
// `Unhandled error. ({ type: 'error', message: '…' })`, and the carefully
|
|
26
|
+
// written `throw new Error('Workflow script execution failed: …')` further down
|
|
27
|
+
// never ran. It looked fine because the UI progress view subscribes to `error`,
|
|
28
|
+
// so the throw only happened headless.
|
|
29
|
+
//
|
|
30
|
+
// Nothing is lost by skipping it: whoever needs the failure has the journal entry
|
|
31
|
+
// and the thrown error; the one subscriber drops `error` on the floor anyway
|
|
32
|
+
// (`workflow-progress.tsx`'s `case 'error': break`).
|
|
33
|
+
if (event.type === 'error' && this.listenerCount('error') === 0) return
|
|
21
34
|
this.emit(event.type, event)
|
|
22
35
|
}
|
|
23
36
|
|
package/src/workflow/journal.ts
CHANGED
|
@@ -13,6 +13,14 @@ export interface JournalEntry {
|
|
|
13
13
|
opts?: Record<string, unknown>
|
|
14
14
|
result?: unknown
|
|
15
15
|
message?: string
|
|
16
|
+
/**
|
|
17
|
+
* Why an `agent` entry has no `result`.
|
|
18
|
+
*
|
|
19
|
+
* Kept out of `result` on purpose: the resume cache is keyed on `result !==
|
|
20
|
+
* undefined`, so parking the message there would make a failed call replay as a
|
|
21
|
+
* successful cached answer.
|
|
22
|
+
*/
|
|
23
|
+
error?: string
|
|
16
24
|
}
|
|
17
25
|
|
|
18
26
|
export interface JournalState {
|
package/src/workflow/runtime.ts
CHANGED
|
@@ -108,7 +108,7 @@ export async function runWorkflow(
|
|
|
108
108
|
const budget = createBudget(budgetTotal)
|
|
109
109
|
|
|
110
110
|
// Wrap primitives with journal recording + cache support
|
|
111
|
-
const
|
|
111
|
+
const runAgent = async (prompt: string, opts?: Record<string, unknown>) => {
|
|
112
112
|
// Check cache first
|
|
113
113
|
if (resultCache) {
|
|
114
114
|
const key = agentCacheKey(prompt, opts || {})
|
|
@@ -125,16 +125,42 @@ export async function runWorkflow(
|
|
|
125
125
|
|
|
126
126
|
bus.emitEvent({ type: 'agent:start', agentId, label: agentId, phase })
|
|
127
127
|
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
128
|
+
let result: unknown
|
|
129
|
+
try {
|
|
130
|
+
result = await workflowAgent(
|
|
131
|
+
prompt,
|
|
132
|
+
registry,
|
|
133
|
+
toolRegistry,
|
|
134
|
+
{
|
|
135
|
+
...(opts || {}),
|
|
136
|
+
permissionSystem: permission,
|
|
137
|
+
} as Record<string, unknown>,
|
|
138
|
+
llm,
|
|
139
|
+
)
|
|
140
|
+
} catch (err) {
|
|
141
|
+
// A failed call is still a call: it gets the same start/end pair and a journal
|
|
142
|
+
// entry, so the run reads as "this agent failed" rather than as a run that
|
|
143
|
+
// silently never mentioned it. The message goes in `error`, not `result` —
|
|
144
|
+
// the resume cache replays on `result !== undefined`.
|
|
145
|
+
const message = err instanceof Error ? err.message : String(err)
|
|
146
|
+
bus.emitEvent({
|
|
147
|
+
type: 'agent:end',
|
|
148
|
+
agentId,
|
|
149
|
+
label: agentId,
|
|
150
|
+
success: false,
|
|
151
|
+
durationMs: Date.now() - startTime,
|
|
152
|
+
})
|
|
153
|
+
bus.emitEvent({ type: 'error', agentId, message })
|
|
154
|
+
appendJournal(runId, {
|
|
155
|
+
type: 'agent',
|
|
156
|
+
prompt,
|
|
157
|
+
opts: opts as Record<string, unknown> | undefined,
|
|
158
|
+
error: message,
|
|
159
|
+
})
|
|
160
|
+
// Still rethrow: a script that awaits this call must see the rejection, and
|
|
161
|
+
// the catch below turns it into the run's own error message.
|
|
162
|
+
throw err
|
|
163
|
+
}
|
|
138
164
|
|
|
139
165
|
const durationMs = Date.now() - startTime
|
|
140
166
|
bus.emitEvent({ type: 'agent:end', agentId, label: agentId, success: true, durationMs })
|
|
@@ -148,6 +174,28 @@ export async function runWorkflow(
|
|
|
148
174
|
return result
|
|
149
175
|
}
|
|
150
176
|
|
|
177
|
+
/**
|
|
178
|
+
* The `agent` the sandbox script sees.
|
|
179
|
+
*
|
|
180
|
+
* Not `async`, because the promise it returns needs a handler attached before it
|
|
181
|
+
* leaves this function. A script that calls `agent(...)` **without awaiting it** —
|
|
182
|
+
* a fire-and-forget fan-out, or `agent('A'); await agent('B')` — leaves the
|
|
183
|
+
* rejection unhandled in the host realm, and the crash reporter is installed
|
|
184
|
+
* unconditionally, so `handleFatal` ends the process: one un-awaited call and the
|
|
185
|
+
* CLI exits with a message about unhandled rejections in a workflow script.
|
|
186
|
+
*
|
|
187
|
+
* Attaching the handler here marks the rejection handled **without swallowing it**:
|
|
188
|
+
* the promise returned to the script is the same one, so `await agent(...)` still
|
|
189
|
+
* throws into the script's own `try`. What changes is only the case where nobody is
|
|
190
|
+
* listening — that case now belongs to the run (journal + `error` event, both
|
|
191
|
+
* written by `runAgent`), not to the process.
|
|
192
|
+
*/
|
|
193
|
+
const agent = (prompt: string, opts?: Record<string, unknown>) => {
|
|
194
|
+
const pending = runAgent(prompt, opts)
|
|
195
|
+
pending.catch(() => {})
|
|
196
|
+
return pending
|
|
197
|
+
}
|
|
198
|
+
|
|
151
199
|
const wrappedPhase = (title: string) => {
|
|
152
200
|
phasePrimitive(title)
|
|
153
201
|
bus.emitEvent({ type: 'phase:start', phase: title, timestamp: Date.now() })
|