@powerhousedao/clint 6.4.0-next.2 → 6.4.0-next.4
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/dist/{build-skills-Bpbbnin0.mjs → build-skills-BTkuL8ne.mjs} +2 -2
- package/dist/{build-skills-Bpbbnin0.mjs.map → build-skills-BTkuL8ne.mjs.map} +1 -1
- package/dist/command-control-Dp41aY0o.mjs +224 -0
- package/dist/command-control-Dp41aY0o.mjs.map +1 -0
- package/dist/{dist-Bd6hUl0J.mjs → dist-BTVqrpN4.mjs} +2 -2
- package/dist/{dist-Bd6hUl0J.mjs.map → dist-BTVqrpN4.mjs.map} +1 -1
- package/dist/{index-CfHcet4v.d.mts → index-DJlqIVLv.d.mts} +13 -10
- package/dist/{index-CfHcet4v.d.mts.map → index-DJlqIVLv.d.mts.map} +1 -1
- package/dist/index.d.mts +227 -8
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +6 -5
- package/dist/integrations/mastra/index.d.mts +20 -3
- package/dist/integrations/mastra/index.d.mts.map +1 -1
- package/dist/integrations/mastra/index.mjs +25 -3
- package/dist/integrations/mastra/index.mjs.map +1 -1
- package/dist/integrations/powerhouse/index.d.mts +3 -3
- package/dist/integrations/powerhouse/index.mjs +1 -1
- package/dist/{markdown-BUeGwhbR.mjs → markdown-B-HyDpvO.mjs} +471 -39
- package/dist/markdown-B-HyDpvO.mjs.map +1 -0
- package/dist/{powerhouse-3XZmdY3_.mjs → powerhouse-C4O-raTW.mjs} +168 -12
- package/dist/powerhouse-C4O-raTW.mjs.map +1 -0
- package/dist/{proxy-ji3EHzLn.mjs → proxy-DgnOKu1A.mjs} +2 -2
- package/dist/proxy-DgnOKu1A.mjs.map +1 -0
- package/dist/remote-reactor-oBsHphPT.mjs.map +1 -1
- package/dist/{repl-Czb7u0x_.mjs → repl-C4gHgy6P.mjs} +2 -2
- package/dist/{repl-Czb7u0x_.mjs.map → repl-C4gHgy6P.mjs.map} +1 -1
- package/dist/runners/cli-runner.d.mts +5 -2
- package/dist/runners/cli-runner.d.mts.map +1 -1
- package/dist/runners/cli-runner.mjs +21 -7
- package/dist/runners/cli-runner.mjs.map +1 -1
- package/dist/runners/mastra-runner.mjs +1 -1
- package/dist/runners/proxy-runner.mjs +1 -1
- package/dist/{src-BmMd0Wl4.mjs → src-FF3zDJY7.mjs} +606 -53
- package/dist/src-FF3zDJY7.mjs.map +1 -0
- package/dist/{start-BHn9LIyX.mjs → start-CCegR8Pi.mjs} +2 -2
- package/dist/{start-BHn9LIyX.mjs.map → start-CCegR8Pi.mjs.map} +1 -1
- package/dist/testing/index.d.mts +2 -2
- package/dist/testing/index.mjs +1 -1
- package/dist/{types-3TnDjQ1w.d.mts → types-BnPpIAL6.d.mts} +2 -2
- package/dist/{types-3TnDjQ1w.d.mts.map → types-BnPpIAL6.d.mts.map} +1 -1
- package/dist/{types-DbQKfvWc.d.mts → types-CIZtG2TY.d.mts} +219 -13
- package/dist/types-CIZtG2TY.d.mts.map +1 -0
- package/package.json +13 -13
- package/dist/markdown-BUeGwhbR.mjs.map +0 -1
- package/dist/powerhouse-3XZmdY3_.mjs.map +0 -1
- package/dist/proxy-ji3EHzLn.mjs.map +0 -1
- package/dist/src-BmMd0Wl4.mjs.map +0 -1
- package/dist/types-DbQKfvWc.d.mts.map +0 -1
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { n as slugToTitle, t as getSchemaFields } from "./schema-BEKAZGyT.mjs";
|
|
2
|
-
import { M as createDocumentChangeTrigger,
|
|
3
|
-
import { a as
|
|
2
|
+
import { F as SIGNING_ASKS, H as defineCommand, I as asOwnSigner, M as createDocumentChangeTrigger, R as callerSigningOf, V as withCallerSigning } from "./powerhouse-C4O-raTW.mjs";
|
|
3
|
+
import { S as formatStreamChunk, a as getCompletions, b as superviseChild, c as defineService, d as sanitizeLogText, f as watchLogFile, i as getCompletionSuffix, m as scanProjects, n as renderMarkdown, o as getGhostSuggestion, s as createServiceManager, t as loadMarkdown, u as resolveServiceName, x as supervisedSpawnOptions, y as killTree } from "./markdown-B-HyDpvO.mjs";
|
|
4
4
|
import { n as createWorkdirStore, t as createMemoryWorkdirStore } from "./store-CxqB-OrX.mjs";
|
|
5
|
-
import "./
|
|
5
|
+
import { c as readPipedStdin, d as untilAborted, l as sendCommand, n as CommandTooLarge, o as commandStoreSchema, s as describeCaller, u as serveCommands } from "./command-control-Dp41aY0o.mjs";
|
|
6
|
+
import "./proxy-DgnOKu1A.mjs";
|
|
7
|
+
import { createRequire } from "node:module";
|
|
6
8
|
import fs, { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
7
9
|
import path, { basename, dirname, join, resolve } from "node:path";
|
|
8
10
|
import { fileURLToPath } from "node:url";
|
|
@@ -10,9 +12,13 @@ import { z } from "zod";
|
|
|
10
12
|
import { Command } from "commander";
|
|
11
13
|
import { randomBytes, randomUUID } from "node:crypto";
|
|
12
14
|
import { homedir } from "node:os";
|
|
13
|
-
import {
|
|
15
|
+
import { restrictFileToOwner, warnNotOwnerOnly } from "@powerhousedao/shared/clis/owner-only";
|
|
16
|
+
import { instanceDataDir, instanceServicesDir, supervisedFactLines } from "@powerhousedao/host-core/instance";
|
|
17
|
+
import { ControlError, callControl, processControlChannel, protocolMismatch } from "@powerhousedao/host-core/control-channel";
|
|
14
18
|
import { spawn } from "node:child_process";
|
|
15
|
-
import
|
|
19
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
20
|
+
import { StringDecoder } from "node:string_decoder";
|
|
21
|
+
import { formatWithOptions } from "node:util";
|
|
16
22
|
import { EventEmitter } from "node:events";
|
|
17
23
|
//#region src/core/pkg.ts
|
|
18
24
|
/**
|
|
@@ -244,6 +250,7 @@ function writeJsonFile(path, data, mode) {
|
|
|
244
250
|
encoding: "utf-8",
|
|
245
251
|
mode
|
|
246
252
|
} : "utf-8");
|
|
253
|
+
if (mode !== void 0 && !restrictFileToOwner(tmp)) warnNotOwnerOnly(path);
|
|
247
254
|
try {
|
|
248
255
|
renameSync(tmp, path);
|
|
249
256
|
} catch (err) {
|
|
@@ -555,7 +562,8 @@ const startParamsSchema = z.object({
|
|
|
555
562
|
workdir: z.string().optional(),
|
|
556
563
|
cwd: z.string().optional(),
|
|
557
564
|
params: z.record(z.string(), z.unknown()).optional(),
|
|
558
|
-
name: z.string().optional()
|
|
565
|
+
name: z.string().optional(),
|
|
566
|
+
lifetime: z.enum(["caller", "supervisor"]).optional()
|
|
559
567
|
}).optional()
|
|
560
568
|
});
|
|
561
569
|
const instanceParamsSchema = z.object({
|
|
@@ -585,7 +593,8 @@ async function restartService(services, id, instanceId, workdir) {
|
|
|
585
593
|
workdir: cwd,
|
|
586
594
|
cwd,
|
|
587
595
|
params: instance?.params,
|
|
588
|
-
name
|
|
596
|
+
name,
|
|
597
|
+
...instance?.supervisor ? { lifetime: instance.supervisor.lifetime } : {}
|
|
589
598
|
});
|
|
590
599
|
}
|
|
591
600
|
/** Answers service requests on `channel` from `services`. */
|
|
@@ -594,7 +603,10 @@ function serveServices(channel, services, cli) {
|
|
|
594
603
|
cli: cli.name,
|
|
595
604
|
version: cli.version
|
|
596
605
|
});
|
|
597
|
-
channel.handle("list", (params) =>
|
|
606
|
+
channel.handle("list", async (params) => {
|
|
607
|
+
await services.supervisor?.().catch(() => void 0);
|
|
608
|
+
return { instances: services.list(parse(listParamsSchema, params).serviceId) };
|
|
609
|
+
});
|
|
598
610
|
channel.handle("start", async (params) => {
|
|
599
611
|
const { id, options } = parse(startParamsSchema, params);
|
|
600
612
|
return {
|
|
@@ -663,19 +675,24 @@ async function connectRemoteServices(local, control) {
|
|
|
663
675
|
}
|
|
664
676
|
/** Thrown by a start that cannot outlive its command. */
|
|
665
677
|
var ServiceStartRefused = class extends Error {
|
|
666
|
-
constructor(id, serveCommand) {
|
|
667
|
-
super(`${id} was not started: a service runs as long as the process that started it, and this command ends. Start it where it keeps running: ${serveCommand ? `\`${serveCommand}\`` : "`ph run <host>`"}, then run this command from a second terminal.`);
|
|
678
|
+
constructor(id, serveCommand, supervisor) {
|
|
679
|
+
super(`${id} was not started: a service runs as long as the process that started it, and this command ends. Start it where it keeps running: ${serveCommand ? `\`${serveCommand}\`` : "`ph run <host>`"}, then run this command from a second terminal.` + (supervisor ? ` Or pass \`--lifetime supervisor\`: the supervisor (pid ${supervisor.pid}) then keeps it running.` : ""));
|
|
668
680
|
this.name = "ServiceStartRefused";
|
|
669
681
|
}
|
|
670
682
|
};
|
|
671
683
|
/**
|
|
672
684
|
* The manager of a command that ends with nothing running to forward to:
|
|
673
|
-
* everything but `start`, which is refused with where to run instead.
|
|
685
|
+
* everything but `start`, which is refused with where to run instead. A
|
|
686
|
+
* start that lives with the user's supervisor outlives the command, and is
|
|
687
|
+
* the local manager's to pass on.
|
|
674
688
|
*/
|
|
675
689
|
function refuseServiceStarts(local, serveCommand) {
|
|
676
690
|
return {
|
|
677
691
|
...local,
|
|
678
|
-
start: (id) =>
|
|
692
|
+
start: async (id, opts) => {
|
|
693
|
+
if (opts?.lifetime === "supervisor") return local.start(id, opts);
|
|
694
|
+
throw new ServiceStartRefused(id, serveCommand, await local.supervisor?.());
|
|
695
|
+
}
|
|
679
696
|
};
|
|
680
697
|
}
|
|
681
698
|
//#endregion
|
|
@@ -693,9 +710,11 @@ function formatStatus(s) {
|
|
|
693
710
|
if (ep.length) parts.push(ep.join(" "));
|
|
694
711
|
}
|
|
695
712
|
if (s.workdir) parts.push(s.workdir);
|
|
713
|
+
if (s.supervisor) parts.push(`supervisor pid ${s.supervisor.pid}, lives with the ${s.supervisor.lifetime}`);
|
|
696
714
|
if (s.error) parts.push(`error: ${s.error}`);
|
|
697
715
|
if (s.restartAttempt) parts.push(`restart #${s.restartAttempt}`);
|
|
698
|
-
|
|
716
|
+
const facts = s.supervisor ? supervisedFactLines(s.supervisor) : [];
|
|
717
|
+
return [parts.join(" "), ...facts.map((line) => ` ${line}`)].join("\n");
|
|
699
718
|
}
|
|
700
719
|
/**
|
|
701
720
|
* Create per-service commands for a service definition.
|
|
@@ -714,6 +733,7 @@ function createServiceCommands(def) {
|
|
|
714
733
|
const startFields = {};
|
|
715
734
|
if (isMultiInstance) startFields.name = z.string().optional().describe("Instance name (for multi-instance services)");
|
|
716
735
|
startFields.workdir = z.string().optional().describe("Working directory for the service");
|
|
736
|
+
if (def.run) startFields.lifetime = z.enum(["caller", "supervisor"]).optional().describe("With a supervisor running (`ph run supervisor`): `caller` (default) ends the service with this process, `supervisor` keeps it until it is stopped");
|
|
717
737
|
if (def.paramsSchema) {
|
|
718
738
|
const paramFields = getSchemaFields(def.paramsSchema);
|
|
719
739
|
for (const field of paramFields) if (def.paramsSchema instanceof z.ZodObject) {
|
|
@@ -745,7 +765,8 @@ function createServiceCommands(def) {
|
|
|
745
765
|
name: input.name,
|
|
746
766
|
workdir: cwd,
|
|
747
767
|
cwd,
|
|
748
|
-
params: Object.keys(params).length > 0 ? params : void 0
|
|
768
|
+
params: Object.keys(params).length > 0 ? params : void 0,
|
|
769
|
+
...def.run && input.lifetime !== void 0 ? { lifetime: input.lifetime } : {}
|
|
749
770
|
});
|
|
750
771
|
return { text: formatStatus(services.list(id).find((s) => s.instanceId === instanceId)) };
|
|
751
772
|
} catch (err) {
|
|
@@ -797,6 +818,7 @@ function createServiceCommands(def) {
|
|
|
797
818
|
execute: async (_input, context) => {
|
|
798
819
|
const services = context.services;
|
|
799
820
|
if (!services) throw new Error("No services configured");
|
|
821
|
+
await services.supervisor?.();
|
|
800
822
|
const all = services.list(id);
|
|
801
823
|
if (all.length === 0) return { text: `No instances of ${id}` };
|
|
802
824
|
return {
|
|
@@ -872,6 +894,254 @@ function createServiceCommands(def) {
|
|
|
872
894
|
return commands;
|
|
873
895
|
}
|
|
874
896
|
//#endregion
|
|
897
|
+
//#region src/core/forwarded-output.ts
|
|
898
|
+
const scopes = new AsyncLocalStorage();
|
|
899
|
+
/** The scope of the command that runs now, when it still takes output. */
|
|
900
|
+
function current() {
|
|
901
|
+
const scope = scopes.getStore();
|
|
902
|
+
return scope?.open ? scope : void 0;
|
|
903
|
+
}
|
|
904
|
+
/** Hands `text` to the caller. False when it could not be: the instance
|
|
905
|
+
* then shows it. Runs outside the scope: what the delivery itself writes is
|
|
906
|
+
* the instance's. */
|
|
907
|
+
function deliver(scope, stream, text) {
|
|
908
|
+
try {
|
|
909
|
+
scopes.run(void 0, () => scope.sink[stream](text));
|
|
910
|
+
return true;
|
|
911
|
+
} catch {
|
|
912
|
+
return false;
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
/** The console methods that print a formatted line, and where. */
|
|
916
|
+
const CONSOLE_METHODS = {
|
|
917
|
+
log: "stdout",
|
|
918
|
+
info: "stdout",
|
|
919
|
+
debug: "stdout",
|
|
920
|
+
error: "stderr",
|
|
921
|
+
warn: "stderr"
|
|
922
|
+
};
|
|
923
|
+
function patchStream(name) {
|
|
924
|
+
const stream = process[name];
|
|
925
|
+
const write = stream.write;
|
|
926
|
+
const patched = (...args) => {
|
|
927
|
+
const [chunk, encoding, callback] = args;
|
|
928
|
+
const scope = current();
|
|
929
|
+
if (!scope) return Reflect.apply(write, stream, args);
|
|
930
|
+
let text;
|
|
931
|
+
if (typeof chunk === "string") text = chunk;
|
|
932
|
+
else if (chunk instanceof Uint8Array) text = (scope.decoders[name] ??= new StringDecoder("utf8")).write(Buffer.from(chunk));
|
|
933
|
+
else return Reflect.apply(write, stream, args);
|
|
934
|
+
if (text !== "" && !deliver(scope, name, text)) return Reflect.apply(write, stream, args);
|
|
935
|
+
const done = typeof encoding === "function" ? encoding : callback;
|
|
936
|
+
if (typeof done === "function") process.nextTick(done, null);
|
|
937
|
+
return true;
|
|
938
|
+
};
|
|
939
|
+
stream.write = patched;
|
|
940
|
+
}
|
|
941
|
+
function patchConsole() {
|
|
942
|
+
const target = globalThis.console;
|
|
943
|
+
for (const [method, stream] of Object.entries(CONSOLE_METHODS)) {
|
|
944
|
+
let outside = target[method];
|
|
945
|
+
const inside = (...args) => {
|
|
946
|
+
const scope = current();
|
|
947
|
+
const text = `${formatWithOptions({ colors: false }, ...args)}\n`;
|
|
948
|
+
if (!scope || !deliver(scope, stream, text)) Reflect.apply(outside, target, args);
|
|
949
|
+
};
|
|
950
|
+
Object.defineProperty(target, method, {
|
|
951
|
+
configurable: true,
|
|
952
|
+
enumerable: true,
|
|
953
|
+
get: () => current() ? inside : outside,
|
|
954
|
+
set: (next) => {
|
|
955
|
+
if (next !== inside) outside = next;
|
|
956
|
+
}
|
|
957
|
+
});
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
let installed = false;
|
|
961
|
+
/** Puts the routing in place, once per process. Nothing changes for output
|
|
962
|
+
* written outside a command. */
|
|
963
|
+
function install() {
|
|
964
|
+
if (installed) return;
|
|
965
|
+
installed = true;
|
|
966
|
+
patchStream("stdout");
|
|
967
|
+
patchStream("stderr");
|
|
968
|
+
patchConsole();
|
|
969
|
+
}
|
|
970
|
+
/**
|
|
971
|
+
* Runs `work` with what it writes straight to the process sent to `sink`
|
|
972
|
+
* until it settles. Resolves and rejects as `work` does.
|
|
973
|
+
*/
|
|
974
|
+
function captureOutput(sink, work) {
|
|
975
|
+
install();
|
|
976
|
+
const scope = {
|
|
977
|
+
sink,
|
|
978
|
+
open: true,
|
|
979
|
+
decoders: {}
|
|
980
|
+
};
|
|
981
|
+
const close = () => {
|
|
982
|
+
for (const name of ["stdout", "stderr"]) {
|
|
983
|
+
const rest = scope.decoders[name]?.end();
|
|
984
|
+
if (rest) deliver(scope, name, rest);
|
|
985
|
+
}
|
|
986
|
+
scope.open = false;
|
|
987
|
+
};
|
|
988
|
+
let running;
|
|
989
|
+
try {
|
|
990
|
+
running = scopes.run(scope, work);
|
|
991
|
+
} catch (error) {
|
|
992
|
+
close();
|
|
993
|
+
return Promise.reject(error instanceof Error ? error : new Error(String(error)));
|
|
994
|
+
}
|
|
995
|
+
return running.finally(close);
|
|
996
|
+
}
|
|
997
|
+
/**
|
|
998
|
+
* Runs `fn` as the instance itself, whatever command called: what it writes
|
|
999
|
+
* goes where the instance writes, and what it writes to the reactor the
|
|
1000
|
+
* instance signs. For the instance's own reactions to what a command does
|
|
1001
|
+
* (its listeners on the event bus).
|
|
1002
|
+
*/
|
|
1003
|
+
function asInstance(fn) {
|
|
1004
|
+
return scopes.getStore() ? scopes.run(void 0, () => asOwnSigner(fn)) : asOwnSigner(fn);
|
|
1005
|
+
}
|
|
1006
|
+
//#endregion
|
|
1007
|
+
//#region src/core/caller-signing.ts
|
|
1008
|
+
function refuse(message, code = "refused") {
|
|
1009
|
+
return Object.assign(new Error(message), { code });
|
|
1010
|
+
}
|
|
1011
|
+
/** The action, target and previous state hash of a `sign-action` ask. */
|
|
1012
|
+
function signRequestOf(payload) {
|
|
1013
|
+
const p = payload;
|
|
1014
|
+
const action = p?.action;
|
|
1015
|
+
const target = p?.target;
|
|
1016
|
+
if (typeof action?.id !== "string" || typeof action.type !== "string" || typeof action.scope !== "string" || typeof action.timestampUtcMs !== "string" || typeof target?.documentId !== "string" || typeof target.branch !== "string" || typeof p?.previousStateHash !== "string") throw refuse("The instance asked to sign something that is no action.", "bad-request");
|
|
1017
|
+
return {
|
|
1018
|
+
action: {
|
|
1019
|
+
id: action.id,
|
|
1020
|
+
type: action.type,
|
|
1021
|
+
scope: action.scope,
|
|
1022
|
+
timestampUtcMs: action.timestampUtcMs,
|
|
1023
|
+
input: action.input
|
|
1024
|
+
},
|
|
1025
|
+
target: {
|
|
1026
|
+
documentId: target.documentId,
|
|
1027
|
+
branch: target.branch
|
|
1028
|
+
},
|
|
1029
|
+
previousStateHash: p.previousStateHash
|
|
1030
|
+
};
|
|
1031
|
+
}
|
|
1032
|
+
/**
|
|
1033
|
+
* How this process answers the asks of a command it forwards. `hold` is
|
|
1034
|
+
* called with true while the session opens (a password may be asked) and
|
|
1035
|
+
* false after: the command's output waits meanwhile.
|
|
1036
|
+
*
|
|
1037
|
+
* Nothing is read before the instance asks: whom the caller signs as is
|
|
1038
|
+
* answered to `signer`, at the first write, so a command that writes nothing
|
|
1039
|
+
* reads no identity and loads none of the code that would.
|
|
1040
|
+
*/
|
|
1041
|
+
function callerAnswers(o) {
|
|
1042
|
+
let session;
|
|
1043
|
+
const open = () => {
|
|
1044
|
+
if (!session) {
|
|
1045
|
+
o.hold?.(true);
|
|
1046
|
+
const target = o.store ? {
|
|
1047
|
+
...o.store.url ? { url: o.store.url } : {},
|
|
1048
|
+
...o.store.dataDir ? { dataDir: o.store.dataDir } : {}
|
|
1049
|
+
} : void 0;
|
|
1050
|
+
session = o.identity.open({
|
|
1051
|
+
workdir: o.workdir,
|
|
1052
|
+
dataDir: o.dataDir,
|
|
1053
|
+
label: o.identity.label,
|
|
1054
|
+
interactive: o.interactive,
|
|
1055
|
+
...target ? { target } : {}
|
|
1056
|
+
}).finally(() => o.hold?.(false));
|
|
1057
|
+
session.catch(() => {
|
|
1058
|
+
session = void 0;
|
|
1059
|
+
});
|
|
1060
|
+
}
|
|
1061
|
+
return session;
|
|
1062
|
+
};
|
|
1063
|
+
const opened = open;
|
|
1064
|
+
return {
|
|
1065
|
+
asks: SIGNING_ASKS,
|
|
1066
|
+
async onAsk(kind, payload) {
|
|
1067
|
+
switch (kind) {
|
|
1068
|
+
case "signer": return (await opened()).signer;
|
|
1069
|
+
case "sign-action": {
|
|
1070
|
+
const request = signRequestOf(payload);
|
|
1071
|
+
return (await opened()).signAction(request.action, request.target, request.previousStateHash);
|
|
1072
|
+
}
|
|
1073
|
+
case "bearer": {
|
|
1074
|
+
const expiresIn = payload?.expiresIn;
|
|
1075
|
+
return { token: await (await opened()).bearer({ expiresIn: typeof expiresIn === "number" && expiresIn > 0 ? Math.min(expiresIn, 3600) : 600 }) };
|
|
1076
|
+
}
|
|
1077
|
+
default: throw refuse(`This process does not answer "${kind}".`, "unsupported");
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
};
|
|
1081
|
+
}
|
|
1082
|
+
//#endregion
|
|
1083
|
+
//#region src/core/legacy-services.ts
|
|
1084
|
+
/**
|
|
1085
|
+
* Service state lives under the data folder (`<data folder>/.ph/<cli>/
|
|
1086
|
+
* services`). Before 6.4 it was the user's, `~/.ph/<cli>/services`, shared
|
|
1087
|
+
* by every project. State found there is not read and never deleted: it is
|
|
1088
|
+
* reported once per data folder, when it is this project's.
|
|
1089
|
+
*/
|
|
1090
|
+
const REPORTED_MARKER = ".legacy-state-reported";
|
|
1091
|
+
const samePath = (a, b) => {
|
|
1092
|
+
const [x, y] = [path.resolve(a), path.resolve(b)];
|
|
1093
|
+
return process.platform === "win32" ? x.toLowerCase() === y.toLowerCase() : x === y;
|
|
1094
|
+
};
|
|
1095
|
+
/** The state files at the old location that this project would have read:
|
|
1096
|
+
* those of its working folder, and those of no folder. */
|
|
1097
|
+
function legacyServiceState(legacyDir, workdir) {
|
|
1098
|
+
const found = [];
|
|
1099
|
+
let services;
|
|
1100
|
+
try {
|
|
1101
|
+
services = fs.readdirSync(legacyDir, { withFileTypes: true });
|
|
1102
|
+
} catch {
|
|
1103
|
+
return found;
|
|
1104
|
+
}
|
|
1105
|
+
for (const service of services) {
|
|
1106
|
+
if (!service.isDirectory()) continue;
|
|
1107
|
+
const dir = path.join(legacyDir, service.name);
|
|
1108
|
+
let files;
|
|
1109
|
+
try {
|
|
1110
|
+
files = fs.readdirSync(dir).filter((file) => file.endsWith(".json"));
|
|
1111
|
+
} catch {
|
|
1112
|
+
continue;
|
|
1113
|
+
}
|
|
1114
|
+
for (const file of files) {
|
|
1115
|
+
const at = path.join(dir, file);
|
|
1116
|
+
try {
|
|
1117
|
+
const state = JSON.parse(fs.readFileSync(at, "utf8"));
|
|
1118
|
+
if (typeof state.workdir !== "string" || samePath(state.workdir, workdir)) found.push(at);
|
|
1119
|
+
} catch {}
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
return found;
|
|
1123
|
+
}
|
|
1124
|
+
/**
|
|
1125
|
+
* Reports this project's state at the old location, once: a marker in the
|
|
1126
|
+
* new services folder remembers it. Returns the report, undefined when
|
|
1127
|
+
* there is nothing to say (or it was said).
|
|
1128
|
+
*/
|
|
1129
|
+
function reportLegacyServiceState(args) {
|
|
1130
|
+
const { legacyDir, servicesDir, workdir } = args;
|
|
1131
|
+
if (samePath(legacyDir, servicesDir)) return void 0;
|
|
1132
|
+
const marker = path.join(servicesDir, REPORTED_MARKER);
|
|
1133
|
+
if (fs.existsSync(marker)) return void 0;
|
|
1134
|
+
const found = legacyServiceState(legacyDir, workdir);
|
|
1135
|
+
if (found.length === 0) return void 0;
|
|
1136
|
+
const message = `Service state of an earlier version is at ${legacyDir} (${found.length} file(s) for this project). It is not read any more: service state is now kept per project, in ${servicesDir}. Nothing was deleted or moved; remove the old folder once no earlier version uses it.`;
|
|
1137
|
+
args.warn(message);
|
|
1138
|
+
try {
|
|
1139
|
+
fs.mkdirSync(servicesDir, { recursive: true });
|
|
1140
|
+
fs.writeFileSync(marker, `${(/* @__PURE__ */ new Date()).toISOString()}\n`);
|
|
1141
|
+
} catch {}
|
|
1142
|
+
return message;
|
|
1143
|
+
}
|
|
1144
|
+
//#endregion
|
|
875
1145
|
//#region src/core/help-command.ts
|
|
876
1146
|
const PREAMBLE = "As a CLI-first agent, your tools map directly onto CLI commands that the user can invoke through the command line directly, in interactive mode, or through you. Use the /cli-docs tool to learn more about the CLI capabilities and your own tools.";
|
|
877
1147
|
/**
|
|
@@ -1024,6 +1294,19 @@ function readSkills(artifacts, onWarn) {
|
|
|
1024
1294
|
}
|
|
1025
1295
|
//#endregion
|
|
1026
1296
|
//#region src/core/templates.ts
|
|
1297
|
+
let loaded;
|
|
1298
|
+
/**
|
|
1299
|
+
* Load Handlebars ahead of a render. Handlebars stays off the start path:
|
|
1300
|
+
* it loads here or on the first sync call.
|
|
1301
|
+
*/
|
|
1302
|
+
async function loadTemplates() {
|
|
1303
|
+
loaded ??= (await import("handlebars")).default;
|
|
1304
|
+
}
|
|
1305
|
+
/** Handlebars for sync callers; required on first use unless already loaded. */
|
|
1306
|
+
function handlebars() {
|
|
1307
|
+
loaded ??= createRequire(import.meta.url)("handlebars");
|
|
1308
|
+
return loaded;
|
|
1309
|
+
}
|
|
1027
1310
|
/**
|
|
1028
1311
|
* Known helper names — both custom defaults and Handlebars built-ins.
|
|
1029
1312
|
* Used by extractTemplateVars to filter out helper references.
|
|
@@ -1068,6 +1351,7 @@ function registerDefaultHelpers(hbs) {
|
|
|
1068
1351
|
* Filters out known helpers and built-in block helpers.
|
|
1069
1352
|
*/
|
|
1070
1353
|
function extractTemplateVars(template) {
|
|
1354
|
+
const Handlebars = handlebars();
|
|
1071
1355
|
const ast = Handlebars.parse(template);
|
|
1072
1356
|
const vars = /* @__PURE__ */ new Set();
|
|
1073
1357
|
const visitor = new Handlebars.Visitor();
|
|
@@ -1105,7 +1389,7 @@ function extractTemplateVars(template) {
|
|
|
1105
1389
|
* Uses Handlebars.create() for isolation — no global state pollution.
|
|
1106
1390
|
*/
|
|
1107
1391
|
function renderSkillTemplate(template, context, options) {
|
|
1108
|
-
const hbs =
|
|
1392
|
+
const hbs = handlebars().create();
|
|
1109
1393
|
registerDefaultHelpers(hbs);
|
|
1110
1394
|
if (options?.helpers) for (const [name, fn] of Object.entries(options.helpers)) hbs.registerHelper(name, fn);
|
|
1111
1395
|
const vars = extractTemplateVars(template);
|
|
@@ -1141,11 +1425,13 @@ function normalizeSkillConfig(value) {
|
|
|
1141
1425
|
* Input schema for skill commands — a single optional --prompt flag.
|
|
1142
1426
|
*/
|
|
1143
1427
|
const skillInputSchema = z.object({ prompt: z.string().optional().describe("Instructions for the skill") });
|
|
1428
|
+
const PROMPT_VAR = /\{\{\s*prompt\s*\}\}/;
|
|
1144
1429
|
/**
|
|
1145
1430
|
* Validate that an instructionTemplate includes the {{prompt}} variable.
|
|
1146
1431
|
* Returns a warning string if missing, or undefined if ok.
|
|
1147
1432
|
*/
|
|
1148
1433
|
function validateInstructionTemplate(skillName, template) {
|
|
1434
|
+
if (!/\{\{!|\{\{\{\{|\\\{\{/.test(template) && PROMPT_VAR.test(template)) return;
|
|
1149
1435
|
if (!extractTemplateVars(template).has("prompt")) return `Skill "${skillName}": instructionTemplate does not include {{prompt}} — the user's message will not be forwarded to the agent`;
|
|
1150
1436
|
}
|
|
1151
1437
|
/**
|
|
@@ -1198,7 +1484,7 @@ function createEventBus() {
|
|
|
1198
1484
|
const emitter = new EventEmitter();
|
|
1199
1485
|
return {
|
|
1200
1486
|
emit: ((event, data) => {
|
|
1201
|
-
emitter.emit(event, data);
|
|
1487
|
+
asInstance(() => emitter.emit(event, data));
|
|
1202
1488
|
}),
|
|
1203
1489
|
on: ((event, handler) => {
|
|
1204
1490
|
emitter.on(event, handler);
|
|
@@ -1781,6 +2067,12 @@ function createCompositeServiceManager(managers, routeMap) {
|
|
|
1781
2067
|
function purgeStoppedInstances(id) {
|
|
1782
2068
|
return getManager(id).purgeStoppedInstances(id);
|
|
1783
2069
|
}
|
|
2070
|
+
async function supervisor() {
|
|
2071
|
+
for (const mgr of managers) {
|
|
2072
|
+
const found = await mgr.supervisor?.();
|
|
2073
|
+
if (found) return found;
|
|
2074
|
+
}
|
|
2075
|
+
}
|
|
1784
2076
|
return {
|
|
1785
2077
|
start,
|
|
1786
2078
|
stop,
|
|
@@ -1791,7 +2083,8 @@ function createCompositeServiceManager(managers, routeMap) {
|
|
|
1791
2083
|
watchLogs,
|
|
1792
2084
|
watchChunks,
|
|
1793
2085
|
scanProjects,
|
|
1794
|
-
purgeStoppedInstances
|
|
2086
|
+
purgeStoppedInstances,
|
|
2087
|
+
supervisor
|
|
1795
2088
|
};
|
|
1796
2089
|
}
|
|
1797
2090
|
//#endregion
|
|
@@ -1956,6 +2249,7 @@ function createReplSession(opts) {
|
|
|
1956
2249
|
const commands = cli.listCommands();
|
|
1957
2250
|
const commandIds = commands.map((c) => c.id);
|
|
1958
2251
|
const hasDefaultCommand = cli.hasAgent;
|
|
2252
|
+
loadMarkdown().catch(() => {});
|
|
1959
2253
|
let prompting = null;
|
|
1960
2254
|
let sessionRef = null;
|
|
1961
2255
|
let currentAbortController = null;
|
|
@@ -2019,7 +2313,10 @@ function createReplSession(opts) {
|
|
|
2019
2313
|
try {
|
|
2020
2314
|
const result = await cli.execute(commandId, args, context);
|
|
2021
2315
|
context.stdout = origStdout;
|
|
2022
|
-
if (isSkillInvocation(result))
|
|
2316
|
+
if (isSkillInvocation(result)) {
|
|
2317
|
+
await loadTemplates();
|
|
2318
|
+
return handleAgentPrompt(renderSkillPromptFromInvocation(result));
|
|
2319
|
+
}
|
|
2023
2320
|
const text = formatResult$1(result);
|
|
2024
2321
|
if (segmentOpened) {
|
|
2025
2322
|
const resultChunk = {
|
|
@@ -2031,6 +2328,7 @@ function createReplSession(opts) {
|
|
|
2031
2328
|
streamParts.push(formatStreamChunk(resultChunk));
|
|
2032
2329
|
sessionRef?.onStreamChunk?.(resultChunk, streamParts.join(""));
|
|
2033
2330
|
}
|
|
2331
|
+
await loadMarkdown();
|
|
2034
2332
|
const rendered = renderMarkdown(text);
|
|
2035
2333
|
const prefix = captured.length > 0 ? captured.join("") : "";
|
|
2036
2334
|
return {
|
|
@@ -2313,6 +2611,7 @@ function createReplSession(opts) {
|
|
|
2313
2611
|
}
|
|
2314
2612
|
context._onToolOutput = void 0;
|
|
2315
2613
|
currentAbortController = null;
|
|
2614
|
+
await loadMarkdown();
|
|
2316
2615
|
return {
|
|
2317
2616
|
text: segments.map((seg) => {
|
|
2318
2617
|
const trimmed = seg.content.trim();
|
|
@@ -2447,7 +2746,7 @@ function createCliRuntime(deps) {
|
|
|
2447
2746
|
await getReactor();
|
|
2448
2747
|
output(`Reactor ready (drive: ${cachedReactor.driveId})`);
|
|
2449
2748
|
if (cachedReactor.personalDriveId) {
|
|
2450
|
-
const { createFolderOperations, createFolderCommands } = await import("./powerhouse-
|
|
2749
|
+
const { createFolderOperations, createFolderCommands } = await import("./powerhouse-C4O-raTW.mjs").then((n) => n.S);
|
|
2451
2750
|
const folderOps = createFolderOperations(cachedReactor.client, cachedReactor.personalDriveId, log);
|
|
2452
2751
|
context.folders = folderOps;
|
|
2453
2752
|
const folderCmds = createFolderCommands(folderOps);
|
|
@@ -2642,6 +2941,10 @@ function defineCli(options) {
|
|
|
2642
2941
|
function configureAgent(loader) {
|
|
2643
2942
|
agentLoader = loader;
|
|
2644
2943
|
}
|
|
2944
|
+
let identityConfig;
|
|
2945
|
+
function configureIdentity(config) {
|
|
2946
|
+
identityConfig = config;
|
|
2947
|
+
}
|
|
2645
2948
|
let reactorConfig;
|
|
2646
2949
|
function configureReactor(config) {
|
|
2647
2950
|
reactorConfig = config;
|
|
@@ -2663,6 +2966,7 @@ function defineCli(options) {
|
|
|
2663
2966
|
config: options.configSchema ? options.configSchema.parse({}) : {},
|
|
2664
2967
|
stdout: defaultStdout,
|
|
2665
2968
|
runProcess: noop,
|
|
2969
|
+
readStdin: readPipedStdin,
|
|
2666
2970
|
...base
|
|
2667
2971
|
};
|
|
2668
2972
|
if (routine) ctx.routine = routine;
|
|
@@ -2904,7 +3208,7 @@ function defineCli(options) {
|
|
|
2904
3208
|
if (!options.configSchema) return [];
|
|
2905
3209
|
return getConfigEnvVars(options.name, options.configSchema);
|
|
2906
3210
|
}
|
|
2907
|
-
function buildProgram(stdout, context, resolvedDescription, onSkillInvocation, wraps) {
|
|
3211
|
+
function buildProgram(stdout, context, resolvedDescription, onSkillInvocation, wraps, elsewhere) {
|
|
2908
3212
|
const program = new Command();
|
|
2909
3213
|
program.name(options.name).version(options.version).description(resolvedDescription).enablePositionalOptions().exitOverride().configureOutput({
|
|
2910
3214
|
writeOut: (str) => stdout(str.trimEnd()),
|
|
@@ -2914,6 +3218,7 @@ function defineCli(options) {
|
|
|
2914
3218
|
if (hasTriggers) program.option("-R, --no-routine", "Skip routine activation");
|
|
2915
3219
|
program.option("--verbose", "Enable debug-level logging");
|
|
2916
3220
|
program.option("--meta", "Output CLI metadata as JSON");
|
|
3221
|
+
program.option("--local", "Run the command in this process, not in a running instance");
|
|
2917
3222
|
if (agentLoader) program.option("--resume <thread-id>", "Resume a previous conversation");
|
|
2918
3223
|
if (!options.workdir) program.option("-w, --workdir <path>", "Set the workspace directory");
|
|
2919
3224
|
if (configFieldCount > 0) program.option("-c, --config <path>", "Load config from a JSON file (relative to cwd)");
|
|
@@ -2965,6 +3270,7 @@ function defineCli(options) {
|
|
|
2965
3270
|
} catch (err) {
|
|
2966
3271
|
throw new Error(formatZodError(err, cmd.id));
|
|
2967
3272
|
}
|
|
3273
|
+
if (elsewhere && await elsewhere(cmd, merged)) return;
|
|
2968
3274
|
const result = wraps ? await wraps.command(cmd.id, () => cmd.execute(parsed, context)) : await cmd.execute(parsed, context);
|
|
2969
3275
|
if (isSkillInvocation(result)) {
|
|
2970
3276
|
if (onSkillInvocation) await onSkillInvocation(result);
|
|
@@ -3021,7 +3327,13 @@ function defineCli(options) {
|
|
|
3021
3327
|
const servicesNow = options.services && options.services.length > 0;
|
|
3022
3328
|
let processServiceManager;
|
|
3023
3329
|
if (servicesNow && options.services) {
|
|
3024
|
-
const svcDir =
|
|
3330
|
+
const svcDir = instanceServicesDir({ dataDir: instanceDataDir(context.workdir) }, options.name);
|
|
3331
|
+
reportLegacyServiceState({
|
|
3332
|
+
legacyDir: userStoreFolder(options.name, "services"),
|
|
3333
|
+
servicesDir: svcDir,
|
|
3334
|
+
workdir: context.workdir,
|
|
3335
|
+
warn: (message) => log.warn(message)
|
|
3336
|
+
});
|
|
3025
3337
|
processServiceManager = createServiceManager(options.services, {
|
|
3026
3338
|
config,
|
|
3027
3339
|
servicesDir: svcDir,
|
|
@@ -3155,6 +3467,9 @@ function defineCli(options) {
|
|
|
3155
3467
|
}),
|
|
3156
3468
|
cwd: runOptions?.workdir ?? process.cwd(),
|
|
3157
3469
|
writeRaw: runOptions?.stdout ?? defaultStdout,
|
|
3470
|
+
writeRawErr: runOptions?.stderr ? (text) => runOptions.stderr(text.replace(/\n$/, "")) : (text) => {
|
|
3471
|
+
process.stderr.write(text);
|
|
3472
|
+
},
|
|
3158
3473
|
configFile: runOptions?.configFile,
|
|
3159
3474
|
resume: runOptions?.resume,
|
|
3160
3475
|
interactiveInput: runOptions?.interactiveInput,
|
|
@@ -3164,7 +3479,9 @@ function defineCli(options) {
|
|
|
3164
3479
|
signal: runOptions?.signal,
|
|
3165
3480
|
members: runOptions?.members,
|
|
3166
3481
|
remoteServices: runOptions?.remoteServices,
|
|
3167
|
-
serveCommand: runOptions?.serveCommand
|
|
3482
|
+
serveCommand: runOptions?.serveCommand,
|
|
3483
|
+
forward: runOptions?.forward,
|
|
3484
|
+
store: runOptions?.store
|
|
3168
3485
|
});
|
|
3169
3486
|
}
|
|
3170
3487
|
/**
|
|
@@ -3189,6 +3506,7 @@ function defineCli(options) {
|
|
|
3189
3506
|
let verboseFlag = false;
|
|
3190
3507
|
let metaFlag = false;
|
|
3191
3508
|
let noRoutineFlag = false;
|
|
3509
|
+
let localFlag = false;
|
|
3192
3510
|
const frameworkFlags = /* @__PURE__ */ new Set([
|
|
3193
3511
|
"--resume",
|
|
3194
3512
|
"--workdir",
|
|
@@ -3202,6 +3520,7 @@ function defineCli(options) {
|
|
|
3202
3520
|
else if (arg === "--verbose") verboseFlag = true;
|
|
3203
3521
|
else if (arg === "--meta") metaFlag = true;
|
|
3204
3522
|
else if (arg === "-R" || arg === "--no-routine") noRoutineFlag = true;
|
|
3523
|
+
else if (arg === "--local") localFlag = true;
|
|
3205
3524
|
else if (frameworkFlags.has(arg) && i + 1 < preCommandArgs.length) {
|
|
3206
3525
|
const value = preCommandArgs[i + 1];
|
|
3207
3526
|
if (arg === "--workdir" || arg === "-w") workdirFlag = value;
|
|
@@ -3240,7 +3559,8 @@ function defineCli(options) {
|
|
|
3240
3559
|
implementationDefaults: options.configDefaults
|
|
3241
3560
|
}) : {};
|
|
3242
3561
|
bootTimings.configResolvedAt = Date.now();
|
|
3243
|
-
const
|
|
3562
|
+
const logLevel = opts.logLevel ?? (verboseFlag ? "debug" : "info");
|
|
3563
|
+
const log = createLogger(logLevel, stderr);
|
|
3244
3564
|
const context = buildContext({
|
|
3245
3565
|
workdir,
|
|
3246
3566
|
workspace,
|
|
@@ -3334,21 +3654,230 @@ function defineCli(options) {
|
|
|
3334
3654
|
...invocation.inputValues ?? {}
|
|
3335
3655
|
}).rendered.trim();
|
|
3336
3656
|
}
|
|
3337
|
-
|
|
3657
|
+
/**
|
|
3658
|
+
* One turn of the agent, its answer written as it streams. Resolves false
|
|
3659
|
+
* when the CLI has no agent.
|
|
3660
|
+
*/
|
|
3661
|
+
async function streamPrompt(prompt, to = {
|
|
3662
|
+
raw: writeRaw,
|
|
3663
|
+
line: stdout,
|
|
3664
|
+
resume: resumeId
|
|
3665
|
+
}) {
|
|
3338
3666
|
const agentProvider = await runtime.getAgent();
|
|
3339
|
-
if (!agentProvider)
|
|
3667
|
+
if (!agentProvider) return false;
|
|
3668
|
+
const threadId = to.resume ?? randomUUID();
|
|
3669
|
+
for await (const chunk of agentProvider.stream(prompt, {
|
|
3670
|
+
threadId,
|
|
3671
|
+
tools: commandMap,
|
|
3672
|
+
...to.signal ? { abortSignal: to.signal } : {}
|
|
3673
|
+
})) to.raw(formatStreamChunk(chunk));
|
|
3674
|
+
to.line("");
|
|
3675
|
+
to.line(`\x1b[2mThread: ${threadId} (continue with: ${options.name} --resume ${threadId} "your message")\x1b[0m`);
|
|
3676
|
+
return true;
|
|
3677
|
+
}
|
|
3678
|
+
async function handleSkillInvocation(invocation) {
|
|
3679
|
+
if (!await runtime.getAgent()) {
|
|
3340
3680
|
stderr("Agent not available — cannot invoke skill");
|
|
3341
3681
|
exit(1);
|
|
3342
3682
|
return;
|
|
3343
3683
|
}
|
|
3344
|
-
|
|
3345
|
-
|
|
3346
|
-
|
|
3347
|
-
|
|
3348
|
-
|
|
3349
|
-
|
|
3350
|
-
|
|
3351
|
-
|
|
3684
|
+
await loadTemplates();
|
|
3685
|
+
await streamPrompt(renderSkillPrompt(invocation));
|
|
3686
|
+
}
|
|
3687
|
+
/** What `cmd` needs of a running instance. */
|
|
3688
|
+
const needsOf = (cmd) => cmd.needs ?? (skillIds.has(cmd.id) ? "agent" : "nothing");
|
|
3689
|
+
const readsStdin = (cmd, input) => typeof cmd.stdin === "function" ? cmd.stdin(input) : cmd.stdin === true;
|
|
3690
|
+
/**
|
|
3691
|
+
* A command the running instance executes for a caller in another
|
|
3692
|
+
* process: with this instance's reactor and agent, its output to the
|
|
3693
|
+
* caller. Resolves with the exit code; rejects only when it was cancelled.
|
|
3694
|
+
*/
|
|
3695
|
+
async function runForwarded(run) {
|
|
3696
|
+
const { request, caller } = run;
|
|
3697
|
+
const line = (message) => run.stdout(`${message}\n`);
|
|
3698
|
+
const fail = (message) => run.stderr(`${message}\n`);
|
|
3699
|
+
const what = request.command ?? "a prompt";
|
|
3700
|
+
log.debug(`Running ${what} for ${caller.user || "an unnamed user"} (pid ${caller.pid}).`);
|
|
3701
|
+
context.emit?.("command:forwarded", {
|
|
3702
|
+
command: request.command,
|
|
3703
|
+
user: caller.user,
|
|
3704
|
+
pid: caller.pid
|
|
3705
|
+
});
|
|
3706
|
+
const signing = callerSigningOf({
|
|
3707
|
+
...run.request.signer ? { signer: run.request.signer } : {},
|
|
3708
|
+
asks: run.asks,
|
|
3709
|
+
ask: (kind, payload) => run.ask(kind, payload)
|
|
3710
|
+
});
|
|
3711
|
+
return captureOutput(run, () => withCallerSigning(signing, () => executeForwarded(run, line, fail)));
|
|
3712
|
+
}
|
|
3713
|
+
async function executeForwarded(run, line, fail) {
|
|
3714
|
+
const { request, caller } = run;
|
|
3715
|
+
try {
|
|
3716
|
+
if (request.prompt !== void 0) {
|
|
3717
|
+
if (await untilAborted(asOwnSigner(() => streamPrompt(request.prompt, {
|
|
3718
|
+
raw: run.stdout,
|
|
3719
|
+
line,
|
|
3720
|
+
signal: run.signal,
|
|
3721
|
+
...request.resume ? { resume: request.resume } : {}
|
|
3722
|
+
})), run.signal)) return 0;
|
|
3723
|
+
fail(`${options.name} has no agent to answer a prompt.`);
|
|
3724
|
+
return 1;
|
|
3725
|
+
}
|
|
3726
|
+
const cmd = commandMap.get(request.command);
|
|
3727
|
+
if (!cmd || cmd.id === "cli-docs") {
|
|
3728
|
+
fail(`Unknown command: ${request.command}`);
|
|
3729
|
+
return 1;
|
|
3730
|
+
}
|
|
3731
|
+
if (needsOf(cmd) === "nothing") {
|
|
3732
|
+
fail(`${cmd.id} runs in the process that calls it, not in the running ${options.name}.`);
|
|
3733
|
+
return 1;
|
|
3734
|
+
}
|
|
3735
|
+
const input = request.input ?? {};
|
|
3736
|
+
let parsed;
|
|
3737
|
+
try {
|
|
3738
|
+
parsed = cmd.inputSchema.parse(input);
|
|
3739
|
+
} catch (err) {
|
|
3740
|
+
fail(formatZodError(err, cmd.id));
|
|
3741
|
+
return 1;
|
|
3742
|
+
}
|
|
3743
|
+
const ctx = {
|
|
3744
|
+
...context,
|
|
3745
|
+
stdout: run.stdout,
|
|
3746
|
+
log: createLogger(request.verbose ? "debug" : logLevel, fail),
|
|
3747
|
+
signal: run.signal,
|
|
3748
|
+
caller,
|
|
3749
|
+
readStdin: readsStdin(cmd, input) ? () => Promise.resolve(request.stdin) : () => Promise.reject(/* @__PURE__ */ new Error(`${cmd.id} reads piped input but does not declare it (stdin), so the caller's was not sent. Pass the input as an option or a file.`))
|
|
3750
|
+
};
|
|
3751
|
+
delete ctx._onToolOutput;
|
|
3752
|
+
ctx.runProcess = (command, runOpts) => processManager.run(command, {
|
|
3753
|
+
...runOpts,
|
|
3754
|
+
onOutput: (text) => ctx.stdout(text + "\n")
|
|
3755
|
+
});
|
|
3756
|
+
const result = await untilAborted(lifecycle.wraps.command(cmd.id, () => cmd.execute(parsed, ctx)), run.signal);
|
|
3757
|
+
if (isSkillInvocation(result)) {
|
|
3758
|
+
await loadTemplates();
|
|
3759
|
+
if (await untilAborted(asOwnSigner(() => streamPrompt(renderSkillPrompt(result), {
|
|
3760
|
+
raw: run.stdout,
|
|
3761
|
+
line,
|
|
3762
|
+
signal: run.signal,
|
|
3763
|
+
...request.resume ? { resume: request.resume } : {}
|
|
3764
|
+
})), run.signal)) return 0;
|
|
3765
|
+
fail("Agent not available — cannot invoke skill");
|
|
3766
|
+
return 1;
|
|
3767
|
+
}
|
|
3768
|
+
const output = formatResult(result);
|
|
3769
|
+
if (output !== void 0) line(output);
|
|
3770
|
+
return 0;
|
|
3771
|
+
} catch (err) {
|
|
3772
|
+
if (run.signal.aborted) throw err;
|
|
3773
|
+
fail(err instanceof Error ? err.message : String(err));
|
|
3774
|
+
return typeof err?.exitCode === "number" && err.exitCode !== 0 ? err.exitCode : 1;
|
|
3775
|
+
}
|
|
3776
|
+
}
|
|
3777
|
+
/** Where a command that needs a running instance is refused without one. */
|
|
3778
|
+
const noInstance = (what) => `${what} runs in a running ${options.name}, and none runs for ${workdir}. Start it with ${opts.serveCommand ? `\`${opts.serveCommand}\`` : "`ph run <host>`"}, then run this again.`;
|
|
3779
|
+
/**
|
|
3780
|
+
* Sends a command (or a prompt) that needs the reactor or the agent to
|
|
3781
|
+
* the running instance and shows its output. Resolves with the exit code,
|
|
3782
|
+
* or undefined when it is to run in this process.
|
|
3783
|
+
*/
|
|
3784
|
+
async function inInstance(what) {
|
|
3785
|
+
const forward = opts.forward;
|
|
3786
|
+
if (!forward || localFlag) return void 0;
|
|
3787
|
+
if ("command" in what && needsOf(what.command) === "nothing") return;
|
|
3788
|
+
const name = "command" in what ? `${options.name} ${what.command.id}` : `A prompt to ${options.name}`;
|
|
3789
|
+
const { target } = forward;
|
|
3790
|
+
const control = target?.control;
|
|
3791
|
+
if (!control) {
|
|
3792
|
+
if (target?.protocol !== void 0) {
|
|
3793
|
+
stderr(`${name} was not sent to the running ${options.name}${target.pid ? ` (pid ${target.pid})` : ""}. ${protocolMismatch(target.protocol)}`);
|
|
3794
|
+
return 1;
|
|
3795
|
+
}
|
|
3796
|
+
if (!forward.required) return void 0;
|
|
3797
|
+
stderr(noInstance(name));
|
|
3798
|
+
return 1;
|
|
3799
|
+
}
|
|
3800
|
+
let hello;
|
|
3801
|
+
try {
|
|
3802
|
+
hello = await callControl(control, "hello", void 0, { timeoutMs: 5e3 });
|
|
3803
|
+
if (!(Array.isArray(hello?.methods) ? hello.methods : []).includes("command")) {
|
|
3804
|
+
if (!forward.required) return void 0;
|
|
3805
|
+
stderr(`${name} needs a running ${options.name}; the instance for ${workdir}${target.pid ? ` (pid ${target.pid})` : ""} takes no commands.`);
|
|
3806
|
+
return 1;
|
|
3807
|
+
}
|
|
3808
|
+
} catch (err) {
|
|
3809
|
+
if (!(err instanceof ControlError)) throw err;
|
|
3810
|
+
if (err.code === "unreachable") {
|
|
3811
|
+
if (!forward.required) return void 0;
|
|
3812
|
+
stderr(noInstance(name));
|
|
3813
|
+
} else stderr(err.message);
|
|
3814
|
+
return 1;
|
|
3815
|
+
}
|
|
3816
|
+
const signs = identityConfig !== void 0 && "command" in what;
|
|
3817
|
+
if (signs && hello?.signing !== 1) {
|
|
3818
|
+
stderr(`${name} was not sent: the running ${options.name}${target.pid ? ` (pid ${target.pid})` : ""} is another version and cannot sign as you. Restart it${opts.serveCommand ? ` (\`${opts.serveCommand}\`)` : ""}, then run this again.`);
|
|
3819
|
+
return 1;
|
|
3820
|
+
}
|
|
3821
|
+
const stdin = "command" in what && readsStdin(what.command, what.input) ? await readPipedStdin() : void 0;
|
|
3822
|
+
let held;
|
|
3823
|
+
const hold = (on) => {
|
|
3824
|
+
if (on) {
|
|
3825
|
+
held ??= [];
|
|
3826
|
+
return;
|
|
3827
|
+
}
|
|
3828
|
+
const waiting = held ?? [];
|
|
3829
|
+
held = void 0;
|
|
3830
|
+
for (const write of waiting) write();
|
|
3831
|
+
};
|
|
3832
|
+
const writeOut = (text) => held ? held.push(() => writeRaw(text)) : writeRaw(text);
|
|
3833
|
+
const writeErr = (text) => held ? held.push(() => opts.writeRawErr(text)) : opts.writeRawErr(text);
|
|
3834
|
+
const store = commandStoreSchema.safeParse(hello?.store);
|
|
3835
|
+
const answers = signs ? callerAnswers({
|
|
3836
|
+
identity: identityConfig,
|
|
3837
|
+
workdir,
|
|
3838
|
+
dataDir: instanceDataDir(workdir),
|
|
3839
|
+
interactive: stdin === void 0 && process.stdin.isTTY === true,
|
|
3840
|
+
...store.success ? { store: store.data } : {},
|
|
3841
|
+
hold
|
|
3842
|
+
}) : void 0;
|
|
3843
|
+
const stop = new AbortController();
|
|
3844
|
+
const abort = () => stop.abort();
|
|
3845
|
+
process.once("SIGINT", abort);
|
|
3846
|
+
process.once("SIGTERM", abort);
|
|
3847
|
+
opts.signal?.addEventListener("abort", abort, { once: true });
|
|
3848
|
+
if (opts.signal?.aborted) abort();
|
|
3849
|
+
try {
|
|
3850
|
+
return await sendCommand(control, {
|
|
3851
|
+
cli: options.name,
|
|
3852
|
+
version: options.version,
|
|
3853
|
+
..."command" in what ? {
|
|
3854
|
+
command: what.command.id,
|
|
3855
|
+
input: what.input
|
|
3856
|
+
} : { prompt: what.prompt },
|
|
3857
|
+
...resumeId ? { resume: resumeId } : {},
|
|
3858
|
+
workdir,
|
|
3859
|
+
...describeCaller(),
|
|
3860
|
+
...verboseFlag ? { verbose: true } : {},
|
|
3861
|
+
...stdin === void 0 ? {} : { stdin }
|
|
3862
|
+
}, {
|
|
3863
|
+
stdout: writeOut,
|
|
3864
|
+
stderr: writeErr,
|
|
3865
|
+
signal: stop.signal,
|
|
3866
|
+
...answers ? {
|
|
3867
|
+
asks: answers.asks,
|
|
3868
|
+
onAsk: (kind, payload) => answers.onAsk(kind, payload)
|
|
3869
|
+
} : {}
|
|
3870
|
+
});
|
|
3871
|
+
} catch (err) {
|
|
3872
|
+
if (err instanceof ControlError && err.code === "cancelled") return 130;
|
|
3873
|
+
if (!(err instanceof ControlError || err instanceof CommandTooLarge)) throw err;
|
|
3874
|
+
stderr(err.message);
|
|
3875
|
+
return 1;
|
|
3876
|
+
} finally {
|
|
3877
|
+
process.off("SIGINT", abort);
|
|
3878
|
+
process.off("SIGTERM", abort);
|
|
3879
|
+
opts.signal?.removeEventListener("abort", abort);
|
|
3880
|
+
}
|
|
3352
3881
|
}
|
|
3353
3882
|
const effectiveRoutine = noRoutineFlag ? void 0 : routine;
|
|
3354
3883
|
const isTTY = interactiveFlag && !opts.interactiveInput && process.stdin.isTTY;
|
|
@@ -3360,22 +3889,32 @@ function defineCli(options) {
|
|
|
3360
3889
|
context.services = (opts.remoteServices ? await connectRemoteServices(local, opts.remoteServices) : void 0) ?? refuseServiceStarts(local, opts.serveCommand);
|
|
3361
3890
|
}
|
|
3362
3891
|
if (opts.remoteServices && !isBuiltinFlag) context.serving = opts.remoteServices;
|
|
3892
|
+
let exitCode;
|
|
3893
|
+
if (opts.forward?.required && !localFlag && !isBuiltinFlag) {
|
|
3894
|
+
const none = (what) => () => Promise.reject(/* @__PURE__ */ new Error(`This command asked for the ${what}, which the running ${options.name} holds: it must declare needs: "${what}" to run there.`));
|
|
3895
|
+
if (!supplyReactor) context.reactor = none("reactor");
|
|
3896
|
+
context.agent = none("agent");
|
|
3897
|
+
}
|
|
3363
3898
|
if (hasPrompt) {
|
|
3364
|
-
const
|
|
3365
|
-
|
|
3366
|
-
|
|
3367
|
-
|
|
3368
|
-
|
|
3369
|
-
|
|
3370
|
-
|
|
3371
|
-
|
|
3372
|
-
stdout("");
|
|
3373
|
-
stdout(`\x1b[2mThread: ${threadId} (continue with: ${options.name} --resume ${threadId} "your message")\x1b[0m`);
|
|
3899
|
+
const prompt = promptArgs.join(" ");
|
|
3900
|
+
exitCode = await inInstance({ prompt });
|
|
3901
|
+
if (exitCode !== void 0) {
|
|
3902
|
+
await runtime.teardown();
|
|
3903
|
+
if (exitCode !== 0) exit(exitCode);
|
|
3904
|
+
return;
|
|
3905
|
+
}
|
|
3906
|
+
if (await streamPrompt(prompt)) {
|
|
3374
3907
|
await runtime.teardown();
|
|
3375
3908
|
return;
|
|
3376
3909
|
}
|
|
3377
3910
|
}
|
|
3378
|
-
const program = buildProgram(stdout, context, resolvedDescription, agentLoader ? handleSkillInvocation : void 0, lifecycle.wraps)
|
|
3911
|
+
const program = buildProgram(stdout, context, resolvedDescription, agentLoader ? handleSkillInvocation : void 0, lifecycle.wraps, async (cmd, input) => {
|
|
3912
|
+
exitCode = await inInstance({
|
|
3913
|
+
command: cmd,
|
|
3914
|
+
input
|
|
3915
|
+
});
|
|
3916
|
+
return exitCode !== void 0;
|
|
3917
|
+
});
|
|
3379
3918
|
try {
|
|
3380
3919
|
await program.parseAsync(argv);
|
|
3381
3920
|
} catch (err) {
|
|
@@ -3392,9 +3931,16 @@ function defineCli(options) {
|
|
|
3392
3931
|
return;
|
|
3393
3932
|
}
|
|
3394
3933
|
await runtime.teardown();
|
|
3934
|
+
if (exitCode) exit(exitCode);
|
|
3395
3935
|
} else if (interactiveFlag || hasKeepAlive) {
|
|
3396
3936
|
if (opts.onServe) try {
|
|
3397
|
-
await opts.onServe();
|
|
3937
|
+
const answer = await opts.onServe();
|
|
3938
|
+
if (answer) {
|
|
3939
|
+
await runtime.teardown();
|
|
3940
|
+
stdout(answer.running);
|
|
3941
|
+
exit(0);
|
|
3942
|
+
return;
|
|
3943
|
+
}
|
|
3398
3944
|
} catch (err) {
|
|
3399
3945
|
await runtime.teardown();
|
|
3400
3946
|
stderr(err instanceof Error ? err.message : String(err));
|
|
@@ -3402,11 +3948,16 @@ function defineCli(options) {
|
|
|
3402
3948
|
return;
|
|
3403
3949
|
}
|
|
3404
3950
|
const control = processControlChannel();
|
|
3405
|
-
if (control
|
|
3406
|
-
|
|
3407
|
-
|
|
3408
|
-
|
|
3409
|
-
|
|
3951
|
+
if (control) {
|
|
3952
|
+
const served = {
|
|
3953
|
+
name: options.name,
|
|
3954
|
+
version: options.version,
|
|
3955
|
+
workdir,
|
|
3956
|
+
...opts.store ? { store: opts.store } : {}
|
|
3957
|
+
};
|
|
3958
|
+
if (context.services) serveServices(control, context.services, served);
|
|
3959
|
+
serveCommands(control, served, runForwarded);
|
|
3960
|
+
}
|
|
3410
3961
|
let session;
|
|
3411
3962
|
if (interactiveFlag) {
|
|
3412
3963
|
if (!options.interactive) {
|
|
@@ -3433,6 +3984,7 @@ function defineCli(options) {
|
|
|
3433
3984
|
},
|
|
3434
3985
|
configureAgent,
|
|
3435
3986
|
configureReactor,
|
|
3987
|
+
configureIdentity,
|
|
3436
3988
|
getCommand,
|
|
3437
3989
|
listCommands,
|
|
3438
3990
|
execute,
|
|
@@ -3455,7 +4007,7 @@ function defineCli(options) {
|
|
|
3455
4007
|
switch (mode) {
|
|
3456
4008
|
case "interactive-terminal": {
|
|
3457
4009
|
/* istanbul ignore next -- Ink REPL requires a real terminal */
|
|
3458
|
-
const { startInkRepl } = await import("./start-
|
|
4010
|
+
const { startInkRepl } = await import("./start-CCegR8Pi.mjs");
|
|
3459
4011
|
/* istanbul ignore next */
|
|
3460
4012
|
await startInkRepl(session, {
|
|
3461
4013
|
services: context.services,
|
|
@@ -3696,6 +4248,7 @@ function defineCli(options) {
|
|
|
3696
4248
|
},
|
|
3697
4249
|
configureAgent,
|
|
3698
4250
|
configureReactor,
|
|
4251
|
+
configureIdentity,
|
|
3699
4252
|
getCommand,
|
|
3700
4253
|
listCommands,
|
|
3701
4254
|
execute,
|
|
@@ -3814,6 +4367,6 @@ async function getProjectMapping(scanResults, folders) {
|
|
|
3814
4367
|
return mappings;
|
|
3815
4368
|
}
|
|
3816
4369
|
//#endregion
|
|
3817
|
-
export {
|
|
4370
|
+
export { connectRemoteServices as A, resolveConfig as B, readSkills as C, createServiceCommands as D, callerAnswers as E, generateConfigCommandHelp as F, formatZodError as G, userConfigPath as H, resolveWorkdir as I, readPackageInfo as K, configKeyToEnvVar as L, restartService as M, serveServices as N, formatStatus as O, createConfigCommand as P, getMissingRequiredFields as R, renderSkillTemplate as S, createHelpCommand as T, userStoreFolder as U, toUpperSnake as V, createLogger as W, createSkillCommands as _, initLifecycle as a, loadTemplates as b, tokenizeArgs as c, createRoutine as d, IDENTITY_WRAPS as f, DEFAULT_SKILL_INSTRUCTION as g, createEventBus as h, defineCli as i, refuseServiceStarts as j, ServiceStartRefused as k, createCompositeServiceManager as l, createProcessManager as m, createTypes as n, createReplSession as o, composeWraps as p, defineTrigger as r, parseReplInput as s, getProjectMapping as t, createRoutineServiceAdapter as u, isSkillInvocation as v, installSkills as w, registerDefaultHelpers as x, extractTemplateVars as y, localConfigPath as z };
|
|
3818
4371
|
|
|
3819
|
-
//# sourceMappingURL=src-
|
|
4372
|
+
//# sourceMappingURL=src-FF3zDJY7.mjs.map
|