@peakflo/agent-harness 0.2.21 → 0.2.23

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/README.md CHANGED
@@ -18,7 +18,9 @@ Run a Peakflo coding agent on your machine.
18
18
 
19
19
  ## Quick start
20
20
 
21
- Use Node.js 22.19 or newer and install Git. The runner checks the Node.js
21
+ Use a patched Node.js release from the `engines.node` range in this package's
22
+ `package.json` (`npm view @peakflo/agent-harness engines.node`) and install Git.
23
+ The runner checks the Node.js
22
24
  version when it starts and stops with one line if it is older (see
23
25
  "Troubleshooting"). Install the Pi coding agent once:
24
26
 
@@ -321,8 +323,9 @@ public registry for this one command:
321
323
  npx --@peakflo:registry=https://registry.npmjs.org @peakflo/agent-harness@latest start
322
324
  ```
323
325
 
324
- **"pf-agent-harness needs Node.js 22.19 or newer".** Switch to a newer
325
- Node.js, for example `nvm install 22 && nvm use 22`, and start again. npm only
326
+ **"pf-agent-harness needs a patched Node.js release (...)".** The message
327
+ lists the supported range; it is the `engines.node` field of `package.json`.
328
+ Switch to a Node.js inside that range, for example `nvm install 22 && nvm use 22`, and start again. npm only
326
329
  prints an `EBADENGINE` warning for an older Node.js and installs anyway; the
327
330
  runner is what stops. The requirement comes from Pi, which the runner starts
328
331
  with the same Node.js. To start on an older Node.js at your own risk, set
@@ -31,6 +31,7 @@ exports.AcpAdapter = exports.ACP_SESSION_START_TIMEOUT_MS = void 0;
31
31
  const child_process_1 = require("child_process");
32
32
  const crypto_1 = require("crypto");
33
33
  const child_stream_guards_1 = require("../runtime/child-stream-guards");
34
+ const permission_mode_1 = require("../runtime/permission-mode");
34
35
  const path_1 = require("path");
35
36
  const util_1 = require("util");
36
37
  const coding_agent_adapter_1 = require("./coding-agent-adapter");
@@ -1275,10 +1276,10 @@ class AcpAdapter {
1275
1276
  // its own config on the runner. A person answering from the control plane
1276
1277
  // is offered the one-time answers only.
1277
1278
  const oneTimeOptions = allApprovalOptions.filter((option) => !isStandingAcpOption(option));
1278
- const approvalOptions = this.agentType === 'cursor' && session.config.permissionMode !== 'allow' && oneTimeOptions.length > 0
1279
+ const approvalOptions = this.agentType === 'cursor' && (0, permission_mode_1.effectivePermissionMode)(session.config) === 'ask' && oneTimeOptions.length > 0
1279
1280
  ? oneTimeOptions
1280
1281
  : allApprovalOptions;
1281
- if (session.config.permissionMode === 'allow') {
1282
+ if ((0, permission_mode_1.effectivePermissionMode)(session.config) === 'allow') {
1282
1283
  // Cursor saves "allow always" as a standing rule (seen: one bypass
1283
1284
  // turn added Shell(echo) and Shell(cat)). That rule could affect later
1284
1285
  // turns. Every request is approved once instead.
@@ -668,7 +668,7 @@ class ClaudeCodeAdapter {
668
668
  cwd: config.workspaceDir,
669
669
  pathToClaudeCodeExecutable: claudePath,
670
670
  env: this.buildClaudeEnvironment(config),
671
- settingSources: [],
671
+ settingSources: ['project'],
672
672
  mcpServers: config.mcpServers,
673
673
  model: config.model,
674
674
  effort,
@@ -696,10 +696,10 @@ class ClaudeCodeAdapter {
696
696
  * onto — see runtime/permission-mode.ts for the table. Claude Code is the
697
697
  * one backend that takes all four natively, so nothing is lost here.
698
698
  *
699
- * A config with NO permissionMode maps to 'default', NOT to
700
- * 'bypassPermissions'. That is deliberate: the old behaviour must not be
701
- * reachable by omission, or every caller that forgets the field silently
702
- * restores the defect.
699
+ * A config with NO permissionMode gets the new-agent default,
700
+ * 'bypassPermissions' (owner decision: "Allow by default"). The fix for
701
+ * G1 is that an explicit 'ask' is now honoured — the user's choice is
702
+ * read, not hardcoded — so 'default', 'plan' and 'acceptEdits' still ask.
703
703
  */
704
704
  permissionMode: claudePermissionMode,
705
705
  // ONLY for the mode that actually asks for it. The SDK requires this flag
@@ -54,6 +54,7 @@ exports.codexApprovalPolicy = codexApprovalPolicy;
54
54
  const child_process_1 = require("child_process");
55
55
  const fs_1 = require("fs");
56
56
  const child_stream_guards_1 = require("../runtime/child-stream-guards");
57
+ const permission_mode_1 = require("../runtime/permission-mode");
57
58
  const path_1 = require("path");
58
59
  const util_1 = require("util");
59
60
  const coding_agent_adapter_1 = require("./coding-agent-adapter");
@@ -128,11 +129,11 @@ function elicitationFormFields(params) {
128
129
  return [...new Set([...required, ...properties])];
129
130
  }
130
131
  function codexApprovalPolicy(config) {
131
- // `'allow'` is what `mapPermissionMode` makes of the agent's
132
- // `bypassPermissions` ("Don't ask for permission"), and of nothing else.
133
- // Only an explicit "allow" runs without asking. Anything else, including a
134
- // value this build does not know, asks.
135
- return config.permissionMode === 'allow' ? 'never' : 'untrusted';
132
+ // `'ask'` is what `mapPermissionMode` makes of an asking mode (default,
133
+ // plan, acceptEdits, or a value this build does not know); that asks before
134
+ // every command not known to be read-only. `'allow'`, and a config with no
135
+ // mode at all (the new-agent default), runs without asking.
136
+ return (0, permission_mode_1.effectivePermissionMode)(config) === 'ask' ? 'untrusted' : 'never';
136
137
  }
137
138
  const MAX_IPC_TOOL_INPUT_CHARS = 20_000;
138
139
  const MAX_IPC_TOOL_OUTPUT_CHARS = 100_000;
@@ -995,7 +996,7 @@ class CodexAppServerAdapter {
995
996
  this.addEvent(session, notification);
996
997
  }
997
998
  handleApprovalRequest(session, request, params) {
998
- if (session.config.permissionMode === 'allow') {
999
+ if ((0, permission_mode_1.effectivePermissionMode)(session.config) === 'allow') {
999
1000
  const responseKind = this.getApprovalResponseKind(request.method);
1000
1001
  const selected = responseKind === 'execCommand' ? 'approved' : 'accept';
1001
1002
  this.sendRpcResponse(session, request.id, this.buildApprovalResponse(responseKind, selected, true, params.permissions));
@@ -17,6 +17,7 @@ exports.resolveCursorModeValue = resolveCursorModeValue;
17
17
  exports.isCursorPlanLimitReply = isCursorPlanLimitReply;
18
18
  exports.mayBecomeCursorPlanLimitReply = mayBecomeCursorPlanLimitReply;
19
19
  exports.describeAcpRpcError = describeAcpRpcError;
20
+ const permission_mode_1 = require("../runtime/permission-mode");
20
21
  function isRecord(value) {
21
22
  return typeof value === 'object' && value !== null && !Array.isArray(value);
22
23
  }
@@ -126,8 +127,10 @@ function resolveCursorModelValue(model, sessionResult) {
126
127
  * A permission request Cursor does raise is still put to the person.
127
128
  */
128
129
  function cursorModeFor(config) {
129
- // Only an explicit "allow" may act. An unknown value is treated as asking.
130
- if (config.permissionMode === 'allow')
130
+ // Only an explicit "ask" restricts Cursor. A config with no mode gets the
131
+ // new-agent default ("allow"); `mapPermissionMode` already turned an unknown
132
+ // lease value into "ask".
133
+ if ((0, permission_mode_1.effectivePermissionMode)(config) === 'allow')
131
134
  return 'agent';
132
135
  return config.sandboxMode === 'read-only' ? 'plan' : 'ask';
133
136
  }
@@ -25,6 +25,7 @@ const opencode_server_policy_1 = require("./opencode-server-policy");
25
25
  const opencode_config_1 = require("./opencode-config");
26
26
  const model_gateway_1 = require("./model-gateway");
27
27
  const coding_agent_adapter_1 = require("./coding-agent-adapter");
28
+ const permission_mode_1 = require("../runtime/permission-mode");
28
29
  /**
29
30
  * A REAL dynamic ESM import, which `await import(...)` is not in this package.
30
31
  *
@@ -1110,7 +1111,7 @@ class OpencodeAdapter {
1110
1111
  * completion in `ask` mode and NOT ONE raised a prompt, while the file on
1111
1112
  * disk said `"bash": "ask"` the whole time. Do not move this below.
1112
1113
  */
1113
- this.writeSessionPermissionConfig(config.workspaceDir, config.permissionMode || 'ask');
1114
+ this.writeSessionPermissionConfig(config.workspaceDir, (0, permission_mode_1.effectivePermissionMode)(config));
1114
1115
  await this.ensureServerRunning(config.serverUrl || DEFAULT_SERVER_URL, config.environment);
1115
1116
  // Config is pushed once on first server connection (ensureServerRunning).
1116
1117
  // Subsequent config changes (key rotation, settings edit) go through
@@ -1164,7 +1165,7 @@ class OpencodeAdapter {
1164
1165
  this.writeTillDoneSessionConfig(ocSessionId, config.tillDone !== false);
1165
1166
  this.clients.set(ocSessionId, ocClient);
1166
1167
  this.promptClients.set(ocSessionId, promptClient);
1167
- this.sessionPermissionModes.set(ocSessionId, config.permissionMode || 'ask');
1168
+ this.sessionPermissionModes.set(ocSessionId, (0, permission_mode_1.effectivePermissionMode)(config));
1168
1169
  if (config.workspaceDir)
1169
1170
  this.sessionWorkspaceDirs.set(ocSessionId, config.workspaceDir);
1170
1171
  if (config.mcpServers)
@@ -1327,7 +1328,7 @@ class OpencodeAdapter {
1327
1328
  * An `allow` session is the one case where approving is what the user
1328
1329
  * actually chose, and it matches what `handleServerEvent` does live.
1329
1330
  */
1330
- const resumeMode = config.permissionMode || 'ask';
1331
+ const resumeMode = (0, permission_mode_1.effectivePermissionMode)(config);
1331
1332
  const staleReply = resumeMode === 'allow' ? 'always' : 'reject';
1332
1333
  const listResult = await v2.permission.list({});
1333
1334
  if (listResult.data && Array.isArray(listResult.data)) {
@@ -1353,7 +1354,7 @@ class OpencodeAdapter {
1353
1354
  }
1354
1355
  this.clients.set(sessionId, ocClient);
1355
1356
  this.promptClients.set(sessionId, promptClient);
1356
- this.sessionPermissionModes.set(sessionId, config.permissionMode || 'ask');
1357
+ this.sessionPermissionModes.set(sessionId, (0, permission_mode_1.effectivePermissionMode)(config));
1357
1358
  if (config.workspaceDir)
1358
1359
  this.sessionWorkspaceDirs.set(sessionId, config.workspaceDir);
1359
1360
  if (config.mcpServers)
@@ -1361,7 +1362,7 @@ class OpencodeAdapter {
1361
1362
  // WIRE 5, on the resume path too. A workspace is rebuilt per turn, so a
1362
1363
  // resumed session that skipped this would silently run unrestricted — the
1363
1364
  // defect returning on the SECOND message of every conversation.
1364
- this.writeSessionPermissionConfig(config.workspaceDir, config.permissionMode || 'ask');
1365
+ this.writeSessionPermissionConfig(config.workspaceDir, (0, permission_mode_1.effectivePermissionMode)(config));
1365
1366
  this.writeTillDoneSessionConfig(sessionId, config.tillDone !== false);
1366
1367
  // Fetch existing messages
1367
1368
  const messagesResult = await ocClient.session.messages({
@@ -2612,7 +2613,7 @@ class OpencodeAdapter {
2612
2613
  }
2613
2614
  console.log(`[OpencodeAdapter] Permission requested: ${permission} for session ${sessionID} (${permissionId}) patterns=${patterns.join(', ')}`);
2614
2615
  // Auto-approve if the agent's permission mode is 'allow'
2615
- const mode = this.sessionPermissionModes.get(sessionID) || 'ask';
2616
+ const mode = this.sessionPermissionModes.get(sessionID) || 'allow';
2616
2617
  if (mode === 'allow') {
2617
2618
  console.log(`[OpencodeAdapter] Auto-approving permission ${permissionId} (permissionMode=allow)`);
2618
2619
  this.autoApprovePermission(sessionID, permissionId).catch((err) => {
@@ -26,6 +26,7 @@ const vendor_environment_1 = require("./vendor-environment");
26
26
  const browser_takeover_1 = require("../runtime/browser-takeover");
27
27
  const cold_start_steps_1 = require("../runtime/cold-start-steps");
28
28
  const dev_server_guard_1 = require("../runtime/dev-server-guard");
29
+ const permission_mode_1 = require("../runtime/permission-mode");
29
30
  const execFileAsync = (0, util_1.promisify)(child_process_1.execFile);
30
31
  const RPC_TIMEOUT_MS = 15_000;
31
32
  const MAX_BUFFERED_PARTS = 1_000;
@@ -569,7 +570,7 @@ class PiAdapter {
569
570
  ...(config.environment ?? {}),
570
571
  ...(config.secretEnvVars ?? {}),
571
572
  ...(gateway ? { PEAKFLO_AI_GATEWAY_API_KEY: gateway.apiKey } : {}),
572
- [PI_PERMISSION_MODE_ENV]: config.permissionMode ?? 'ask'
573
+ [PI_PERMISSION_MODE_ENV]: (0, permission_mode_1.effectivePermissionMode)(config)
573
574
  };
574
575
  delete env.AI_AGENT;
575
576
  delete env.PI_CODING_AGENT;
@@ -1079,7 +1080,8 @@ class PiAdapter {
1079
1080
  ? event.options.filter((option) => typeof option === 'string')
1080
1081
  : []
1081
1082
  };
1082
- if (method === 'confirm' && session.config.permissionMode === 'allow') {
1083
+ if (method === 'confirm' &&
1084
+ (0, permission_mode_1.effectivePermissionMode)(session.config) === 'allow') {
1083
1085
  this.sendRecord(session, {
1084
1086
  type: 'extension_ui_response',
1085
1087
  id,
package/dist/cli.js CHANGED
@@ -96,7 +96,8 @@ Options:
96
96
  default for desktop/self-hosted; never runs
97
97
  in a sandbox.
98
98
 
99
- Needs Node.js 22.19 or newer; start stops with one line on an older one.
99
+ Needs a Node.js release in the engines.node range of package.json; start stops
100
+ with one line (exit code 1) that names the range on any other release.
100
101
  PF_ALLOW_UNSUPPORTED_NODE=1 starts anyway, at your own risk.
101
102
 
102
103
  In a managed sandbox pf-bootstrap hands the token over a private IPC channel,
@@ -96,8 +96,9 @@ export declare function isProtocolSupported(peerProtocolVersion: unknown, floor?
96
96
  * ingest and must exit rather than hammer a control plane that will never
97
97
  * serve them.
98
98
  *
99
- * 401 IS FINAL, AND THAT IS DELIBERATE — a harness must NOT try to rotate its
100
- * way out of one. Rotation is authenticated with the CURRENT credential, so a
99
+ * 401 IS FINAL, AND THAT IS DELIBERATE — a harness must NOT loop trying to
100
+ * rotate its way out of one. (It makes ONE rotation attempt on a heartbeat 401,
101
+ * in case the credential is only skewed, then stops.) Rotation is authenticated with the CURRENT credential, so a
101
102
  * credential that has already expired cannot rotate itself; a harness that
102
103
  * tried would loop between two routes that can only both fail. `rotateAfter`
103
104
  * is the mechanism: rotate on schedule, comfortably before expiry, and treat
package/dist/contract.js CHANGED
@@ -115,8 +115,9 @@ function isProtocolSupported(peerProtocolVersion, floor = exports.MIN_SUPPORTED_
115
115
  * ingest and must exit rather than hammer a control plane that will never
116
116
  * serve them.
117
117
  *
118
- * 401 IS FINAL, AND THAT IS DELIBERATE — a harness must NOT try to rotate its
119
- * way out of one. Rotation is authenticated with the CURRENT credential, so a
118
+ * 401 IS FINAL, AND THAT IS DELIBERATE — a harness must NOT loop trying to
119
+ * rotate its way out of one. (It makes ONE rotation attempt on a heartbeat 401,
120
+ * in case the credential is only skewed, then stops.) Rotation is authenticated with the CURRENT credential, so a
120
121
  * credential that has already expired cannot rotate itself; a harness that
121
122
  * tried would loop between two routes that can only both fail. `rotateAfter`
122
123
  * is the mechanism: rotate on schedule, comfortably before expiry, and treat
@@ -47,6 +47,12 @@ export interface StoredCredential {
47
47
  credential: string;
48
48
  /** ISO 8601, or null when the control plane returned no expiry. */
49
49
  credentialExpiresAt: string | null;
50
+ /**
51
+ * ISO 8601. When the control plane wants this credential rotated. Persisted
52
+ * so a restart can resume the schedule instead of waiting for a fresh
53
+ * registration (which a stored-credential start never has).
54
+ */
55
+ rotateAfter?: string | null;
50
56
  /** ISO 8601. When this row was written, for operator diagnostics. */
51
57
  savedAt: string;
52
58
  }
package/dist/harness.d.ts CHANGED
@@ -51,7 +51,7 @@ export declare class VersionRefusedError extends Error {
51
51
  }
52
52
  /** A service cannot re-enrol without a new one-time token from a user. */
53
53
  export declare class StoredCredentialUnavailableError extends Error {
54
- constructor();
54
+ constructor(reason?: string);
55
55
  }
56
56
  /** The sandbox supervisor, not the harness, owns package installation. */
57
57
  export declare class UpgradeRequestedError extends Error {
@@ -243,6 +243,13 @@ export declare class Harness {
243
243
  private lastHeartbeatAt;
244
244
  private lastHeartbeatError;
245
245
  private consecutiveHeartbeatFailures;
246
+ /**
247
+ * True while the harness drains ONLY because heartbeats failed ("presumed
248
+ * offline"). It is not a drain the control plane asked for, so it ends on
249
+ * the first heartbeat that gets through, and the lease loop waits instead of
250
+ * exiting.
251
+ */
252
+ private offlineDraining;
246
253
  private stopping;
247
254
  /** Releases this Harness's reference to the process-wide generic wrappers. */
248
255
  private releaseGitHubGuard;
@@ -338,6 +345,16 @@ export declare class Harness {
338
345
  * will surface that.
339
346
  */
340
347
  private rotateCredential;
348
+ /**
349
+ * The control plane answered 401/403 to the runner credential.
350
+ *
351
+ * Try ONE rotation first: a credential that is merely close to the edge (a
352
+ * clock skew, a heartbeat that raced the expiry) may still rotate. If it
353
+ * cannot, the credential is gone. A service has no token to enrol with, so
354
+ * retrying would loop for ever. Stop with a message that says what to do and
355
+ * a non-zero exit so launchd and systemd show a failure.
356
+ */
357
+ private handleCredentialRejected;
341
358
  /**
342
359
  * Re-probe the model catalogue.
343
360
  *
package/dist/harness.js CHANGED
@@ -30,6 +30,8 @@ const vendor_backends_1 = require("./vendor-backends");
30
30
  const version_1 = require("./version");
31
31
  /** Backoff after a lease poll fails, so an unreachable control plane is not hammered. */
32
32
  const LEASE_ERROR_BACKOFF_MS = 5_000;
33
+ /** The longest wait between heartbeat retries while the control plane is unreachable. */
34
+ const OFFLINE_RETRY_CAP_MS = 60_000;
33
35
  const LEASE_MIN_EMPTY_POLL_MS = 250;
34
36
  /**
35
37
  * How often the model catalogue is re-probed once the harness is running.
@@ -117,8 +119,8 @@ class VersionRefusedError extends Error {
117
119
  exports.VersionRefusedError = VersionRefusedError;
118
120
  /** A service cannot re-enrol without a new one-time token from a user. */
119
121
  class StoredCredentialUnavailableError extends Error {
120
- constructor() {
121
- super('No usable stored runner credential. For your own agent, open Agents in Spaces and use "Reconnect" on this machine (or "Connect your own agent") to get a new command, then run it here. For a self-hosted runner, start it once in a terminal to sign in again.');
122
+ constructor(reason) {
123
+ super(`${reason ? `${reason} ` : ''}No usable stored runner credential. For your own agent, open Agents in Spaces and use "Reconnect" on this machine (or "Connect your own agent") to get a new command, then run it here. For a self-hosted runner, start it once in a terminal to sign in again.`);
122
124
  this.name = 'StoredCredentialUnavailableError';
123
125
  }
124
126
  }
@@ -263,6 +265,13 @@ class Harness {
263
265
  lastHeartbeatAt = null;
264
266
  lastHeartbeatError = null;
265
267
  consecutiveHeartbeatFailures = 0;
268
+ /**
269
+ * True while the harness drains ONLY because heartbeats failed ("presumed
270
+ * offline"). It is not a drain the control plane asked for, so it ends on
271
+ * the first heartbeat that gets through, and the lease loop waits instead of
272
+ * exiting.
273
+ */
274
+ offlineDraining = false;
266
275
  stopping = false;
267
276
  /** Releases this Harness's reference to the process-wide generic wrappers. */
268
277
  releaseGitHubGuard = null;
@@ -706,6 +715,10 @@ class Harness {
706
715
  this.observeHarnessPin(response.harnessVersion);
707
716
  this.observeSandboxToolsPin(response.sandboxToolsVersion);
708
717
  this.applyCommandsSafely(response.sessionCommands ?? []);
718
+ // THE STORED-CREDENTIAL START MUST ROTATE TOO. This is the path every
719
+ // background service takes. Without a timer here the credential lived
720
+ // out its 24 h TTL and the service stopped for good.
721
+ this.scheduleRotation(stored.rotateAfter ?? undefined, stored.credentialExpiresAt ?? undefined);
709
722
  log('Reused stored runner credential', {
710
723
  runnerId: stored.runnerId,
711
724
  tenantId: stored.tenantId
@@ -731,6 +744,7 @@ class Harness {
731
744
  // a good credential over a momentary outage.
732
745
  this.tenantId = stored.tenantId;
733
746
  this.runnerId = stored.runnerId;
747
+ this.scheduleRotation(stored.rotateAfter ?? undefined, stored.credentialExpiresAt ?? undefined);
734
748
  log('Could not validate stored credential (transient); proceeding', {
735
749
  runnerId: stored.runnerId,
736
750
  error: error instanceof Error ? error.message : String(error)
@@ -753,6 +767,7 @@ class Harness {
753
767
  tenantId: this.tenantId,
754
768
  credential: response.runnerCredential,
755
769
  credentialExpiresAt: response.credentialExpiresAt ?? null,
770
+ rotateAfter: response.rotateAfter ?? null,
756
771
  savedAt: new Date().toISOString()
757
772
  });
758
773
  }
@@ -801,7 +816,7 @@ class Harness {
801
816
  */
802
817
  async rotateCredential() {
803
818
  if (this.stopping) {
804
- return;
819
+ return false;
805
820
  }
806
821
  try {
807
822
  const response = await this.client.rotateCredential((0, version_1.getHarnessVersion)());
@@ -811,6 +826,7 @@ class Harness {
811
826
  tenantId: this.tenantId,
812
827
  credential: response.runnerCredential,
813
828
  credentialExpiresAt: response.credentialExpiresAt ?? null,
829
+ rotateAfter: response.rotateAfter ?? null,
814
830
  savedAt: new Date().toISOString()
815
831
  });
816
832
  for (const renewal of this.activeRenewals) {
@@ -819,6 +835,7 @@ class Harness {
819
835
  }
820
836
  log('Rotated runner credential', { rotateAfter: response.rotateAfter });
821
837
  this.scheduleRotation(response.rotateAfter, response.credentialExpiresAt);
838
+ return true;
822
839
  }
823
840
  catch (error) {
824
841
  log('Credential rotation failed', {
@@ -831,8 +848,34 @@ class Harness {
831
848
  }, 30_000);
832
849
  this.rotateTimer.unref();
833
850
  }
851
+ return false;
834
852
  }
835
853
  }
854
+ /**
855
+ * The control plane answered 401/403 to the runner credential.
856
+ *
857
+ * Try ONE rotation first: a credential that is merely close to the edge (a
858
+ * clock skew, a heartbeat that raced the expiry) may still rotate. If it
859
+ * cannot, the credential is gone. A service has no token to enrol with, so
860
+ * retrying would loop for ever. Stop with a message that says what to do and
861
+ * a non-zero exit so launchd and systemd show a failure.
862
+ */
863
+ async handleCredentialRejected(error) {
864
+ if (await this.rotateCredential()) {
865
+ log('Runner credential was rejected; rotation succeeded', {
866
+ status: error.status
867
+ });
868
+ return true;
869
+ }
870
+ this.credentialStore.clear();
871
+ this.fatal = new StoredCredentialUnavailableError(`The control plane rejected this runner credential (HTTP ${error.status}${error.code ? `, ${error.code}` : ''}).`);
872
+ log('Runner credential rejected and cannot be rotated; stopping', {
873
+ status: error.status,
874
+ code: error.code
875
+ });
876
+ await this.stop();
877
+ return false;
878
+ }
836
879
  /* ------------------------------------------------------------------ */
837
880
  /* Heartbeat */
838
881
  /* ------------------------------------------------------------------ */
@@ -1187,13 +1230,13 @@ class Harness {
1187
1230
  }
1188
1231
  return Date.now() - this.modelProbeAt >= MODEL_PROBE_REFRESH_MS;
1189
1232
  }
1190
- scheduleHeartbeat() {
1233
+ scheduleHeartbeat(delayMs) {
1191
1234
  if (this.stopping) {
1192
1235
  return;
1193
1236
  }
1194
1237
  this.heartbeatTimer = setTimeout(() => {
1195
1238
  void this.sendHeartbeat();
1196
- }, this.heartbeatIntervalMs);
1239
+ }, delayMs ?? this.heartbeatIntervalMs);
1197
1240
  // Never hold the event loop open on the heartbeat alone.
1198
1241
  this.heartbeatTimer.unref();
1199
1242
  }
@@ -1258,6 +1301,15 @@ class Harness {
1258
1301
  this.lastHeartbeatAt = new Date().toISOString();
1259
1302
  this.lastHeartbeatError = null;
1260
1303
  this.consecutiveHeartbeatFailures = 0;
1304
+ if (this.offlineDraining) {
1305
+ // The network is back and the control plane still knows this runner:
1306
+ // take work again. No re-enrolment is needed, the credential is valid.
1307
+ this.offlineDraining = false;
1308
+ if (this.status === 'draining' && !this.stopping) {
1309
+ this.status = 'ready';
1310
+ log('Control plane reachable again, resuming');
1311
+ }
1312
+ }
1261
1313
  if (response.heartbeatIntervalMs) {
1262
1314
  this.heartbeatIntervalMs = response.heartbeatIntervalMs;
1263
1315
  }
@@ -1287,6 +1339,14 @@ class Harness {
1287
1339
  await this.stop();
1288
1340
  return;
1289
1341
  }
1342
+ if (error instanceof control_plane_1.ControlPlaneError &&
1343
+ (error.status === 401 || error.status === 403) &&
1344
+ !this.stopping) {
1345
+ if (await this.handleCredentialRejected(error)) {
1346
+ this.scheduleHeartbeat(1_000);
1347
+ }
1348
+ return;
1349
+ }
1290
1350
  this.consecutiveHeartbeatFailures += 1;
1291
1351
  this.lastHeartbeatError =
1292
1352
  error instanceof Error ? error.message : String(error);
@@ -1300,10 +1360,16 @@ class Harness {
1300
1360
  if (this.consecutiveHeartbeatFailures >= contract_1.MISSED_HEARTBEATS_BEFORE_OFFLINE &&
1301
1361
  this.status === 'ready') {
1302
1362
  this.status = 'draining';
1363
+ this.offlineDraining = true;
1303
1364
  log('Presumed offline by the control plane, draining');
1304
1365
  }
1305
1366
  }
1306
- this.scheduleHeartbeat();
1367
+ // Keep retrying while offline, with a capped back-off so a long outage is
1368
+ // not hammered. The first heartbeat that gets through resumes the runner.
1369
+ const failures = this.consecutiveHeartbeatFailures;
1370
+ this.scheduleHeartbeat(failures > 0
1371
+ ? Math.min(this.heartbeatIntervalMs * 2 ** Math.min(failures - 1, 4), OFFLINE_RETRY_CAP_MS)
1372
+ : undefined);
1307
1373
  }
1308
1374
  /** A bad command must not stop the others or fail a transcript ingest. */
1309
1375
  applyCommandsSafely(commands) {
@@ -1576,7 +1642,9 @@ class Harness {
1576
1642
  }
1577
1643
  if (this.status === 'draining') {
1578
1644
  // Draining means "finish what you hold, take nothing new".
1579
- if (this.active.size === 0) {
1645
+ // An OFFLINE drain is different: nothing asked this runner to leave, so
1646
+ // wait for the heartbeat to resume it instead of ending the process.
1647
+ if (this.active.size === 0 && !this.offlineDraining) {
1580
1648
  break;
1581
1649
  }
1582
1650
  await sleep(1_000);
@@ -1598,7 +1666,11 @@ class Harness {
1598
1666
  break;
1599
1667
  }
1600
1668
  if (error instanceof control_plane_1.ControlPlaneError && error.final) {
1601
- this.fatal = error;
1669
+ this.fatal =
1670
+ (error.status === 401 || error.status === 403) &&
1671
+ this.reusedStoredCredential
1672
+ ? new StoredCredentialUnavailableError(`The control plane rejected this runner credential (HTTP ${error.status}).`)
1673
+ : error;
1602
1674
  break;
1603
1675
  }
1604
1676
  log('Lease poll failed', {
@@ -0,0 +1,3 @@
1
+ import type { LeasedSkill } from '../types';
2
+ /** Install only the published skills in this lease. Prior leased files are removed. */
3
+ export declare function syncLeasedSkills(workspace: string, _backend: string, skills: LeasedSkill[]): Promise<void>;
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.syncLeasedSkills = syncLeasedSkills;
4
+ const promises_1 = require("node:fs/promises");
5
+ const node_path_1 = require("node:path");
6
+ const START = '<!-- workflo leased skills start -->';
7
+ const END = '<!-- workflo leased skills end -->';
8
+ const MANIFEST = '.workflo-leased-skills.json';
9
+ function slug(name) {
10
+ return (name
11
+ .toLowerCase()
12
+ .replace(/[^a-z0-9-]+/g, '-')
13
+ .replace(/^-|-$/g, '') || 'skill');
14
+ }
15
+ function yaml(value) {
16
+ return JSON.stringify(value.replace(/[\r\n]+/g, ' ').trim());
17
+ }
18
+ async function documentation(path, section) {
19
+ const old = await (0, promises_1.readFile)(path, 'utf8').catch(() => '');
20
+ const start = old.indexOf(START);
21
+ const end = old.indexOf(END);
22
+ const base = start >= 0 && end > start
23
+ ? old.slice(0, start) + old.slice(end + END.length)
24
+ : old;
25
+ await (0, promises_1.writeFile)(path, `${base.trimEnd()}\n\n${START}\n${section}${END}\n`, 'utf8');
26
+ }
27
+ /** Install only the published skills in this lease. Prior leased files are removed. */
28
+ async function syncLeasedSkills(workspace, _backend, skills) {
29
+ const roots = ['.claude', '.agents'];
30
+ const manifestPath = (0, node_path_1.join)(workspace, MANIFEST);
31
+ const manifest = await (0, promises_1.readFile)(manifestPath, 'utf8').catch(() => null);
32
+ if (skills.length === 0 && manifest === null)
33
+ return;
34
+ const previous = JSON.parse(manifest ?? '[]');
35
+ const names = new Set();
36
+ const entries = [];
37
+ for (const root of roots)
38
+ await (0, promises_1.mkdir)((0, node_path_1.join)(workspace, root, 'skills'), { recursive: true });
39
+ for (const skill of skills) {
40
+ const name = slug(skill.name);
41
+ if (names.has(name))
42
+ throw new Error(`Duplicate leased skill: ${name}`);
43
+ names.add(name);
44
+ if (/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|\b(?:sk-proj-|sk_live_)[A-Za-z0-9_-]+/.test(skill.content))
45
+ throw new Error(`Leased skill ${name} contains a secret`);
46
+ const description = name === 'reuse-candidates'
47
+ ? 'Read this list before each default-agent turn; RUN THIS marks the best active workflow.'
48
+ : name === 'reuse-first'
49
+ ? 'Use on every default-agent turn to check and run an existing workflow first.'
50
+ : name === 'find-and-automate'
51
+ ? 'Use first for requests about automating, finding problems, or building workflows.'
52
+ : name === 'automation-memory'
53
+ ? 'Use for a repeat automation run to check approved company memory.'
54
+ : name === 'self-improving-workflows'
55
+ ? 'Use when a person creates or improves a workflow.'
56
+ : `Use for tasks about ${skill.name}.`;
57
+ for (const root of roots) {
58
+ const directory = (0, node_path_1.join)(workspace, root, 'skills', name);
59
+ await (0, promises_1.mkdir)(directory, { recursive: true });
60
+ await (0, promises_1.writeFile)((0, node_path_1.join)(directory, 'SKILL.md'), `---\nname: ${yaml(skill.name)}\ndescription: ${yaml(description)}\n---\n\n${skill.content}\n`, 'utf8');
61
+ }
62
+ entries.push({ name: skill.name, description });
63
+ }
64
+ for (const old of previous) {
65
+ if (/^[a-z0-9-]+$/.test(old) && !names.has(old))
66
+ for (const root of roots)
67
+ await (0, promises_1.rm)((0, node_path_1.join)(workspace, root, 'skills', old), {
68
+ recursive: true,
69
+ force: true
70
+ });
71
+ }
72
+ for (const root of roots) {
73
+ const lines = entries.map((entry) => `- [${entry.name}](${root}/skills/${slug(entry.name)}/SKILL.md) — ${entry.description}`);
74
+ const section = `## Skills Reference\n\n${lines.join('\n') || 'No skills in this lease.'}\n\n`;
75
+ await documentation((0, node_path_1.join)(workspace, root === '.claude' ? 'CLAUDE.md' : 'AGENTS.md'), section);
76
+ }
77
+ await (0, promises_1.writeFile)(manifestPath, JSON.stringify([...names]), 'utf8');
78
+ }
@@ -17,8 +17,12 @@
17
17
  * adapter default. That is defect G1 — a Permission control that is recorded,
