aiterm-mcp 0.61.19 → 0.61.21
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 +38 -1
- package/README.ja.md +36 -4
- package/README.md +38 -5
- package/dist/agent-goal-native-result.js +172 -0
- package/dist/agent-goal-ui.js +50 -0
- package/dist/agent-goal.js +221 -0
- package/dist/codex-goal-connection.js +23 -0
- package/dist/codex-relay-client.js +3 -2
- package/dist/core.js +311 -10
- package/dist/execution-contract.js +1 -1
- package/dist/execution-dispatch.js +4 -1
- package/dist/execution-immediate-stop.js +77 -24
- package/dist/execution-native-server.js +9 -5
- package/dist/harnesses/claude-goal.js +243 -0
- package/dist/harnesses/codex-goal-editor.js +134 -0
- package/dist/harnesses/codex-goal.js +94 -0
- package/dist/harnesses/cursor.js +27 -0
- package/dist/harnesses/grok-goal.js +261 -0
- package/dist/harnesses/grok.js +25 -2
- package/dist/index.js +22 -0
- package/dist/process-runtime.js +18 -0
- package/dist/process-start.js +35 -0
- package/dist/runtime-error-os.js +2 -32
- package/docs/DESIGN.md +44 -2
- package/package.json +1 -1
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
// Claude owns goal state. A fresh local status command, never a historical
|
|
2
|
+
// attachment alone, establishes current state for the bound native session.
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
const currentSessionSchema = z.object({ pid: z.number().int().positive(), sessionId: z.string().uuid(), procStart: z.string().regex(/^\d+$/u), pidDomain: z.string(), version: z.literal("2.1.310"), kind: z.literal("interactive") });
|
|
5
|
+
export function claudeCurrentSessionOwner(record, expected) {
|
|
6
|
+
const parsed = currentSessionSchema.safeParse(record);
|
|
7
|
+
if (!parsed.success || parsed.data.pid !== expected.pid || parsed.data.procStart !== expected.procStart || parsed.data.pidDomain !== expected.pidDomain)
|
|
8
|
+
return "unavailable";
|
|
9
|
+
return parsed.data.sessionId === expected.sessionId ? "match" : "mismatch";
|
|
10
|
+
}
|
|
11
|
+
export const claudeNativeGoalStatusSchema = z.object({
|
|
12
|
+
type: z.literal("goal_status"), condition: z.string().min(1), met: z.boolean(),
|
|
13
|
+
sentinel: z.boolean().optional(), reason: z.string().optional(),
|
|
14
|
+
iterations: z.number().int().nonnegative().optional(),
|
|
15
|
+
durationMs: z.number().nonnegative().optional(), tokens: z.number().int().nonnegative().optional(),
|
|
16
|
+
}).strict();
|
|
17
|
+
export const claudeCurrentGoalSchema = z.object({
|
|
18
|
+
kind: z.literal("claude-code"), phase: z.literal("active"),
|
|
19
|
+
native: claudeNativeGoalStatusSchema.extend({ met: z.literal(false) }),
|
|
20
|
+
reported_turns: z.number().int().nonnegative().optional(),
|
|
21
|
+
}).strict();
|
|
22
|
+
export const claudeGoalHistorySchema = z.object({
|
|
23
|
+
kind: z.literal("claude-code"), terminal: z.enum(["achieved", "cleared"]), native: claudeNativeGoalStatusSchema,
|
|
24
|
+
}).strict();
|
|
25
|
+
const querySchema = z.object({ uuid: z.string().min(1), timestamp: z.string().datetime(),
|
|
26
|
+
sessionId: z.string().min(1), isSidechain: z.literal(false), version: z.literal("2.1.310"),
|
|
27
|
+
type: z.literal("system"), subtype: z.literal("local_command"), content: z.string(),
|
|
28
|
+
commandRun: z.object({ command: z.literal("goal"), args: z.literal("") }),
|
|
29
|
+
});
|
|
30
|
+
export function observeClaudeGoalStatus(rows, nativeSessionId, queryUuid) {
|
|
31
|
+
const matches = rows.flatMap((value, at) => typeof value === "object" && value !== null
|
|
32
|
+
&& value.uuid === queryUuid ? [at] : []);
|
|
33
|
+
if (matches.length !== 1)
|
|
34
|
+
throw new Error("fresh_bound_native_status_required");
|
|
35
|
+
const at = matches[0], query = querySchema.parse(rows[at]);
|
|
36
|
+
if (query.sessionId !== nativeSessionId)
|
|
37
|
+
throw new Error("native_goal_binding_mismatch");
|
|
38
|
+
const status = /^<local-command-stdout>([\s\S]*)<\/local-command-stdout>$/u.exec(query.content)?.[1];
|
|
39
|
+
if (status === undefined)
|
|
40
|
+
throw new Error("native_status_format_unavailable");
|
|
41
|
+
let current = null;
|
|
42
|
+
let history;
|
|
43
|
+
for (const value of rows.slice(0, at + 1)) {
|
|
44
|
+
const row = value;
|
|
45
|
+
if (row?.type !== "attachment" || row.attachment?.type !== "goal_status")
|
|
46
|
+
continue;
|
|
47
|
+
if (row.sessionId !== nativeSessionId || row.isSidechain !== false)
|
|
48
|
+
throw new Error("native_goal_binding_mismatch");
|
|
49
|
+
const native = claudeNativeGoalStatusSchema.parse(row.attachment);
|
|
50
|
+
if (native.met) {
|
|
51
|
+
current = null;
|
|
52
|
+
history = { kind: "claude-code", terminal: native.sentinel ? "cleared" : "achieved", native };
|
|
53
|
+
}
|
|
54
|
+
else
|
|
55
|
+
current = native;
|
|
56
|
+
}
|
|
57
|
+
const result = { query_uuid: query.uuid, observed_at: query.timestamp, ...(history ? { history } : {}) };
|
|
58
|
+
if (status === "No goal set" || status === "No goal set. Usage: `/goal <condition>`")
|
|
59
|
+
return { ...result, current: null };
|
|
60
|
+
if (!current)
|
|
61
|
+
throw new Error("native_goal_evidence_missing");
|
|
62
|
+
const prefix = "Goal active: " + current.condition;
|
|
63
|
+
if (!status.startsWith(prefix))
|
|
64
|
+
throw new Error("native_goal_status_mismatch");
|
|
65
|
+
const active = /^ \((\d+) turns?\)(?:\nLast check: ([\s\S]*))?$/u.exec(status.slice(prefix.length));
|
|
66
|
+
if (!active || active[2] !== current.reason || !Number.isSafeInteger(Number(active[1])))
|
|
67
|
+
throw new Error("native_goal_status_mismatch");
|
|
68
|
+
return { ...result, current: claudeCurrentGoalSchema.parse({ kind: "claude-code", phase: "active", native: current, reported_turns: Number(active[1]) }) };
|
|
69
|
+
}
|
|
70
|
+
export async function readFreshClaudeGoal(nativeSessionId, port) {
|
|
71
|
+
if (!port.same())
|
|
72
|
+
throw new Error("generation_replaced");
|
|
73
|
+
const before = port.readRows();
|
|
74
|
+
const seen = new Set(before.map(row => row?.uuid));
|
|
75
|
+
await port.query();
|
|
76
|
+
const now = port.now ?? (() => performance.now()), until = now() + 2000;
|
|
77
|
+
do {
|
|
78
|
+
if (!port.same())
|
|
79
|
+
throw new Error("generation_replaced_after_status");
|
|
80
|
+
const rows = port.readRows();
|
|
81
|
+
// A truncated/replaced transcript is not a fresh append.
|
|
82
|
+
if (rows.length < before.length || before.some((row, i) => JSON.stringify(row) !== JSON.stringify(rows[i])))
|
|
83
|
+
throw new Error("native_goal_transcript_replaced");
|
|
84
|
+
const candidates = rows.slice(before.length).filter(value => {
|
|
85
|
+
const row = value;
|
|
86
|
+
return row?.type === "system" && row.subtype === "local_command" && row.commandRun?.command === "goal"
|
|
87
|
+
&& row.commandRun.args === "" && row.sessionId === nativeSessionId && row.isSidechain === false && !seen.has(row.uuid);
|
|
88
|
+
});
|
|
89
|
+
if (candidates.length > 1)
|
|
90
|
+
throw new Error("native_goal_status_ambiguous");
|
|
91
|
+
if (candidates.length === 1)
|
|
92
|
+
return observeClaudeGoalStatus(rows, nativeSessionId, candidates[0].uuid);
|
|
93
|
+
await port.pause(40);
|
|
94
|
+
} while (now() < until);
|
|
95
|
+
throw new Error("native_goal_fresh_status_unavailable");
|
|
96
|
+
}
|
|
97
|
+
import { nativeGoalStyledRows } from "../agent-goal-ui.js";
|
|
98
|
+
import { AgentGoalNotIssuedError } from "../agent-goal.js";
|
|
99
|
+
function plain(screen) { return screen.replace(/\x1b\[[0-?]*[ -/]*[@-~]/gu, ""); }
|
|
100
|
+
export function claudeGoalComposer(screen) {
|
|
101
|
+
const lines = plain(screen).split("\n");
|
|
102
|
+
let at = lines.length - 1;
|
|
103
|
+
while (at >= 0 && !/^\s*❯/u.test(lines[at]))
|
|
104
|
+
at--;
|
|
105
|
+
const rule = /^\s*─{8,}\s*$/u;
|
|
106
|
+
if (at < 1 || !rule.test(lines[at - 1]))
|
|
107
|
+
return null;
|
|
108
|
+
const end = lines.findIndex((line, i) => i > at && rule.test(line));
|
|
109
|
+
if (end < 0)
|
|
110
|
+
return null;
|
|
111
|
+
const first = /^\s*❯[ \u00a0]?(.*)$/u.exec(lines[at]);
|
|
112
|
+
if (!first)
|
|
113
|
+
return null;
|
|
114
|
+
const continuation = lines.slice(at + 1, end);
|
|
115
|
+
if (continuation.some(line => !line.startsWith(" ")))
|
|
116
|
+
return null;
|
|
117
|
+
const prefix = /^\s*❯[ \u00a0]?/u.exec(lines[at])[0];
|
|
118
|
+
const styled = nativeGoalStyledRows(screen)[at]?.slice([...prefix].length).filter(cell => cell.text.trim()) ?? [];
|
|
119
|
+
const placeholder = continuation.length === 0 && first[1].trimEnd() === "Press up to edit queued messages"
|
|
120
|
+
&& styled.length > 0 && styled.some(cell => cell.dim) && styled.every(cell => cell.dim || cell.inverse);
|
|
121
|
+
return { text: placeholder ? "" : [first[1].trimEnd(), ...continuation.map(line => line.slice(2).trimEnd())].join("\n"), columns: lines[at - 1].trim().length, rows: lines.length };
|
|
122
|
+
}
|
|
123
|
+
export function claudeGoalComposerEmpty(screen) {
|
|
124
|
+
return claudeGoalComposer(screen)?.text === "";
|
|
125
|
+
}
|
|
126
|
+
export function observeClaudeGoalDialog(screen, rows, sessionId) {
|
|
127
|
+
const lines = plain(screen).split("\n").map(line => line.trim());
|
|
128
|
+
const knownVersion = lines.some(line => /Claude Code v2\.1\.310(?:\s|$)/u.test(line))
|
|
129
|
+
|| rows.some(value => { const row = value; return row?.sessionId === sessionId && row.isSidechain === false && row.version === "2.1.310"; });
|
|
130
|
+
if (!knownVersion)
|
|
131
|
+
return null;
|
|
132
|
+
let end = lines.length - 1;
|
|
133
|
+
while (end >= 0 && lines[end] !== "Esc to dismiss" && lines[end] !== "/goal clear to stop early · Esc to dismiss")
|
|
134
|
+
end--;
|
|
135
|
+
if (end < 0 || lines.slice(end + 1).some(line => line !== ""))
|
|
136
|
+
return null;
|
|
137
|
+
let current = null;
|
|
138
|
+
let history;
|
|
139
|
+
for (const value of rows) {
|
|
140
|
+
const row = value;
|
|
141
|
+
if (row?.type !== "attachment" || row.attachment?.type !== "goal_status")
|
|
142
|
+
continue;
|
|
143
|
+
if (row.sessionId !== sessionId || row.isSidechain !== false || row.version !== "2.1.310")
|
|
144
|
+
throw new Error("native_goal_binding_mismatch");
|
|
145
|
+
const native = claudeNativeGoalStatusSchema.parse(row.attachment);
|
|
146
|
+
if (native.met) {
|
|
147
|
+
current = null;
|
|
148
|
+
history = { kind: "claude-code", terminal: native.sentinel ? "cleared" : "achieved", native };
|
|
149
|
+
}
|
|
150
|
+
else
|
|
151
|
+
current = native;
|
|
152
|
+
}
|
|
153
|
+
if (lines[end] === "Esc to dismiss" && lines.slice(end - 5, end).filter(Boolean).join("\n") === "Goal\nNo goal set\n/goal <condition> to set one")
|
|
154
|
+
return { current: null, ...(history ? { history } : {}) };
|
|
155
|
+
if (!current || lines[end] !== "/goal clear to stop early · Esc to dismiss")
|
|
156
|
+
return null;
|
|
157
|
+
let header = end - 1;
|
|
158
|
+
while (header >= 0 && lines[header] !== "◎ Goal active")
|
|
159
|
+
header--;
|
|
160
|
+
if (header < 0)
|
|
161
|
+
return null;
|
|
162
|
+
const body = lines.slice(header + 1, end).filter(Boolean);
|
|
163
|
+
// Wrapped/truncated conditions are not a canonical match. Keep the native
|
|
164
|
+
// original and refuse this viewport rather than inventing a normalized goal.
|
|
165
|
+
const conditionLines = current.condition.split("\n");
|
|
166
|
+
// Exact native newlines are supported; no guessed wrapping/whitespace.
|
|
167
|
+
if (conditionLines.some(line => !line || line !== line.trim()))
|
|
168
|
+
return null;
|
|
169
|
+
if (!/^running .+ · .+ tokens$/u.test(body[0]) || JSON.stringify(body.slice(1)) !== JSON.stringify(["Goal: " + conditionLines[0], ...conditionLines.slice(1)]))
|
|
170
|
+
return null;
|
|
171
|
+
return { current: { kind: "claude-code", phase: "active", native: { ...current, met: false } }, ...(history ? { history } : {}) };
|
|
172
|
+
}
|
|
173
|
+
export async function submitClaudeGoalCommand(ui, command) {
|
|
174
|
+
if (!claudeGoalComposerEmpty(ui.read()))
|
|
175
|
+
throw new AgentGoalNotIssuedError("goal_input_not_empty_or_ready");
|
|
176
|
+
await ui.paste(command);
|
|
177
|
+
const now = ui.now ?? (() => performance.now());
|
|
178
|
+
let until = now() + 1500, ready = false;
|
|
179
|
+
do {
|
|
180
|
+
if (claudeGoalComposer(ui.read())?.text === command) {
|
|
181
|
+
ready = true;
|
|
182
|
+
break;
|
|
183
|
+
}
|
|
184
|
+
await ui.pause(40);
|
|
185
|
+
} while (now() < until);
|
|
186
|
+
if (!ready)
|
|
187
|
+
throw new Error("native_goal_status_input_unconfirmed");
|
|
188
|
+
await ui.keys(["Enter"]);
|
|
189
|
+
}
|
|
190
|
+
/** A bounded, fully visible literal objective. Native wrapping and file
|
|
191
|
+
* folding remain unsupported before submission rather than being normalized. */
|
|
192
|
+
export function validateClaudeGoalObjective(objective, screen) {
|
|
193
|
+
if (objective.trim().toLowerCase() === "clear")
|
|
194
|
+
throw new AgentGoalNotIssuedError("native_goal_objective_reserved", "unsupported");
|
|
195
|
+
const lines = objective.split("\n"), composer = claudeGoalComposer(screen);
|
|
196
|
+
if (!composer || composer.text !== "")
|
|
197
|
+
throw new AgentGoalNotIssuedError("goal_input_not_empty_or_ready");
|
|
198
|
+
if (/[\u0000-\u0009\u000b-\u001f\u007f-\u009f\u2028\u2029]/u.test(objective) || lines.some(line => !line || line !== line.trim()))
|
|
199
|
+
throw new AgentGoalNotIssuedError("native_goal_objective_not_representable", "unsupported");
|
|
200
|
+
// This is a conservative upper bound, not a Unicode width approximation:
|
|
201
|
+
// ASCII occupies one cell; every other point is allowed up to two cells.
|
|
202
|
+
const boundedWidth = (line) => [...line].reduce((n, c) => n + (c.codePointAt(0) <= 0x7e ? 1 : 2), 0);
|
|
203
|
+
if (lines.length + 10 > composer.rows || lines.some(line => boundedWidth(line) + 10 > composer.columns))
|
|
204
|
+
throw new AgentGoalNotIssuedError("native_goal_objective_exceeds_viewport", "unsupported");
|
|
205
|
+
}
|
|
206
|
+
export async function setClaudeGoalObjective(ui, objective) {
|
|
207
|
+
validateClaudeGoalObjective(objective, ui.read());
|
|
208
|
+
await submitClaudeGoalCommand(ui, `/goal ${objective}`);
|
|
209
|
+
const now = ui.now ?? (() => performance.now()), until = now() + 1500;
|
|
210
|
+
do {
|
|
211
|
+
if (claudeGoalComposerEmpty(ui.read()))
|
|
212
|
+
return;
|
|
213
|
+
await ui.pause(40);
|
|
214
|
+
} while (now() < until);
|
|
215
|
+
throw new Error("native_goal_set_command_unconfirmed");
|
|
216
|
+
}
|
|
217
|
+
export async function clearClaudeGoal(ui) {
|
|
218
|
+
await submitClaudeGoalCommand(ui, "/goal clear");
|
|
219
|
+
const now = ui.now ?? (() => performance.now()), until = now() + 1500;
|
|
220
|
+
do {
|
|
221
|
+
if (claudeGoalComposerEmpty(ui.read()))
|
|
222
|
+
return;
|
|
223
|
+
await ui.pause(40);
|
|
224
|
+
} while (now() < until);
|
|
225
|
+
throw new Error("native_goal_clear_command_unconfirmed");
|
|
226
|
+
}
|
|
227
|
+
export async function readClaudeGoalDialog(sessionId, ui, readRows) {
|
|
228
|
+
await submitClaudeGoalCommand(ui, "/goal");
|
|
229
|
+
const now = ui.now ?? (() => performance.now());
|
|
230
|
+
let until = now() + 2000;
|
|
231
|
+
do {
|
|
232
|
+
const observation = observeClaudeGoalDialog(ui.read(), readRows(), sessionId);
|
|
233
|
+
if (observation) {
|
|
234
|
+
// Dismiss only the same recognized native goal dialog, once.
|
|
235
|
+
if (!observeClaudeGoalDialog(ui.read(), readRows(), sessionId))
|
|
236
|
+
throw new Error("native_goal_dialog_changed");
|
|
237
|
+
await ui.keys(["Escape"]);
|
|
238
|
+
return observation;
|
|
239
|
+
}
|
|
240
|
+
await ui.pause(40);
|
|
241
|
+
} while (now() < until);
|
|
242
|
+
throw new Error("native_goal_fresh_dialog_unavailable");
|
|
243
|
+
}
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
// Official TUI input lives here; core owns the existing PTY and admission.
|
|
2
|
+
import { codexPaneObservation } from "./codex.js";
|
|
3
|
+
import { AgentGoalNotIssuedError } from "../agent-goal.js";
|
|
4
|
+
import { nativeGoalStyledRows as rows } from "../agent-goal-ui.js";
|
|
5
|
+
const plain = (line) => line.map(x => x.text).join('');
|
|
6
|
+
export function codexGoalUiState(raw) {
|
|
7
|
+
const lines = rows(raw), text = lines.map(plain).join('\n');
|
|
8
|
+
let marker = -1;
|
|
9
|
+
for (let i = 0; i < lines.length; i++)
|
|
10
|
+
if (/^\s*›(?:\s|$)/u.test(plain(lines[i])))
|
|
11
|
+
marker = i;
|
|
12
|
+
if (marker < 0)
|
|
13
|
+
return { kind: 'other', empty: false, text: '' };
|
|
14
|
+
const start = plain(lines[marker]).indexOf('›') + 1;
|
|
15
|
+
const body = [lines[marker].slice(start), ...lines.slice(marker + 1)];
|
|
16
|
+
const header = lines.slice(0, marker).map(plain).join('\n');
|
|
17
|
+
const footer = body.findIndex(line => /^\s*enter submit · esc back\s*$/u.test(plain(line))
|
|
18
|
+
&& line.some(cell => cell.decorated && cell.text.trim()));
|
|
19
|
+
if (/\bEdit goal\s*$/u.test(header.trimEnd()) && footer >= 0) {
|
|
20
|
+
const content = body.slice(0, footer).flat();
|
|
21
|
+
const value = body.slice(0, footer).map((line, i) => plain(line).slice(i === 0 ? 1 : 2).trimEnd()).join('\n').trim();
|
|
22
|
+
const empty = value === 'Type a goal objective and press Enter'
|
|
23
|
+
&& content.filter(c => c.text.trim()).every(c => c.dim);
|
|
24
|
+
return { kind: 'editor', empty, text: empty ? '' : value };
|
|
25
|
+
}
|
|
26
|
+
if (!['idle', 'busy'].includes(codexPaneObservation(text).state))
|
|
27
|
+
return { kind: 'other', empty: false, text: '' };
|
|
28
|
+
const end = body.findIndex(line => {
|
|
29
|
+
const value = plain(line);
|
|
30
|
+
return line.some(c => c.decorated && c.text.trim())
|
|
31
|
+
&& (/^\s*\? for shortcuts|^\s*⚠\s*\d+ warnings|^\s*\S+\s+(?:default|minimal|low|medium|high|xhigh|ultra)\s*·\s/u.test(value));
|
|
32
|
+
});
|
|
33
|
+
const content = (end < 0 ? body : body.slice(0, end));
|
|
34
|
+
const cells = content.flat().filter(c => c.text.trim());
|
|
35
|
+
return { kind: 'composer', empty: cells.every(c => c.dim),
|
|
36
|
+
text: cells.every(c => c.dim) ? '' : content.map((line, i) => plain(line).slice(i === 0 ? 1 : 2).trimEnd()).join('\n').trim() };
|
|
37
|
+
}
|
|
38
|
+
async function wait(ui, predicate) {
|
|
39
|
+
const now = ui.now ?? (() => performance.now());
|
|
40
|
+
const until = now() + 1500;
|
|
41
|
+
do {
|
|
42
|
+
if (predicate(codexGoalUiState(ui.read())))
|
|
43
|
+
return true;
|
|
44
|
+
await ui.pause(40);
|
|
45
|
+
} while (now() < until);
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
export async function submitCodexGoalCommand(ui, command) {
|
|
49
|
+
const before = codexGoalUiState(ui.read());
|
|
50
|
+
if (before.kind !== 'composer' || !before.empty)
|
|
51
|
+
throw new AgentGoalNotIssuedError('goal_input_not_empty_or_ready');
|
|
52
|
+
await ui.paste('/goal ' + command);
|
|
53
|
+
if (!await wait(ui, s => s.kind === 'composer' && s.text === '/goal ' + command))
|
|
54
|
+
throw new Error('Goal command input unconfirmed');
|
|
55
|
+
await ui.keys(['Enter']);
|
|
56
|
+
}
|
|
57
|
+
export function editableCodexGoal(goal) {
|
|
58
|
+
return !!goal && !goal.objective.startsWith('Read the Codex goal objective file at ')
|
|
59
|
+
&& !/[\u0000-\u0009\u000b-\u001f\u007f]/u.test(goal.objective);
|
|
60
|
+
}
|
|
61
|
+
export async function createCodexGoalObjective(ui, objective) {
|
|
62
|
+
if (['clear', 'edit', 'pause', 'resume'].includes(objective.trim().toLowerCase()))
|
|
63
|
+
throw new AgentGoalNotIssuedError('native_goal_create_objective_reserved', 'unsupported');
|
|
64
|
+
if (/[\u0000-\u0009\u000b-\u001f\u007f]/u.test(objective))
|
|
65
|
+
throw new AgentGoalNotIssuedError('native_goal_objective_not_representable', 'unsupported');
|
|
66
|
+
const before = codexGoalUiState(ui.read());
|
|
67
|
+
if (before.kind !== 'composer' || !before.empty)
|
|
68
|
+
throw new AgentGoalNotIssuedError('goal_input_not_empty_or_ready');
|
|
69
|
+
// The official composer folds an individual paste above 1000 characters
|
|
70
|
+
// into an attachment. Complete bounded literal paste events avoid that
|
|
71
|
+
// transformation; core preserves their order on the same input channel.
|
|
72
|
+
const text = '/goal ' + objective;
|
|
73
|
+
let chunk = '';
|
|
74
|
+
for (const character of text) {
|
|
75
|
+
chunk += character;
|
|
76
|
+
if ([...chunk].length >= 128 || character === '\n') {
|
|
77
|
+
await ui.paste(chunk);
|
|
78
|
+
chunk = '';
|
|
79
|
+
await ui.pause(40);
|
|
80
|
+
if (codexGoalUiState(ui.read()).kind !== 'composer')
|
|
81
|
+
throw new Error('Goal creation input owner changed');
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (chunk)
|
|
85
|
+
await ui.paste(chunk);
|
|
86
|
+
const expected = text.split('\n').map(line => line.trimEnd()).join('\n').trim();
|
|
87
|
+
if (!await wait(ui, state => {
|
|
88
|
+
if (state.kind !== 'composer' || state.empty || /\[Pasted (?:Content|Text)/u.test(state.text))
|
|
89
|
+
return false;
|
|
90
|
+
if (state.text === expected)
|
|
91
|
+
return true;
|
|
92
|
+
// A native viewport can hide earlier rows. The last visible row must
|
|
93
|
+
// finish the ordered literal input; canonical readback still compares
|
|
94
|
+
// the complete objective, never a suffix or a display approximation.
|
|
95
|
+
const tail = state.text.split('\n').filter(line => line.trim()).at(-1)?.trim() ?? '';
|
|
96
|
+
return tail.length > 0 && expected.endsWith(tail);
|
|
97
|
+
}))
|
|
98
|
+
throw new Error('Goal creation input unconfirmed');
|
|
99
|
+
await ui.keys(['Enter']);
|
|
100
|
+
}
|
|
101
|
+
export async function editCodexGoalObjective(ui, before, objective) {
|
|
102
|
+
if (!editableCodexGoal(before) || /[\u0000-\u0009\u000b-\u001f\u007f]/u.test(objective))
|
|
103
|
+
throw new AgentGoalNotIssuedError('native_goal_objective_not_representable', 'unsupported');
|
|
104
|
+
await submitCodexGoalCommand(ui, 'edit');
|
|
105
|
+
if (!await wait(ui, s => s.kind === 'editor'))
|
|
106
|
+
throw new Error('Native goal editor unconfirmed');
|
|
107
|
+
let submitted = false;
|
|
108
|
+
try {
|
|
109
|
+
const count = [...new Intl.Segmenter(undefined, { granularity: 'grapheme' }).segment(before.objective)].length;
|
|
110
|
+
await ui.keys(Array(count).fill('BSpace'));
|
|
111
|
+
if (!await wait(ui, s => s.kind === 'editor' && s.empty))
|
|
112
|
+
throw new Error('Native goal editor clearing unconfirmed');
|
|
113
|
+
await ui.paste(objective);
|
|
114
|
+
const visibleObjective = objective.split('\n').map(line => line.trimEnd()).join('\n').trim();
|
|
115
|
+
if (!await wait(ui, s => s.kind === 'editor' && s.text === visibleObjective))
|
|
116
|
+
throw new Error('Native goal editor input unconfirmed');
|
|
117
|
+
// No command can be retried after this boundary.
|
|
118
|
+
submitted = true;
|
|
119
|
+
await ui.keys(['Enter']);
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
if (!submitted && codexGoalUiState(ui.read()).kind === 'editor') {
|
|
123
|
+
// The native prompt handles bare Esc itself. Vim insert takes one Esc
|
|
124
|
+
// before the next cancels; only send another while this editor remains.
|
|
125
|
+
for (let n = 0; n < 2 && codexGoalUiState(ui.read()).kind === 'editor'; n++) {
|
|
126
|
+
await ui.keys(['Escape']);
|
|
127
|
+
await ui.pause(40);
|
|
128
|
+
}
|
|
129
|
+
if (codexGoalUiState(ui.read()).kind === 'composer')
|
|
130
|
+
throw new AgentGoalNotIssuedError('native_goal_editor_input_unconfirmed', 'unsupported');
|
|
131
|
+
}
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// Attach to the existing official native server. No process or thread resume.
|
|
2
|
+
import { withCodexRelay, verifyLoadedParent } from "../codex-relay-client.js";
|
|
3
|
+
import { nativeCodexGoalSocket } from "../codex-goal-connection.js";
|
|
4
|
+
import { withCodexReceiver } from "../codex-parent-receiver.js";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { AgentGoalConnectionError } from "../agent-goal.js";
|
|
7
|
+
import { nativeGoalSchema } from "../agent-goal.js";
|
|
8
|
+
import { editableCodexGoal } from "./codex-goal-editor.js";
|
|
9
|
+
export async function withCodexGoal(target, run, cliControl, cliEdit, cliCreate) {
|
|
10
|
+
if (!target.codex_home || !target.vendor_session_id)
|
|
11
|
+
throw new Error("Codex goal binding unavailable");
|
|
12
|
+
let attached = false;
|
|
13
|
+
try {
|
|
14
|
+
return await withCodexRelay(nativeCodexGoalSocket(target.codex_home), async (request) => {
|
|
15
|
+
await verifyLoadedParent(request, target.vendor_session_id);
|
|
16
|
+
attached = true;
|
|
17
|
+
return run(request);
|
|
18
|
+
}, 15_000, { experimentalApi: true });
|
|
19
|
+
}
|
|
20
|
+
catch (error) {
|
|
21
|
+
// Only topology discovery can select a different read transport. Once
|
|
22
|
+
// attached, no action or failure is replayed through another process.
|
|
23
|
+
if (attached || (error instanceof AgentGoalConnectionError && error.availability === "unsupported"))
|
|
24
|
+
throw error;
|
|
25
|
+
}
|
|
26
|
+
return withCodexReceiver({ thread_id: target.vendor_session_id, codex_home: target.codex_home }, async (request) => {
|
|
27
|
+
const value = await request("thread/read", { threadId: target.vendor_session_id, includeTurns: false });
|
|
28
|
+
if (value?.thread?.id !== target.vendor_session_id)
|
|
29
|
+
throw new Error("Codex goal thread binding mismatch");
|
|
30
|
+
return withOrdinaryCodexGoal(request, target.vendor_session_id, run, cliControl, cliEdit, cliCreate);
|
|
31
|
+
}, { ...(target.executable ? { executable: target.executable } : {}) });
|
|
32
|
+
}
|
|
33
|
+
/** Budget-only updates use the official service without competing for the
|
|
34
|
+
* live rollout writer. Objective/status mutations stay with the owning CLI. */
|
|
35
|
+
export async function withOrdinaryCodexGoal(request, threadId, run, cliControl, cliEdit, cliCreate) {
|
|
36
|
+
const budgetUpdate = z.object({ threadId: z.literal(threadId), origin: z.literal("user"), tokenBudget: z.number().int().positive() }).strict();
|
|
37
|
+
const objectiveUpdate = z.object({ threadId: z.literal(threadId), origin: z.literal("user"), objective: z.string().min(1) }).strict();
|
|
38
|
+
const createUpdate = objectiveUpdate.extend({ status: z.literal("active") });
|
|
39
|
+
let before = null;
|
|
40
|
+
const fields = { create: { objective: !!cliCreate, token_budget: false }, edit: { objective: false, token_budget: true, combined: false } };
|
|
41
|
+
return run(async (method, params) => {
|
|
42
|
+
if (method === "thread/goal/get") {
|
|
43
|
+
const value = await request(method, params);
|
|
44
|
+
before = nativeGoalSchema.nullable().parse(value.goal);
|
|
45
|
+
fields.edit.objective = !!cliEdit && editableCodexGoal(before);
|
|
46
|
+
return value;
|
|
47
|
+
}
|
|
48
|
+
if (method === "thread/goal/set" && budgetUpdate.safeParse(params).success)
|
|
49
|
+
return request(method, params);
|
|
50
|
+
const create = createUpdate.safeParse(params);
|
|
51
|
+
if (method === "thread/goal/set" && create.success && cliCreate && before === null) {
|
|
52
|
+
await cliCreate(create.data.objective);
|
|
53
|
+
const deadline = Date.now() + 3000;
|
|
54
|
+
do {
|
|
55
|
+
const observed = await request("thread/goal/get", { threadId });
|
|
56
|
+
if (observed?.goal?.threadId === threadId && observed.goal.objective === create.data.objective)
|
|
57
|
+
return observed;
|
|
58
|
+
await new Promise(resolve => setTimeout(resolve, 40));
|
|
59
|
+
} while (Date.now() < deadline);
|
|
60
|
+
throw new Error("CLI goal creation acknowledgement unconfirmed");
|
|
61
|
+
}
|
|
62
|
+
const edit = objectiveUpdate.safeParse(params);
|
|
63
|
+
if (method === "thread/goal/set" && edit.success && cliEdit && before) {
|
|
64
|
+
await cliEdit(before, edit.data.objective);
|
|
65
|
+
const deadline = Date.now() + 3000;
|
|
66
|
+
do {
|
|
67
|
+
const observed = await request("thread/goal/get", { threadId });
|
|
68
|
+
if (observed?.goal?.threadId === threadId && observed.goal.objective === edit.data.objective)
|
|
69
|
+
return observed;
|
|
70
|
+
await new Promise(resolve => setTimeout(resolve, 40));
|
|
71
|
+
} while (Date.now() < deadline);
|
|
72
|
+
throw new Error("CLI goal edit acknowledgement unconfirmed");
|
|
73
|
+
}
|
|
74
|
+
const value = params;
|
|
75
|
+
if (!cliControl || value.threadId !== threadId || value.origin !== "user"
|
|
76
|
+
|| Object.keys(value).some(key => !["threadId", "status", "origin"].includes(key)))
|
|
77
|
+
throw new Error("Read-only native goal connection");
|
|
78
|
+
const command = method === "thread/goal/clear" ? "clear"
|
|
79
|
+
: method === "thread/goal/set" && value.status === "paused" ? "pause"
|
|
80
|
+
: method === "thread/goal/set" && value.status === "active" ? "resume" : null;
|
|
81
|
+
if (!command)
|
|
82
|
+
throw new Error("Unsupported CLI goal operation");
|
|
83
|
+
await cliControl(command); // once, through the current CLI's own goal action
|
|
84
|
+
const deadline = Date.now() + 3_000;
|
|
85
|
+
do {
|
|
86
|
+
const observed = await request("thread/goal/get", { threadId });
|
|
87
|
+
if (command === "clear" ? observed?.goal === null : observed?.goal?.threadId === threadId
|
|
88
|
+
&& observed.goal.status === (command === "pause" ? "paused" : "active"))
|
|
89
|
+
return command === "clear" ? { cleared: true } : observed;
|
|
90
|
+
await new Promise(resolve => setTimeout(resolve, 40));
|
|
91
|
+
} while (Date.now() < deadline);
|
|
92
|
+
throw new Error("CLI goal acknowledgement unconfirmed");
|
|
93
|
+
}, { inspect: true, create: !!cliCreate, edit: true, pause: !!cliControl, resume: !!cliControl, clear: !!cliControl }, fields);
|
|
94
|
+
}
|
package/dist/harnesses/cursor.js
CHANGED
|
@@ -256,6 +256,9 @@ export async function observeCursorDone(meta, timeout, requestedCursor, readScre
|
|
|
256
256
|
// 最初の周回では必ず読む(timeout=0の照会も1回は読む)。
|
|
257
257
|
if (screenDue()) {
|
|
258
258
|
const screen = readScreen(meta.aiterm_session);
|
|
259
|
+
const providerFailure = cursorProviderFailure(screen);
|
|
260
|
+
if (providerFailure)
|
|
261
|
+
return observation("error", null, null, providerFailure.message, providerFailure.kind);
|
|
259
262
|
const limited = cursorUsageLimit(screen)?.message ?? null;
|
|
260
263
|
if (limited)
|
|
261
264
|
return observation("rate_limited", null, limited);
|
|
@@ -566,6 +569,27 @@ export function cursorTuiReady(screen) {
|
|
|
566
569
|
return true;
|
|
567
570
|
return /Cursor Agent/i.test(screen) && CURSOR_COMPOSER_MARKER_RE.test(screen);
|
|
568
571
|
}
|
|
572
|
+
/** Current official billing refusal, not an idle/completed turn or an authentication error. */
|
|
573
|
+
export function cursorProviderFailure(screen) {
|
|
574
|
+
const clean = screen.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "");
|
|
575
|
+
const heading = [...clean.matchAll(/^[ \t]*Error:[ \t]*[^\n]*/gim)].at(-1);
|
|
576
|
+
if (!heading)
|
|
577
|
+
return null;
|
|
578
|
+
const current = clean.slice(heading.index);
|
|
579
|
+
const after = clean.slice(heading.index + heading[0].length);
|
|
580
|
+
if (cursorTuiBusy(after) || CURSOR_FOLLOWUP_MARKER_RE.test(after) || CURSOR_START_PROMPT_MARKER_RE.test(after)
|
|
581
|
+
|| after.split("\n").some(line => CURSOR_COMPOSER_CONTENT_MARKER_RE.test(line)))
|
|
582
|
+
return null;
|
|
583
|
+
try {
|
|
584
|
+
const payload = JSON.parse(current.slice(current.indexOf(":") + 1).trim());
|
|
585
|
+
if (payload?.error?.code !== "prepaid_balance_exhausted")
|
|
586
|
+
return null;
|
|
587
|
+
}
|
|
588
|
+
catch {
|
|
589
|
+
return null;
|
|
590
|
+
}
|
|
591
|
+
return { kind: "prepaid_balance_exhausted", message: "Cursor: prepaid_balance_exhausted" };
|
|
592
|
+
}
|
|
569
593
|
// 利用上限に達したCursorは、入力欄も戻さずに説明を出して止まる(2026.09.26-dd393fe、macOSで実測)。
|
|
570
594
|
// transcriptには、user turnを残さずにturn_ended(status "error")だけを書く事がある(実記録で8件)。その時は完了の条件
|
|
571
595
|
// (user turnが増えている)に当たらないので、画面で見る。user turnがある時は、完了待ちが記録から読む(cursorTurnError)。
|
|
@@ -623,6 +647,9 @@ export function cursorPromptHooksRunning(screen) {
|
|
|
623
647
|
}
|
|
624
648
|
export function cursorPaneObservation(screen) {
|
|
625
649
|
const tail = screen.split("\n").slice(-32).join("\n");
|
|
650
|
+
const providerFailure = cursorProviderFailure(tail);
|
|
651
|
+
if (providerFailure)
|
|
652
|
+
return { state: "blocked", reason: providerFailure.kind, detail: providerFailure.message };
|
|
626
653
|
if (cursorUsageLimit(tail))
|
|
627
654
|
return { state: "blocked", reason: "rate_limited" };
|
|
628
655
|
const hookBlocked = cursorHookBlocked(tail);
|