killeros 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Killeros.ts CHANGED
@@ -1,7 +1,9 @@
1
- import { execFileSync } from "node:child_process";
2
- import { readFileSync } from "node:fs";
1
+ import { execFileSync, spawn } from "node:child_process";
2
+ import { promises as fs, closeSync, existsSync, openSync, readFileSync, readSync } from "node:fs";
3
3
  import os from "node:os";
4
+ import path from "node:path";
4
5
  import {
6
+ CONFIG_DIR_NAME,
5
7
  CustomEditor,
6
8
  DynamicBorder,
7
9
  VERSION,
@@ -17,6 +19,7 @@ import {
17
19
  decodeKittyPrintable,
18
20
  Editor,
19
21
  Key,
22
+ Markdown,
20
23
  matchesKey,
21
24
  SelectList,
22
25
  Text,
@@ -28,6 +31,7 @@ import {
28
31
  type TUI,
29
32
  } from "@earendil-works/pi-tui";
30
33
  import { Type } from "typebox";
34
+ import { registerSubagentTool } from "./subagents.ts";
31
35
 
32
36
  const COMMAND_BLUE_RGB = "120;169;255";
33
37
  const FOOTER_REFRESH_INTERVAL_MS = 1_000;
@@ -321,9 +325,771 @@ function registerConcisePrompt(pi: ExtensionAPI): void {
321
325
  }));
322
326
  }
323
327
 