18
18
  * served, rendered, and enforced nowhere.
19
19
  *
20
- * A stored mode keeps the user's choice. Missing and unrecognised modes
21
- * fail closed onto 'ask'.
20
+ * A stored mode keeps the user's choice. A MISSING mode (null, undefined or
21
+ * '') means nobody chose one, so it gets the new-agent default,
22
+ * `bypassPermissions` → 'allow' (owner decision: "Allow by default", #1858,
23
+ * #1977; re-applied after #2012 reverted it). A NON-EMPTY mode this build does
24
+ * not recognise still fails closed onto 'ask': it may be a stricter mode from
25
+ * a newer control plane.
22
26
  *
23
27
  * ---------------------------------------------------------------------------
24
28
  * THE TABLE, AND WHAT IS AND IS NOT FAITHFUL
@@ -103,11 +107,21 @@ export declare function mapPermissionMode(mode: LeasePermissionMode | string | n
103
107
  * This is why the mapping is lossless there and lossy on Pi: the loss is
104
108
  * in the BACKEND, not in the wire.
105
109
  *
106
- * Absent `permissionMode` means the caller never set one. That is the pre-G1
107
- * state and it must NOT silently become `bypassPermissions` again, so it maps
108
- * to `'default'` — Claude Code's own asking mode.
110
+ * Absent `permissionMode` means the caller never set one, so it gets the
111
+ * new-agent default, `bypassPermissions` — the same as `mapPermissionMode`
112
+ * gives a missing lease mode. Only an explicit `'ask'` reaches Claude Code's
113
+ * asking modes.
109
114
  */
110
115
  export declare function claudeCodePermissionMode(config: {
111
116
  permissionMode?: AdapterPermissionMode;
112
117
  sandboxMode?: AdapterSandboxMode;
113
118
  }): LeasePermissionMode;
119
+ /**
120
+ * The mode an ADAPTER acts on. `'ask'` only for an explicit `'ask'`; a config
121
+ * with no `permissionMode` gets the new-agent default, `'allow'`. Every
122
+ * adapter decides "auto-approve or prompt" through this, so no backend picks
123
+ * its own fallback for a missing value.
124
+ */
125
+ export declare function effectivePermissionMode(config: {
126
+ permissionMode?: AdapterPermissionMode | string | null;
127
+ }): AdapterPermissionMode;
@@ -18,8 +18,12 @@
18
18
  * adapter default. That is defect G1 — a Permission control that is recorded,
19
19
  * served, rendered, and enforced nowhere.
20
20
  *
21
- * A stored mode keeps the user's choice. Missing and unrecognised modes
22
- * fail closed onto 'ask'.
21
+ * A stored mode keeps the user's choice. A MISSING mode (null, undefined or
22
+ * '') means nobody chose one, so it gets the new-agent default,
23
+ * `bypassPermissions` → 'allow' (owner decision: "Allow by default", #1858,
24
+ * #1977; re-applied after #2012 reverted it). A NON-EMPTY mode this build does
25
+ * not recognise still fails closed onto 'ask': it may be a stricter mode from
26
+ * a newer control plane.
23
27
  *
24
28
  * ---------------------------------------------------------------------------
25
29
  * THE TABLE, AND WHAT IS AND IS NOT FAITHFUL
@@ -83,6 +87,7 @@
83
87
  Object.defineProperty(exports, "__esModule", { value: true });
84
88
  exports.mapPermissionMode = mapPermissionMode;
85
89
  exports.claudeCodePermissionMode = claudeCodePermissionMode;
90
+ exports.effectivePermissionMode = effectivePermissionMode;
86
91
  /**
87
92
  * THE ONLY PLACE the four-valued lease mode becomes the two-valued adapter
88
93
  * mode. Deliberately total: an unknown value — a newer control plane, a hand-
@@ -91,6 +96,10 @@ exports.claudeCodePermissionMode = claudeCodePermissionMode;
91
96
  */
92
97
  function mapPermissionMode(mode) {
93
98
  switch (mode) {
99
+ // Missing: nobody chose. The new-agent default is "don't ask".
100
+ case null:
101
+ case undefined:
102
+ case '':
94
103
  case 'bypassPermissions':
95
104
  return {
96
105
  permissionMode: 'allow',
@@ -115,12 +124,13 @@ function mapPermissionMode(mode) {
115
124
  * This is why the mapping is lossless there and lossy on Pi: the loss is
116
125
  * in the BACKEND, not in the wire.
117
126
  *
118
- * Absent `permissionMode` means the caller never set one. That is the pre-G1
119
- * state and it must NOT silently become `bypassPermissions` again, so it maps
120
- * to `'default'` — Claude Code's own asking mode.
127
+ * Absent `permissionMode` means the caller never set one, so it gets the
128
+ * new-agent default, `bypassPermissions` — the same as `mapPermissionMode`
129
+ * gives a missing lease mode. Only an explicit `'ask'` reaches Claude Code's
130
+ * asking modes.
121
131
  */
122
132
  function claudeCodePermissionMode(config) {
123
- if (config.permissionMode === 'allow') {
133
+ if (config.permissionMode !== 'ask') {
124
134
  return 'bypassPermissions';
125
135
  }
126
136
  if (config.sandboxMode === 'read-only') {
@@ -141,3 +151,12 @@ function claudeCodePermissionMode(config) {
141
151
  }
142
152
  return 'default';
143
153
  }
154
+ /**
155
+ * The mode an ADAPTER acts on. `'ask'` only for an explicit `'ask'`; a config
156
+ * with no `permissionMode` gets the new-agent default, `'allow'`. Every
157
+ * adapter decides "auto-approve or prompt" through this, so no backend picks
158
+ * its own fallback for a missing value.
159
+ */
160
+ function effectivePermissionMode(config) {
161
+ return config.permissionMode === 'ask' ? 'ask' : 'allow';
162
+ }
@@ -693,4 +693,10 @@ export declare class SessionRunner {
693
693
  */
694
694
  private logMcpToolStore;
695
695
  private buildSessionConfig;
696
+ /**
697
+ * A MISSING lease mode runs as the new-agent default (allow). That is the
698
+ * owner's decision, but it is also what a dropped field would look like, so
699
+ * it is logged rather than taken silently.
700
+ */
701
+ private leasePermission;
696
702
  }
@@ -40,6 +40,7 @@ const cold_start_steps_1 = require("./cold-start-steps");
40
40
  const conversation_1 = require("./conversation");
41
41
  const credential_proxy_1 = require("./credential-proxy");
42
42
  const knowledge_tools_1 = require("./knowledge-tools");
43
+ const leased_skills_1 = require("./leased-skills");
43
44
  const mcp_preflight_1 = require("./mcp-preflight");
44
45
  const mcp_tool_store_1 = require("./mcp-tool-store");
45
46
  const mcp_toolset_1 = require("./mcp-toolset");
@@ -895,6 +896,7 @@ class SessionRunner {
895
896
  const endSpaceFiles = coldStart.begin('space_files_sync');
896
897
  try {
897
898
  await this.syncSpaceFilesForTurn(session, workspaceDir);
899
+ await (0, leased_skills_1.syncLeasedSkills)(workspaceDir, session.agent.backend, session.agent.skills);
898
900
  }
899
901
  finally {
900
902
  endSpaceFiles();
@@ -2933,8 +2935,20 @@ class SessionRunner {
2933
2935
  * ./permission-mode.ts. `sandboxMode` is set from the same call because
2934
2936
  * it is what carries the part of the intent 'ask' | 'allow' cannot.
2935
2937
  */
2936
- ...(0, permission_mode_1.mapPermissionMode)(session.agent.permissionMode)
2938
+ ...this.leasePermission(session)
2937
2939
  };
2938
2940
  }
2941
+ /**
2942
+ * A MISSING lease mode runs as the new-agent default (allow). That is the
2943
+ * owner's decision, but it is also what a dropped field would look like, so
2944
+ * it is logged rather than taken silently.
2945
+ */
2946
+ leasePermission(session) {
2947
+ const mode = session.agent.permissionMode;
2948
+ if (!mode) {
2949
+ this.logger.warn(`[SessionRunner] permission-mode-missing session=${session.sessionId} using=allow`);
2950
+ }
2951
+ return (0, permission_mode_1.mapPermissionMode)(mode);
2952
+ }
2939
2953
  }
2940
2954
  exports.SessionRunner = SessionRunner;
package/dist/service.d.ts CHANGED
@@ -17,6 +17,9 @@ export interface ServiceContext {
17
17
  output?: (message: string) => void;
18
18
  sleep?: (ms: number) => void;
19
19
  portOccupied?: (port: number) => Promise<boolean>;
20
+ /** Test hooks for stopping a leftover process. */
21
+ kill?: (pid: number, signal: 'SIGTERM' | 'SIGKILL') => void;
22
+ pidAlive?: (pid: number) => boolean;
20
23
  /**
21
24
  * A per-vendor service from `connect` (`ai.peakflo.agent-harness.<vendor>`),
22
25
  * so Claude Code, Codex and Cursor can each run as their own personal
@@ -69,7 +72,18 @@ export declare class ServiceManager {
69
72
  healthPort: number;
70
73
  }): void;
71
74
  status(): void;
72
- uninstall(): void;
75
+ /** Process ID of the running service, or 0 when it is not running. */
76
+ private runningPid;
77
+ private launchDomain;
78
+ private isLoaded;
79
+ /** Stop a process that outlived its service manager entry. */
80
+ private terminate;
81
+ /**
82
+ * Remove the service for good: stop the process, drop the manager entry,
83
+ * delete the unit file, and free the health port. Safe to run twice. It
84
+ * reports success only after the manager no longer lists the service.
85
+ */
86
+ uninstall(): Promise<void>;
73
87
  }
74
88
  export declare function runServiceCommand(input: string[], context: ServiceContext): Promise<void>;
75
89
  export {};
package/dist/service.js CHANGED
@@ -558,25 +558,142 @@ class ServiceManager {
558
558
  this.output(`Status: stopped. Last error: ${savedError || 'service manager could not read status'}.`);
559
559
  }
560
560
  }
561
- uninstall() {
561
+ /** Process ID of the running service, or 0 when it is not running. */
562
+ runningPid() {
563
+ try {
564
+ if (this.platform === 'darwin') {
565
+ const info = this.run('launchctl', [
566
+ 'print',
567
+ `${this.launchDomain()}/${this.label}`
568
+ ]);
569
+ return Number(info.match(/\bpid = (\d+)/)?.[1] ?? 0);
570
+ }
571
+ const info = this.run('systemctl', [
572
+ '--user',
573
+ 'show',
574
+ this.unit,
575
+ '--property=MainPID'
576
+ ]);
577
+ return Number(info.match(/^MainPID=(\d+)$/m)?.[1] ?? 0);
578
+ }
579
+ catch {
580
+ return 0;
581
+ }
582
+ }
583
+ launchDomain() {
584
+ return `gui/${this.context.uid ?? process.getuid?.() ?? (0, node_os_1.userInfo)().uid}`;
585
+ }
586
+ isLoaded() {
587
+ try {
588
+ if (this.platform === 'darwin') {
589
+ this.run('launchctl', [
590
+ 'print',
591
+ `${this.launchDomain()}/${this.label}`
592
+ ]);
593
+ return true;
594
+ }
595
+ const info = this.run('systemctl', [
596
+ '--user',
597
+ 'show',
598
+ this.unit,
599
+ '--property=LoadState'
600
+ ]);
601
+ return /^LoadState=(?!not-found)/m.test(info);
602
+ }
603
+ catch {
604
+ return false;
605
+ }
606
+ }
607
+ /** Stop a process that outlived its service manager entry. */
608
+ terminate(pid) {
609
+ if (!pid || pid === process.pid)
610
+ return;
611
+ const alive = this.context.pidAlive ??
612
+ ((id) => {
613
+ try {
614
+ process.kill(id, 0);
615
+ return true;
616
+ }
617
+ catch {
618
+ return false;
619
+ }
620
+ });
621
+ const kill = this.context.kill ?? ((id, sig) => process.kill(id, sig));
622
+ const wait = this.context.sleep ?? sleep;
623
+ for (const signal of ['SIGTERM', 'SIGKILL']) {
624
+ if (!alive(pid))
625
+ return;
626
+ try {
627
+ kill(pid, signal);
628
+ }
629
+ catch {
630
+ return;
631
+ }
632
+ for (let tick = 0; tick < 10 && alive(pid); tick++)
633
+ wait(500);
634
+ }
635
+ }
636
+ /**
637
+ * Remove the service for good: stop the process, drop the manager entry,
638
+ * delete the unit file, and free the health port. Safe to run twice. It
639
+ * reports success only after the manager no longer lists the service.
640
+ */
641
+ async uninstall() {
562
642
  this.supported();
643
+ const pid = this.runningPid();
644
+ let healthPort = null;
645
+ try {
646
+ healthPort = Number(argValue(this.readConfig().startArgs, '--health-port') ?? '7777');
647
+ }
648
+ catch {
649
+ /* no saved settings */
650
+ }
563
651
  if (this.platform === 'darwin') {
564
- const domain = `gui/${this.context.uid ?? process.getuid?.() ?? (0, node_os_1.userInfo)().uid}`;
652
+ const target = `${this.launchDomain()}/${this.label}`;
565
653
  try {
566
- this.run('launchctl', ['bootout', `${domain}/${this.label}`]);
654
+ this.run('launchctl', ['bootout', target]);
567
655
  }
568
656
  catch {
569
- /* absent */
657
+ try {
658
+ this.run('launchctl', ['remove', this.label]);
659
+ }
660
+ catch {
661
+ /* absent */
662
+ }
663
+ }
664
+ }
665
+ else {
666
+ try {
667
+ this.run('systemctl', ['--user', 'disable', '--now', this.unit]);
668
+ }
669
+ catch {
670
+ /* absent or already stopped */
570
671
  }
571
672
  }
572
- else if ((0, node_fs_1.existsSync)(this.serviceFile)) {
573
- this.run('systemctl', ['--user', 'disable', '--now', this.unit]);
673
+ this.terminate(pid);
674
+ if (this.isLoaded() && (0, node_fs_1.existsSync)(this.serviceFile)) {
675
+ // Keep the unit file so that "service uninstall" can be run again.
676
+ throw new Error(`The service manager still lists ${this.platform === 'darwin' ? this.label : this.unit}. It was not removed. Run: ${this.platform === 'darwin'
677
+ ? `launchctl bootout ${this.launchDomain()}/${this.label}`
678
+ : `systemctl --user disable --now ${this.unit}`}, then run service uninstall again.`);
574
679
  }
575
680
  (0, node_fs_1.rmSync)(this.serviceFile, { force: true });
576
681
  (0, node_fs_1.rmSync)(this.stateFile, { force: true });
577
682
  clearServiceFailure(this.home);
578
- if (this.platform === 'linux')
579
- this.run('systemctl', ['--user', 'daemon-reload']);
683
+ if (this.platform === 'linux') {
684
+ try {
685
+ this.run('systemctl', ['--user', 'daemon-reload']);
686
+ this.run('systemctl', ['--user', 'reset-failed', this.unit]);
687
+ }
688
+ catch {
689
+ /* nothing to reload */
690
+ }
691
+ }
692
+ if (healthPort &&
693
+ (await (this.context.portOccupied ?? portOccupied)(healthPort))) {
694
+ this.output(`Service removed, but health port ${healthPort} is still in use by another process. Find it with: lsof -i :${healthPort}`);
695
+ return;
696
+ }
580
697
  this.output('Service removed. The saved runner credential remains in the workspace.');
581
698
  }
582
699
  }
@@ -609,7 +726,7 @@ async function runServiceCommand(input, context) {
609
726
  manager.repair(args.slice(1));
610
727
  break;
611
728
  case 'uninstall':
612
- manager.uninstall();
729
+ await manager.uninstall();
613
730
  break;
614
731
  default:
615
732
  throw new Error('Use service install, status, repair, or uninstall.');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peakflo/agent-harness",
3
- "version": "0.2.21",
3
+ "version": "0.2.23",
4
4
  "description": "Headless Peakflo coding-agent harness. One codebase, three hosting modes: a Daytona cloud sandbox, a customer VM, and the 20x desktop.",
5
5
  "license": "MIT",
6
6
  "type": "commonjs",