Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 48 additions & 6 deletions lib/kernel/claude_code/claude_code_kernel.dart
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import 'claude_numbers.dart';
import 'claude_sdk_tools.dart';
import 'turn_stats.dart';
import 'control_channel.dart';
import 'forked_runs.dart';
import 'local_time_zone.dart';
import 'tool_result_tally.dart';
import 'usage_limit.dart';
Expand Down Expand Up @@ -139,12 +140,15 @@ class ClaudeCodeKernel
_usageOffBy = usageOffBy ?? _usageOn,
_providers = providers ?? ModelProviders.current,
_providerEnvironment = providerEnvironment ?? providerLaunchEnvironment {
_translator = ClaudeTranslator(
emit: emit,
nextSeq: () => nextSeq,
goalSaid: _syncGoal,
ownModel: _ownModel,
);
_translator =
ClaudeTranslator(
emit: emit,
nextSeq: () => nextSeq,
goalSaid: _syncGoal,
ownModel: _ownModel,
)
..onForkedCommand = _followForked
..onForkedCommandEnded = _forkedEnded;
_providers.addListener(_providersChanged);
ExtensionSwitches.changes?.addListener(_applySwitches);
_live.add(this);
Expand Down Expand Up @@ -327,6 +331,42 @@ class ClaudeCodeKernel
/// kept when null. This machine's sessions only.
static TurnStats? turnStats;

/// Where a skill run from a slash command is read as it goes (main.dart
/// sets it); not read, shown once done, when null (see [ForkedRuns]).
static ForkedRuns? forkedRuns;

/// The runs read as they go, by their messages' parent.
final Map<String, ForkedRun> _followedRuns = {};

/// The environment the CLI last started with, besides the machine's:
/// where it keeps its sessions may be in it.
Map<String, String>? _launchEnv;

/// Reads the run [command] as it goes: this machine's sessions only.
void _followForked(String command) {
final runs = forkedRuns;
final session = _sessionId;
if (runs == null || session == null || _remoteHost != null) return;
_followedRuns.remove(command)?.cancel();
_followedRuns[command] = runs.watch(
cwd: _cwd,
sessionId: session,
env: _launchEnv,
onLine: (line) {
if (!_disposed) _translator.forkedLine(command, line);
},
);
}

void _forkedEnded(String command) => _followedRuns.remove(command)?.finish();

void _stopFollowing() {
for (final run in _followedRuns.values) {
run.cancel();
}
_followedRuns.clear();
}

/// [turnStats] for this session's history: none for a remote one's.
TurnStats? get _turnStats => _remoteHost == null ? turnStats : null;

Expand Down Expand Up @@ -625,6 +665,7 @@ class ClaudeCodeKernel
_contextReported = false;
_appliedSwitches = ExtensionSwitches.current();
final sdkServers = ClaudeSdkTools.serversFor(_cwd);
_launchEnv = env;
final transport = await _start(
_launched = ClaudeLaunch(
cwd: _cwd,
Expand Down Expand Up @@ -952,6 +993,7 @@ class ClaudeCodeKernel
ExtensionSwitches.changes?.removeListener(_applySwitches);
_live.remove(this);
_cancelSdkCalls();
_stopFollowing();
_teardown();
closeEvents();
}
Expand Down
36 changes: 35 additions & 1 deletion lib/kernel/claude_code/claude_code_translator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,16 @@ class ClaudeTranslator {
/// own (`context: fork`), by the id its messages give as their parent
/// (`forked-command-<name>`): no call started it (see [_forkedSkill]).
final Map<String, String> _forkedCommands = {};

/// Told of a skill run from a slash command as it starts, and as it ends,
/// by its messages' parent (`forked-command-<name>`): its messages may be
/// read as it goes ([forkedLine]), the CLI sending them only once done.
void Function(String command)? onForkedCommand;
void Function(String command)? onForkedCommandEnded;

/// Those whose messages came as they went ([forkedLine]): the same, sent
/// all at once at the end, are not shown again.
final Set<String> _followed = {};
final Set<String> _denied = {};

/// Calls made and not answered yet: those of a stopped turn never are.
Expand Down Expand Up @@ -364,6 +374,10 @@ class ClaudeTranslator {

void translate(Map<String, Object?> message) {
final given = message['parent_tool_use_id'] as String?;
if (_followed.contains(given) &&
(message['type'] == 'assistant' || message['type'] == 'user')) {
return;
}
final parent = _forkedCommands[given] ?? given;
switch (message['type']) {
case 'stream_event' when parent == null:
Expand Down Expand Up @@ -2056,7 +2070,9 @@ class ClaudeTranslator {
if (call == null) {
if (description == null || !description.startsWith('/')) return null;
id = taskId;
_forkedCommands['forked-command-${description.substring(1)}'] = id;
final command = 'forked-command-${description.substring(1)}';
_forkedCommands[command] = id;
if (!replaying) onForkedCommand?.call(command);
} else if (skill?.name == 'Skill') {
id = call;
} else {
Expand All @@ -2075,6 +2091,21 @@ class ClaudeTranslator {
return id;
}

/// A line the subagent of the skill run from a slash command [command]
/// wrote, as it went (see [onForkedCommand]): into its card.
void forkedLine(String command, Map<String, Object?> line) {
final card = _forkedCommands[command];
if (card == null) return;
switch (line['type']) {
case 'assistant':
_followed.add(command);
_assistant(line, card);
case 'user':
_followed.add(command);
_user(line, card);
}
}

/// The subagent [toolUseId] started, if one did, now runs on its own.
void _agentToBackground(String? toolUseId) {
final agent = toolUseId == null ? null : _agents[toolUseId];
Expand Down Expand Up @@ -2110,6 +2141,9 @@ class ClaudeTranslator {
String? outputFile,
Map<String, Object?> usage = const {},
}) {
for (final MapEntry(key: command, value: card) in _forkedCommands.entries) {
if (card == taskId) onForkedCommandEnded?.call(command);
}
if (_tasks[taskId] case final task?) {
_tasks[taskId] = task.copyWith(
status: status,
Expand Down
31 changes: 31 additions & 0 deletions lib/kernel/claude_code/forked_runs.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import 'forked_runs_stub.dart'
if (dart.library.io) 'forked_runs_io.dart'
as platform;

/// A skill run from a slash command in a subagent of its own (`/code-review`,
/// `context: fork`): the CLI sends nothing of it until it is done, but
/// writes its messages as it goes, in the session's `subagents/` folder.
/// Read from there, they show in its card as it works (#1131).
abstract interface class ForkedRuns {
/// Follows the run that session [sessionId] (of a project in [cwd], its
/// CLI started with [env] besides the machine's) starts now: each line
/// its subagent writes, to [onLine], from the first.
ForkedRun watch({
required String cwd,
required String sessionId,
Map<String, String>? env,
required void Function(Map<String, Object?> line) onLine,
});
}

/// A run followed ([ForkedRuns.watch]).
abstract interface class ForkedRun {
/// The run is done: what is left of its lines is read, then no more.
void finish();

/// No more lines, at once.
void cancel();
}

/// This machine's; null where there are no files (the web).
ForkedRuns? forkedRunsHere() => platform.forkedRunsHere();
175 changes: 175 additions & 0 deletions lib/kernel/claude_code/forked_runs_io.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:bao_agent/bao_agent.dart' show AgentPaths;
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;

import 'claude_environment.dart';
import 'forked_runs.dart';

ForkedRuns? forkedRunsHere() => ForkedRunFiles();

/// [ForkedRuns] in Claude Code's own files: the session's `subagents/`
/// folder beside its transcript, looked at every [interval].
class ForkedRunFiles implements ForkedRuns {
ForkedRunFiles({
this.interval = const Duration(milliseconds: 700),
@visibleForTesting this.folderOf,
});

final Duration interval;

/// Where session [sessionId]'s subagents write; by default as the CLI
/// does, in its config folder.
final Future<String> Function(
String cwd,
String sessionId,
Map<String, String>? env,
)?
folderOf;

static Future<String> _folder(
String cwd,
String sessionId,
Map<String, String>? env,
) async {
final paths = AgentPaths.from({...await ClaudeEnvironment.of(), ...?env});
final transcript =
paths.findSession(sessionId) ?? paths.sessionFile(cwd, sessionId);
return p.join(p.withoutExtension(transcript), 'subagents');
}

@override
ForkedRun watch({
required String cwd,
required String sessionId,
Map<String, String>? env,
required void Function(Map<String, Object?> line) onLine,
}) => _Tail(
(folderOf ?? _folder)(cwd, sessionId, env),
interval: interval,
onLine: onLine,
)..start();
}

class _Tail implements ForkedRun {
_Tail(this._folder, {required this.interval, required this.onLine});

final Future<String> _folder;
final Duration interval;
final void Function(Map<String, Object?> line) onLine;

/// When it started: a subagent of this run is one made since.
final DateTime _since = DateTime.now().subtract(const Duration(seconds: 2));

Timer? _timer;
bool _done = false;
bool _reading = false;

/// The run's own transcript, once found.
File? _file;
int _offset = 0;
final List<int> _partial = [];

void start() {
_timer = Timer.periodic(interval, (_) => unawaited(_read()));
unawaited(_read());
}

@override
void finish() {
_timer?.cancel();
_timer = null;
unawaited(_read(last: true));
}

@override
void cancel() {
_done = true;
_timer?.cancel();
_timer = null;
}

Future<void> _read({bool last = false}) async {
if (_done || _reading) {
// The last read, after the one under way.
if (last && !_done) {
unawaited(Future<void>.delayed(interval, () => _read(last: true)));
}
return;
}
_reading = true;
try {
final file = _file ??= await _find();
if (file != null) await _readNew(file);
} on Object catch (error) {
debugPrint('Forked run not read: $error');
} finally {
_reading = false;
if (last) _done = true;
}
}

/// The run's subagent: made since it started, by no call (a slash
/// command's) and by no other subagent (those it starts itself).
Future<File?> _find() async {
final folder = Directory(await _folder);
if (!folder.existsSync()) return null;
final found = <(DateTime, File)>[];
await for (final entry in folder.list()) {
if (entry is! File || !entry.path.endsWith('.meta.json')) continue;
final made = entry.statSync().modified;
if (made.isBefore(_since)) continue;
final Object? meta;
try {
meta = jsonDecode(await entry.readAsString());
} on FormatException {
continue; // Being written.
}
if (meta is! Map ||
meta['toolUseId'] != null ||
meta['parentAgentId'] != null) {
continue;
}
final transcript = File(
'${entry.path.substring(0, entry.path.length - '.meta.json'.length)}'
'.jsonl',
);
if (transcript.existsSync()) found.add((made, transcript));
}
if (found.isEmpty) return null;
found.sort((a, b) => a.$1.compareTo(b.$1));
return found.first.$2;
}

Future<void> _readNew(File file) async {
final length = await file.length();
if (length <= _offset) return;
final open = await file.open();
try {
await open.setPosition(_offset);
final bytes = await open.read(length - _offset);
_offset += bytes.length;
_partial.addAll(bytes);
} finally {
await open.close();
}
// Whole lines only: the last may be still being written.
final end = _partial.lastIndexOf(10);
if (end < 0) return;
final text = utf8.decode(_partial.sublist(0, end), allowMalformed: true);
_partial.removeRange(0, end + 1);
for (final line in const LineSplitter().convert(text)) {
if (line.trim().isEmpty || _done) continue;
try {
if (jsonDecode(line) case final Map<String, Object?> message) {
onLine(message);
}
} on FormatException {
// Not a line of its.
}
}
}
}
3 changes: 3 additions & 0 deletions lib/kernel/claude_code/forked_runs_stub.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import 'forked_runs.dart';

ForkedRuns? forkedRunsHere() => null;
4 changes: 4 additions & 0 deletions lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ import 'kernel/claude_code/claude_code_kernel.dart';
import 'kernel/claude_code/claude_core_setting.dart';
import 'kernel/claude_code/claude_onboarding.dart';
import 'kernel/claude_code/claude_path_setting.dart';
import 'kernel/claude_code/forked_runs.dart';
import 'kernel/claude_code/process_transport.dart';
import 'kernel/claude_code/turn_stats_stub.dart'
if (dart.library.io) 'kernel/claude_code/turn_stats_io.dart'
Expand Down Expand Up @@ -590,6 +591,9 @@ void followSettingsFiles(SettingsFiles files) {
ClaudeCodeKernel.turnStats = turnStatsIn(
p.join(DataDirectory.current.path, 'turn-stats'),
);
// A skill run from a slash command, read as it goes from what the CLI
// writes of it (it sends nothing of it until done).
ClaudeCodeKernel.forkedRuns = forkedRunsHere();
// The calls to custom upstreams (Settings → Usage, the side panel's
// Usage page): in the data folder, a file a day, kept as long as the
// user says.
Expand Down
Loading