paseo-plugin-zcode-provider 0.5.0 → 0.5.2

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/server/goal.ts ADDED
@@ -0,0 +1,58 @@
1
+ import type { GoalState } from "./vendor/zcode/packages/shared/src/zcode-protocol-v4/snapshot.js";
2
+ import {
3
+ buildConversationGoalIterationSummaries,
4
+ getConversationGoalElapsedSeconds,
5
+ } from "./vendor/zcode/packages/ui/src/v4/conversationGoalSummaryModel.js";
6
+ import type { GoalView } from "../shared/goal.js";
7
+
8
+ /** The goal as ZCode Desktop's status panel lays it out. */
9
+ export function goalView(
10
+ agentId: string,
11
+ goal: GoalState,
12
+ now: number,
13
+ ): GoalView {
14
+ const inProgress =
15
+ goal.status === "active" ||
16
+ goal.status === "verifying" ||
17
+ goal.status === "notSatisfied";
18
+ return {
19
+ agentId,
20
+ status: goal.status,
21
+ // The daemon's clock and ZCode's are the same host's; a client's is not.
22
+ elapsedSeconds: getConversationGoalElapsedSeconds(goal, now),
23
+ running: inProgress && goal.activeRunStartedAtMs != null,
24
+ iterations: buildConversationGoalIterationSummaries(goal).map((row) => ({
25
+ iteration: row.iteration,
26
+ title: row.title,
27
+ completedCount: row.completedCount,
28
+ totalCount: row.totalCount,
29
+ completed: row.completed,
30
+ })),
31
+ };
32
+ }
33
+
34
+ /**
35
+ * The open sessions by Paseo agent. A provider session ID is Paseo's own and
36
+ * changes on every open, so clients name the agent instead (ADR 27).
37
+ */
38
+ export class GoalDirectory {
39
+ private readonly sessions = new Map<string, () => GoalState | null>();
40
+
41
+ /** Returns the function that removes the session again. */
42
+ register(agentId: string, read: () => GoalState | null): () => void {
43
+ this.sessions.set(agentId, read);
44
+ return () => {
45
+ // Paseo can open an agent's next session before closing the previous one.
46
+ if (this.sessions.get(agentId) === read) this.sessions.delete(agentId);
47
+ };
48
+ }
49
+
50
+ views(now = Date.now()): GoalView[] {
51
+ const views: GoalView[] = [];
52
+ for (const [agentId, read] of this.sessions) {
53
+ const goal = read();
54
+ if (goal) views.push(goalView(agentId, goal, now));
55
+ }
56
+ return views;
57
+ }
58
+ }
@@ -165,7 +165,10 @@ export function rowTimeline(
165
165
  case "timelineMarker":
166
166
  // Paseo appends every notification it receives, so a changing row is
167
167
  // reported once, in its final state.
168
- if (row.marker.type === "compact" && row.marker.status === "running")
168
+ if (
169
+ (row.marker.type === "compact" && row.marker.status === "running") ||
170
+ (row.marker.type === "goalVerify" && row.marker.outcome === "running")
171
+ )
169
172
  return;
170
173
  return {
171
174
  id,
@@ -51,6 +51,8 @@ import {
51
51
  } from "./session.js";
52
52
  import { SessionSnapshotSchema, SessionListSchema } from "./host/schemas.js";
53
53
  import { TimelineSnapshots } from "./timeline.js";
54
+ import { GoalDirectory } from "./goal.js";
55
+ import { parseGoalCommand } from "./goal-command.js";
54
56
  import type { NativeSessionEvent } from "./session-types.js";
55
57
  import {
56
58
  defaultTimelinePreferences,
@@ -116,6 +118,8 @@ interface SessionEntry {
116
118
  messages: Map<string, boolean>;
117
119
  inputGeneration: number;
118
120
  queue: Promise<void>;
121
+ /** Removes the session from the goal directory. */
122
+ forgetGoal: () => void;
119
123
  }
120
124
 
121
125
  export function createZCodeProvider(
@@ -123,6 +127,7 @@ export function createZCodeProvider(
123
127
  persistenceStore = new SessionPersistenceStore(),
124
128
  status: ProviderRegistration["status"] = createRuntimeStatus(),
125
129
  timeline: () => TimelinePreferences = () => defaultTimelinePreferences,
130
+ goals = new GoalDirectory(),
126
131
  ): ProviderRegistration {
127
132
  return {
128
133
  id: "zcode",
@@ -141,6 +146,7 @@ export function createZCodeProvider(
141
146
  bridgeFactory,
142
147
  persistenceStore,
143
148
  timeline,
149
+ goals,
144
150
  );
145
151
  },
146
152
  };
@@ -162,6 +168,7 @@ export class ZCodeConnection implements ProviderConnection {
162
168
  private readonly bridgeFactory: BridgeFactory,
163
169
  private readonly persistenceStore: SessionPersistenceStore,
164
170
  private readonly timeline: () => TimelinePreferences,
171
+ private readonly goals = new GoalDirectory(),
165
172
  ) {}
166
173
 
167
174
  onEvent(listener: (event: ProviderEvent) => void): () => void {
@@ -418,6 +425,25 @@ export class ZCodeConnection implements ProviderConnection {
418
425
  ? prompt.arguments.trim()
419
426
  : (text?.match(/^\/plan(?:\s+([\s\S]*))?$/)?.[1]?.trim() ??
420
427
  (text === "/plan" ? "" : undefined));
428
+ // The command ran without a turn.
429
+ const completed = () => {
430
+ entry.messages.set(input.prompt.clientMessageId, true);
431
+ this.emit({
432
+ type: "session.prompt_result",
433
+ sessionId: input.sessionId,
434
+ clientMessageId: input.prompt.clientMessageId,
435
+ result: { type: "completed" },
436
+ });
437
+ };
438
+ const beforeSend = async () => {
439
+ if (!entry.submitted) {
440
+ await this.persistenceStore.save(
441
+ entry.persistence,
442
+ entry.native.id,
443
+ );
444
+ entry.submitted = true;
445
+ }
446
+ };
421
447
  if (planTask !== undefined) {
422
448
  if (prompt.type === "message" && prompt.content.length !== 1)
423
449
  throw new AdapterError(
@@ -426,34 +452,51 @@ export class ZCodeConnection implements ProviderConnection {
426
452
  );
427
453
  await entry.native.configureMode(undefined, true);
428
454
  if (!planTask) {
429
- entry.messages.set(input.prompt.clientMessageId, true);
430
- this.emit({
431
- type: "session.prompt_result",
432
- sessionId: input.sessionId,
433
- clientMessageId: input.prompt.clientMessageId,
434
- result: { type: "completed" },
435
- });
455
+ completed();
436
456
  return;
437
457
  }
438
458
  }
459
+ const command =
460
+ prompt.type === "command"
461
+ ? `/${prompt.name}${prompt.arguments ? ` ${prompt.arguments}` : ""}`
462
+ : undefined;
463
+ // Like /plan, /goal is not text to the Server: ZCode Desktop sends the
464
+ // V4 goal commands for it (ADR 27).
465
+ const goalText =
466
+ command ??
467
+ (prompt.type === "message" && prompt.content.length === 1
468
+ ? text
469
+ : undefined);
470
+ const goal =
471
+ planTask === undefined && goalText !== undefined
472
+ ? parseGoalCommand(goalText)
473
+ : undefined;
474
+ if (goal?.kind === "empty" || goal?.kind === "unsupported")
475
+ throw new AdapterError(
476
+ "INVALID_CONFIGURATION",
477
+ goal.kind === "empty"
478
+ ? "Usage: /goal <objective>, /goal pause or /goal resume"
479
+ : `ZCode's Server has no /goal ${goal.action}. Use /goal <objective> to replace the goal, or /goal pause.`,
480
+ );
481
+ if (goal?.kind === "pause") {
482
+ await entry.native.pauseGoal();
483
+ completed();
484
+ return;
485
+ }
486
+ if (goal) {
487
+ await entry.native.startGoal(goal, {
488
+ clientMessageId: input.prompt.clientMessageId,
489
+ beforeSend,
490
+ });
491
+ return;
492
+ }
439
493
  await entry.native.startTurn(
440
- planTask ??
441
- (prompt.type === "command"
442
- ? `/${prompt.name}${prompt.arguments ? ` ${prompt.arguments}` : ""}`
443
- : prompt.content),
494
+ planTask ?? (prompt.type === "command" ? command! : prompt.content),
444
495
  {
445
496
  clientMessageId: input.prompt.clientMessageId,
446
497
  delivery: input.prompt.delivery,
447
498
  clearPendingPermissions: input.prompt.clearPendingPermissions,
448
- beforeSend: async () => {
449
- if (!entry.submitted) {
450
- await this.persistenceStore.save(
451
- entry.persistence,
452
- entry.native.id,
453
- );
454
- entry.submitted = true;
455
- }
456
- },
499
+ beforeSend,
457
500
  },
458
501
  );
459
502
  return;
@@ -531,6 +574,7 @@ export class ZCodeConnection implements ProviderConnection {
531
574
  const nativeId = await this.persistenceStore.resolve(persistence);
532
575
  const host = await this.host(config.env, cwd);
533
576
  let native: ZCodeSession | undefined;
577
+ let forgetGoal = () => {};
534
578
  try {
535
579
  const { selection } = await initializeWorkspace(host, cwd);
536
580
  const requested = nativeId
@@ -621,8 +665,17 @@ export class ZCodeConnection implements ProviderConnection {
621
665
  messages: new Map(),
622
666
  inputGeneration: 0,
623
667
  queue: Promise.resolve(),
668
+ forgetGoal() {},
624
669
  };
625
670
  this.sessions.set(input.sessionId, entry);
671
+ // Paseo sets PASEO_AGENT_ID in the launch environment of every session.
672
+ const agentId = config.env.PASEO_AGENT_ID;
673
+ if (agentId) {
674
+ const session = native;
675
+ forgetGoal = entry.forgetGoal = this.goals.register(agentId, () =>
676
+ session.goal(),
677
+ );
678
+ }
626
679
  this.emit({
627
680
  type: "session.opened",
628
681
  requestId: input.requestId,
@@ -666,6 +719,7 @@ export class ZCodeConnection implements ProviderConnection {
666
719
  });
667
720
  } catch (error) {
668
721
  this.sessions.delete(input.sessionId);
722
+ forgetGoal();
669
723
  try {
670
724
  await native?.close();
671
725
  } finally {
@@ -802,6 +856,7 @@ export class ZCodeConnection implements ProviderConnection {
802
856
  private async closeSession(id: string): Promise<void> {
803
857
  const entry = this.requireSession(id);
804
858
  this.sessions.delete(id);
859
+ entry.forgetGoal();
805
860
  try {
806
861
  await entry.native.close();
807
862
  } finally {
package/server/session.ts CHANGED
@@ -15,6 +15,7 @@ import type {
15
15
  ConversationRow,
16
16
  TurnHeaderRow,
17
17
  } from "./vendor/zcode/packages/shared/src/zcode-protocol-v4/rows.js";
18
+ import type { GoalState } from "./vendor/zcode/packages/shared/src/zcode-protocol-v4/snapshot.js";
18
19
  import { Conversation, conversationCommand } from "./conversation.js";
19
20
  import {
20
21
  rowTimeline,
@@ -24,6 +25,7 @@ import {
24
25
  } from "./presentation.js";
25
26
  import { readModelSelection, resolveModelSelection } from "./models.js";
26
27
  import { uploadAttachments } from "./attachments.js";
28
+ import { parseGoalCommand, type GoalCommand } from "./goal-command.js";
27
29
  import {
28
30
  catalogModels,
29
31
  decodeModel,
@@ -218,9 +220,16 @@ export class ZCodeSession {
218
220
  private observe(): void {
219
221
  if (!this.initialized || this.failed || this.closed) return;
220
222
  for (const row of this.state.rows.window) {
221
- if (row.kind === "userInput" && row.sourceCommandId) {
223
+ // ZCode has taken up an input once a row carries its command ID: its
224
+ // user input row, or the header of the turn it started. Compaction adds
225
+ // no user input row (ADR 28). Later turns can carry the same ID, as each
226
+ // turn toward a goal does; they are not that input again.
227
+ if (
228
+ (row.kind === "userInput" || row.kind === "turnHeader") &&
229
+ row.sourceCommandId
230
+ ) {
222
231
  const input = this.admissions.get(row.sourceCommandId);
223
- if (input) {
232
+ if (input && (row.kind === "userInput" || !input.consumed)) {
224
233
  input.consumed = true;
225
234
  input.productTurnId = this.productTurn(row);
226
235
  if (this.active?.inputs.has(row.sourceCommandId)) {
@@ -638,14 +647,210 @@ export class ZCodeSession {
638
647
  "SESSION_BUSY",
639
648
  "ZCode cannot accept this input in its current execution state",
640
649
  );
650
+ return this.admit(
651
+ previous,
652
+ {
653
+ clientMessageId: options?.clientMessageId,
654
+ releasesInteractions: options?.clearPendingPermissions === true,
655
+ },
656
+ async ({ commandId, assertSending, sending }) => {
657
+ const native = await mapPrompt(prompt, this.workspace);
658
+ if (!native.content.trim() && !native.attachments.length)
659
+ throw new AdapterError(
660
+ "UNSUPPORTED_CONTENT",
661
+ "ZCode requires nonempty input",
662
+ );
663
+ if (previous && native.content.trimStart().startsWith("/"))
664
+ throw new AdapterError(
665
+ "SESSION_BUSY",
666
+ "ZCode commands require an idle session",
667
+ );
668
+ // Text input does not interpret /goal; the model would read it as is.
669
+ if (parseGoalCommand(native.content))
670
+ throw new AdapterError(
671
+ "INVALID_CONFIGURATION",
672
+ "The /goal command requires a single text input without attachments",
673
+ );
674
+ await options?.beforeSend?.();
675
+ assertSending();
676
+ if (!previous && !this.state.queue.autoDrain)
677
+ await this.control("setAutoDrain", { autoDrain: true });
678
+ const attachments = await uploadAttachments(
679
+ this.bridge,
680
+ this.workspace,
681
+ this.id,
682
+ native.attachments,
683
+ assertSending,
684
+ );
685
+ assertSending();
686
+ const config = this.state.config;
687
+ if (!config.modelSelection?.options?.reasoningLevel)
688
+ throw new AdapterError(
689
+ "INVALID_CONFIGURATION",
690
+ "Select a ZCode model and reasoning level before sending",
691
+ );
692
+ sending();
693
+ const ack = await conversationCommand(
694
+ this.bridge,
695
+ this.workspace,
696
+ this.id,
697
+ "sendText",
698
+ {
699
+ text: native.content,
700
+ attachments,
701
+ modelSelection: config.modelSelection,
702
+ mode: config.mode,
703
+ planEnabled: config.planEnabled === true,
704
+ toolDisallowlist: [...UNSUPPORTED_TOOLS],
705
+ requestedDelivery: previous
706
+ ? attachments.length
707
+ ? "queue"
708
+ : "guide"
709
+ : "startNow",
710
+ },
711
+ { commandId },
712
+ );
713
+ if (["failed", "rejected", "stale", "noop"].includes(ack.status))
714
+ throw new AdapterError(
715
+ "NATIVE_INPUT_REJECTED",
716
+ "ZCode rejected the input",
717
+ );
718
+ if (
719
+ ack.status !== "accepted" ||
720
+ ack.result?.type !== "inputAccepted" ||
721
+ ack.result.inputId !== commandId
722
+ )
723
+ throw new AdapterError(
724
+ "NATIVE_PROTOCOL_ERROR",
725
+ "ZCode input acknowledgement is inconsistent",
726
+ );
727
+ },
728
+ );
729
+ }
730
+ /**
731
+ * `/goal <objective>` and `/goal resume`. ZCode records the goal and starts
732
+ * the turn that works toward it; that turn and its verification belong to
733
+ * this run. ZCode starts later iterations itself, as turns of their own.
734
+ */
735
+ async startGoal(
736
+ command: Extract<GoalCommand, { kind: "set" | "resume" }>,
737
+ options: { clientMessageId: string; beforeSend?: () => Promise<void> },
738
+ ): Promise<{ turnId: string }> {
739
+ this.assertIdle();
740
+ // The Server rejects the two together, in any order.
741
+ if (this.state.config.planEnabled)
742
+ throw new AdapterError(
743
+ "INVALID_CONFIGURATION",
744
+ "ZCode cannot work toward a goal in Plan mode. Turn Plan mode off first.",
745
+ );
746
+ if (
747
+ command.kind === "resume" &&
748
+ !this.state.availability.resumeGoal.allowed
749
+ )
750
+ throw new AdapterError(
751
+ "INVALID_CONFIGURATION",
752
+ "ZCode has no paused goal to resume",
753
+ );
754
+ return this.admit(
755
+ undefined,
756
+ {
757
+ clientMessageId: options.clientMessageId,
758
+ // Resuming adds no user input row; the turn it starts is the evidence.
759
+ consumed: command.kind === "resume",
760
+ },
761
+ async ({ commandId, assertSending, sending }) => {
762
+ await options.beforeSend?.();
763
+ assertSending();
764
+ if (!this.state.queue.autoDrain)
765
+ await this.control("setAutoDrain", { autoDrain: true });
766
+ assertSending();
767
+ const config = this.state.config;
768
+ if (!config.modelSelection?.options?.reasoningLevel)
769
+ throw new AdapterError(
770
+ "INVALID_CONFIGURATION",
771
+ "Select a ZCode model and reasoning level before sending",
772
+ );
773
+ sending();
774
+ // sendGoalCommand takes no toolDisallowlist; see ADR 27.
775
+ const ack =
776
+ command.kind === "resume"
777
+ ? await this.cas("resumeGoal", {})
778
+ : await conversationCommand(
779
+ this.bridge,
780
+ this.workspace,
781
+ this.id,
782
+ "sendGoalCommand",
783
+ {
784
+ text: command.objective,
785
+ displayText: command.displayText,
786
+ modelSelection: config.modelSelection,
787
+ mode: config.mode,
788
+ planEnabled: false,
789
+ },
790
+ { commandId },
791
+ );
792
+ if (ack.status !== "accepted")
793
+ throw new AdapterError(
794
+ "NATIVE_INPUT_REJECTED",
795
+ "ZCode rejected the goal command",
796
+ );
797
+ },
798
+ );
799
+ }
800
+ /**
801
+ * `/goal pause`, for a goal that stays active without a turn. Stopping a
802
+ * turn pauses its goal in ZCode itself.
803
+ */
804
+ async pauseGoal(): Promise<void> {
805
+ this.assertIdle();
806
+ // Typed during a turn, the command arrives after Paseo stopped that turn,
807
+ // which paused the goal already.
808
+ if (this.state.goal?.status === "paused") return;
809
+ if (!this.state.availability.pauseGoal.allowed)
810
+ throw new AdapterError(
811
+ "INVALID_CONFIGURATION",
812
+ "ZCode has no active goal to pause",
813
+ );
814
+ const ack = await this.cas("pauseGoal", {});
815
+ if (ack.status !== "accepted")
816
+ throw new AdapterError(
817
+ "NATIVE_INPUT_REJECTED",
818
+ "ZCode rejected the goal command",
819
+ );
820
+ await this.conversation.waitFor(
821
+ () => !this.state.availability.pauseGoal.allowed,
822
+ );
823
+ }
824
+ /** The goal of the conversation, for the Goal pill (ADR 27). */
825
+ goal(): GoalState | null {
826
+ return this.conversation.state?.goal ?? null;
827
+ }
828
+ /**
829
+ * Admits one input into a run. `send` prepares and issues the command; it
830
+ * calls `sending` before the command leaves and throws
831
+ * NATIVE_INPUT_REJECTED when ZCode refuses it.
832
+ */
833
+ private async admit(
834
+ previous: Run | undefined,
835
+ options: {
836
+ clientMessageId?: string;
837
+ releasesInteractions?: boolean;
838
+ consumed?: boolean;
839
+ },
840
+ send: (context: {
841
+ commandId: string;
842
+ assertSending: () => void;
843
+ sending: () => void;
844
+ }) => Promise<void>,
845
+ ): Promise<{ turnId: string }> {
641
846
  const run = previous ?? this.newRun();
642
847
  this.active = run;
643
848
  run.inFlight++;
644
849
  const commandId = randomUUID(),
645
850
  input: Admission = {
646
- clientMessageId: options?.clientMessageId,
851
+ clientMessageId: options.clientMessageId,
647
852
  accepted: false,
648
- consumed: false,
853
+ consumed: options.consumed === true,
649
854
  };
650
855
  run.inputs.set(commandId, input);
651
856
  this.admissions.set(commandId, input);
@@ -659,74 +864,17 @@ export class ZCodeSession {
659
864
  );
660
865
  };
661
866
  try {
662
- const native = await mapPrompt(prompt, this.workspace);
663
- if (!native.content.trim() && !native.attachments.length)
664
- throw new AdapterError(
665
- "UNSUPPORTED_CONTENT",
666
- "ZCode requires nonempty input",
667
- );
668
- if (previous && native.content.trimStart().startsWith("/"))
669
- throw new AdapterError(
670
- "SESSION_BUSY",
671
- "ZCode commands require an idle session",
672
- );
673
- await options?.beforeSend?.();
674
- assertSending();
675
- if (!previous && !this.state.queue.autoDrain)
676
- await this.control("setAutoDrain", { autoDrain: true });
677
- const attachments = await uploadAttachments(
678
- this.bridge,
679
- this.workspace,
680
- this.id,
681
- native.attachments,
867
+ await send({
868
+ commandId,
682
869
  assertSending,
683
- );
684
- assertSending();
685
- const config = this.state.config;
686
- if (!config.modelSelection?.options?.reasoningLevel)
687
- throw new AdapterError(
688
- "INVALID_CONFIGURATION",
689
- "Select a ZCode model and reasoning level before sending",
690
- );
691
- sent = true;
692
- const ack = await conversationCommand(
693
- this.bridge,
694
- this.workspace,
695
- this.id,
696
- "sendText",
697
- {
698
- text: native.content,
699
- attachments,
700
- modelSelection: config.modelSelection,
701
- mode: config.mode,
702
- planEnabled: config.planEnabled === true,
703
- toolDisallowlist: [...UNSUPPORTED_TOOLS],
704
- requestedDelivery: previous
705
- ? attachments.length
706
- ? "queue"
707
- : "guide"
708
- : "startNow",
870
+ sending: () => {
871
+ sent = true;
709
872
  },
710
- { commandId },
711
- );
712
- if (["failed", "rejected", "stale", "noop"].includes(ack.status))
713
- throw new AdapterError(
714
- "NATIVE_INPUT_REJECTED",
715
- "ZCode rejected the input",
716
- );
717
- if (
718
- ack.status !== "accepted" ||
719
- ack.result?.type !== "inputAccepted" ||
720
- ack.result.inputId !== commandId
721
- )
722
- throw new AdapterError(
723
- "NATIVE_PROTOCOL_ERROR",
724
- "ZCode input acknowledgement is inconsistent",
725
- );
873
+ });
726
874
  this.assertOpen();
727
875
  input.accepted = true;
728
- input.releasesInteractions = options?.clearPendingPermissions === true;
729
- if (options?.clientMessageId)
876
+ input.releasesInteractions = options.releasesInteractions === true;
877
+ if (options.clientMessageId)
730
878
  this.emit({
731
879
  type: "prompt_accepted",
732
880
  clientMessageId: options.clientMessageId,
@@ -754,6 +902,15 @@ export class ZCodeSession {
754
902
  }
755
903
  }
756
904
  private async control(type: string, payload: unknown): Promise<void> {
905
+ const ack = await this.cas(type, payload);
906
+ if (ack.status !== "accepted" && ack.status !== "noop")
907
+ throw new AdapterError(
908
+ "NATIVE_PROTOCOL_ERROR",
909
+ `ZCode ${type} was rejected`,
910
+ );
911
+ }
912
+ /** Sends a command that carries the revision it was decided on. */
913
+ private async cas(type: string, payload: unknown) {
757
914
  this.assertOpen();
758
915
  // A stale CAS proves no mutation occurred. No input is retried here.
759
916
  let revision = this.state.revision;
@@ -766,12 +923,7 @@ export class ZCodeSession {
766
923
  payload,
767
924
  { revision },
768
925
  );
769
- if (ack.status === "accepted" || ack.status === "noop") return;
770
- if (ack.status !== "stale")
771
- throw new AdapterError(
772
- "NATIVE_PROTOCOL_ERROR",
773
- `ZCode ${type} was rejected`,
774
- );
926
+ if (ack.status !== "stale") return ack;
775
927
  revision = ack.revisionAtDecision;
776
928
  }
777
929
  throw new AdapterError(
@@ -831,13 +983,11 @@ export class ZCodeSession {
831
983
  const target = this.state.control.activeWorks.find(
832
984
  (w) => w.foregroundExecutionId,
833
985
  )?.foregroundExecutionId;
834
- if (this.state.control.canStop && !target)
835
- throw new AdapterError(
836
- "NATIVE_PROTOCOL_ERROR",
837
- "ZCode did not identify its stoppable foreground execution",
838
- );
986
+ // The ID keeps a late stop from ending a later execution. The works of a
987
+ // manual compaction name none; like ZCode Desktop, stop without one then.
839
988
  if (target)
840
989
  await this.control("stop", { expectedForegroundExecutionId: target });
990
+ else if (this.state.control.canStop) await this.control("stop", {});
841
991
  await this.conversation.waitFor(
842
992
  () =>
843
993
  !this.state.control.canStop &&