@dna113p/machines 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +186 -0
  3. package/dist/codex/machines/ui/machines.html +286 -0
  4. package/dist/examples/agent.d.ts +1 -0
  5. package/dist/examples/agent.js +19 -0
  6. package/dist/examples/choices.d.ts +1 -0
  7. package/dist/examples/choices.js +17 -0
  8. package/dist/examples/host.d.ts +3 -0
  9. package/dist/examples/host.js +32 -0
  10. package/dist/examples/human.d.ts +1 -0
  11. package/dist/examples/human.js +17 -0
  12. package/dist/examples/named-agents.d.ts +1 -0
  13. package/dist/examples/named-agents.js +38 -0
  14. package/dist/examples/operation.d.ts +1 -0
  15. package/dist/examples/operation.js +10 -0
  16. package/dist/examples/pi.d.ts +1 -0
  17. package/dist/examples/pi.js +29 -0
  18. package/dist/mcp/server.d.ts +17 -0
  19. package/dist/mcp/server.js +313 -0
  20. package/dist/pi-extension/index.d.ts +52 -0
  21. package/dist/pi-extension/index.js +390 -0
  22. package/dist/src/acp.d.ts +7 -0
  23. package/dist/src/acp.js +184 -0
  24. package/dist/src/agent-bindings.d.ts +15 -0
  25. package/dist/src/agent-bindings.js +113 -0
  26. package/dist/src/catalog.d.ts +31 -0
  27. package/dist/src/catalog.js +68 -0
  28. package/dist/src/cli.d.ts +2 -0
  29. package/dist/src/cli.js +392 -0
  30. package/dist/src/discovery-worker.d.ts +3 -0
  31. package/dist/src/discovery-worker.js +52 -0
  32. package/dist/src/discovery.d.ts +8 -0
  33. package/dist/src/discovery.js +94 -0
  34. package/dist/src/host.d.ts +25 -0
  35. package/dist/src/host.js +357 -0
  36. package/dist/src/index.d.ts +210 -0
  37. package/dist/src/index.js +204 -0
  38. package/dist/src/launcher.d.ts +19 -0
  39. package/dist/src/launcher.js +98 -0
  40. package/dist/src/machine-module.d.ts +3 -0
  41. package/dist/src/machine-module.js +55 -0
  42. package/dist/src/session.d.ts +40 -0
  43. package/dist/src/session.js +165 -0
  44. package/dist/src/terminal-human.d.ts +2 -0
  45. package/dist/src/terminal-human.js +100 -0
  46. package/docs/architecture.md +111 -0
  47. package/docs/authoring.md +193 -0
  48. package/docs/integrations.md +142 -0
  49. package/package.json +58 -0
  50. package/skills/machine-builder/SKILL.md +34 -0