328
+ const INIT_READ_ONLY_TOOLS = new Set(["read", "ls", "find", "grep"]);
329
+
330
+ interface InitWorkflowState {
331
+ active: boolean;
332
+ targetPath?: string;
333
+ writeAttempted: boolean;
334
+ writeSucceeded: boolean;
335
+ writeToolCallId?: string;
336
+ settle?: (writeSucceeded: boolean) => void;
337
+ }
338
+
339
+ function resetInitState(state: InitWorkflowState): void {
340
+ state.active = false;
341
+ state.targetPath = undefined;
342
+ state.writeAttempted = false;
343
+ state.writeSucceeded = false;
344
+ state.writeToolCallId = undefined;
345
+ }
346
+
347
+ const GOAL_ENTRY_TYPE = "killeros-goal";
348
+ const GOAL_CONTINUATION_TYPE = "killeros-goal-continuation";
349
+ const GOAL_OBJECTIVE_LIMIT = 4_000;
350
+ const GOAL_VERSION = 1;
351
+
352
+ type GoalStatus = "active" | "paused" | "blocked" | "complete";
353
+ type GoalEntryEvent = "set" | "replace" | "edit" | "turn" | "pause" | "resume" | "blocked" | "complete" | "error" | "clear" | "checkpoint";
354
+
355
+ interface GoalState {
356
+ version: 1;
357
+ revision: number;
358
+ objective: string;
359
+ status: GoalStatus;
360
+ createdAt: number;
361
+ updatedAt: number;
362
+ activeMilliseconds: number;
363
+ activeStartedAt?: number;
364
+ turns: number;
365
+ blockedAuditStartTurn: number;
366
+ baselineTokens: number;
367
+ result?: string;
368
+ }
369
+
370
+ interface GoalEntryData {
371
+ version: 1;
372
+ event: GoalEntryEvent;
373
+ state: GoalState | null;
374
+ }
375
+
376
+ interface GoalRuntime {
377
+ state?: GoalState;
378
+ continuationScheduled: boolean;
379
+ continuationHeld: boolean;
380
+ goalTurnInFlight: boolean;
381
+ agentEndObserved: boolean;
382
+ persistenceRetryNeeded: boolean;
383
+ lastStopReason?: string;
384
+ lastError?: string;
385
+ requestRender?: () => void;
386
+ }
387
+
388
+ const GoalUpdateParams = Type.Object({
389
+ status: Type.Union([Type.Literal("complete"), Type.Literal("blocked")], {
390
+ description: "Mark the active goal complete or blocked",
391
+ }),
392
+ evidence: Type.String({
393
+ minLength: 1,
394
+ maxLength: 2_000,
395
+ description: "Concise evidence that the objective is complete, or the repeated blocker and attempted workarounds",
396
+ }),
397
+ });
398
+
399
+ interface GoalUpdateDetails {
400
+ status: "complete" | "blocked";
401
+ evidence: string;
402
+ }
403
+
404
+ function isGoalStatus(value: unknown): value is GoalStatus {
405
+ return value === "active" || value === "paused" || value === "blocked" || value === "complete";
406
+ }
407
+
408
+ function finiteNonNegative(value: unknown): value is number {
409
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
410
+ }
411
+
412
+ function parseGoalState(value: unknown): GoalState | undefined {
413
+ if (!value || typeof value !== "object") return undefined;
414
+ const candidate = value as Partial<GoalState>;
415
+ if (candidate.version !== GOAL_VERSION
416
+ || !Number.isInteger(candidate.revision) || (candidate.revision ?? 0) < 1
417
+ || typeof candidate.objective !== "string" || !candidate.objective.trim()
418
+ || [...candidate.objective].length > GOAL_OBJECTIVE_LIMIT
419
+ || !isGoalStatus(candidate.status)
420
+ || !finiteNonNegative(candidate.createdAt)
421
+ || !finiteNonNegative(candidate.updatedAt)
422
+ || !finiteNonNegative(candidate.activeMilliseconds)
423
+ || !Number.isInteger(candidate.turns) || (candidate.turns ?? -1) < 0
424
+ || candidate.blockedAuditStartTurn !== undefined
425
+ && (!Number.isInteger(candidate.blockedAuditStartTurn) || candidate.blockedAuditStartTurn < 0 || candidate.blockedAuditStartTurn > candidate.turns!)
426
+ || !finiteNonNegative(candidate.baselineTokens)
427
+ || candidate.activeStartedAt !== undefined && !finiteNonNegative(candidate.activeStartedAt)
428
+ || candidate.result !== undefined && typeof candidate.result !== "string") {
429
+ return undefined;
430
+ }
431
+ return {
432
+ version: GOAL_VERSION,
433
+ revision: candidate.revision!,
434
+ objective: candidate.objective.trim(),
435
+ status: candidate.status,
436
+ createdAt: candidate.createdAt,
437
+ updatedAt: candidate.updatedAt,
438
+ activeMilliseconds: candidate.activeMilliseconds,
439
+ activeStartedAt: candidate.activeStartedAt,
440
+ turns: candidate.turns!,
441
+ blockedAuditStartTurn: candidate.blockedAuditStartTurn ?? 0,
442
+ baselineTokens: candidate.baselineTokens,
443
+ result: candidate.result,
444
+ };
445
+ }
446
+
447
+ function goalBranchEntries(ctx: ExtensionContext): ReturnType<ExtensionContext["sessionManager"]["getEntries"]> {
448
+ try {
449
+ return ctx.sessionManager.getBranch();
450
+ } catch {
451
+ return [];
452
+ }
453
+ }
454
+
455
+ function restoreGoalState(ctx: ExtensionContext): GoalState | undefined {
456
+ const entries = goalBranchEntries(ctx);
457
+ for (let index = entries.length - 1; index >= 0; index -= 1) {
458
+ const entry = entries[index];
459
+ if (entry?.type !== "custom" || entry.customType !== GOAL_ENTRY_TYPE) continue;
460
+ const data = entry.data as Partial<GoalEntryData> | undefined;
461
+ if (!data || data.version !== GOAL_VERSION) return undefined;
462
+ if (data.state === null) return undefined;
463
+ const restored = parseGoalState(data.state);
464
+ if (!restored) return undefined;
465
+ return restored.status === "active"
466
+ ? { ...restored, activeStartedAt: Date.now() }
467
+ : { ...restored, activeStartedAt: undefined };
468
+ }
469
+ return undefined;
470
+ }
471
+
472
+ function goalElapsedMilliseconds(state: GoalState, now = Date.now()): number {
473
+ const activeInterval = state.status === "active" && state.activeStartedAt !== undefined
474
+ ? Math.max(0, now - state.activeStartedAt)
475
+ : 0;
476
+ return state.activeMilliseconds + activeInterval;
477
+ }
478
+
479
+ function stopGoalClock(state: GoalState, now: number): GoalState {
480
+ if (state.status !== "active" || state.activeStartedAt === undefined) return state;
481
+ return {
482
+ ...state,
483
+ activeMilliseconds: state.activeMilliseconds + Math.max(0, now - state.activeStartedAt),
484
+ activeStartedAt: undefined,
485
+ };
486
+ }
487
+
488
+ function sumGoalTokens(ctx: ExtensionContext): number {
489
+ let total = 0;
490
+ for (const entry of goalBranchEntries(ctx)) {
491
+ if (entry.type === "message" && (entry.message.role === "assistant" || entry.message.role === "toolResult")) {
492
+ total += entry.message.usage?.totalTokens ?? 0;
493
+ } else if ((entry.type === "compaction" || entry.type === "branch_summary") && entry.usage) {
494
+ total += entry.usage.totalTokens;
495
+ }
496
+ }
497
+ return total;
498
+ }
499
+
500
+ function persistGoalState(
501
+ pi: ExtensionAPI,
502
+ runtime: GoalRuntime,
503
+ event: GoalEntryEvent,
504
+ state: GoalState | undefined,
505
+ ): void {
506
+ const data: GoalEntryData = { version: GOAL_VERSION, event, state: state ?? null };
507
+ pi.appendEntry(GOAL_ENTRY_TYPE, data);
508
+ runtime.state = state;
509
+ runtime.persistenceRetryNeeded = false;
510
+ runtime.requestRender?.();
511
+ }
512
+
513
+ function transitionGoal(
514
+ pi: ExtensionAPI,
515
+ runtime: GoalRuntime,
516
+ event: GoalEntryEvent,
517
+ status: GoalStatus,
518
+ result?: string,
519
+ resetBlockedAudit = false,
520
+ ): GoalState {
521
+ const current = runtime.state;
522
+ if (!current) throw new Error("No goal is set");
523
+ const now = Date.now();
524
+ const stopped = stopGoalClock(current, now);
525
+ const next: GoalState = {
526
+ ...stopped,
527
+ revision: stopped.revision + 1,
528
+ status,
529
+ updatedAt: now,
530
+ activeStartedAt: status === "active" ? now : undefined,
531
+ blockedAuditStartTurn: resetBlockedAudit ? stopped.turns : stopped.blockedAuditStartTurn,
532
+ result,
533
+ };
534
+ persistGoalState(pi, runtime, event, next);
535
+ if (status !== "active") runtime.continuationScheduled = false;
536
+ return next;
537
+ }
538
+
539
+ function goalStatusLabel(status: GoalStatus): string {
540
+ return `${status.charAt(0).toLocaleUpperCase()}${status.slice(1)}`;
541
+ }
542
+
543
+ function goalStatusSummary(state: GoalState, ctx: ExtensionContext): string {
544
+ const usedTokens = Math.max(0, sumGoalTokens(ctx) - state.baselineTokens);
545
+ const lines = [
546
+ `Goal ${goalStatusLabel(state.status).toLocaleLowerCase()} · ${state.turns} turn${state.turns === 1 ? "" : "s"} · ${formatTime(goalElapsedMilliseconds(state))} · ${formatTokens(usedTokens)} tokens`,
547
+ state.objective,
548
+ ];
549
+ if (state.result) lines.push(state.result);
550
+ return lines.join("\n");
551
+ }
552
+
553
+ function pauseGoalAfterFailure(
554
+ pi: ExtensionAPI,
555
+ runtime: GoalRuntime,
556
+ ctx: ExtensionContext,
557
+ reason: string,
558
+ recoveryInstruction = "Run /goal resume after resolving the problem.",
559
+ ): void {
560
+ if (runtime.state?.status !== "active") return;
561
+ try {
562
+ transitionGoal(pi, runtime, "error", "paused", reason);
563
+ } catch {
564
+ runtime.state = runtime.state ? { ...stopGoalClock(runtime.state, Date.now()), status: "paused", result: reason } : undefined;
565
+ runtime.persistenceRetryNeeded = true;
566
+ runtime.continuationScheduled = false;
567
+ runtime.requestRender?.();
568
+ }
569
+ ctx.ui.notify(`Goal paused: ${reason}\n${recoveryInstruction}`, "error");
570
+ }
571
+
572
+ function scheduleGoalContinuation(
573
+ pi: ExtensionAPI,
574
+ runtime: GoalRuntime,
575
+ initState: InitWorkflowState,
576
+ ctx: ExtensionContext,
577
+ ): void {
578
+ if (!isGoalModeSupported(ctx)
579
+ || !isSavedSession(ctx)
580
+ || runtime.state?.status !== "active"
581
+ || runtime.continuationScheduled
582
+ || runtime.continuationHeld
583
+ || initState.active
584
+ || ctx.hasPendingMessages()) return;
585
+ const current = runtime.state;
586
+ const now = Date.now();
587
+ const next: GoalState = {
588
+ ...current,
589
+ revision: current.revision + 1,
590
+ turns: current.turns + 1,
591
+ updatedAt: now,
592
+ activeStartedAt: current.activeStartedAt ?? now,
593
+ };
594
+ try {
595
+ persistGoalState(pi, runtime, "turn", next);
596
+ } catch (error) {
597
+ pauseGoalAfterFailure(pi, runtime, ctx, `continuation state could not be saved: ${error instanceof Error ? error.message : String(error)}`);
598
+ return;
599
+ }
600
+
601
+ runtime.continuationScheduled = true;
602
+ runtime.goalTurnInFlight = true;
603
+ runtime.agentEndObserved = false;
604
+ runtime.lastStopReason = undefined;
605
+ runtime.lastError = undefined;
606
+ try {
607
+ pi.sendMessage({
608
+ customType: GOAL_CONTINUATION_TYPE,
609
+ content: goalContinuationMessage(next, ctx),
610
+ display: false,
611
+ }, { triggerTurn: true, deliverAs: "followUp" });
612
+ } catch (error) {
613
+ runtime.continuationScheduled = false;
614
+ runtime.goalTurnInFlight = false;
615
+ pauseGoalAfterFailure(pi, runtime, ctx, `continuation could not start: ${error instanceof Error ? error.message : String(error)}`);
616
+ }
617
+ }
618
+
619
+ function goalInstructions(state: GoalState, heading: string): string {
620
+ return [
621
+ `# ${heading}`,
622
+ `Status: active · Turn: ${state.turns}`,
623
+ "Objective:",
624
+ state.objective,
625
+ "",
626
+ "Continue making concrete progress toward this unchanged objective. Re-check repository state and prior results instead of repeating work.",
627
+ "Do not stop merely because one response is complete: KillerOS will start another goal turn while the goal remains active.",
628
+ "Before declaring completion, audit every part of the objective and verify the relevant results. Then call killeros_goal_update with status complete and concise evidence.",
629
+ "Call killeros_goal_update with status blocked only when the same external impasse has prevented progress for three consecutive goal turns; name the blocker and attempted workarounds.",
630
+ "Never use the goal tool to pause, resume, edit, replace, or clear the objective. Those transitions belong to the user.",
631
+ ].join("\n");
632
+ }
633
+
634
+ function goalSystemPrompt(state: GoalState): string {
635
+ return goalInstructions(state, "Active KillerOS goal");
636
+ }
637
+
638
+ function goalContinuationMessage(state: GoalState, ctx: ExtensionContext): string {
639
+ const sections = [goalInstructions(state, "KillerOS long-running goal turn")];
640
+ if (ctx.isProjectTrusted()) {
641
+ const personal = resolvePersonalInstructions(ctx.cwd);
642
+ if (personal) {
643
+ sections.push(`<personal_instructions source=${JSON.stringify(personal.source)}>\n${personal.content}\n</personal_instructions>`);
644
+ }
645
+ }
646
+ sections.push(CONCISE_SYSTEM_PROMPT);
647
+ return sections.join("\n\n");
648
+ }
649
+
650
+ function isGoalModeSupported(ctx: ExtensionContext): boolean {
651
+ return ctx.mode === "tui" || ctx.mode === "rpc";
652
+ }
653
+
654
+ function isSavedSession(ctx: ExtensionContext): boolean {
655
+ try {
656
+ return Boolean(ctx.sessionManager.getSessionFile());
657
+ } catch {
658
+ return false;
659
+ }
660
+ }
661
+
662
+ function validateGoalObjective(input: string): string | undefined {
663
+ const objective = input.trim();
664
+ if (!objective) return undefined;
665
+ return [...objective].length <= GOAL_OBJECTIVE_LIMIT ? objective : undefined;
666
+ }
667
+
668
+ function registerGoal(
669
+ pi: ExtensionAPI,
670
+ runtime: GoalRuntime,
671
+ initState: InitWorkflowState,
672
+ ): void {
673
+ pi.registerEntryRenderer<GoalEntryData>(GOAL_ENTRY_TYPE, (entry, _options, theme) => {
674
+ const data = entry.data;
675
+ if (!data || data.version !== GOAL_VERSION || data.event === "turn" || data.event === "checkpoint") return undefined;
676
+ if (data.event === "clear" || data.state === null) return new Text(theme.fg("dim", "Goal cleared"), 0, 0);
677
+ const state = parseGoalState(data.state);
678
+ if (!state) return undefined;
679
+ const icon = state.status === "active" ? "✻" : state.status === "paused" ? "Ⅱ" : state.status === "blocked" ? "!" : "✓";
680
+ const color: ThemeColor = state.status === "active" ? "accent" : state.status === "paused" ? "warning" : state.status === "blocked" ? "error" : "success";
681
+ return new Text(`${theme.fg(color, `${icon} Goal ${state.status}`)}${theme.fg("dim", ` · ${state.objective}`)}`, 0, 0);
682
+ });
683
+
684
+ pi.registerTool<typeof GoalUpdateParams, GoalUpdateDetails>({
685
+ name: "killeros_goal_update",
686
+ label: "Goal update",
687
+ description: "Mark the active KillerOS long-running goal complete after verification, or blocked after the same impasse persists for three consecutive goal turns.",
688
+ parameters: GoalUpdateParams,
689
+ executionMode: "sequential",
690
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
691
+ if (!isGoalModeSupported(ctx)) throw new Error("KillerOS goals require TUI or RPC mode");
692
+ if (!isSavedSession(ctx)) throw new Error("KillerOS goals require a saved session");
693
+ const state = runtime.state;
694
+ if (!state || state.status !== "active") throw new Error("There is no active KillerOS goal to update");
695
+ const evidence = params.evidence.trim();
696
+ if (!evidence) throw new Error("Goal evidence must not be empty");
697
+ if (params.status === "blocked" && state.turns - state.blockedAuditStartTurn < 3) {
698
+ throw new Error("A goal cannot be marked blocked before three goal turns in the current audit; keep working and audit the same blocker again");
699
+ }
700
+ transitionGoal(pi, runtime, params.status, params.status, evidence);
701
+ return {
702
+ content: [{ type: "text", text: `Goal marked ${params.status}: ${evidence}` }],
703
+ details: { status: params.status, evidence },
704
+ };
705
+ },
706
+ renderCall(args, theme) {
707
+ return new Text(`${theme.fg("toolTitle", theme.bold("goal "))}${theme.fg("muted", args.status)}`, 0, 0);
708
+ },
709
+ renderResult(result, _options, theme) {
710
+ const details = result.details;
711
+ return new Text(details
712
+ ? `${theme.fg(details.status === "complete" ? "success" : "warning", details.status === "complete" ? "✓ Complete" : "! Blocked")}${theme.fg("dim", ` · ${details.evidence}`)}`
713
+ : theme.fg("dim", "Goal updated"), 0, 0);
714
+ },
715
+ });
716
+
717
+ pi.on("session_start", (_event, ctx) => {
718
+ runtime.state = restoreGoalState(ctx);
719
+ runtime.continuationScheduled = false;
720
+ runtime.continuationHeld = false;
721
+ runtime.goalTurnInFlight = false;
722
+ runtime.agentEndObserved = false;
723
+ runtime.persistenceRetryNeeded = false;
724
+ runtime.lastStopReason = undefined;
725
+ runtime.lastError = undefined;
726
+ runtime.requestRender?.();
727
+ if (runtime.state?.status === "active") {
728
+ setImmediate(() => scheduleGoalContinuation(pi, runtime, initState, ctx));
729
+ }
730
+ });
731
+
732
+ pi.on("session_tree", (_event, ctx) => {
733
+ runtime.state = restoreGoalState(ctx);
734
+ runtime.continuationScheduled = false;
735
+ runtime.continuationHeld = false;
736
+ runtime.goalTurnInFlight = false;
737
+ runtime.agentEndObserved = false;
738
+ runtime.persistenceRetryNeeded = false;
739
+ runtime.lastStopReason = undefined;
740
+ runtime.lastError = undefined;
741
+ runtime.requestRender?.();
742
+ if (runtime.state?.status === "active") {
743
+ setImmediate(() => scheduleGoalContinuation(pi, runtime, initState, ctx));
744
+ }
745
+ });
746
+
747
+ pi.on("session_shutdown", (_event, ctx) => {
748
+ if (runtime.state?.status === "active") {
749
+ const now = Date.now();
750
+ const checkpoint: GoalState = {
751
+ ...stopGoalClock(runtime.state, now),
752
+ revision: runtime.state.revision + 1,
753
+ updatedAt: now,
754
+ };
755
+ try {
756
+ persistGoalState(pi, runtime, "checkpoint", checkpoint);
757
+ } catch (error) {
758
+ reportError(ctx, "Goal state could not be checkpointed", error);
759
+ }
760
+ }
761
+ runtime.state = undefined;
762
+ runtime.continuationScheduled = false;
763
+ runtime.continuationHeld = false;
764
+ runtime.goalTurnInFlight = false;
765
+ runtime.agentEndObserved = false;
766
+ runtime.persistenceRetryNeeded = false;
767
+ runtime.lastStopReason = undefined;
768
+ runtime.lastError = undefined;
769
+ });
770
+
771
+ pi.on("before_agent_start", (event, ctx) => {
772
+ runtime.continuationScheduled = false;
773
+ const current = runtime.state;
774
+ if (!isGoalModeSupported(ctx) || !isSavedSession(ctx) || !current || current.status !== "active" || initState.active) return;
775
+ const now = Date.now();
776
+ const next: GoalState = {
777
+ ...current,
778
+ revision: current.revision + 1,
779
+ turns: current.turns + 1,
780
+ updatedAt: now,
781
+ activeStartedAt: current.activeStartedAt ?? now,
782
+ };
783
+ try {
784
+ persistGoalState(pi, runtime, "turn", next);
785
+ } catch (error) {
786
+ pauseGoalAfterFailure(pi, runtime, ctx, `turn state could not be saved: ${error instanceof Error ? error.message : String(error)}`);
787
+ return;
788
+ }
789
+ runtime.goalTurnInFlight = true;
790
+ runtime.agentEndObserved = false;
791
+ runtime.lastStopReason = undefined;
792
+ runtime.lastError = undefined;
793
+ return { systemPrompt: `${event.systemPrompt}\n\n${goalSystemPrompt(next)}` };
794
+ });
795
+
796
+ pi.on("agent_end", (event) => {
797
+ if (!runtime.goalTurnInFlight) return;
798
+ const finalAssistant = [...event.messages].reverse().find((message) => message.role === "assistant");
799
+ runtime.agentEndObserved = finalAssistant !== undefined;
800
+ runtime.lastStopReason = finalAssistant?.stopReason;
801
+ runtime.lastError = finalAssistant?.errorMessage;
802
+ });
803
+
804
+ pi.registerCommand("goal", {
805
+ description: "Set or view the goal for a long-running task",
806
+ getArgumentCompletions: (prefix) => {
807
+ const normalized = prefix.trimStart().toLocaleLowerCase();
808
+ if (normalized.includes(" ")) return null;
809
+ const actions = [
810
+ { value: "clear", description: "Remove the current goal" },
811
+ { value: "edit", description: "Edit and reactivate the current goal" },
812
+ { value: "pause", description: "Stop automatic continuation" },
813
+ { value: "resume", description: "Resume automatic continuation" },
814
+ ];
815
+ return actions
816
+ .filter((action) => action.value.startsWith(normalized))
817
+ .map((action) => ({ ...action, label: action.value }));
818
+ },
819
+ handler: async (args, ctx) => {
820
+ if (ctx.mode === "print" || ctx.mode === "json") {
821
+ ctx.ui.notify("/goal requires TUI or RPC mode", "error");
822
+ return;
823
+ }
824
+ if (!isSavedSession(ctx)) {
825
+ ctx.ui.notify("/goal requires a saved session", "error");
826
+ return;
827
+ }
828
+ const input = args.trim();
829
+ const control = input.toLocaleLowerCase();
830
+ const isControl = control === "clear" || control === "edit" || control === "pause" || control === "resume";
831
+
832
+ if (!input) {
833
+ if (!runtime.state) {
834
+ ctx.ui.notify("No goal is set. Use /goal <objective> to start a long-running task.", "info");
835
+ return;
836
+ }
837
+ ctx.ui.notify(goalStatusSummary(runtime.state, ctx), "info");
838
+ return;
839
+ }
840
+
841
+ if (control === "clear") {
842
+ if (!runtime.state) {
843
+ ctx.ui.notify("No goal is set", "info");
844
+ return;
845
+ }
846
+ try {
847
+ persistGoalState(pi, runtime, "clear", undefined);
848
+ runtime.continuationScheduled = false;
849
+ ctx.ui.notify("Goal cleared", "info");
850
+ } catch (error) {
851
+ if (runtime.state?.status === "active") {
852
+ pauseGoalAfterFailure(
853
+ pi,
854
+ runtime,
855
+ ctx,
856
+ `the requested clear could not be saved: ${error instanceof Error ? error.message : String(error)}`,
857
+ "Automatic continuation is stopped. Retry /goal clear to remove the goal.",
858
+ );
859
+ } else {
860
+ reportError(ctx, "Goal could not be cleared", error);
861
+ }
862
+ }
863
+ return;
864
+ }
865
+
866
+ if (control === "pause") {
867
+ if (!runtime.state) {
868
+ ctx.ui.notify("No goal is set", "info");
869
+ return;
870
+ }
871
+ if (runtime.state.status === "paused") {
872
+ if (!runtime.persistenceRetryNeeded) {
873
+ ctx.ui.notify("Goal is already paused", "info");
874
+ return;
875
+ }
876
+ const now = Date.now();
877
+ const checkpoint: GoalState = {
878
+ ...runtime.state,
879
+ revision: runtime.state.revision + 1,
880
+ updatedAt: now,
881
+ };
882
+ try {
883
+ persistGoalState(pi, runtime, "pause", checkpoint);
884
+ ctx.ui.notify("Goal pause saved", "info");
885
+ } catch (error) {
886
+ reportError(ctx, "Goal pause still could not be saved", error);
887
+ }
888
+ return;
889
+ }
890
+ if (runtime.state.status !== "active") {
891
+ ctx.ui.notify(`Goal is ${runtime.state.status}; only an active goal can be paused`, "warning");
892
+ return;
893
+ }
894
+ try {
895
+ transitionGoal(pi, runtime, "pause", "paused");
896
+ ctx.ui.notify("Goal paused. Run /goal resume to continue.", "info");
897
+ } catch (error) {
898
+ pauseGoalAfterFailure(
899
+ pi,
900
+ runtime,
901
+ ctx,
902
+ `the requested pause could not be saved: ${error instanceof Error ? error.message : String(error)}`,
903
+ "Automatic continuation is stopped. If session storage is still unavailable, retry /goal pause after it recovers.",
904
+ );
905
+ }
906
+ return;
907
+ }
908
+
909
+ if (control === "resume") {
910
+ if (initState.active) {
911
+ ctx.ui.notify("Wait for /init to finish before resuming a goal", "error");
912
+ return;
913
+ }
914
+ if (!runtime.state) {
915
+ ctx.ui.notify("No goal is set", "info");
916
+ return;
917
+ }
918
+ if (runtime.state.status === "active") {
919
+ ctx.ui.notify("Goal is already active", "info");
920
+ return;
921
+ }
922
+ if (runtime.state.status === "complete") {
923
+ ctx.ui.notify("The goal is complete. Set a new objective or use /goal edit.", "info");
924
+ return;
925
+ }
926
+ try {
927
+ transitionGoal(pi, runtime, "resume", "active", undefined, true);
928
+ runtime.continuationScheduled = false;
929
+ scheduleGoalContinuation(pi, runtime, initState, ctx);
930
+ ctx.ui.notify("Goal resumed", "info");
931
+ } catch (error) {
932
+ reportError(ctx, "Goal could not be resumed", error);
933
+ }
934
+ return;
935
+ }
936
+
937
+ if (control === "edit") {
938
+ if (initState.active) {
939
+ ctx.ui.notify("Wait for /init to finish before editing a goal", "error");
940
+ return;
941
+ }
942
+ if (!runtime.state) {
943
+ ctx.ui.notify("No goal is set", "info");
944
+ return;
945
+ }
946
+ if (ctx.mode !== "tui") {
947
+ ctx.ui.notify("/goal edit requires interactive TUI mode", "error");
948
+ return;
949
+ }
950
+ runtime.continuationHeld = true;
951
+ let waitError: unknown;
952
+ try {
953
+ await ctx.waitForIdle();
954
+ } catch (error) {
955
+ waitError = error;
956
+ } finally {
957
+ runtime.continuationHeld = false;
958
+ }
959
+ if (waitError) {
960
+ reportError(ctx, "Goal could not wait for the active turn", waitError);
961
+ scheduleGoalContinuation(pi, runtime, initState, ctx);
962
+ return;
963
+ }
964
+ const edited = await ctx.ui.editor("Edit long-running goal", runtime.state.objective);
965
+ if (edited === undefined) {
966
+ scheduleGoalContinuation(pi, runtime, initState, ctx);
967
+ return;
968
+ }
969
+ const objective = validateGoalObjective(edited);
970
+ if (!objective) {
971
+ ctx.ui.notify(edited.trim() ? "A goal objective may not exceed 4,000 characters" : "A goal objective may not be empty", "error");
972
+ scheduleGoalContinuation(pi, runtime, initState, ctx);
973
+ return;
974
+ }
975
+ const now = Date.now();
976
+ const current = stopGoalClock(runtime.state, now);
977
+ const next: GoalState = {
978
+ ...current,
979
+ revision: current.revision + 1,
980
+ objective,
981
+ status: "active",
982
+ updatedAt: now,
983
+ activeStartedAt: now,
984
+ blockedAuditStartTurn: current.turns,
985
+ result: undefined,
986
+ };
987
+ try {
988
+ persistGoalState(pi, runtime, "edit", next);
989
+ runtime.continuationScheduled = false;
990
+ scheduleGoalContinuation(pi, runtime, initState, ctx);
991
+ ctx.ui.notify("Goal updated and active", "info");
992
+ } catch (error) {
993
+ reportError(ctx, "Goal could not be edited", error);
994
+ scheduleGoalContinuation(pi, runtime, initState, ctx);
995
+ }
996
+ return;
997
+ }
998
+
999
+ if (isControl) return;
1000
+ if (initState.active) {
1001
+ ctx.ui.notify("Wait for /init to finish before starting a goal", "error");
1002
+ return;
1003
+ }
1004
+ const objective = validateGoalObjective(input);
1005
+ if (!objective) {
1006
+ ctx.ui.notify(input ? "A goal objective may not exceed 4,000 characters" : "A goal objective may not be empty", "error");
1007
+ return;
1008
+ }
1009
+
1010
+ const unfinished = runtime.state && runtime.state.status !== "complete";
1011
+ if (unfinished) {
1012
+ if (!ctx.hasUI) {
1013
+ ctx.ui.notify("Clear the current goal before replacing it outside TUI mode", "error");
1014
+ return;
1015
+ }
1016
+ const replace = await ctx.ui.confirm("Replace active goal", "Replace the current unfinished goal and discard its continuation state?");
1017
+ if (!replace) return;
1018
+ }
1019
+
1020
+ runtime.continuationHeld = true;
1021
+ let waitError: unknown;
1022
+ try {
1023
+ await ctx.waitForIdle();
1024
+ } catch (error) {
1025
+ waitError = error;
1026
+ } finally {
1027
+ runtime.continuationHeld = false;
1028
+ }
1029
+ if (waitError) {
1030
+ reportError(ctx, "Goal could not wait for the active turn", waitError);
1031
+ scheduleGoalContinuation(pi, runtime, initState, ctx);
1032
+ return;
1033
+ }
1034
+ const now = Date.now();
1035
+ const state: GoalState = {
1036
+ version: GOAL_VERSION,
1037
+ revision: 1,
1038
+ objective,
1039
+ status: "active",
1040
+ createdAt: now,
1041
+ updatedAt: now,
1042
+ activeMilliseconds: 0,
1043
+ activeStartedAt: now,
1044
+ turns: 0,
1045
+ blockedAuditStartTurn: 0,
1046
+ baselineTokens: sumGoalTokens(ctx),
1047
+ };
1048
+ try {
1049
+ persistGoalState(pi, runtime, unfinished ? "replace" : "set", state);
1050
+ scheduleGoalContinuation(pi, runtime, initState, ctx);
1051
+ ctx.ui.notify("Goal active. KillerOS will continue until completion, a repeated blocker, or pause.", "info");
1052
+ } catch (error) {
1053
+ reportError(ctx, "Goal could not be started", error);
1054
+ scheduleGoalContinuation(pi, runtime, initState, ctx);
1055
+ }
1056
+ },
1057
+ });
1058
+ }
1059
+
1060
+ function registerGoalSettlement(
1061
+ pi: ExtensionAPI,
1062
+ runtime: GoalRuntime,
1063
+ initState: InitWorkflowState,
1064
+ ): void {
1065
+ pi.on("agent_settled", (_event, ctx) => {
1066
+ const wasGoalTurn = runtime.goalTurnInFlight;
1067
+ const agentEndObserved = runtime.agentEndObserved;
1068
+ runtime.goalTurnInFlight = false;
1069
+ runtime.agentEndObserved = false;
1070
+ runtime.continuationScheduled = false;
1071
+ if (!wasGoalTurn || runtime.state?.status !== "active" || initState.active) return;
1072
+ if (!agentEndObserved) {
1073
+ pauseGoalAfterFailure(pi, runtime, ctx, "the goal turn ended without an agent result");
1074
+ return;
1075
+ }
1076
+ if (runtime.lastStopReason === "error" || runtime.lastStopReason === "aborted") {
1077
+ const reason = runtime.lastError || (runtime.lastStopReason === "aborted" ? "the agent turn was aborted" : "the agent turn failed");
1078
+ runtime.lastStopReason = undefined;
1079
+ runtime.lastError = undefined;
1080
+ pauseGoalAfterFailure(pi, runtime, ctx, reason);
1081
+ return;
1082
+ }
1083
+ runtime.lastStopReason = undefined;
1084
+ runtime.lastError = undefined;
1085
+ scheduleGoalContinuation(pi, runtime, initState, ctx);
1086
+ });
1087
+ }
1088
+
324
1089
  const OptionSchema = Type.Object({
325
1090
  label: Type.String({ minLength: 1, maxLength: 200, description: "Display label for the option" }),
326
1091
  description: Type.Optional(Type.String({ maxLength: 500, description: "Optional detail shown for the selected option" })),
1092
+ preview: Type.Optional(Type.String({ maxLength: 8_000, description: "Optional markdown proposal preview shown for the selected option" })),
327
1093
  });
