diff --git a/.agents/skills/testmax-n8n-ai/SKILL.md b/.agents/skills/testmax-n8n-ai/SKILL.md index b4a6ce279a2..fc3e4925e3a 100644 --- a/.agents/skills/testmax-n8n-ai/SKILL.md +++ b/.agents/skills/testmax-n8n-ai/SKILL.md @@ -83,6 +83,7 @@ The most important settings: | `COMPARE_BINARY_CHECKS` | `1` (default) runs the deterministic binary checks of the Instance AI eval suite. `0` turns it off | | `GOOGLE_GENERATIVE_AI_API_KEY`, `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, `MISTRAL_API_KEY`, `GROQ_API_KEY` | Model keys for the real AI runs. A workflow model without a key skips those runs | | `CLAUDE_MODEL`, `CODEX_MODEL` | Model ids. Empty uses the CLI default. A prefix such as `anthropic/` is removed | +| `CODEX_REASONING_EFFORT` | Reasoning effort of Codex: `minimal`, `low`, `medium` (default), `high` or `xhigh`. The Effort column of the page shows the effort of each run | | `COMPARE_CLAUDE_TOOLS` | `none` (default) gives Claude Code only the n8n tools. `default` also gives it its built-in tools, all allowed (see "How the builders run") | | `CLAUDE_API_KEY` | Anthropic key for Claude Code. Falls back to `ANTHROPIC_API_KEY` | | `CODEX_API_KEY` | OpenAI key for Codex. Falls back to `OPENAI_API_KEY` | @@ -641,7 +642,14 @@ The runner answers every confirmation card with one fixed policy, so runs can be compared. It approves actions and plans, picks the first option of a question, allows a domain once, defers workflow and credential setup cards, and denies access to local files and MCP connections. `iai/run.json` lists -each decision. +each decision. After `run-finish`, the runner waits until the thread is idle +for 10 seconds, so it does not miss a background task or a follow-up run. +This wait is not part of the time: `finishedAt` is the time of the last +`run-finish` event. n8n does not report the reasoning effort, so the Effort +column shows the effort that n8n uses for `N8N_INSTANCE_AI_MODEL` and +`N8N_INSTANCE_AI_REASONING_EFFORT`, with the rules of +`apply-agent-thinking.ts`. Claude Code reports its effort in the session +file. Codex reports it in the recorded model request. **Claude Code and Codex** run in a Docker container (`COMPARE_ISOLATION=container`): @@ -689,12 +697,20 @@ By default the CLIs run in interactive mode (`COMPARE_CLI_MODE=interactive`): prompt when the input box shows, plus a short wait, not as an argument. - Claude uses `--permission-mode dontAsk`: the n8n tools are pre-approved, and all other tools are denied without a question. +- When the CLI shows a question picker, the script selects the first + option, which is the recommended option. This is the same policy as for + Instance AI. A picker with several tabs gets one answer for each tab, then + Submit. `/answers.json` lists each answer. - The model key reaches the CLI through a variable that only the CLI reads (`apiKeyHelper` for Claude, a provider `env_key` for Codex). Thus no screen asks to confirm the key or shows part of it, and no key is in a file. - The script reads the session file of the CLI for the progress lines, the end of the turn, the trace and the tokens. Claude Code then shows no cost estimate, so the cost needs the published prices. +- The time on the page is the model turn from the session file + (`turnStartedAt` to `turnFinishedAt` in `run.json`). It does not include + the container start-up, the wait before the prompt is pasted, or the + shutdown. - After each run, the script searches the run folder for the model key and the MCP token. It prints a warning with the file name if it finds one. diff --git a/.agents/skills/testmax-n8n-ai/scripts/build_report.py b/.agents/skills/testmax-n8n-ai/scripts/build_report.py index 4c64ce1ba0c..dbf42ad2bf9 100644 --- a/.agents/skills/testmax-n8n-ai/scripts/build_report.py +++ b/.agents/skills/testmax-n8n-ai/scripts/build_report.py @@ -113,6 +113,11 @@ def read_jsonl(path): def run_seconds(meta): + # A CLI run also spends time on container start-up, the prompt paste wait and shutdown. + if 'turnStartedAt' in meta or 'turnFinishedAt' in meta: + if meta.get('turnStartedAt') and meta.get('turnFinishedAt'): + return ts(meta['turnFinishedAt']) - ts(meta['turnStartedAt']) + return None return ts(meta['finishedAt']) - ts(meta['startedAt']) if meta.get('finishedAt') and meta.get('startedAt') else None @@ -1381,6 +1386,8 @@ def render_row_cells(name, meta, data, result): out = sum(c['out'] for c in calls) cells = [ f'{esc(run_title(name, meta))}', esc(data.get('model') or '-'), + (f'{esc(meta["effort"])}' + if meta.get('effort') and meta.get('effortSource') else esc(meta.get('effort') or '-')), result, data['duration'], str(len(calls)), f'{len(tools)}' + (f' ({errors} err)' if errors else ''), kilo(prompt), f'{100 * cached / prompt:.0f}%' if prompt else '-', kilo(out), cost, @@ -1628,7 +1635,7 @@ def render_brief(prompt, expected): ) -THEAD = ('RunModelResultActive timeLLM callsTool calls' +THEAD = ('RunModelEffortResultActive timeLLM callsTool calls' 'Input tokensCachedOutput tokensCost') diff --git a/.agents/skills/testmax-n8n-ai/scripts/langsmith_usage.py b/.agents/skills/testmax-n8n-ai/scripts/langsmith_usage.py index 47a5237e9ec..e8a273dfdfc 100644 --- a/.agents/skills/testmax-n8n-ai/scripts/langsmith_usage.py +++ b/.agents/skills/testmax-n8n-ai/scripts/langsmith_usage.py @@ -7,7 +7,8 @@ LANGSMITH_PROJECT from the config (see n8n_api.config). langsmith_usage.py --run-dir /iai -It takes all LLM runs in the project between startedAt and finishedAt from run.json. +It takes all LLM runs in the project between startedAt and finishedAt from run.json +(usageFinishedAt when it is set). Do not start other Instance AI work on the same instance during the run, or use --by-trace. langsmith_usage.py --run-dir --by-trace @@ -150,7 +151,7 @@ def main(): traces = set(meta.get('langsmithRunIds') or []) if args.by_trace and not traces: raise SystemExit('run.json has no langsmithRunIds. Is LANGSMITH_TRACING=true on the instance?') - calls = fetch_calls(meta['startedAt'], meta['finishedAt'], traces if args.by_trace else None) + calls = fetch_calls(meta['startedAt'], meta.get('usageFinishedAt') or meta['finishedAt'], traces if args.by_trace else None) (run_dir / 'usage.json').write_text(json.dumps(calls, indent=1)) (run_dir / 'context.json').write_text(json.dumps(fetch_contexts(calls), indent=1)) print(json.dumps(totals(calls), indent=2)) diff --git a/.agents/skills/testmax-n8n-ai/scripts/run_cli_builder.py b/.agents/skills/testmax-n8n-ai/scripts/run_cli_builder.py index 49af4d1296e..04f5107f3a6 100644 --- a/.agents/skills/testmax-n8n-ai/scripts/run_cli_builder.py +++ b/.agents/skills/testmax-n8n-ai/scripts/run_cli_builder.py @@ -130,12 +130,43 @@ def codex_interactive_args(model): return args +def codex_effort_setting(): + return setting('CODEX_REASONING_EFFORT', default='medium') + + +def run_effort(builder, session_file, out): + """The reasoning effort that the model got: from the session file for Claude Code, and from the + recorded request for Codex. Without a recorded request, the Codex effort is the configured one.""" + if builder == 'claude': + if session_file and session_file.exists(): + for line in reversed(session_file.read_text().splitlines()): + try: + row = json.loads(line) + except json.JSONDecodeError: + continue + if row.get('type') == 'assistant' and row.get('effort'): + return row['effort'], 'session file' + return None, None + requests = out / 'requests.jsonl' + if requests.exists(): + for line in requests.read_text().splitlines(): + try: + body = json.loads(line) + except json.JSONDecodeError: + continue + effort = ((body.get('body', body)).get('reasoning') or {}).get('effort') + if effort: + return effort, 'model request' + return codex_effort_setting(), 'CODEX_REASONING_EFFORT' + + def write_codex_config(home, url, key_env=None, api_base=OPENAI_BASE_URL): """Write config.toml. With key_env, a provider reads the key from that variable, so the interactive screen does not ask for a sign-in and no key is stored in auth.json.""" codex_home = home / '.codex' codex_home.mkdir(parents=True, exist_ok=True) - lines = ['approval_policy = "never"', 'sandbox_mode = "read-only"'] + lines = ['approval_policy = "never"', 'sandbox_mode = "read-only"', + f'model_reasoning_effort = "{codex_effort_setting()}"'] if key_env: lines.append('model_provider = "sandbox-openai"') lines += ['', '[features]'] + [f'{name} = false' for name in CODEX_FEATURES_OFF] @@ -320,6 +351,28 @@ class SessionReader: return rows +def turn_span(builder, session_file): + """Start and end of the model turn in the session file, without container start-up, the prompt paste + wait and shutdown. (None, None) when the file has no turn.""" + if not session_file or not session_file.exists(): + return None, None + rows = [] + for line in session_file.read_text().splitlines(): + try: + rows.append(json.loads(line)) + except json.JSONDecodeError: + continue + if builder == 'claude': + users = [r['timestamp'] for r in rows if r.get('type') == 'user' and r.get('timestamp')] + replies = [r['timestamp'] for r in rows if r.get('type') == 'assistant' and r.get('timestamp')] + return (users[0], replies[-1]) if users and replies else (None, None) + starts = [r['timestamp'] for r in rows + if r.get('type') == 'event_msg' and (r.get('payload') or {}).get('type') == 'task_started'] + ends = [r['timestamp'] for r in rows + if r.get('type') == 'event_msg' and (r.get('payload') or {}).get('type') == 'task_complete'] + return (starts[0], ends[-1]) if starts and ends else (None, None) + + def docker_command(container, out, env_names): cmd = [ 'docker', 'run', '--rm', '-i', '--name', container, @@ -403,6 +456,43 @@ def run_headless(args, out, prompt, cmd, run_env, cwd, container): 'reportedCostUsd': (result or {}).get('total_cost_usd')} +# The review screen of a picker with several tabs has no footer, only the submit question. +QUESTION_MARKERS = ('Enter to select', 'Ready to submit your answers?') +ANSWER_SETTLE_S = 2 + + +class QuestionAnswerer: + """Answers a question picker on the CLI screen with its first option, like the Instance AI runner. + + The first option is the recommended one. A picker with several tabs gets one Enter per tab, then Submit. + """ + + def __init__(self, container, log_path): + self.container, self.log_path, self.answers, self.seen_at, self.last_screen = container, log_path, [], None, None + + def poll(self): + screen = subprocess.run(['docker', 'exec', self.container, 'tmux', 'capture-pane', '-p', '-t', 'run'], + capture_output=True, text=True).stdout + if not any(marker in screen for marker in QUESTION_MARKERS): + self.last_screen, self.seen_at = None, None + return None + # Wait until the picker stops changing, so a key press does not land while it draws. + if screen != self.last_screen: + self.last_screen, self.seen_at = screen, time.time() + return None + if time.time() - self.seen_at < ANSWER_SETTLE_S: + return None + subprocess.run(['docker', 'exec', self.container, 'tmux', 'send-keys', '-t', 'run', 'Enter'], + capture_output=True) + question = QUESTION_MARKERS[1] if QUESTION_MARKERS[1] in screen else next( + (l.strip() for l in screen.splitlines() if l.strip().endswith('?')), '') + option = next((l.strip().lstrip('❯ ').strip() for l in screen.splitlines() if l.strip().startswith('❯ 1.')), '') + self.answers.append({'at': time.time(), 'question': question, 'answer': option or 'first option'}) + self.log_path.write_text(json.dumps(self.answers, indent=2, ensure_ascii=False)) + self.last_screen, self.seen_at = None, None + return f'answered "{question[:80]}" with "{option[:80] or "first option"}"' + + def run_interactive(args, out, home, prompt, run_env, container): screen_dir = out / '.screen' argv = (claude_interactive_args(args.model, args.claude_tools) if args.builder == 'claude' @@ -425,10 +515,15 @@ def run_interactive(args, out, home, prompt, run_env, container): if live_enabled() and not open_terminal(LABELS[args.builder], watch, SCREEN['cols'], SCREEN['rows']): print(f'watch {LABELS[args.builder]}: {watch}', flush=True) deadline, last_growth = time.time() + args.timeout_min * 60, time.time() + answerer = QuestionAnswerer(container, out / 'answers.json') if args.isolation == 'container' else None while proc.poll() is None and not state: rows = reader.rows() if rows: last_growth = time.time() + answered = answerer.poll() if answerer else None + if answered: + print(f'[{args.builder}] {answered}', flush=True) + last_growth = time.time() for row in rows: lines, row_state = session_lines(args.builder, row) for line in lines: @@ -584,6 +679,8 @@ def main(): result = run_headless(args, out, prompt, cmd, run_env, str(work), container) session_file = find_session_file(args.builder, home, result['sessionId']) + turn_started_at, turn_finished_at = turn_span(args.builder, session_file) + effort, effort_source = run_effort(args.builder, session_file, out) meta = { 'kind': args.builder, 'isolation': args.isolation, @@ -592,6 +689,10 @@ def main(): **({'claudeTools': args.claude_tools} if args.builder == 'claude' else {}), 'startedAt': started_at, 'finishedAt': now_iso(), + 'turnStartedAt': turn_started_at, + 'turnFinishedAt': turn_finished_at, + 'effort': effort, + 'effortSource': effort_source, 'exitCode': result['exitCode'], 'sessionId': result['sessionId'], 'sessionFile': str(session_file.relative_to(out)) if session_file else None, diff --git a/.agents/skills/testmax-n8n-ai/scripts/run_instance_ai.py b/.agents/skills/testmax-n8n-ai/scripts/run_instance_ai.py index bee2bbcda25..14a98a252ee 100644 --- a/.agents/skills/testmax-n8n-ai/scripts/run_instance_ai.py +++ b/.agents/skills/testmax-n8n-ai/scripts/run_instance_ai.py @@ -31,7 +31,7 @@ from pathlib import Path from live import enabled as live_enabled from live import open_url, recording -from n8n_api import N8nClient +from n8n_api import N8nClient, setting DEFAULT_TEXT_ANSWER = 'Use sensible defaults and continue.' HERE = Path(__file__).resolve().parent @@ -82,6 +82,33 @@ class Recorder: self.proc.kill() +ANTHROPIC_EFFORTS = ('low', 'medium', 'high', 'xhigh', 'max') +CUSTOM_EFFORTS = ('none', 'minimal', *ANTHROPIC_EFFORTS) +# Keep in sync with instance-ai.config.ts and CUSTOM_MODEL_DEFAULTS in utils/custom-model-defaults.ts. +DEFAULT_INSTANCE_AI_MODEL = 'anthropic/claude-opus-4-8' +CUSTOM_MODEL_EFFORTS = (('kimi-k3', 'low'), ('glm-5.2', 'medium')) + + +def configured_effort(): + """The orchestrator effort that n8n uses for N8N_INSTANCE_AI_MODEL, with the rules of + packages/@n8n/instance-ai/src/agent/apply-agent-thinking.ts. n8n does not report the effort, so this + reads the settings that the server reads. None when the provider has no fixed effort.""" + model = (setting('N8N_INSTANCE_AI_MODEL') or DEFAULT_INSTANCE_AI_MODEL).lower() + provider = model.split('/', 1)[0] if '/' in model else '' + effort = (setting('N8N_INSTANCE_AI_REASONING_EFFORT') or '').strip().lower() + if provider in ('anthropic', 'google-vertex-anthropic'): + return effort if effort in ANTHROPIC_EFFORTS else 'medium' + if provider in ('custom', 'moonshotai'): + if effort in CUSTOM_EFFORTS: + return effort + return next((e for match, e in CUSTOM_MODEL_EFFORTS if match in model), None) + if provider == 'openai': + return 'medium' if 'gpt-5.6' in model else 'high' + if provider == 'xai' and 'grok-4.5' in model: + return 'medium' + return None + + def now_iso(): return datetime.now(timezone.utc).isoformat() @@ -205,7 +232,8 @@ def main(): open_url(thread_url) workflow_ids, decisions, langsmith_run_ids = [], [], [] - saw_finish, idle_since = False, None + # The idle wait after run-finish is the runner's, so the run ends at the last run-finish. + saw_finish, idle_since, finish_ts = False, None, None deadline = time.time() + args.timeout_min * 60 while time.time() < deadline: try: @@ -221,9 +249,10 @@ def main(): if etype == 'run-start': if payload.get('langsmithRunId'): langsmith_run_ids.append(payload['langsmithRunId']) - idle_since = None + idle_since, finish_ts = None, None elif etype == 'run-finish': saw_finish = True + finish_ts = event.get('ts') or time.time() * 1000 print(f'run-finish {payload.get("status", "")}', flush=True) elif etype == 'tool-call': print(f'tool {payload.get("toolName")}', flush=True) @@ -255,7 +284,10 @@ def main(): else: print('timeout: the thread did not go idle', flush=True) - finished_at = now_iso() + finished_at = (datetime.fromtimestamp(finish_ts / 1000, timezone.utc).isoformat() if finish_ts + else now_iso()) + # Background tasks can still call the LLM after run-finish, so the usage window ends at idle. + usage_finished_at = now_iso() stop.set() events_file.close() recorder.stop() @@ -279,10 +311,13 @@ def main(): 'threadId': thread_id, 'startedAt': started_at, 'finishedAt': finished_at, + 'usageFinishedAt': usage_finished_at, 'workflowIds': workflow_ids, 'workflowId': workflow_ids[-1] if workflow_ids else None, 'langsmithRunIds': langsmith_run_ids, 'decisions': decisions, + 'effort': configured_effort(), + 'effortSource': 'n8n settings (N8N_INSTANCE_AI_MODEL, N8N_INSTANCE_AI_REASONING_EFFORT)', 'threadUrl': thread_url, 'screen': 'screen.webm' if (out / 'screen.webm').exists() else None, } diff --git a/.env.ai-surfaces.example b/.env.ai-surfaces.example index cbf7ebabf21..af53d7d4f26 100644 --- a/.env.ai-surfaces.example +++ b/.env.ai-surfaces.example @@ -63,6 +63,8 @@ CLAUDE_API_KEY= # --- Codex + n8n MCP ----------------------------------------------------------- # Empty model uses the Codex default. CODEX_MODEL= +# Reasoning effort of Codex: minimal, low, medium, high or xhigh. Empty uses medium. +CODEX_REASONING_EFFORT= # Falls back to OPENAI_API_KEY. CODEX_API_KEY=