@@ -0,0 +1,210 @@
1
+ import { type AnyStateMachine, type SnapshotFrom, type StateValue } from "xstate";
2
+ export interface Event {
3
+ readonly type: string;
4
+ readonly [key: string]: unknown;
5
+ }
6
+ export type HumanOptions = {
7
+ readonly choices: readonly string[];
8
+ readonly suggestions?: never;
9
+ } | {
10
+ readonly choices?: never;
11
+ readonly suggestions?: readonly string[];
12
+ };
13
+ export type HumanPrompt = string | (() => string);
14
+ export interface HumanRequest {
15
+ readonly prompt: string;
16
+ readonly choices?: readonly string[];
17
+ readonly suggestions?: readonly string[];
18
+ }
19
+ export type HumanRunner = (request: HumanRequest) => string | Promise<string>;
20
+ export interface AgentOptions {
21
+ readonly cwd?: string;
22
+ readonly using?: string;
23
+ }
24
+ export type AgentPrompt = string | (() => string);
25
+ export interface AgentRequest {
26
+ readonly prompt: string;
27
+ readonly outcomes: readonly string[];
28
+ readonly cwd?: string;
29
+ }
30
+ interface AgentInvocation extends AgentRequest {
31
+ readonly using: string;
32
+ }
33
+ export type AgentUpdate = {
34
+ readonly type: "identity";
35
+ readonly harness: string;
36
+ readonly model?: string;
37
+ readonly thinking?: string;
38
+ } | {
39
+ readonly type: "output";
40
+ readonly text: string;
41
+ } | {
42
+ readonly type: "tool";
43
+ readonly id: string;
44
+ readonly title?: string;
45
+ readonly status?: "pending" | "in_progress" | "completed" | "failed";
46
+ };
47
+ export type AgentReporter = (update: AgentUpdate) => void;
48
+ export type AgentRunner = (request: AgentRequest, report?: AgentReporter) => Event | Promise<Event>;
49
+ export interface RunOptions {
50
+ readonly agents?: Readonly<Record<string, AgentRunner>>;
51
+ readonly human?: HumanRunner;
52
+ readonly onAgentUpdate?: AgentReporter;
53
+ readonly onHumanInput?: (active: boolean) => void;
54
+ readonly onState?: (state: StateValue) => void;
55
+ }
56
+ export declare const machine: <const TConfig extends import("xstate").MachineConfig<import("xstate").MachineContext, import("xstate").AnyEventObject, {
57
+ src: "agent";
58
+ logic: import("xstate").PromiseActorLogic<Event, AgentInvocation, import("xstate").EventObject>;
59
+ id: string | undefined;
60
+ } | {
61
+ src: "human";
62
+ logic: import("xstate").PromiseActorLogic<Event, HumanRequest, import("xstate").EventObject>;
63
+ id: string | undefined;
64
+ }, {
65
+ type: "humanInputFinished";
66
+ params: unknown;
67
+ } | {
68
+ type: "humanInputStarted";
69
+ params: unknown;
70
+ }, never, never, string, import("xstate").NonReducibleUnknown, import("xstate").NonReducibleUnknown, import("xstate").EventObject, import("xstate").MetaObject>, TResolvedChildren extends Record<string, string> = import("xstate").Cast<TConfig extends {
71
+ invoke: infer TInvoke;
72
+ } ? TInvoke extends readonly (infer E)[] ? ((E extends {
73
+ id: infer TId extends string;
74
+ src: infer TSrc extends string;
75
+ } ? { [K in TId]: TSrc; } : {}) extends infer T ? T extends (E extends {
76
+ id: infer TId extends string;
77
+ src: infer TSrc extends string;
78
+ } ? { [K in TId]: TSrc; } : {}) ? T extends any ? (x: T) => void : never : never : never) extends (x: infer I) => void ? I : never : TInvoke extends {
79
+ id: infer TId extends string;
80
+ src: infer TSrc extends string;
81
+ } ? { [K in TId]: TSrc; } : {} : {}, Record<string, string>>>(config: TConfig) => import("xstate").StateMachine<import("xstate").MachineContext, import("xstate").AnyEventObject | ([import("xstate").RoutableStateId<TConfig>] extends [never] ? never : {
82
+ type: 'xstate.route';
83
+ to: import("xstate").RoutableStateId<TConfig>;
84
+ }), import("xstate").Cast<{ [A in {
85
+ src: "agent";
86
+ logic: import("xstate").PromiseActorLogic<Event, AgentInvocation, import("xstate").EventObject>;
87
+ id: import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "agent" extends infer T_2 ? T_2 extends "agent" ? T_2 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_2] & string : string | undefined : never : never;
88
+ } | {
89
+ src: "human";
90
+ logic: import("xstate").PromiseActorLogic<Event, HumanRequest, import("xstate").EventObject>;
91
+ id: import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "human" extends infer T_3 ? T_3 extends "human" ? T_3 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_3] & string : string | undefined : never : never;
92
+ } as A["id"] extends infer T_4 ? T_4 extends A["id"] ? T_4 extends string ? string extends T_4 ? never : T_4 : never : never : never]?: import("xstate").ActorRefFromLogic<A["logic"]> | undefined; } & {
93
+ include: {
94
+ [id: string]: (((import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "agent" extends infer T_2 ? T_2 extends "agent" ? T_2 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_2] & string : string | undefined : never : never) extends infer T_4 ? T_4 extends (import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "agent" extends infer T_2 ? T_2 extends "agent" ? T_2 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_2] & string : string | undefined : never : never) ? T_4 extends string ? string extends T_4 ? never : T_4 : never : never : never) extends never ? {
95
+ src: "agent";
96
+ logic: import("xstate").PromiseActorLogic<Event, AgentInvocation, import("xstate").EventObject>;
97
+ id: import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "agent" extends infer T_2 ? T_2 extends "agent" ? T_2 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_2] & string : string | undefined : never : never;
98
+ } : never) | (((import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "human" extends infer T_3 ? T_3 extends "human" ? T_3 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_3] & string : string | undefined : never : never) extends infer T_5 ? T_5 extends (import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "human" extends infer T_3 ? T_3 extends "human" ? T_3 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_3] & string : string | undefined : never : never) ? T_5 extends string ? string extends T_5 ? never : T_5 : never : never : never) extends never ? {
99
+ src: "human";
100
+ logic: import("xstate").PromiseActorLogic<Event, HumanRequest, import("xstate").EventObject>;
101
+ id: import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "human" extends infer T_3 ? T_3 extends "human" ? T_3 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_3] & string : string | undefined : never : never;
102
+ } : never) extends never ? import("xstate").AnyActorRef | undefined : (((import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "agent" extends infer T_2 ? T_2 extends "agent" ? T_2 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_2] & string : string | undefined : never : never) extends infer T_4 ? T_4 extends (import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "agent" extends infer T_2 ? T_2 extends "agent" ? T_2 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_2] & string : string | undefined : never : never) ? T_4 extends string ? string extends T_4 ? never : T_4 : never : never : never) extends never ? {
103
+ src: "agent";
104
+ logic: import("xstate").PromiseActorLogic<Event, AgentInvocation, import("xstate").EventObject>;
105
+ id: import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "agent" extends infer T_2 ? T_2 extends "agent" ? T_2 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_2] & string : string | undefined : never : never;
106
+ } : never) | (((import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "human" extends infer T_3 ? T_3 extends "human" ? T_3 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_3] & string : string | undefined : never : never) extends infer T_5 ? T_5 extends (import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "human" extends infer T_3 ? T_3 extends "human" ? T_3 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_3] & string : string | undefined : never : never) ? T_5 extends string ? string extends T_5 ? never : T_5 : never : never : never) extends never ? {
107
+ src: "human";
108
+ logic: import("xstate").PromiseActorLogic<Event, HumanRequest, import("xstate").EventObject>;
109
+ id: import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "human" extends infer T_3 ? T_3 extends "human" ? T_3 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_3] & string : string | undefined : never : never;
110
+ } : never) extends any ? import("xstate").ActorRefFromLogic<((((import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "agent" extends infer T_2 ? T_2 extends "agent" ? T_2 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_2] & string : string | undefined : never : never) extends infer T_4 ? T_4 extends (import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "agent" extends infer T_2 ? T_2 extends "agent" ? T_2 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_2] & string : string | undefined : never : never) ? T_4 extends string ? string extends T_4 ? never : T_4 : never : never : never) extends never ? {
111
+ src: "agent";
112
+ logic: import("xstate").PromiseActorLogic<Event, AgentInvocation, import("xstate").EventObject>;
113
+ id: import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "agent" extends infer T_2 ? T_2 extends "agent" ? T_2 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_2] & string : string | undefined : never : never;
114
+ } : never) | (((import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "human" extends infer T_3 ? T_3 extends "human" ? T_3 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_3] & string : string | undefined : never : never) extends infer T_5 ? T_5 extends (import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "human" extends infer T_3 ? T_3 extends "human" ? T_3 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_3] & string : string | undefined : never : never) ? T_5 extends string ? string extends T_5 ? never : T_5 : never : never : never) extends never ? {
115
+ src: "human";
116
+ logic: import("xstate").PromiseActorLogic<Event, HumanRequest, import("xstate").EventObject>;
117
+ id: import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "human" extends infer T_3 ? T_3 extends "human" ? T_3 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_3] & string : string | undefined : never : never;
118
+ } : never))["logic"]> | undefined : never;
119
+ };
120
+ exclude: unknown;
121
+ }[(((import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "agent" extends infer T_6 ? T_6 extends "agent" ? T_6 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_6] & string : string | undefined : never : never) extends infer T_7 ? T_7 extends (import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "agent" extends infer T_6 ? T_6 extends "agent" ? T_6 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_6] & string : string | undefined : never : never) ? T_7 extends string ? string extends T_7 ? never : T_7 : never : never : never) extends never ? {
122
+ src: "agent";
123
+ logic: import("xstate").PromiseActorLogic<Event, AgentInvocation, import("xstate").EventObject>;
124
+ id: import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "agent" extends infer T_2 ? T_2 extends "agent" ? T_2 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_2] & string : string | undefined : never : never;
125
+ } : never) | (((import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "human" extends infer T_8 ? T_8 extends "human" ? T_8 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_8] & string : string | undefined : never : never) extends infer T_9 ? T_9 extends (import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "human" extends infer T_8 ? T_8 extends "human" ? T_8 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_8] & string : string | undefined : never : never) ? T_9 extends string ? string extends T_9 ? never : T_9 : never : never : never) extends never ? {
126
+ src: "human";
127
+ logic: import("xstate").PromiseActorLogic<Event, HumanRequest, import("xstate").EventObject>;
128
+ id: import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "human" extends infer T_3 ? T_3 extends "human" ? T_3 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_3] & string : string | undefined : never : never;
129
+ } : never) extends never ? "exclude" : "include"] extends infer T_1 ? { [K in keyof T_1]: T_1[K]; } : never, Record<string, import("xstate").AnyActorRef | undefined>>, {
130
+ src: "agent";
131
+ logic: import("xstate").PromiseActorLogic<Event, AgentInvocation, import("xstate").EventObject>;
132
+ id: import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "agent" extends infer T_2 ? T_2 extends "agent" ? T_2 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_2] & string : string | undefined : never : never;
133
+ } | {
134
+ src: "human";
135
+ logic: import("xstate").PromiseActorLogic<Event, HumanRequest, import("xstate").EventObject>;
136
+ id: import("xstate").IsNever<TResolvedChildren> extends true ? string | undefined : "human" extends infer T_3 ? T_3 extends "human" ? T_3 extends keyof import("xstate").Invert<TResolvedChildren> ? import("xstate").Invert<TResolvedChildren>[T_3] & string : string | undefined : never : never;
137
+ }, {
138
+ type: "humanInputFinished";
139
+ params: unknown;
140
+ } | {
141
+ type: "humanInputStarted";
142
+ params: unknown;
143
+ }, never, never, import("xstate").ToStateValue<TConfig>, string, import("xstate").NonReducibleUnknown, import("xstate").NonReducibleUnknown, import("xstate").EventObject, import("xstate").MetaObject, { -readonly [K in keyof TConfig as K & ("id" | "states")]: K extends "states" ? { [SK in keyof TConfig["states"]]: NonNullable<TConfig["states"][SK]> extends infer T_10 extends import("xstate").StateSchema ? { -readonly [K_1 in keyof T_10 as K_1 & ("id" | "states")]: K_1 extends "states" ? { [SK_1 in keyof T_10["states"]]: NonNullable<T_10["states"][SK_1]> extends infer T_11 extends import("xstate").StateSchema ? { -readonly [K_2 in keyof T_11 as K_2 & ("id" | "states")]: K_2 extends "states" ? { [SK_2 in keyof T_11["states"]]: NonNullable<T_11["states"][SK_2]> extends infer T_12 extends import("xstate").StateSchema ? { -readonly [K_3 in keyof T_12 as K_3 & ("id" | "states")]: K_3 extends "states" ? { [SK_3 in keyof T_12["states"]]: NonNullable<T_12["states"][SK_3]> extends infer T_13 extends import("xstate").StateSchema ? { -readonly [K_4 in keyof T_13 as K_4 & ("id" | "states")]: K_4 extends "states" ? { [SK_4 in keyof T_13["states"]]: NonNullable<T_13["states"][SK_4]> extends infer T_14 extends import("xstate").StateSchema ? { -readonly [K_5 in keyof T_14 as K_5 & ("id" | "states")]: K_5 extends "states" ? { [SK_5 in keyof T_14["states"]]: NonNullable<T_14["states"][SK_5]> extends infer T_15 extends import("xstate").StateSchema ? { -readonly [K_6 in keyof T_15 as K_6 & ("id" | "states")]: K_6 extends "states" ? { [SK_6 in keyof T_15["states"]]: NonNullable<T_15["states"][SK_6]> extends infer T_16 extends import("xstate").StateSchema ? { -readonly [K_7 in keyof T_16 as K_7 & ("id" | "states")]: K_7 extends "states" ? { [SK_7 in keyof T_16["states"]]: NonNullable<T_16["states"][SK_7]> extends infer T_17 extends import("xstate").StateSchema ? { -readonly [K_8 in keyof T_17 as K_8 & ("id" | "states")]: K_8 extends "states" ? { [SK_8 in keyof T_17["states"]]: NonNullable<T_17["states"][SK_8]> extends infer T_18 extends import("xstate").StateSchema ? { -readonly [K_9 in keyof T_18 as K_9 & ("id" | "states")]: K_9 extends "states" ? { [SK_9 in keyof T_18["states"]]: NonNullable<T_18["states"][SK_9]> extends infer T_19 extends import("xstate").StateSchema ? { -readonly [K_10 in keyof T_19 as K_10 & ("id" | "states")]: K_10 extends "states" ? { [SK_10 in keyof T_19["states"]]: /*elided*/ any; } : T_19[K_10]; } : never; } : T_18[K_9]; } : never; } : T_17[K_8]; } : never; } : T_16[K_7]; } : never; } : T_15[K_6]; } : never; } : T_14[K_5]; } : never; } : T_13[K_4]; } : never; } : T_12[K_3]; } : never; } : T_11[K_2]; } : never; } : T_10[K_1]; } : never; } : TConfig[K]; }>;
144
+ export declare function operation<const TTransitions extends Readonly<Record<string, unknown>>>(runOperation: () => Event | Promise<Event>, on: TTransitions): {
145
+ readonly invoke: {
146
+ readonly src: import("xstate").PromiseActorLogic<Event, import("xstate").NonReducibleUnknown, import("xstate").EventObject>;
147
+ readonly onDone: {
148
+ readonly actions: readonly [(args: unknown) => void, import("xstate").ActionFunction<any, any, Event, undefined, never, never, never, never, never>];
149
+ };
150
+ readonly onError: {
151
+ readonly actions: (args: unknown) => never;
152
+ };
153
+ };
154
+ readonly on: TTransitions;
155
+ };
156
+ export declare function human<const TTransitions extends Readonly<Record<string, unknown>>>(prompt: HumanPrompt, on: TTransitions, options?: HumanOptions): {
157
+ readonly entry: "humanInputStarted";
158
+ readonly exit: "humanInputFinished";
159
+ readonly invoke: {
160
+ readonly src: "human";
161
+ readonly input: () => {
162
+ prompt: string;
163
+ choices?: readonly string[] | undefined;
164
+ suggestions?: readonly string[] | undefined;
165
+ };
166
+ readonly onDone: {
167
+ readonly actions: readonly [(args: unknown) => void, import("xstate").ActionFunction<any, any, Event, undefined, never, never, never, never, never>];
168
+ };
169
+ readonly onError: {
170
+ readonly actions: (args: unknown) => never;
171
+ };
172
+ };
173
+ readonly on: TTransitions;
174
+ };
175
+ export declare function agent<const TTransitions extends Readonly<Record<string, unknown>>>(prompt: AgentPrompt, on: TTransitions, options?: AgentOptions): {
176
+ readonly meta: {
177
+ readonly "machines.agent": {
178
+ readonly using: string;
179
+ };
180
+ };
181
+ readonly invoke: {
182
+ readonly src: "agent";
183
+ readonly input: () => {
184
+ using: string;
185
+ prompt: string;
186
+ outcomes: string[];
187
+ cwd?: string | undefined;
188
+ };
189
+ readonly onDone: {
190
+ readonly actions: readonly [(args: unknown) => void, import("xstate").ActionFunction<any, any, Event, undefined, never, never, never, never, never>];
191
+ };
192
+ readonly onError: {
193
+ readonly actions: (args: unknown) => never;
194
+ };
195
+ };
196
+ readonly on: TTransitions;
197
+ };
198
+ export declare function final(): {
199
+ readonly type: "final";
200
+ };
201
+ export interface MachinePrimitives {
202
+ readonly agent: typeof agent;
203
+ readonly final: typeof final;
204
+ readonly human: typeof human;
205
+ readonly machine: typeof machine;
206
+ readonly operation: typeof operation;
207
+ }
208
+ export declare function requiredAgentNames(definition: AnyStateMachine): readonly string[];
209
+ export declare function run<TMachine extends AnyStateMachine>(definition: TMachine, options?: RunOptions): Promise<SnapshotFrom<TMachine>>;
210
+ export {};
@@ -0,0 +1,204 @@
1
+ import { terminalHuman } from "./terminal-human.js";
2
+ import { createActor, fromPromise, raise, setup, } from "xstate";
3
+ const machines = setup({
4
+ actions: {
5
+ humanInputFinished: () => { },
6
+ humanInputStarted: () => { },
7
+ },
8
+ actors: {
9
+ agent: fromPromise(async () => {
10
+ throw new Error("This Machine reached an Agent state, but no Agent runner was supplied");
11
+ }),
12
+ human: fromPromise(async ({ input }) => submittedHumanEvent(input, terminalHuman)),
13
+ },
14
+ });
15
+ const agentMetaKey = "machines.agent";
16
+ export const machine = machines.createMachine;
17
+ export function operation(runOperation, on) {
18
+ return {
19
+ invoke: {
20
+ src: fromPromise(async () => runOperation()),
21
+ ...actorLifecycle("Operation", on),
22
+ },
23
+ on,
24
+ };
25
+ }
26
+ export function human(prompt, on, options = {}) {
27
+ if (options.choices !== undefined && options.choices.length === 0) {
28
+ throw new Error("Human choices must include at least one value");
29
+ }
30
+ return {
31
+ entry: "humanInputStarted",
32
+ exit: "humanInputFinished",
33
+ invoke: {
34
+ src: "human",
35
+ input: () => ({
36
+ prompt: typeof prompt === "function" ? prompt() : prompt,
37
+ ...(options.choices === undefined ? {} : { choices: options.choices }),
38
+ ...(options.suggestions === undefined
39
+ ? {}
40
+ : { suggestions: options.suggestions }),
41
+ }),
42
+ ...actorLifecycle("Human", on),
43
+ },
44
+ on,
45
+ };
46
+ }
47
+ export function agent(prompt, on, options = {}) {
48
+ const using = options.using ?? "default";
49
+ if (typeof using !== "string" || using.trim() === "" || using !== using.trim()) {
50
+ throw new Error("Agent runner name must be a non-empty trimmed string");
51
+ }
52
+ return {
53
+ meta: {
54
+ [agentMetaKey]: { using },
55
+ },
56
+ invoke: {
57
+ src: "agent",
58
+ input: () => ({
59
+ using,
60
+ prompt: typeof prompt === "function" ? prompt() : prompt,
61
+ outcomes: Object.keys(on),
62
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
63
+ }),
64
+ ...actorLifecycle("Agent", on),
65
+ },
66
+ on,
67
+ };
68
+ }
69
+ function actorLifecycle(actorName, on) {
70
+ return {
71
+ onDone: {
72
+ actions: [
73
+ (args) => {
74
+ const { event, self } = args;
75
+ assertHandledEvent(actorName, event.output, on, self.getSnapshot().value);
76
+ },
77
+ raise(({ event }) => event.output),
78
+ ],
79
+ },
80
+ onError: {
81
+ actions: (args) => {
82
+ const { event, self } = args;
83
+ throw actorError(actorName, event.error, self.getSnapshot().value);
84
+ },
85
+ },
86
+ };
87
+ }
88
+ async function submittedHumanEvent(request, runner) {
89
+ // XState can start an initial invoked actor before its parent's entry actions.
90
+ // Let onHumanInput(true) release terminal hotkeys before the runner takes stdin.
91
+ const answer = await Promise.resolve().then(() => runner(request));
92
+ if (typeof answer !== "string") {
93
+ throw new Error("Human runner must return a string");
94
+ }
95
+ if (request.choices !== undefined && !request.choices.includes(answer)) {
96
+ throw new Error(`Expected one of: ${request.choices.join(", ")}`);
97
+ }
98
+ return { type: "submitted", value: answer };
99
+ }
100
+ export function final() {
101
+ return { type: "final" };
102
+ }
103
+ export function requiredAgentNames(definition) {
104
+ const names = new Set();
105
+ collectAgentNames(definition.config, names);
106
+ return [...names].sort((left, right) => left.localeCompare(right));
107
+ }
108
+ export function run(definition, options = {}) {
109
+ return new Promise((resolve, reject) => {
110
+ const agentRunners = options.agents ?? {};
111
+ assertAgentRunners(agentRunners);
112
+ assertRequiredAgentRunners(definition, agentRunners);
113
+ const runnable = definition.provide({
114
+ actions: {
115
+ humanInputFinished: () => options.onHumanInput?.(false),
116
+ humanInputStarted: () => options.onHumanInput?.(true),
117
+ },
118
+ actors: {
119
+ human: fromPromise(async ({ input }) => submittedHumanEvent(input, options.human ?? terminalHuman)),
120
+ ...(Object.keys(agentRunners).length === 0
121
+ ? {}
122
+ : {
123
+ agent: fromPromise(async ({ input }) => {
124
+ const { using, ...request } = input;
125
+ const runner = agentRunners[using];
126
+ if (runner === undefined) {
127
+ throw new Error(`Agent runner "${using}" was not supplied`);
128
+ }
129
+ return runner(request, options.onAgentUpdate);
130
+ }),
131
+ }),
132
+ },
133
+ });
134
+ const actor = createActor(runnable);
135
+ const initialValue = actor.getSnapshot().value;
136
+ let previousState = JSON.stringify(initialValue);
137
+ actor.subscribe({
138
+ next: (snapshot) => {
139
+ const value = snapshot.value;
140
+ const state = JSON.stringify(value);
141
+ if (state === previousState)
142
+ return;
143
+ previousState = state;
144
+ options.onState?.(value);
145
+ },
146
+ complete: () => resolve(actor.getSnapshot()),
147
+ error: reject,
148
+ });
149
+ options.onState?.(initialValue);
150
+ actor.start();
151
+ });
152
+ }
153
+ function collectAgentNames(value, names) {
154
+ if (value === null || typeof value !== "object")
155
+ return;
156
+ const state = value;
157
+ const metadata = state.meta?.[agentMetaKey];
158
+ if (metadata !== null
159
+ && typeof metadata === "object"
160
+ && "using" in metadata
161
+ && typeof metadata.using === "string") {
162
+ names.add(metadata.using);
163
+ }
164
+ if (state.states !== undefined) {
165
+ for (const child of Object.values(state.states))
166
+ collectAgentNames(child, names);
167
+ }
168
+ }
169
+ function assertAgentRunners(runners) {
170
+ for (const [name, runner] of Object.entries(runners)) {
171
+ if (name.trim() === "" || name !== name.trim()) {
172
+ throw new Error("Agent runner names must be non-empty trimmed strings");
173
+ }
174
+ if (typeof runner !== "function") {
175
+ throw new Error(`Agent runner "${name}" must be a function`);
176
+ }
177
+ }
178
+ }
179
+ function assertRequiredAgentRunners(definition, runners) {
180
+ const missing = requiredAgentNames(definition)
181
+ .filter((name) => !Object.hasOwn(runners, name));
182
+ if (missing.length === 0)
183
+ return;
184
+ const noun = missing.length === 1 ? "runner" : "runners";
185
+ throw new Error(`Machine requires missing Agent ${noun}: ${missing.join(", ")}`);
186
+ }
187
+ function assertHandledEvent(actorName, event, transitions, state) {
188
+ if (event === null
189
+ || typeof event !== "object"
190
+ || !("type" in event)
191
+ || typeof event.type !== "string") {
192
+ throw new Error(`${actorName} in state "${formatState(state)}" returned an invalid event`);
193
+ }
194
+ if (!Object.hasOwn(transitions, event.type)) {
195
+ throw new Error(`State "${formatState(state)}" does not handle event "${event.type}"`);
196
+ }
197
+ }
198
+ function actorError(actorName, cause, state) {
199
+ const message = cause instanceof Error ? cause.message : String(cause);
200
+ return new Error(`${actorName} failed in state "${formatState(state)}": ${message}`, { cause });
201
+ }
202
+ function formatState(state) {
203
+ return typeof state === "string" ? state : JSON.stringify(state);
204
+ }
@@ -0,0 +1,19 @@
1
+ import type { AnyStateMachine, SnapshotFrom } from "xstate";
2
+ import { type LauncherLocation, type MachineSummary, type AgentPresetSummary } from "./catalog.ts";
3
+ export type { LauncherLocation, MachineSummary, AgentPresetSummary } from "./catalog.ts";
4
+ import { type RunOptions } from "./index.ts";
5
+ export interface PrepareMachineRunOptions extends LauncherLocation {
6
+ readonly machine: string;
7
+ readonly input?: string;
8
+ readonly agents?: Readonly<Record<string, string>>;
9
+ }
10
+ export interface PreparedMachineRun {
11
+ readonly name: string;
12
+ readonly description: string;
13
+ readonly path: string;
14
+ readonly agentRoles: Readonly<Record<string, string>>;
15
+ start(options?: Omit<RunOptions, "agents">): Promise<SnapshotFrom<AnyStateMachine>>;
16
+ }
17
+ export declare function listMachines(location?: LauncherLocation): Promise<readonly MachineSummary[]>;
18
+ export declare function listAgentPresets(location?: LauncherLocation): Promise<readonly AgentPresetSummary[]>;
19
+ export declare function prepareMachineRun(options: PrepareMachineRunOptions): Promise<PreparedMachineRun>;
@@ -0,0 +1,98 @@
1
+ import { basename, dirname, isAbsolute, resolve } from "node:path";
2
+ import { configuredAgentPresets } from "./catalog.js";
3
+ import { queryCatalog } from "./discovery-worker.js";
4
+ import { loadMachineModule, readAgentRoles, requireMachineDescription } from "./machine-module.js";
5
+ import { discoverMachines, machinesUserHome } from "./discovery.js";
6
+ import { agent, final, human, machine, operation, requiredAgentNames, run, } from "./index.js";
7
+ export async function listMachines(location = {}) {
8
+ return queryCatalog("machines", location);
9
+ }
10
+ export async function listAgentPresets(location = {}) {
11
+ return queryCatalog("agents", location);
12
+ }
13
+ export async function prepareMachineRun(options) {
14
+ const cwd = options.cwd ?? process.cwd();
15
+ const home = options.home ?? machinesUserHome();
16
+ const path = await resolveMachine(options.machine, cwd, home);
17
+ const loaded = await loadMachineModule(path);
18
+ const description = requireMachineDescription(loaded, path);
19
+ const agentRoles = readAgentRoles(loaded, path);
20
+ if (typeof loaded.default !== "function") {
21
+ throw new Error(`Machine "${path}" must default-export a factory`);
22
+ }
23
+ const definition = await loaded.default({ agent, final, human, machine, operation }, options.input ?? "");
24
+ const configured = await configuredAgentPresets(cwd, home);
25
+ const usedAgentRoles = requiredAgentNames(definition);
26
+ const agents = applyAgentOverrides(path, configured.agents, configured.presets, new Set([...usedAgentRoles, ...Object.keys(agentRoles)]), options.agents ?? {});
27
+ preflightAgentRoles(path, usedAgentRoles, agentRoles, agents);
28
+ let started = false;
29
+ return {
30
+ name: machineName(path),
31
+ description,
32
+ path,
33
+ agentRoles,
34
+ start(runOptions = {}) {
35
+ if (started)
36
+ throw new Error(`Prepared Machine "${path}" has already started`);
37
+ started = true;
38
+ return run(definition, { ...runOptions, agents });
39
+ },
40
+ };
41
+ }
42
+ async function resolveMachine(selector, cwd, home) {
43
+ if (isAbsolute(selector) || selector.includes("/") || selector.endsWith(".ts")) {
44
+ return resolve(cwd, selector);
45
+ }
46
+ const machines = await discoverMachines(cwd, home);
47
+ const found = machines.find((candidate) => candidate.name === selector);
48
+ if (found === undefined) {
49
+ throw new Error(`Machine "${selector}" not found. Run "machine list" to see available Machines.`);
50
+ }
51
+ return found.path;
52
+ }
53
+ function applyAgentOverrides(machinePath, agents, presets, requiredRoles, overrides) {
54
+ const resolved = { ...agents };
55
+ for (const [role, presetName] of Object.entries(overrides)) {
56
+ if (role.trim() === "" || role !== role.trim()) {
57
+ throw new Error("Agent override roles must be non-empty trimmed strings");
58
+ }
59
+ if (presetName.trim() === "" || presetName !== presetName.trim()) {
60
+ throw new Error(`Agent override for role "${role}" must name a preset`);
61
+ }
62
+ if (!requiredRoles.has(role)) {
63
+ throw new Error(`Machine "${machinePath}" does not declare or use Agent role "${role}"`);
64
+ }
65
+ const selected = Object.hasOwn(presets, presetName) ? presets[presetName] : undefined;
66
+ if (selected === undefined) {
67
+ const available = Object.keys(presets).sort().join(", ");
68
+ throw new Error(`Agent preset "${presetName}" was not found for role "${role}". Available presets: ${available}`);
69
+ }
70
+ resolved[role] = selected.runner;
71
+ }
72
+ return resolved;
73
+ }
74
+ function preflightAgentRoles(machinePath, usedNames, declaredRoles, agents) {
75
+ const undeclared = usedNames.filter((name) => name !== "default" && !Object.hasOwn(declaredRoles, name));
76
+ if (undeclared.length > 0) {
77
+ throw new Error(`Machine "${machinePath}" uses undeclared Agent roles: ${undeclared.join(", ")}`);
78
+ }
79
+ const required = new Set([...usedNames, ...Object.keys(declaredRoles)]);
80
+ const missing = [...required].filter((name) => !Object.hasOwn(agents, name));
81
+ if (missing.length === 0)
82
+ return;
83
+ const lines = missing.map((name) => {
84
+ const description = declaredRoles[name];
85
+ return description === undefined ? `- ${name}` : `- ${name}: ${description}`;
86
+ });
87
+ throw new Error([
88
+ `Machine "${machinePath}" is missing required Agent runners:`,
89
+ ...lines,
90
+ "Configure them in ~/.machines/agents.ts or the nearest project .machines/agents.ts.",
91
+ ].join("\n"));
92
+ }
93
+ function machineName(path) {
94
+ const fileName = basename(path);
95
+ return fileName === "index.ts"
96
+ ? basename(dirname(path))
97
+ : fileName.replace(/\.ts$/u, "");
98
+ }
@@ -0,0 +1,3 @@
1
+ export declare function loadMachineModule(machinePath: string): Promise<Record<string, unknown>>;
2
+ export declare function requireMachineDescription(loaded: Record<string, unknown>, machinePath: string): string;
3
+ export declare function readAgentRoles(loaded: Record<string, unknown>, machinePath: string): Readonly<Record<string, string>>;
@@ -0,0 +1,55 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { pathToFileURL } from "node:url";
10
+ export async function loadMachineModule(machinePath) {
11
+ try {
12
+ return await import(__rewriteRelativeImportExtension(pathToFileURL(machinePath).href));
13
+ }
14
+ catch (cause) {
15
+ const message = cause instanceof Error ? cause.message : String(cause);
16
+ throw new Error(`Could not load Machine "${machinePath}": ${message}`, { cause });
17
+ }
18
+ }
19
+ export function requireMachineDescription(loaded, machinePath) {
20
+ const { description } = loaded;
21
+ if (description === undefined) {
22
+ throw new Error(`Machine "${machinePath}" must export a description`);
23
+ }
24
+ if (typeof description !== "string" || description.trim() === "") {
25
+ throw new Error(`Machine "${machinePath}" description must be a non-empty string`);
26
+ }
27
+ const value = description.trim();
28
+ if (/\r|\n|\t/u.test(value)) {
29
+ throw new Error(`Machine "${machinePath}" description must fit in one tab-safe line`);
30
+ }
31
+ return value;
32
+ }
33
+ export function readAgentRoles(loaded, machinePath) {
34
+ const { agentRoles } = loaded;
35
+ if (agentRoles === undefined)
36
+ return {};
37
+ if (agentRoles === null || typeof agentRoles !== "object" || Array.isArray(agentRoles)) {
38
+ throw new Error(`Machine "${machinePath}" agentRoles must be an object`);
39
+ }
40
+ const roles = {};
41
+ for (const [name, description] of Object.entries(agentRoles)) {
42
+ if (name.trim() === "" || name !== name.trim()) {
43
+ throw new Error(`Machine "${machinePath}" contains a non-trimmed or empty Agent role name`);
44
+ }
45
+ if (typeof description !== "string" || description.trim() === "") {
46
+ throw new Error(`Agent role "${name}" in "${machinePath}" must have a description`);
47
+ }
48
+ const value = description.trim();
49
+ if (/\r|\n|\t/u.test(value)) {
50
+ throw new Error(`Agent role "${name}" in "${machinePath}" must fit in one line`);
51
+ }
52
+ roles[name] = value;
53
+ }
54
+ return roles;
55
+ }
@@ -0,0 +1,40 @@
1
+ import type { StateValue } from "xstate";
2
+ import { type HostedHumanRequest } from "./host.ts";
3
+ import type { AgentUpdate } from "./index.ts";
4
+ import type { PrepareMachineRunOptions } from "./launcher.ts";
5
+ export type RunStatus = "running" | "waiting" | "completed" | "failed";
6
+ export interface RunSnapshot {
7
+ readonly id: string;
8
+ readonly machine: string;
9
+ readonly description: string;
10
+ readonly path: string;
11
+ readonly cwd: string;
12
+ readonly status: RunStatus;
13
+ readonly state?: StateValue;
14
+ readonly startedAt: string;
15
+ readonly updatedAt: string;
16
+ readonly elapsedSeconds: number;
17
+ readonly agent?: Extract<AgentUpdate, {
18
+ type: "identity";
19
+ }>;
20
+ readonly human?: HostedHumanRequest;
21
+ readonly error?: string;
22
+ }
23
+ export interface SessionEvent {
24
+ readonly type: "updated" | "human" | "finished";
25
+ readonly run: RunSnapshot;
26
+ }
27
+ /** Owns runs from startup to disposal. Presentation belongs to its subscribers. */
28
+ export declare class MachineSession {
29
+ #private;
30
+ subscribe(listener: (event: SessionEvent) => void): () => void;
31
+ start(options: PrepareMachineRunOptions): Promise<RunSnapshot>;
32
+ status(runId?: string): RunSnapshot[];
33
+ respond(input: {
34
+ readonly runId: string;
35
+ readonly requestId: string;
36
+ readonly response: string;
37
+ }): Promise<RunSnapshot>;
38
+ close(): void;
39
+ }
40
+ export declare function isActive(status: RunStatus): boolean;