@flowdrop/flowdrop 2.0.0-beta.10 → 2.0.0-beta.11

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 (61) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/chat/batchFeedback.js +1 -1
  3. package/dist/chat/commandClassifier.d.ts +11 -0
  4. package/dist/chat/commandClassifier.js +20 -0
  5. package/dist/chat/historyBuilder.d.ts +39 -0
  6. package/dist/chat/historyBuilder.js +82 -0
  7. package/dist/chat/index.d.ts +2 -1
  8. package/dist/chat/index.js +2 -1
  9. package/dist/chat/responseParser.js +16 -12
  10. package/dist/commands/parser.d.ts +12 -0
  11. package/dist/commands/parser.js +33 -6
  12. package/dist/components/ConfigForm.svelte +30 -6
  13. package/dist/components/SettingsPanel.svelte +9 -0
  14. package/dist/components/WorkflowEditor.svelte +5 -2
  15. package/dist/components/chat/AIChatPanel.svelte +42 -6
  16. package/dist/components/chat/CommandPreview.svelte +10 -1
  17. package/dist/components/form/FormPorts.svelte +21 -3
  18. package/dist/components/form/FormRangeField.svelte +5 -3
  19. package/dist/components/form/FormToggle.svelte +27 -2
  20. package/dist/components/form/FormToggle.svelte.d.ts +5 -0
  21. package/dist/components/playground/ChatInput.svelte +316 -26
  22. package/dist/components/playground/ChatInput.svelte.d.ts +31 -1
  23. package/dist/components/playground/ControlPanel.svelte +22 -0
  24. package/dist/components/playground/ControlPanel.svelte.d.ts +13 -0
  25. package/dist/components/playground/Playground.svelte +217 -4
  26. package/dist/config/endpoints.d.ts +48 -1
  27. package/dist/config/endpoints.js +18 -5
  28. package/dist/messages/defaults.d.ts +98 -0
  29. package/dist/messages/defaults.js +58 -1
  30. package/dist/playground/commands/args.d.ts +32 -0
  31. package/dist/playground/commands/args.js +50 -0
  32. package/dist/playground/commands/dispatch.d.ts +143 -0
  33. package/dist/playground/commands/dispatch.js +162 -0
  34. package/dist/playground/commands/index.d.ts +14 -0
  35. package/dist/playground/commands/index.js +10 -0
  36. package/dist/playground/commands/parser.d.ts +38 -0
  37. package/dist/playground/commands/parser.js +163 -0
  38. package/dist/playground/commands/registry.d.ts +42 -0
  39. package/dist/playground/commands/registry.js +122 -0
  40. package/dist/playground/commands/suggest.d.ts +37 -0
  41. package/dist/playground/commands/suggest.js +46 -0
  42. package/dist/playground/commands/types.d.ts +111 -0
  43. package/dist/playground/commands/types.js +15 -0
  44. package/dist/playground/index.d.ts +19 -0
  45. package/dist/playground/index.js +25 -0
  46. package/dist/playground/runAction.d.ts +48 -0
  47. package/dist/playground/runAction.js +31 -0
  48. package/dist/services/pipelineSignalService.d.ts +97 -0
  49. package/dist/services/pipelineSignalService.js +94 -0
  50. package/dist/services/playgroundService.d.ts +12 -0
  51. package/dist/services/playgroundService.js +22 -0
  52. package/dist/services/workflowLaunchService.d.ts +74 -0
  53. package/dist/services/workflowLaunchService.js +74 -0
  54. package/dist/types/chat.d.ts +5 -1
  55. package/dist/types/settings.d.ts +11 -0
  56. package/dist/types/settings.js +2 -1
  57. package/dist/utils/canvasSelection.d.ts +25 -0
  58. package/dist/utils/canvasSelection.js +37 -0
  59. package/dist/utils/nodeFormSchema.d.ts +51 -0
  60. package/dist/utils/nodeFormSchema.js +87 -0
  61. package/package.json +1 -1
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Playground Slash Command Registry
3
+ *
4
+ * The single source of truth for which commands exist and when they are
5
+ * offered. Availability is derived from the *configured endpoints*, never from
6
+ * knowledge of a particular backend: FlowDrop ships as a standalone library and
7
+ * may be pointed at any API implementing the shape.
8
+ *
9
+ * @module playground/commands/registry
10
+ */
11
+ /**
12
+ * Canonical command list. Order is the order shown by `/help`.
13
+ *
14
+ * Declared as a plain tuple so the parser can bound its typo search and the
15
+ * type system keeps {@link SlashCommandName} and this array in lockstep.
16
+ */
17
+ export const COMMAND_NAMES = [
18
+ 'help',
19
+ 'run',
20
+ 'new',
21
+ 'stop',
22
+ 'reset',
23
+ 'delete',
24
+ 'pause',
25
+ 'resume',
26
+ 'cancel'
27
+ ];
28
+ /**
29
+ * Availability predicates.
30
+ *
31
+ * `playground.stopExecution`, `createSession` and `deleteSession` are required
32
+ * keys in {@link EndpointConfig}, so their commands are available whenever a
33
+ * config exists at all. `resetSession` is optional — the one place where the
34
+ * "absence of an endpoint is absence of a command" rule currently bites.
35
+ */
36
+ const hasPlayground = (config) => config?.endpoints?.playground != null;
37
+ /**
38
+ * Signal commands exist only where the backend exposes a signal plane. The
39
+ * whole block is optional, so this is the coarsest form of the availability
40
+ * rule: no endpoints, no commands.
41
+ */
42
+ const hasSignals = (config) => config?.endpoints?.signals != null;
43
+ /**
44
+ * Structure only — no display text. What each command *says* lives in
45
+ * `m().playground.commands.catalog` so it can be translated; what each command
46
+ * *is* lives here so pure logic never has to parse prose.
47
+ */
48
+ export const COMMAND_DESCRIPTORS = [
49
+ {
50
+ name: 'help',
51
+ takesArgs: false,
52
+ // Needs no backend — it only describes what is already configured.
53
+ isAvailable: () => true
54
+ },
55
+ {
56
+ name: 'run',
57
+ takesArgs: true,
58
+ isAvailable: (config) => config?.endpoints?.workflows?.run != null
59
+ },
60
+ {
61
+ name: 'new',
62
+ takesArgs: false,
63
+ isAvailable: hasPlayground
64
+ },
65
+ {
66
+ name: 'stop',
67
+ takesArgs: false,
68
+ isAvailable: hasPlayground
69
+ },
70
+ {
71
+ name: 'reset',
72
+ takesArgs: false,
73
+ isAvailable: (config) => hasPlayground(config) && config?.endpoints.playground.resetSession != null
74
+ },
75
+ {
76
+ name: 'delete',
77
+ takesArgs: false,
78
+ isAvailable: hasPlayground
79
+ },
80
+ {
81
+ name: 'pause',
82
+ takesArgs: true,
83
+ isAvailable: hasSignals
84
+ },
85
+ {
86
+ name: 'resume',
87
+ takesArgs: true,
88
+ isAvailable: hasSignals
89
+ },
90
+ {
91
+ name: 'cancel',
92
+ takesArgs: true,
93
+ isAvailable: hasSignals
94
+ }
95
+ ];
96
+ /**
97
+ * Commands that act on a specific pipeline and cannot run without a resolved
98
+ * target. Distinct from session commands, which act on the conversation.
99
+ */
100
+ export const SIGNAL_COMMANDS = new Set([
101
+ 'pause',
102
+ 'resume',
103
+ 'cancel'
104
+ ]);
105
+ /** Look up a descriptor by name. */
106
+ export function getDescriptor(name) {
107
+ return COMMAND_DESCRIPTORS.find((d) => d.name === name);
108
+ }
109
+ /**
110
+ * The commands offerable against a given configuration.
111
+ *
112
+ * Callers should gate both the palette and dispatch on this: a command that is
113
+ * parseable but unavailable must report "not supported here", never issue a
114
+ * request to an endpoint that was never configured.
115
+ */
116
+ export function getAvailableCommands(config) {
117
+ return COMMAND_DESCRIPTORS.filter((d) => d.isAvailable(config));
118
+ }
119
+ /** True when the named command can run against this configuration. */
120
+ export function isCommandAvailable(name, config) {
121
+ return getDescriptor(name)?.isAvailable(config) ?? false;
122
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Command Completion
3
+ *
4
+ * Suggestions for the composer's `/` palette.
5
+ *
6
+ * Scope is deliberately narrow: **command names only**. Completing argument
7
+ * *values* would mean knowing a workflow's declared launch inputs, which live
8
+ * server-side — guessing them client-side would offer inputs the backend will
9
+ * reject. Names are the part this client can complete honestly.
10
+ *
11
+ * @module playground/commands/suggest
12
+ */
13
+ import type { EndpointConfig } from '../../config/endpoints.js';
14
+ import type { CommandLabels } from './types.js';
15
+ /**
16
+ * One completion. Shape matches the shared autocomplete listbox so the composer
17
+ * and the editor console present suggestions identically.
18
+ */
19
+ export interface CommandSuggestion {
20
+ /** Text that replaces the input when accepted. */
21
+ value: string;
22
+ /** Primary text — the usage line, which shows the argument shape. */
23
+ label: string;
24
+ /** Secondary text — what the command does. */
25
+ detail?: string;
26
+ }
27
+ /**
28
+ * Compute completions for the current composer input.
29
+ *
30
+ * Returns nothing unless the input is an unescaped `/` command still being
31
+ * named. In particular:
32
+ *
33
+ * - `hello` → nothing; this is a message, not a command.
34
+ * - `//st` → nothing; the escape means the user is writing literal text.
35
+ * - `/stop ` → nothing; the name is settled and arguments follow.
36
+ */
37
+ export declare function suggestCommands(input: string, config: EndpointConfig | null, labels: CommandLabels): CommandSuggestion[];
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Command Completion
3
+ *
4
+ * Suggestions for the composer's `/` palette.
5
+ *
6
+ * Scope is deliberately narrow: **command names only**. Completing argument
7
+ * *values* would mean knowing a workflow's declared launch inputs, which live
8
+ * server-side — guessing them client-side would offer inputs the backend will
9
+ * reject. Names are the part this client can complete honestly.
10
+ *
11
+ * @module playground/commands/suggest
12
+ */
13
+ import { getAvailableCommands } from './registry.js';
14
+ /**
15
+ * Compute completions for the current composer input.
16
+ *
17
+ * Returns nothing unless the input is an unescaped `/` command still being
18
+ * named. In particular:
19
+ *
20
+ * - `hello` → nothing; this is a message, not a command.
21
+ * - `//st` → nothing; the escape means the user is writing literal text.
22
+ * - `/stop ` → nothing; the name is settled and arguments follow.
23
+ */
24
+ export function suggestCommands(input, config, labels) {
25
+ // Leading whitespace is tolerated when sending, so tolerate it here too.
26
+ const trimmed = input.trimStart();
27
+ if (!trimmed.startsWith('/'))
28
+ return [];
29
+ // `//` is the escape for a literal leading slash — not a command.
30
+ if (trimmed.startsWith('//'))
31
+ return [];
32
+ const body = trimmed.slice(1);
33
+ // A space means the name is complete; we do not complete argument values.
34
+ if (/\s/.test(body))
35
+ return [];
36
+ const prefix = body.toLowerCase();
37
+ return getAvailableCommands(config)
38
+ .filter((d) => d.name.startsWith(prefix))
39
+ .map((d) => ({
40
+ // Commands that take arguments get a trailing space, so accepting the
41
+ // completion leaves the caret where the argument goes.
42
+ value: `/${d.name}${d.takesArgs ? ' ' : ''}`,
43
+ label: labels[d.name].usage,
44
+ detail: labels[d.name].summary
45
+ }));
46
+ }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Playground Slash Command Types
3
+ *
4
+ * The composer's out-of-band control lane. A leading `/` routes input to the
5
+ * control plane instead of the pipeline, so plain text stops meaning exactly
6
+ * one thing ("launch a run with this as input").
7
+ *
8
+ * Deliberately separate from `$lib/commands` (the workflow-editing DSL): that
9
+ * grammar is bare-verb, synchronous, and targets the workflow store, while this
10
+ * one is slash-prefixed, asynchronous, and targets session/pipeline services.
11
+ * Sharing a union would force each executor to handle commands it cannot run.
12
+ *
13
+ * @module playground/commands/types
14
+ */
15
+ import type { EndpointConfig } from '../../config/endpoints.js';
16
+ /**
17
+ * Every member maps onto a door the backend already exposes; none invents
18
+ * behaviour. Adding a member here without a corresponding endpoint would break
19
+ * the rule that the client never mints a command the backend cannot honour.
20
+ *
21
+ * Two groups, deliberately distinguished:
22
+ *
23
+ * - **Session shell** (`new`, `delete`, `stop`, `reset`, `help`) — act on the
24
+ * session, which is a client-side conversation container.
25
+ * - **Pipeline signals** (`pause`, `resume`, `cancel`) — act on a *specific
26
+ * running pipeline*, and therefore need a resolved target.
27
+ */
28
+ export type SlashCommandName = 'stop' | 'reset' | 'new' | 'delete' | 'help' | 'run' | 'pause' | 'resume' | 'cancel';
29
+ /** A successfully parsed command. */
30
+ export interface SlashCommand {
31
+ /** Canonical, lower-cased command name. */
32
+ name: SlashCommandName;
33
+ /** Positional arguments, whitespace-separated, in source order. */
34
+ args: string[];
35
+ /** The raw input the command was parsed from, for logging and echo. */
36
+ raw: string;
37
+ }
38
+ /**
39
+ * Outcome of parsing composer input.
40
+ *
41
+ * `message` covers plain text *and* escaped input (`//foo` → `/foo`), so the
42
+ * caller never has to re-apply the escape rule.
43
+ */
44
+ export type ParseResult = {
45
+ kind: 'empty';
46
+ } | {
47
+ kind: 'message';
48
+ content: string;
49
+ } | {
50
+ kind: 'command';
51
+ command: SlashCommand;
52
+ } | {
53
+ kind: 'unknown';
54
+ name: string;
55
+ suggestions: SlashCommandName[];
56
+ };
57
+ /**
58
+ * Human-readable text for one command.
59
+ *
60
+ * Kept out of {@link SlashCommandDescriptor} and sourced from the messages
61
+ * module instead: every other user-facing string in the playground is
62
+ * overridable for translation, and the palette and `/help` should not be the
63
+ * two surfaces stuck in English.
64
+ */
65
+ export interface CommandLabel {
66
+ /** Short help text. Rendered by `/help` and as palette detail. */
67
+ summary: string;
68
+ /** Usage line, e.g. `/pause [reason]`. Rendered as the palette label. */
69
+ usage: string;
70
+ }
71
+ /** Labels for every command, keyed by name. See `m().playground.commands.catalog`. */
72
+ export type CommandLabels = Record<SlashCommandName, CommandLabel>;
73
+ /**
74
+ * Structural description of a command: what it is, not what it says.
75
+ *
76
+ * Carries only what logic branches on. Display text lives in
77
+ * {@link CommandLabels} so it can be translated without the registry — and so
78
+ * nothing has to infer behaviour by pattern-matching a display string.
79
+ */
80
+ export interface SlashCommandDescriptor {
81
+ name: SlashCommandName;
82
+ /**
83
+ * Whether the command accepts arguments.
84
+ *
85
+ * Drives the trailing space on an accepted completion, so the caret lands
86
+ * where the argument goes. Declared rather than sniffed out of the usage
87
+ * line: usage text is prose, and prose gets translated.
88
+ */
89
+ takesArgs: boolean;
90
+ /**
91
+ * Whether this command can run against the given endpoint configuration.
92
+ *
93
+ * This is the genericity contract: a command is offered only when the
94
+ * backend it needs is configured. A host pointing FlowDrop at a backend
95
+ * without session reset gets no `/reset`, rather than a command that 404s.
96
+ *
97
+ * Commands needing no backend (`/help`) return true unconditionally.
98
+ */
99
+ isAvailable: (config: EndpointConfig | null) => boolean;
100
+ }
101
+ /** Result of dispatching a command. Rendered as transient composer feedback. */
102
+ export type CommandOutcome = {
103
+ status: 'ok';
104
+ message?: string;
105
+ } | {
106
+ status: 'info';
107
+ message: string;
108
+ } | {
109
+ status: 'error';
110
+ message: string;
111
+ };
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Playground Slash Command Types
3
+ *
4
+ * The composer's out-of-band control lane. A leading `/` routes input to the
5
+ * control plane instead of the pipeline, so plain text stops meaning exactly
6
+ * one thing ("launch a run with this as input").
7
+ *
8
+ * Deliberately separate from `$lib/commands` (the workflow-editing DSL): that
9
+ * grammar is bare-verb, synchronous, and targets the workflow store, while this
10
+ * one is slash-prefixed, asynchronous, and targets session/pipeline services.
11
+ * Sharing a union would force each executor to handle commands it cannot run.
12
+ *
13
+ * @module playground/commands/types
14
+ */
15
+ export {};
@@ -128,6 +128,18 @@ export { default as MessageBubble } from '../components/playground/MessageBubble
128
128
  export { InterruptBubble, ConfirmationPrompt, ChoicePrompt, TextInputPrompt, FormPrompt, ReviewPrompt } from '../components/interrupt/index.js';
129
129
  export { PlaygroundService } from '../services/playgroundService.js';
130
130
  export { InterruptService } from '../services/interruptService.js';
131
+ /**
132
+ * Launching a run is its own verb, distinct from posting a message. Exported so
133
+ * hosts can build a RUN affordance that starts a run without fabricating a
134
+ * chat turn.
135
+ */
136
+ export { WorkflowLaunchService, workflowLaunchService, type LaunchResult, type LaunchOptions, type LaunchInputError } from '../services/workflowLaunchService.js';
137
+ /**
138
+ * Signals travel *into* a running pipeline, the opposite direction from
139
+ * interrupts. Exported so hosts can drive pause/resume/cancel from their own
140
+ * chrome rather than only through the composer's command lane.
141
+ */
142
+ export { PipelineSignalService, pipelineSignalService, type SignalType, type SignalResult, type SignalRefusal, type SendSignalOptions } from '../services/pipelineSignalService.js';
131
143
  export { PlaygroundStore } from '../stores/playgroundStore.svelte.js';
132
144
  export type { PlaygroundSession, PlaygroundMessage, PlaygroundInputField, PlaygroundMessageRequest, PlaygroundMessagesResult, PlaygroundConfig, PlaygroundMode, PlaygroundSessionStatus, PlaygroundMessageRole, PlaygroundMessageLevel, PlaygroundMessageMetadata, PlaygroundApiResponse, PlaygroundSessionsResponse, PlaygroundSessionResponse, PlaygroundMessageResponse, PlaygroundMessagesApiResponse, PlaygroundExecution } from '../types/playground.js';
133
145
  export { isChatInputNode, CHAT_INPUT_PATTERNS, defaultShouldStopPolling, defaultIsTerminalStatus, DEFAULT_STOP_POLLING_STATUSES, DEFAULT_TERMINAL_STATUSES } from '../types/playground.js';
@@ -138,3 +150,10 @@ export type { InterruptWithState } from '../stores/interruptStore.svelte.js';
138
150
  export { mountPlayground, unmountPlayground, mountPlaygroundStudio, mountPlaygroundApp, type PlaygroundMountOptions, type PlaygroundStudioMountOptions, type PlaygroundAppMountOptions, type MountedPlayground } from './mount.js';
139
151
  export type { PipelineViewDef, PipelineViewProps } from '../types/index.js';
140
152
  export { createEndpointConfig, defaultEndpointConfig, buildEndpointUrl, type EndpointConfig } from '../config/endpoints.js';
153
+ /**
154
+ * The composer's out-of-band control lane. Exported so hosts can inspect what
155
+ * is available against their configuration (`getAvailableCommands`) or reuse
156
+ * the parser — including its escape rule — in their own surfaces.
157
+ */
158
+ export { resolveRunAction, type RunAction, type ResolveRunActionOptions } from './runAction.js';
159
+ export { parseSlashCommand, isKnownCommand, isCommandInput, dispatchCommand, COMMAND_NAMES, COMMAND_DESCRIPTORS, getDescriptor, getAvailableCommands, isCommandAvailable, type SlashCommand, type SlashCommandName, type SlashCommandDescriptor, type CommandLabel, type CommandLabels, type ParseResult, type CommandOutcome, type CommandHandlers, type CommandContext, type CommandMessages } from './commands/index.js';
@@ -141,6 +141,21 @@ export { PlaygroundService } from '../services/playgroundService.js';
141
141
  // ============================================================================
142
142
  export { InterruptService } from '../services/interruptService.js';
143
143
  // ============================================================================
144
+ // Pipeline Signal Service (operator control)
145
+ // ============================================================================
146
+ /**
147
+ * Launching a run is its own verb, distinct from posting a message. Exported so
148
+ * hosts can build a RUN affordance that starts a run without fabricating a
149
+ * chat turn.
150
+ */
151
+ export { WorkflowLaunchService, workflowLaunchService } from '../services/workflowLaunchService.js';
152
+ /**
153
+ * Signals travel *into* a running pipeline, the opposite direction from
154
+ * interrupts. Exported so hosts can drive pause/resume/cancel from their own
155
+ * chrome rather than only through the composer's command lane.
156
+ */
157
+ export { PipelineSignalService, pipelineSignalService } from '../services/pipelineSignalService.js';
158
+ // ============================================================================
144
159
  // Playground Store
145
160
  // ============================================================================
146
161
  export { PlaygroundStore } from '../stores/playgroundStore.svelte.js';
@@ -158,3 +173,13 @@ export { mountPlayground, unmountPlayground, mountPlaygroundStudio, mountPlaygro
158
173
  // Endpoint Configuration (re-exported for convenience)
159
174
  // ============================================================================
160
175
  export { createEndpointConfig, defaultEndpointConfig, buildEndpointUrl } from '../config/endpoints.js';
176
+ // ============================================================================
177
+ // Slash Commands
178
+ // ============================================================================
179
+ /**
180
+ * The composer's out-of-band control lane. Exported so hosts can inspect what
181
+ * is available against their configuration (`getAvailableCommands`) or reuse
182
+ * the parser — including its escape rule — in their own surfaces.
183
+ */
184
+ export { resolveRunAction } from './runAction.js';
185
+ export { parseSlashCommand, isKnownCommand, isCommandInput, dispatchCommand, COMMAND_NAMES, COMMAND_DESCRIPTORS, getDescriptor, getAvailableCommands, isCommandAvailable } from './commands/index.js';
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Run Action Resolution
3
+ *
4
+ * Decides what pressing Run should actually do.
5
+ *
6
+ * Starting a run by posting a chat message fabricates a user turn: the text
7
+ * enters the conversation, is fed to the chat input as though typed, and is
8
+ * replayed as history on the following turn — indistinguishable downstream from
9
+ * something a person wrote. Launching avoids all of that.
10
+ *
11
+ * But a message is still the correct action twice over:
12
+ *
13
+ * 1. **The host asked for one.** An explicitly configured `predefinedMessage`
14
+ * is a deliberate choice to open the run with a specific turn, and honouring
15
+ * it keeps that configuration meaningful.
16
+ * 2. **Nothing else is possible.** Against a backend with no launch verb, a
17
+ * message is the only way to start a run at all, so the fabricated turn is
18
+ * the lesser evil.
19
+ *
20
+ * Both callers — the Run button and auto-run — route through here so the rule
21
+ * is stated once instead of drifting between them.
22
+ *
23
+ * @module playground/runAction
24
+ */
25
+ /** What Run should do in the current configuration. */
26
+ export type RunAction =
27
+ /** Start a run with no inputs and no chat message. */
28
+ {
29
+ kind: 'launch';
30
+ }
31
+ /** Post this message, which starts a run as a side effect. */
32
+ | {
33
+ kind: 'message';
34
+ content: string;
35
+ };
36
+ export interface ResolveRunActionOptions {
37
+ /** Whether launching is possible — a handler is wired and the backend supports it. */
38
+ canLaunch: boolean;
39
+ /**
40
+ * Host-configured opening message. Its *presence* is the signal, so an
41
+ * explicit empty string still counts as "the host wants a message".
42
+ */
43
+ predefinedMessage?: string;
44
+ /** Message used when falling back without a configured one. */
45
+ defaultMessage: string;
46
+ }
47
+ /** Resolve what Run should do. Pure; see the module docblock for the rules. */
48
+ export declare function resolveRunAction({ canLaunch, predefinedMessage, defaultMessage }: ResolveRunActionOptions): RunAction;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Run Action Resolution
3
+ *
4
+ * Decides what pressing Run should actually do.
5
+ *
6
+ * Starting a run by posting a chat message fabricates a user turn: the text
7
+ * enters the conversation, is fed to the chat input as though typed, and is
8
+ * replayed as history on the following turn — indistinguishable downstream from
9
+ * something a person wrote. Launching avoids all of that.
10
+ *
11
+ * But a message is still the correct action twice over:
12
+ *
13
+ * 1. **The host asked for one.** An explicitly configured `predefinedMessage`
14
+ * is a deliberate choice to open the run with a specific turn, and honouring
15
+ * it keeps that configuration meaningful.
16
+ * 2. **Nothing else is possible.** Against a backend with no launch verb, a
17
+ * message is the only way to start a run at all, so the fabricated turn is
18
+ * the lesser evil.
19
+ *
20
+ * Both callers — the Run button and auto-run — route through here so the rule
21
+ * is stated once instead of drifting between them.
22
+ *
23
+ * @module playground/runAction
24
+ */
25
+ /** Resolve what Run should do. Pure; see the module docblock for the rules. */
26
+ export function resolveRunAction({ canLaunch, predefinedMessage, defaultMessage }) {
27
+ if (canLaunch && predefinedMessage === undefined) {
28
+ return { kind: 'launch' };
29
+ }
30
+ return { kind: 'message', content: predefinedMessage ?? defaultMessage };
31
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Pipeline Signal Service
3
+ *
4
+ * Operator signals *into* a running pipeline — pause, resume, cancel.
5
+ *
6
+ * The opposite direction from `interruptService`: an interrupt is raised by a
7
+ * node inside a run and awaits an answer, while a signal is raised by an
8
+ * external party and acts on a run that never asked.
9
+ *
10
+ * ## Why this returns a result instead of throwing
11
+ *
12
+ * Every refusal here is an ordinary, expected outcome the composer must render
13
+ * differently — a run that already finished, a duplicate signal, a resume with
14
+ * nothing to resume. Turning those into exceptions would force every caller to
15
+ * re-parse HTTP status codes out of message strings. Only genuine transport
16
+ * failures reject.
17
+ *
18
+ * ## Accepted is not applied
19
+ *
20
+ * A successful pause or cancel returns `accepted`, never `applied`. Backends
21
+ * are expected to observe signals cooperatively — the reference implementation
22
+ * polls between job steps, so the in-flight step always finishes first. Callers
23
+ * must render "pause requested", not "paused", and let a status poll confirm.
24
+ *
25
+ * @module services/pipelineSignalService
26
+ */
27
+ import type { EndpointConfig } from '../config/endpoints.js';
28
+ import type { AuthProvider } from '../types/auth.js';
29
+ /**
30
+ * Signals a pipeline can be sent.
31
+ *
32
+ * Open by design: this is the set the reference backend implements today, but
33
+ * the direction is a general concept and other backends may define more. Widen
34
+ * with care — the client must never offer a signal nothing implements.
35
+ */
36
+ export type SignalType = 'pause' | 'resume' | 'cancel' | (string & {});
37
+ /** Why a signal was refused. Maps onto distinct, user-visible explanations. */
38
+ export type SignalRefusal =
39
+ /** The run already finished — nothing left to signal. */
40
+ 'terminal'
41
+ /** A signal is already pending on this pipeline; the backend rejects a second. */
42
+ | 'duplicate'
43
+ /** Resume with no pause outstanding. */
44
+ | 'not-paused'
45
+ /** No such pipeline. */
46
+ | 'not-found'
47
+ /** Caller lacks permission for this pipeline. */
48
+ | 'forbidden'
49
+ /** Refused for a reason this client does not model. */
50
+ | 'rejected';
51
+ export type SignalResult =
52
+ /**
53
+ * The backend accepted the signal. It has *not* necessarily taken effect —
54
+ * see the module docblock.
55
+ */
56
+ {
57
+ status: 'accepted';
58
+ signal: SignalType;
59
+ pipelineId: string;
60
+ } | {
61
+ status: 'refused';
62
+ reason: SignalRefusal;
63
+ message: string;
64
+ } | {
65
+ status: 'unsupported';
66
+ };
67
+ /** Options accepted by every signal. */
68
+ export interface SendSignalOptions {
69
+ /**
70
+ * Free-text audit note recorded against the signal.
71
+ *
72
+ * Note this is an audit field, not an execution-control one. In the reference
73
+ * backend a pipeline's *paused reason* is a separate, enumerated concept that
74
+ * governs auto-resume, and an operator pause deliberately carries none — the
75
+ * absence is what keeps a human-initiated pause from resuming itself. Sending
76
+ * a note here must not populate that field.
77
+ */
78
+ reason?: string;
79
+ }
80
+ declare class PipelineSignalService {
81
+ #private;
82
+ /**
83
+ * True when this configuration exposes a signal plane at all.
84
+ *
85
+ * Callers gate on this rather than assuming: a backend without signals is a
86
+ * supported configuration, not an error.
87
+ */
88
+ isSupported(config: EndpointConfig | null): boolean;
89
+ /** Pause a running pipeline. */
90
+ pause(config: EndpointConfig | null, pipelineId: string, options?: SendSignalOptions, authProvider?: AuthProvider): Promise<SignalResult>;
91
+ /** Resume a paused pipeline. */
92
+ resume(config: EndpointConfig | null, pipelineId: string, options?: SendSignalOptions, authProvider?: AuthProvider): Promise<SignalResult>;
93
+ /** Cancel a running pipeline. Terminal and durable — it cannot be undone. */
94
+ cancel(config: EndpointConfig | null, pipelineId: string, options?: SendSignalOptions, authProvider?: AuthProvider): Promise<SignalResult>;
95
+ }
96
+ export declare const pipelineSignalService: PipelineSignalService;
97
+ export { PipelineSignalService };
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Pipeline Signal Service
3
+ *
4
+ * Operator signals *into* a running pipeline — pause, resume, cancel.
5
+ *
6
+ * The opposite direction from `interruptService`: an interrupt is raised by a
7
+ * node inside a run and awaits an answer, while a signal is raised by an
8
+ * external party and acts on a run that never asked.
9
+ *
10
+ * ## Why this returns a result instead of throwing
11
+ *
12
+ * Every refusal here is an ordinary, expected outcome the composer must render
13
+ * differently — a run that already finished, a duplicate signal, a resume with
14
+ * nothing to resume. Turning those into exceptions would force every caller to
15
+ * re-parse HTTP status codes out of message strings. Only genuine transport
16
+ * failures reject.
17
+ *
18
+ * ## Accepted is not applied
19
+ *
20
+ * A successful pause or cancel returns `accepted`, never `applied`. Backends
21
+ * are expected to observe signals cooperatively — the reference implementation
22
+ * polls between job steps, so the in-flight step always finishes first. Callers
23
+ * must render "pause requested", not "paused", and let a status poll confirm.
24
+ *
25
+ * @module services/pipelineSignalService
26
+ */
27
+ import { buildEndpointUrl } from '../config/endpoints.js';
28
+ import { authenticatedFetch } from '../utils/fetchWithAuth.js';
29
+ import { logger } from '../utils/logger.js';
30
+ /** Map a refusal HTTP status + payload onto a modelled reason. */
31
+ function classifyRefusal(status, message) {
32
+ if (status === 404)
33
+ return 'not-found';
34
+ if (status === 403 || status === 401)
35
+ return 'forbidden';
36
+ if (status === 409) {
37
+ const text = message.toLowerCase();
38
+ if (text.includes('terminal'))
39
+ return 'terminal';
40
+ if (text.includes('already pending') || text.includes('already'))
41
+ return 'duplicate';
42
+ if (text.includes('no active pause') || text.includes('pause'))
43
+ return 'not-paused';
44
+ return 'rejected';
45
+ }
46
+ return 'rejected';
47
+ }
48
+ class PipelineSignalService {
49
+ /**
50
+ * True when this configuration exposes a signal plane at all.
51
+ *
52
+ * Callers gate on this rather than assuming: a backend without signals is a
53
+ * supported configuration, not an error.
54
+ */
55
+ isSupported(config) {
56
+ return config?.endpoints?.signals != null;
57
+ }
58
+ /** Pause a running pipeline. */
59
+ async pause(config, pipelineId, options = {}, authProvider) {
60
+ return this.#send(config, 'pause', pipelineId, options, authProvider);
61
+ }
62
+ /** Resume a paused pipeline. */
63
+ async resume(config, pipelineId, options = {}, authProvider) {
64
+ return this.#send(config, 'resume', pipelineId, options, authProvider);
65
+ }
66
+ /** Cancel a running pipeline. Terminal and durable — it cannot be undone. */
67
+ async cancel(config, pipelineId, options = {}, authProvider) {
68
+ return this.#send(config, 'cancel', pipelineId, options, authProvider);
69
+ }
70
+ async #send(config, signal, pipelineId, options, authProvider) {
71
+ const signals = config?.endpoints?.signals;
72
+ if (!config || !signals)
73
+ return { status: 'unsupported' };
74
+ const url = buildEndpointUrl(config, signals[signal], { pipelineId }, signals.baseUrl);
75
+ const response = await authenticatedFetch(url, {
76
+ method: 'POST',
77
+ headers: { 'Content-Type': 'application/json' },
78
+ body: JSON.stringify(options.reason ? { reason: options.reason } : {})
79
+ }, { config, endpointKey: 'signals', authProvider });
80
+ if (response.ok) {
81
+ return { status: 'accepted', signal, pipelineId };
82
+ }
83
+ const payload = (await response.json().catch(() => ({})));
84
+ const message = payload.error ?? payload.message ?? `HTTP ${response.status}: ${response.statusText}`;
85
+ logger.warn(`Pipeline signal "${signal}" refused for ${pipelineId}:`, message);
86
+ return {
87
+ status: 'refused',
88
+ reason: classifyRefusal(response.status, message),
89
+ message
90
+ };
91
+ }
92
+ }
93
+ export const pipelineSignalService = new PipelineSignalService();
94
+ export { PipelineSignalService };