328
1094
 
329
1095
  const QuestionParams = Type.Object({
@@ -338,6 +1104,7 @@ const QuestionParams = Type.Object({
338
1104
  interface DisplayOption {
339
1105
  label: string;
340
1106
  description?: string;
1107
+ preview?: string;
341
1108
  originalIndex: number;
342
1109
  isOther: boolean;
343
1110
  }
@@ -417,6 +1184,7 @@ function registerQuestionTool(pi: ExtensionAPI): void {
417
1184
  ...params.options.map((option, index) => ({
418
1185
  label: option.label,
419
1186
  description: option.description,
1187
+ preview: option.preview,
420
1188
  originalIndex: index + 1,
421
1189
  isOther: false,
422
1190
  })),
@@ -596,6 +1364,48 @@ function registerQuestionTool(pi: ExtensionAPI): void {
596
1364
  }
597
1365
  });
598
1366
 
1367
+ const selectedPreview = visibleOptions[optionIndex]?.preview;
1368
+ if (!editMode && selectedPreview) {
1369
+ const footerRows = 3;
1370
+ const previewChromeRows = 2;
1371
+ const availableRows = tui.terminal.rows - lines.length - footerRows;
1372
+ if (availableRows > previewChromeRows) {
1373
+ lines.push("");
1374
+ addWrappedWithPrefix(" ", theme.fg("accent", theme.bold("Proposal preview")));
1375
+ const markdownLines = new Markdown(
1376
+ selectedPreview,
1377
+ 1,
1378
+ 0,
1379
+ {
1380
+ heading: (text) => theme.fg("accent", theme.bold(text)),
1381
+ link: (text) => theme.fg("accent", text),
1382
+ linkUrl: (text) => theme.fg("dim", text),
1383
+ code: (text) => theme.fg("mdCode", text),
1384
+ codeBlock: (text) => theme.fg("mdCodeBlock", text),
1385
+ codeBlockBorder: (text) => theme.fg("mdCodeBlockBorder", text),
1386
+ quote: (text) => theme.fg("mdQuote", text),
1387
+ quoteBorder: (text) => theme.fg("mdQuoteBorder", text),
1388
+ hr: (text) => theme.fg("mdHr", text),
1389
+ listBullet: (text) => theme.fg("mdListBullet", text),
1390
+ bold: (text) => theme.bold(text),
1391
+ italic: (text) => theme.italic(text),
1392
+ strikethrough: (text) => theme.strikethrough(text),
1393
+ underline: (text) => theme.underline(text),
1394
+ },
1395
+ { color: (text) => theme.fg("muted", text) },
1396
+ ).render(renderWidth);
1397
+ const maxPreviewRows = Math.min(12, availableRows - previewChromeRows);
1398
+ if (markdownLines.length <= maxPreviewRows) {
1399
+ lines.push(...markdownLines);
1400
+ } else {
1401
+ const visiblePreviewRows = Math.max(0, maxPreviewRows - 1);
1402
+ lines.push(...markdownLines.slice(0, visiblePreviewRows));
1403
+ const hiddenRows = markdownLines.length - visiblePreviewRows;
1404
+ lines.push(theme.fg("dim", ` … ${hiddenRows} more line${hiddenRows === 1 ? "" : "s"}`));
1405
+ }
1406
+ }
1407
+ }
1408
+
599
1409
  if (editMode) {
600
1410
  lines.push("");
601
1411
  addWrappedWithPrefix(" ", theme.fg("muted", "Your answer:"));
@@ -689,6 +1499,515 @@ function registerQuestionTool(pi: ExtensionAPI): void {
689
1499
  });
690
1500
  }
691
1501
 
1502
+ const PERSONAL_INSTRUCTIONS_FILE = "AGENTS.local.md";
1503
+ const PERSONAL_INSTRUCTIONS_LIMIT = 32 * 1024;
1504
+
1505
+ function readBoundedText(filePath: string, limit = PERSONAL_INSTRUCTIONS_LIMIT): string | undefined {
1506
+ let descriptor: number | undefined;
1507
+ try {
1508
+ descriptor = openSync(filePath, "r");
1509
+ const buffer = Buffer.alloc(limit + 1);
1510
+ const bytesRead = readSync(descriptor, buffer, 0, buffer.length, 0);
1511
+ const content = buffer.toString("utf8", 0, Math.min(bytesRead, limit));
1512
+ if (!content.trim()) return undefined;
1513
+ return bytesRead > limit
1514
+ ? `${content}\n\n[Personal instructions truncated by KillerOS]`
1515
+ : content;
1516
+ } catch {
1517
+ return undefined;
1518
+ } finally {
1519
+ if (descriptor !== undefined) {
1520
+ try {
1521
+ closeSync(descriptor);
1522
+ } catch {
1523
+ // Ignore cleanup failures after a bounded best-effort read.
1524
+ }
1525
+ }
1526
+ }
1527
+ }
1528
+
1529
+ function resolvePersonalInstructions(cwd: string): { content: string; source: string } | undefined {
1530
+ const localPath = path.join(cwd, PERSONAL_INSTRUCTIONS_FILE);
1531
+ const local = readBoundedText(localPath);
1532
+ if (!local) return undefined;
1533
+
1534
+ const importMatch = local.trim().match(/^@(.+)$/u);
1535
+ if (!importMatch) return { content: local, source: localPath };
1536
+
1537
+ const requestedPath = importMatch[1]!.trim();
1538
+ const importedPath = requestedPath.startsWith("~/") || requestedPath.startsWith("~\\")
1539
+ ? path.join(os.homedir(), requestedPath.slice(2))
1540
+ : path.resolve(cwd, requestedPath);
1541
+ const imported = readBoundedText(importedPath);
1542
+ return imported ? { content: imported, source: importedPath } : { content: local, source: localPath };
1543
+ }
1544
+
1545
+ function registerPersonalInstructions(pi: ExtensionAPI, initState: InitWorkflowState): void {
1546
+ pi.on("before_agent_start", (event, ctx) => {
1547
+ if (initState.active || !ctx.isProjectTrusted()) return;
1548
+ const personal = resolvePersonalInstructions(ctx.cwd);
1549
+ if (!personal) return;
1550
+ return {
1551
+ systemPrompt: [
1552
+ event.systemPrompt,
1553
+ "",
1554
+ `<personal_instructions source="${personal.source}">`,
1555
+ personal.content,
1556
+ "</personal_instructions>",
1557
+ ].join("\n"),
1558
+ };
1559
+ });
1560
+ }
1561
+
1562
+ type KillerosHookEvent = "tool_call" | "tool_result" | "agent_settled";
1563
+
1564
+ interface KillerosHook {
1565
+ matcher?: string;
1566
+ command: string;
1567
+ timeoutMs?: number;
1568
+ }
1569
+
1570
+ interface KillerosHookConfig {
1571
+ hooks?: Partial<Record<KillerosHookEvent, KillerosHook[]>>;
1572
+ }
1573
+
1574
+ interface HookExecutionResult {
1575
+ code: number;
1576
+ stdout: string;
1577
+ stderr: string;
1578
+ timedOut: boolean;
1579
+ }
1580
+
1581
+ const HOOK_EVENTS: readonly KillerosHookEvent[] = ["tool_call", "tool_result", "agent_settled"];
1582
+ const HOOK_OUTPUT_LIMIT = 16 * 1024;
1583
+
1584
+ function loadKillerosHooks(ctx: ExtensionContext): KillerosHookConfig {
1585
+ const configPath = path.join(ctx.cwd, CONFIG_DIR_NAME, "killeros-hooks.json");
1586
+ if (!existsSync(configPath)) return {};
1587
+ if (!ctx.isProjectTrusted()) {
1588
+ ctx.ui.notify(`Ignored untrusted project hooks in ${configPath}`, "warning");
1589
+ return {};
1590
+ }
1591
+
1592
+ try {
1593
+ const parsed = JSON.parse(readFileSync(configPath, "utf8")) as KillerosHookConfig;
1594
+ const hooks: KillerosHookConfig["hooks"] = {};
1595
+ for (const event of HOOK_EVENTS) {
1596
+ const candidates = parsed.hooks?.[event];
1597
+ if (!Array.isArray(candidates)) continue;
1598
+ hooks[event] = candidates.filter((hook, index) => {
1599
+ const valid = hook
1600
+ && typeof hook.command === "string"
1601
+ && hook.command.trim().length > 0
1602
+ && (hook.matcher === undefined || typeof hook.matcher === "string")
1603
+ && (hook.timeoutMs === undefined || Number.isFinite(hook.timeoutMs));
1604
+ if (!valid) {
1605
+ ctx.ui.notify(`Ignored invalid ${event} hook ${index + 1} in ${configPath}`, "warning");
1606
+ return false;
1607
+ }
1608
+ if (hook.matcher && hook.matcher !== "*") {
1609
+ try {
1610
+ new RegExp(hook.matcher, "u");
1611
+ } catch {
1612
+ ctx.ui.notify(`Ignored ${event} hook ${index + 1}: invalid matcher ${JSON.stringify(hook.matcher)}`, "warning");
1613
+ return false;
1614
+ }
1615
+ }
1616
+ return true;
1617
+ });
1618
+ }
1619
+ return { hooks };
1620
+ } catch (error) {
1621
+ reportError(ctx, `Invalid ${CONFIG_DIR_NAME}/killeros-hooks.json`, error);
1622
+ return {};
1623
+ }
1624
+ }
1625
+
1626
+ function matchesHook(hook: KillerosHook, value: string): boolean {
1627
+ if (!hook.matcher || hook.matcher === "*") return true;
1628
+ try {
1629
+ return new RegExp(hook.matcher, "u").test(value);
1630
+ } catch {
1631
+ return false;
1632
+ }
1633
+ }
1634
+
1635
+ function appendBounded(current: string, chunk: Buffer | string): string {
1636
+ if (current.length >= HOOK_OUTPUT_LIMIT) return current;
1637
+ return (current + chunk.toString()).slice(0, HOOK_OUTPUT_LIMIT);
1638
+ }
1639
+
1640
+ function executeHook(command: string, cwd: string, environment: Record<string, string>, timeoutMs = 30_000): Promise<HookExecutionResult> {
1641
+ return new Promise((resolve) => {
1642
+ const child = spawn(command, {
1643
+ cwd,
1644
+ env: { ...process.env, ...environment },
1645
+ shell: true,
1646
+ stdio: ["ignore", "pipe", "pipe"],
1647
+ windowsHide: true,
1648
+ });
1649
+ let stdout = "";
1650
+ let stderr = "";
1651
+ let completed = false;
1652
+ let timedOut = false;
1653
+ let timer: NodeJS.Timeout | undefined;
1654
+ const finish = (code: number): void => {
1655
+ if (completed) return;
1656
+ completed = true;
1657
+ if (timer) clearTimeout(timer);
1658
+ resolve({ code, stdout, stderr, timedOut });
1659
+ };
1660
+ child.stdout.on("data", (chunk) => { stdout = appendBounded(stdout, chunk); });
1661
+ child.stderr.on("data", (chunk) => { stderr = appendBounded(stderr, chunk); });
1662
+ child.on("error", (error) => {
1663
+ stderr = appendBounded(stderr, error.message);
1664
+ finish(1);
1665
+ });
1666
+ child.on("close", (code) => finish(code ?? 1));
1667
+ timer = setTimeout(() => {
1668
+ timedOut = true;
1669
+ child.kill("SIGTERM");
1670
+ setTimeout(() => child.kill("SIGKILL"), 1_000).unref?.();
1671
+ finish(124);
1672
+ }, Math.max(1_000, Math.min(timeoutMs, 300_000)));
1673
+ timer.unref?.();
1674
+ });
1675
+ }
1676
+
1677
+ function hookEnvironment(event: KillerosHookEvent, toolName = "", payload: unknown = {}): Record<string, string> {
1678
+ return {
1679
+ KILLEROS_EVENT: event,
1680
+ KILLEROS_TOOL: toolName,
1681
+ KILLEROS_PAYLOAD: JSON.stringify(payload).slice(0, 8_000),
1682
+ };
1683
+ }
1684
+
1685
+ function hookFailureMessage(hook: KillerosHook, result: HookExecutionResult): string {
1686
+ const detail = result.stderr.trim() || result.stdout.trim() || `exit code ${result.code}`;
1687
+ return `Hook failed${result.timedOut ? " (timed out)" : ""}: ${hook.command}\n${detail}`;
1688
+ }
1689
+
1690
+ function registerLifecycleHooks(pi: ExtensionAPI): void {
1691
+ let config: KillerosHookConfig = {};
1692
+ pi.on("session_start", (_event, ctx) => { config = loadKillerosHooks(ctx); });
1693
+
1694
+ pi.on("tool_call", async (event, ctx) => {
1695
+ for (const hook of config.hooks?.tool_call ?? []) {
1696
+ if (!matchesHook(hook, event.toolName)) continue;
1697
+ const result = await executeHook(
1698
+ hook.command,
1699
+ ctx.cwd,
1700
+ hookEnvironment("tool_call", event.toolName, event.input),
1701
+ hook.timeoutMs,
1702
+ );
1703
+ if (result.code !== 0) {
1704
+ const reason = hookFailureMessage(hook, result);
1705
+ ctx.ui.notify(reason, "error");
1706
+ return { block: true, reason };
1707
+ }
1708
+ }
1709
+ });
1710
+
1711
+ pi.on("tool_result", async (event, ctx) => {
1712
+ for (const hook of config.hooks?.tool_result ?? []) {
1713
+ if (!matchesHook(hook, event.toolName)) continue;
1714
+ const result = await executeHook(
1715
+ hook.command,
1716
+ ctx.cwd,
1717
+ hookEnvironment("tool_result", event.toolName, {
1718
+ input: event.input,
1719
+ isError: event.isError,
1720
+ }),
1721
+ hook.timeoutMs,
1722
+ );
1723
+ if (result.code !== 0) ctx.ui.notify(hookFailureMessage(hook, result), "error");
1724
+ }
1725
+ });
1726
+
1727
+ pi.on("agent_settled", async (_event, ctx) => {
1728
+ for (const hook of config.hooks?.agent_settled ?? []) {
1729
+ const result = await executeHook(
1730
+ hook.command,
1731
+ ctx.cwd,
1732
+ hookEnvironment("agent_settled"),
1733
+ hook.timeoutMs,
1734
+ );
1735
+ if (result.code !== 0) ctx.ui.notify(hookFailureMessage(hook, result), "error");
1736
+ }
1737
+ });
1738
+ }
1739
+
1740
+ const INIT_SURVEY_OUTPUT_LIMIT = 40 * 1024;
1741
+ const INIT_SURVEY_FILE_LIMIT = 8 * 1024;
1742
+ const INIT_SURVEY_PATH_LIMIT = 400;
1743
+ const INIT_SURVEY_DIRECTORY_LIMIT = 120;
1744
+ const INIT_SURVEY_DEPTH_LIMIT = 4;
1745
+ const INIT_SURVEY_EXCLUDED_DIRS = new Set([
1746
+ ".agents", ".claude", ".git", ".next", ".pi", ".pytest_cache", ".turbo", ".venv", "__pycache__", "archive", "build", "coverage", "data", "dist", "logs", "node_modules", "target", "test-results", "vendor",
1747
+ ]);
1748
+ const INIT_SURVEY_EXCLUDED_FILES = new Set([
1749
+ ".cursorrules", "AGENTS.md", "AGENTS.local.md", "CLAUDE.md", "CLAUDE.local.md", "GEMINI.md", "MEMORY.md", "SKILL.md", "copilot-instructions.md",
1750
+ ]);
1751
+ const INIT_SURVEY_ROOT_FILES = [
1752
+ "README.md",
1753
+ "README.rst",
1754
+ "README.txt",
1755
+ "package.json",
1756
+ "pyproject.toml",
1757
+ "requirements.txt",
1758
+ "Cargo.toml",
1759
+ "go.mod",
1760
+ "Makefile",
1761
+ "Dockerfile",
1762
+ "compose.yaml",
1763
+ "compose.yml",
1764
+ "config.yaml",
1765
+ "config.yml",
1766
+ "tsconfig.json",
1767
+ "vite.config.ts",
1768
+ "vite.config.js",
1769
+ "eslint.config.js",
1770
+ "eslint.config.mjs",
1771
+ ] as const;
1772
+ const INIT_SURVEY_NESTED_FILES = new Set([
1773
+ "package.json", "pyproject.toml", "requirements.txt", "Cargo.toml", "go.mod",
1774
+ ]);
1775
+
1776
+ async function collectInitProjectFiles(cwd: string): Promise<string[]> {
1777
+ const files: string[] = [];
1778
+ const queue: Array<{ relativePath: string; depth: number }> = [{ relativePath: "", depth: 0 }];
1779
+ let directoriesRead = 0;
1780
+ while (queue.length && files.length < INIT_SURVEY_PATH_LIMIT && directoriesRead < INIT_SURVEY_DIRECTORY_LIMIT) {
1781
+ const current = queue.shift()!;
1782
+ directoriesRead += 1;
1783
+ let entries;
1784
+ try {
1785
+ entries = await fs.readdir(path.join(cwd, current.relativePath), { withFileTypes: true });
1786
+ } catch (error) {
1787
+ if (!current.relativePath) throw error;
1788
+ continue;
1789
+ }
1790
+ entries.sort((left, right) => left.name === right.name ? 0 : left.name < right.name ? -1 : 1);
1791
+ for (const entry of entries) {
1792
+ if (files.length >= INIT_SURVEY_PATH_LIMIT) break;
1793
+ const relativePath = path.join(current.relativePath, entry.name);
1794
+ if (entry.isDirectory()) {
1795
+ if (current.depth < INIT_SURVEY_DEPTH_LIMIT && !INIT_SURVEY_EXCLUDED_DIRS.has(entry.name)) {
1796
+ queue.push({ relativePath, depth: current.depth + 1 });
1797
+ }
1798
+ } else if (entry.isFile() && !INIT_SURVEY_EXCLUDED_FILES.has(entry.name)) {
1799
+ files.push(relativePath.replaceAll("\\", "/"));
1800
+ }
1801
+ }
1802
+ }
1803
+ return files;
1804
+ }
1805
+
1806
+ async function readFilePrefix(filePath: string, limit: number): Promise<string> {
1807
+ const handle = await fs.open(filePath, "r");
1808
+ try {
1809
+ const buffer = Buffer.alloc(limit);
1810
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
1811
+ return buffer.toString("utf8", 0, bytesRead);
1812
+ } finally {
1813
+ await handle.close();
1814
+ }
1815
+ }
1816
+
1817
+ async function runInitSurvey(
1818
+ cwd: string,
1819
+ ): Promise<{ output: string; error?: string }> {
1820
+ let projectFiles: string[];
1821
+ try {
1822
+ projectFiles = await collectInitProjectFiles(cwd);
1823
+ } catch (error) {
1824
+ return { output: "", error: error instanceof Error ? error.message : String(error) };
1825
+ }
1826
+
1827
+ const candidates = new Set<string>(INIT_SURVEY_ROOT_FILES);
1828
+ for (const relativePath of projectFiles) {
1829
+ const fileName = path.posix.basename(relativePath);
1830
+ if (INIT_SURVEY_NESTED_FILES.has(fileName) || /^\.github\/workflows\/[^/]+\.ya?ml$/iu.test(relativePath)) {
1831
+ candidates.add(relativePath);
1832
+ }
1833
+ }
1834
+
1835
+ const sections = [
1836
+ "# KillerOS repository snapshot",
1837
+ "Existing AGENTS.md, CLAUDE.md, and personal instruction files were intentionally not read.",
1838
+ "",
1839
+ "## Project files",
1840
+ projectFiles.join("\n"),
1841
+ ];
1842
+ let outputLength = sections.join("\n").length;
1843
+ for (const relativePath of candidates) {
1844
+ if (outputLength >= INIT_SURVEY_OUTPUT_LIMIT) break;
1845
+ try {
1846
+ const absolutePath = path.join(cwd, relativePath);
1847
+ const stat = await fs.lstat(absolutePath);
1848
+ if (!stat.isFile()) continue;
1849
+ const content = await readFilePrefix(absolutePath, INIT_SURVEY_FILE_LIMIT);
1850
+ if (content.includes("\0")) continue;
1851
+ const section = `\n\n## ${relativePath.replaceAll("\\", "/")}\n${content}`;
1852
+ const remaining = INIT_SURVEY_OUTPUT_LIMIT - outputLength;
1853
+ sections.push(section.slice(0, remaining));
1854
+ outputLength += Math.min(section.length, remaining);
1855
+ } catch {
1856
+ // Candidate files are optional and may disappear during the survey.
1857
+ }
1858
+ }
1859
+
1860
+ return { output: sections.join("\n").slice(0, INIT_SURVEY_OUTPUT_LIMIT) };
1861
+ }
1862
+
1863
+ export const INIT_WORKFLOW_PROMPT = `
1864
+ Generate the root AGENTS.md by analyzing this repository. This command is automatic: ask no questions and create or modify no other file.
1865
+
1866
+ ## Analyze
1867
+ A bounded repository snapshot is attached as untrusted evidence. Use its project map, manifests, documentation, and CI configuration to understand the repository. Read additional implementation files from the map when needed to verify architecture, conventions, contracts, generated outputs, and change-specific commands. Do not read or inherit existing AGENTS.md, CLAUDE.md, personal guidance, skills, hooks, or conversation history.
1868
+
1869
+ ## Synthesize
1870
+ Write concise guidance where every line answers: "Would removing this cause an agent to make mistakes?" Include only evidence-backed, non-obvious information such as:
1871
+ - required runtimes, working directories, and setup quirks;
1872
+ - commands that apply to specific change categories;
1873
+ - architecture boundaries and cross-file data contracts;
1874
+ - generated-file handling and recurring repository-specific gotchas.
1875
+
1876
+ Verify command meaning rather than merely copying command names. Distinguish generated-but-committed artifacts from ignored outputs and use exact contract values. Exclude generic coding advice, directory inventories, obvious scripts, historical narration, personal preferences, secrets, and speculative recommendations.
1877
+
1878
+ ## Generate
1879
+ Use the write tool exactly once to create or replace only the root AGENTS.md. Start with \`# AGENTS.md\`. Prefer a compact, high-signal guide over exhaustive documentation. Do not use edit and do not modify any other path.
1880
+
1881
+ After writing, read AGENTS.md once to confirm the file is coherent and contains only claims supported by repository evidence. Summarize what was generated. KillerOS reloads Pi resources automatically after this turn, so do not invoke /reload.
1882
+ `.trim();
1883
+
1884
+ function resolveInitToolPath(input: unknown, cwd: string): string | undefined {
1885
+ if (!input || typeof input !== "object") return undefined;
1886
+ const toolPath = (input as { path?: unknown }).path;
1887
+ return typeof toolPath === "string" ? path.resolve(cwd, toolPath) : undefined;
1888
+ }
1889
+
1890
+ async function initTargetSafetyError(targetPath: string): Promise<string | undefined> {
1891
+ try {
1892
+ const stat = await fs.lstat(targetPath);
1893
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.nlink > 1) {
1894
+ return "/init requires root AGENTS.md to be absent or a regular, non-linked file";
1895
+ }
1896
+ } catch (error) {
1897
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
1898
+ return `/init could not inspect root AGENTS.md: ${error instanceof Error ? error.message : String(error)}`;
1899
+ }
1900
+ }
1901
+ return undefined;
1902
+ }
1903
+
1904
+ function registerInitCommand(pi: ExtensionAPI, initState: InitWorkflowState, goalRuntime: GoalRuntime): void {
1905
+ pi.on("tool_call", async (event) => {
1906
+ const targetPath = initState.targetPath;
1907
+ if (!initState.active || !targetPath || INIT_READ_ONLY_TOOLS.has(event.toolName)) return;
1908
+ const toolPath = resolveInitToolPath(event.input, path.dirname(targetPath));
1909
+ if (event.toolName === "write" && toolPath === targetPath && !initState.writeAttempted) {
1910
+ const safetyError = await initTargetSafetyError(targetPath);
1911
+ if (safetyError) return { block: true, reason: safetyError };
1912
+ initState.writeAttempted = true;
1913
+ initState.writeToolCallId = event.toolCallId;
1914
+ return;
1915
+ }
1916
+ return {
1917
+ block: true,
1918
+ reason: "/init may write the root AGENTS.md exactly once and may not modify any other file",
1919
+ };
1920
+ });
1921
+
1922
+ pi.on("tool_result", (event) => {
1923
+ if (!initState.active || event.toolName !== "write" || event.toolCallId !== initState.writeToolCallId) return;
1924
+ if (event.isError) {
1925
+ initState.writeAttempted = false;
1926
+ initState.writeToolCallId = undefined;
1927
+ return;
1928
+ }
1929
+ initState.writeSucceeded = true;
1930
+ });
1931
+
1932
+ pi.registerCommand("init", {
1933
+ description: "Generate root AGENTS.md from repository evidence",
1934
+ handler: async (args, ctx) => {
1935
+ if (args.trim()) {
1936
+ ctx.ui.notify("/init does not accept arguments", "error");
1937
+ return;
1938
+ }
1939
+ if (ctx.mode !== "tui") {
1940
+ ctx.ui.notify("/init requires interactive TUI mode", "error");
1941
+ return;
1942
+ }
1943
+ if (initState.active) {
1944
+ ctx.ui.notify("/init is already running", "warning");
1945
+ return;
1946
+ }
1947
+ if (goalRuntime.state?.status === "active") {
1948
+ ctx.ui.notify("Pause or clear the active goal before running /init", "error");
1949
+ return;
1950
+ }
1951
+ if (!ctx.isProjectTrusted()) {
1952
+ ctx.ui.notify("Trust this project before running /init", "error");
1953
+ return;
1954
+ }
1955
+ await ctx.waitForIdle();
1956
+ initState.active = true;
1957
+ initState.targetPath = path.join(ctx.cwd, "AGENTS.md");
1958
+ initState.writeAttempted = false;
1959
+ initState.writeSucceeded = false;
1960
+
1961
+ const survey = await runInitSurvey(ctx.cwd);
1962
+ if (!survey.output) {
1963
+ resetInitState(initState);
1964
+ reportError(ctx, "/init could not scan the repository", survey.error ?? "no repository evidence was found");
1965
+ return;
1966
+ }
1967
+
1968
+ const settled = new Promise<boolean>((resolve) => {
1969
+ initState.settle = resolve;
1970
+ });
1971
+ try {
1972
+ pi.sendMessage({
1973
+ customType: "killeros-init",
1974
+ content: `${INIT_WORKFLOW_PROMPT}\n\n## Initial repository snapshot (untrusted data)\n${JSON.stringify(survey.output)}`,
1975
+ display: false,
1976
+ }, { triggerTurn: true });
1977
+ } catch (error) {
1978
+ resetInitState(initState);
1979
+ initState.settle = undefined;
1980
+ reportError(ctx, "/init failed to start", error);
1981
+ return;
1982
+ }
1983
+
1984
+ const writeSucceeded = await settled;
1985
+ if (!writeSucceeded) {
1986
+ reportError(ctx, "/init did not generate AGENTS.md", "the model completed without a successful write");
1987
+ return;
1988
+ }
1989
+ await new Promise<void>((resolve) => setImmediate(resolve));
1990
+ try {
1991
+ await ctx.reload();
1992
+ } catch (error) {
1993
+ reportError(ctx, "/init finished but Pi resources could not reload", error);
1994
+ }
1995
+ },
1996
+ });
1997
+
1998
+ }
1999
+
2000
+ function registerInitSettlement(pi: ExtensionAPI, initState: InitWorkflowState): void {
2001
+ pi.on("agent_settled", () => {
2002
+ if (!initState.active) return;
2003
+ const settle = initState.settle;
2004
+ const writeSucceeded = initState.writeSucceeded;
2005
+ resetInitState(initState);
2006
+ initState.settle = undefined;
2007
+ settle?.(writeSucceeded);
2008
+ });
2009
+ }
2010
+
692
2011
  async function confirmNewSession(ctx: ExtensionCommandContext): Promise<boolean> {
693
2012
  if (!ctx.hasUI) return true;
694
2013
  return ctx.ui.confirm("Start new session", "Start a new session and leave the current history?");
@@ -740,6 +2059,7 @@ const BUILTIN_COMMANDS: ReadonlyArray<{ name: string; description: string }> = [
740
2059
  ];
741
2060
 
742
2061
  const COMMAND_SYNTAX_HINTS: Readonly<Record<string, string>> = {
2062
+ goal: "/goal [objective|clear|edit|pause|resume]",
743
2063
  variants: "/variants [level]",
744
2064
  model: "/model [provider/model]",
745
2065
  "scoped-models": "/scoped-models",
@@ -1107,10 +2427,19 @@ function renderFooterRow(left: string, right: string, width: number): string {
1107
2427
  return ` ${clippedLeft}${gap}${clippedRight} `;
1108
2428
  }
1109
2429
 
1110
- function registerFooter(pi: ExtensionAPI): void {
2430
+ function formatGoalFooter(state: GoalState | undefined, theme: Theme): string {
2431
+ if (!state) return "";
2432
+ if (state.status === "active") return theme.fg("accent", `✻ goal · ${formatTime(goalElapsedMilliseconds(state))}`);
2433
+ if (state.status === "paused") return theme.fg("warning", "Ⅱ goal paused");
2434
+ if (state.status === "blocked") return theme.fg("error", "! goal blocked");
2435
+ return theme.fg("success", "✓ goal complete");
2436
+ }
2437
+
2438
+ function registerFooter(pi: ExtensionAPI, goalRuntime: GoalRuntime): void {
1111
2439
  let currentModel: ExtensionContext["model"];
1112
2440
  let thinkingLevel: ThinkingLevel = "off";
1113
2441
  let activeTui: TUI | undefined;
2442
+ goalRuntime.requestRender = () => activeTui?.requestRender();
1114
2443
 
1115
2444
  pi.on("session_start", (_event, ctx) => {
1116
2445
  if (ctx.mode !== "tui") return;
@@ -1144,15 +2473,17 @@ function registerFooter(pi: ExtensionAPI): void {
1144
2473
  const signature = formatModel(model, theme);
1145
2474
  const fullDirectory = theme.fg("dim", cwd);
1146
2475
  const focusedDirectory = theme.fg("dim", compactDirectory(cwd));
2476
+ const goal = formatGoalFooter(goalRuntime.state, theme);
1147
2477
  const rich = joinFooterParts([
1148
2478
  signature,
1149
2479
  level,
1150
2480
  context,
2481
+ goal,
1151
2482
  branch ? theme.fg("dim", branch) : "",
1152
2483
  theme.fg("dim", formatTime(Date.now() - sessionStart)),
1153
2484
  theme.fg("dim", formatCost(sumSessionCost(ctx))),
1154
2485
  ], theme);
1155
- const focused = joinFooterParts([signature, context], theme);
2486
+ const focused = joinFooterParts([signature, context, goal], theme);
1156
2487
 
1157
2488
  if (footerRowFits(rich, fullDirectory, width)) {
1158
2489
  return [renderFooterRow(rich, fullDirectory, width)];
@@ -1166,6 +2497,11 @@ function registerFooter(pi: ExtensionAPI): void {
1166
2497
  if (footerRowFits(focused, "", width)) {
1167
2498
  return [renderFooterRow(focused, "", width)];
1168
2499
  }
2500
+ if (goal) {
2501
+ const essentialGoal = joinFooterParts([context, goal], theme);
2502
+ if (footerRowFits(essentialGoal, "", width)) return [renderFooterRow(essentialGoal, "", width)];
2503
+ return [renderFooterRow(goal, context, width)];
2504
+ }
1169
2505
 
1170
2506
  const essentialModel = formatModel(model, theme, false);
1171
2507
  return [renderFooterRow(essentialModel, context, width)];
@@ -1184,15 +2520,35 @@ function registerFooter(pi: ExtensionAPI): void {
1184
2520
  });
1185
2521
  pi.on("session_shutdown", () => {
1186
2522
  activeTui = undefined;
2523
+ goalRuntime.requestRender = undefined;
1187
2524
  });
1188
2525
  }
1189
2526
 
1190
2527
  export default function Killeros(pi: ExtensionAPI): void {
2528
+ const initState: InitWorkflowState = {
2529
+ active: false,
2530
+ writeAttempted: false,
2531
+ writeSucceeded: false,
2532
+ };
2533
+ const goalRuntime: GoalRuntime = {
2534
+ continuationScheduled: false,
2535
+ continuationHeld: false,
2536
+ goalTurnInFlight: false,
2537
+ agentEndObserved: false,
2538
+ persistenceRetryNeeded: false,
2539
+ };
1191
2540
  registerShellUi(pi);
1192
2541
  registerConcisePrompt(pi);
2542
+ registerGoal(pi, goalRuntime, initState);
2543
+ registerPersonalInstructions(pi, initState);
1193
2544
  registerQuestionTool(pi);
2545
+ registerSubagentTool(pi);
1194
2546
  registerAliases(pi);
1195
2547
  registerSlashAutocomplete(pi);
1196
- registerFooter(pi);
2548
+ registerFooter(pi, goalRuntime);
1197
2549
  registerVariants(pi);
2550
+ registerInitCommand(pi, initState, goalRuntime);
2551
+ registerLifecycleHooks(pi);
2552
+ registerGoalSettlement(pi, goalRuntime, initState);
2553
+ registerInitSettlement(pi, initState);
1198
2554
  }