prompt-language-shell 0.8.6 → 0.9.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.
@@ -30,11 +30,18 @@ export function routeTasksWithConfirm(tasks, message, service, userRequest, life
30
30
  const validTasks = tasks.filter((task) => task.type !== TaskType.Ignore && task.type !== TaskType.Discard);
31
31
  // Check if no valid tasks remain after filtering
32
32
  if (validTasks.length === 0) {
33
- const message = createMessage(getUnknownRequestMessage());
34
- workflowHandlers.addToQueue(message);
33
+ const msg = createMessage(getUnknownRequestMessage());
34
+ workflowHandlers.addToQueue(msg);
35
35
  return;
36
36
  }
37
37
  const operation = getOperationName(validTasks);
38
+ // Create routing context for downstream functions
39
+ const context = {
40
+ service,
41
+ userRequest,
42
+ workflowHandlers,
43
+ requestHandlers: requestHandlers,
44
+ };
38
45
  if (hasDefineTask) {
39
46
  // Has DEFINE tasks - add Schedule to queue for user selection
40
47
  // Refinement flow will call this function again with refined tasks
@@ -49,9 +56,9 @@ export function routeTasksWithConfirm(tasks, message, service, userRequest, life
49
56
  const scheduleDefinition = createScheduleDefinition(message, validTasks, () => {
50
57
  // Schedule completed - add Confirm to queue
51
58
  const confirmDefinition = createConfirmDefinition(() => {
52
- // User confirmed - complete both Confirm and Schedule, then route to appropriate component
59
+ // User confirmed - complete both Confirm and Schedule, then route
53
60
  lifecycleHandlers.completeActiveAndPending();
54
- executeTasksAfterConfirm(validTasks, service, userRequest, workflowHandlers, requestHandlers);
61
+ executeTasksAfterConfirm(validTasks, context);
55
62
  }, () => {
56
63
  // User cancelled - complete both Confirm and Schedule, then show cancellation
57
64
  lifecycleHandlers.completeActiveAndPending();
@@ -91,7 +98,8 @@ function validateTaskTypes(tasks) {
91
98
  * Validates task types and routes each type appropriately
92
99
  * Supports mixed types at top level with Groups
93
100
  */
94
- function executeTasksAfterConfirm(tasks, service, userRequest, workflowHandlers, requestHandlers) {
101
+ function executeTasksAfterConfirm(tasks, context) {
102
+ const { service, userRequest, workflowHandlers, requestHandlers } = context;
95
103
  // Validate task types (Groups must have uniform subtasks)
96
104
  try {
97
105
  validateTaskTypes(tasks);
@@ -101,6 +109,60 @@ function executeTasksAfterConfirm(tasks, service, userRequest, workflowHandlers,
101
109
  return;
102
110
  }
103
111
  const scheduledTasks = asScheduledTasks(tasks);
112
+ // Collect ALL Execute tasks (standalone and from groups) for upfront validation
113
+ const allExecuteTasks = [];
114
+ for (const task of scheduledTasks) {
115
+ if (task.type === TaskType.Execute) {
116
+ allExecuteTasks.push(task);
117
+ }
118
+ else if (task.type === TaskType.Group && task.subtasks) {
119
+ const subtasks = task.subtasks;
120
+ if (subtasks.length > 0 && subtasks[0].type === TaskType.Execute) {
121
+ allExecuteTasks.push(...subtasks);
122
+ }
123
+ }
124
+ }
125
+ // Validate ALL Execute tasks together to collect ALL missing config upfront
126
+ if (allExecuteTasks.length > 0) {
127
+ try {
128
+ const validation = validateExecuteTasks(allExecuteTasks);
129
+ if (validation.validationErrors.length > 0) {
130
+ // Show error feedback for invalid skills
131
+ const errorMessages = validation.validationErrors.map((error) => {
132
+ const issuesList = error.issues
133
+ .map((issue) => ` - ${issue}`)
134
+ .join('\n');
135
+ return `Invalid skill definition "${error.skill}":\n\n${issuesList}`;
136
+ });
137
+ workflowHandlers.addToQueue(createFeedback(FeedbackType.Failed, errorMessages.join('\n\n')));
138
+ return;
139
+ }
140
+ else if (validation.missingConfig.length > 0) {
141
+ // Missing config detected - create ONE Validate component for ALL missing config
142
+ workflowHandlers.addToQueue(createValidateDefinition(validation.missingConfig, userRequest, service, (error) => {
143
+ requestHandlers.onError(error);
144
+ }, () => {
145
+ // After config is complete, resume task routing
146
+ routeTasksAfterConfig(scheduledTasks, context);
147
+ }, (operation) => {
148
+ requestHandlers.onAborted(operation);
149
+ }));
150
+ return;
151
+ }
152
+ }
153
+ catch (error) {
154
+ requestHandlers.onError(error instanceof Error ? error.message : String(error));
155
+ return;
156
+ }
157
+ }
158
+ // No missing config - proceed with normal routing
159
+ routeTasksAfterConfig(scheduledTasks, context);
160
+ }
161
+ /**
162
+ * Route tasks after config is complete (or when no config is needed)
163
+ * Processes tasks in order, grouping by type
164
+ */
165
+ function routeTasksAfterConfig(scheduledTasks, context) {
104
166
  // Process tasks in order, preserving Group boundaries
105
167
  // Track consecutive standalone tasks to group them by type
106
168
  let consecutiveStandaloneTasks = [];
@@ -120,7 +182,7 @@ function executeTasksAfterConfirm(tasks, service, userRequest, workflowHandlers,
120
182
  const taskType = type;
121
183
  if (typeTasks.length === 0)
122
184
  continue;
123
- routeTasksByType(taskType, typeTasks, service, userRequest, workflowHandlers, requestHandlers);
185
+ routeTasksByType(taskType, typeTasks, context);
124
186
  }
125
187
  consecutiveStandaloneTasks = [];
126
188
  };
@@ -133,7 +195,7 @@ function executeTasksAfterConfirm(tasks, service, userRequest, workflowHandlers,
133
195
  if (task.subtasks.length > 0) {
134
196
  const subtasks = task.subtasks;
135
197
  const taskType = subtasks[0].type;
136
- routeTasksByType(taskType, subtasks, service, userRequest, workflowHandlers, requestHandlers);
198
+ routeTasksByType(taskType, subtasks, context);
137
199
  }
138
200
  }
139
201
  else {
@@ -145,89 +207,81 @@ function executeTasksAfterConfirm(tasks, service, userRequest, workflowHandlers,
145
207
  processStandaloneTasks();
146
208
  }
147
209
  /**
148
- * Route tasks by type to appropriate components
149
- * Extracted to allow reuse for both Groups and standalone tasks
210
+ * Route Answer tasks - creates separate Answer component for each question
150
211
  */
151
- function routeTasksByType(taskType, typeTasks, service, userRequest, workflowHandlers, requestHandlers) {
152
- if (taskType === TaskType.Answer) {
153
- // Create separate Answer component for each question
154
- for (const task of typeTasks) {
155
- workflowHandlers.addToQueue(createAnswerDefinition(task.action, service));
156
- }
212
+ function routeAnswerTasks(tasks, context) {
213
+ for (const task of tasks) {
214
+ context.workflowHandlers.addToQueue(createAnswerDefinition(task.action, context.service));
157
215
  }
158
- else if (taskType === TaskType.Introspect) {
159
- workflowHandlers.addToQueue(createIntrospectDefinition(typeTasks, service));
160
- }
161
- else if (taskType === TaskType.Config) {
162
- // Route to Config flow - extract keys and descriptions from task params
163
- const configKeys = typeTasks
164
- .map((task) => task.params?.key)
165
- .filter((key) => key !== undefined);
166
- // Extract and cache labels from task descriptions
167
- // Only cache labels for dynamically discovered keys (not in schema)
168
- const schema = getConfigSchema();
169
- const labels = {};
170
- for (const task of typeTasks) {
171
- const key = task.params?.key;
172
- if (key && task.action && !(key in schema)) {
173
- labels[key] = task.action;
174
- }
175
- }
176
- if (Object.keys(labels).length > 0) {
177
- saveConfigLabels(labels);
216
+ }
217
+ /**
218
+ * Route Introspect tasks - creates single Introspect component for all tasks
219
+ */
220
+ function routeIntrospectTasks(tasks, context) {
221
+ context.workflowHandlers.addToQueue(createIntrospectDefinition(tasks, context.service));
222
+ }
223
+ /**
224
+ * Route Config tasks - extracts keys, caches labels, creates Config component
225
+ */
226
+ function routeConfigTasks(tasks, context) {
227
+ const configKeys = tasks
228
+ .map((task) => task.params?.key)
229
+ .filter((key) => key !== undefined);
230
+ // Extract and cache labels from task descriptions
231
+ // Only cache labels for dynamically discovered keys (not in schema)
232
+ const schema = getConfigSchema();
233
+ const labels = {};
234
+ for (const task of tasks) {
235
+ const key = task.params?.key;
236
+ if (key && task.action && !(key in schema)) {
237
+ labels[key] = task.action;
178
238
  }
179
- workflowHandlers.addToQueue(createConfigDefinitionWithKeys(configKeys, (config) => {
180
- // Save config - Config component will handle completion and feedback
181
- try {
182
- // Convert flat dotted keys to nested structure grouped by section
183
- const configBySection = unflattenConfig(config);
184
- // Save each section
185
- for (const [section, sectionConfig] of Object.entries(configBySection)) {
186
- saveConfig(section, sectionConfig);
187
- }
188
- }
189
- catch (error) {
190
- const errorMessage = error instanceof Error
191
- ? error.message
192
- : 'Failed to save configuration';
193
- throw new Error(errorMessage);
194
- }
195
- }, (operation) => {
196
- requestHandlers.onAborted(operation);
197
- }));
198
239
  }
199
- else if (taskType === TaskType.Execute) {
200
- // Execute tasks with validation
240
+ if (Object.keys(labels).length > 0) {
241
+ saveConfigLabels(labels);
242
+ }
243
+ context.workflowHandlers.addToQueue(createConfigDefinitionWithKeys(configKeys, (config) => {
244
+ // Save config - Config component will handle completion and feedback
201
245
  try {
202
- const validation = validateExecuteTasks(typeTasks);
203
- if (validation.validationErrors.length > 0) {
204
- // Show error feedback for invalid skills
205
- const errorMessages = validation.validationErrors.map((error) => {
206
- const issuesList = error.issues
207
- .map((issue) => ` - ${issue}`)
208
- .join('\n');
209
- return `Invalid skill definition "${error.skill}":\n\n${issuesList}`;
210
- });
211
- workflowHandlers.addToQueue(createFeedback(FeedbackType.Failed, errorMessages.join('\n\n')));
212
- }
213
- else if (validation.missingConfig.length > 0) {
214
- workflowHandlers.addToQueue(createValidateDefinition(validation.missingConfig, userRequest, service, (error) => {
215
- requestHandlers.onError(error);
216
- }, () => {
217
- workflowHandlers.addToQueue(createExecuteDefinition(typeTasks, service));
218
- }, (operation) => {
219
- requestHandlers.onAborted(operation);
220
- }));
221
- }
222
- else {
223
- workflowHandlers.addToQueue(createExecuteDefinition(typeTasks, service));
246
+ // Convert flat dotted keys to nested structure grouped by section
247
+ const configBySection = unflattenConfig(config);
248
+ // Save each section
249
+ for (const [section, sectionConfig] of Object.entries(configBySection)) {
250
+ saveConfig(section, sectionConfig);
224
251
  }
225
252
  }
226
253
  catch (error) {
227
- // Handle skill reference errors (e.g., unknown skills)
228
- const errorMessage = error instanceof Error ? error.message : String(error);
229
- const message = createMessage(errorMessage);
230
- workflowHandlers.addToQueue(message);
254
+ const errorMessage = error instanceof Error
255
+ ? error.message
256
+ : 'Failed to save configuration';
257
+ throw new Error(errorMessage);
231
258
  }
259
+ }, (operation) => {
260
+ context.requestHandlers.onAborted(operation);
261
+ }));
262
+ }
263
+ /**
264
+ * Route Execute tasks - creates Execute component (validation already done)
265
+ */
266
+ function routeExecuteTasks(tasks, context) {
267
+ context.workflowHandlers.addToQueue(createExecuteDefinition(tasks, context.service));
268
+ }
269
+ /**
270
+ * Registry mapping task types to their route handlers
271
+ */
272
+ const taskRouteHandlers = {
273
+ [TaskType.Answer]: routeAnswerTasks,
274
+ [TaskType.Introspect]: routeIntrospectTasks,
275
+ [TaskType.Config]: routeConfigTasks,
276
+ [TaskType.Execute]: routeExecuteTasks,
277
+ };
278
+ /**
279
+ * Route tasks by type to appropriate components
280
+ * Uses registry pattern for extensibility
281
+ */
282
+ function routeTasksByType(taskType, tasks, context) {
283
+ const handler = taskRouteHandlers[taskType];
284
+ if (handler) {
285
+ handler(tasks, context);
232
286
  }
233
287
  }
@@ -1,3 +1,4 @@
1
+ import { spawn } from 'child_process';
1
2
  export var ExecutionStatus;
2
3
  (function (ExecutionStatus) {
3
4
  ExecutionStatus["Pending"] = "pending";
@@ -58,18 +59,186 @@ export class DummyExecutor {
58
59
  });
59
60
  }
60
61
  }
62
+ // Marker for extracting pwd from command output
63
+ const PWD_MARKER = '__PWD_MARKER_7x9k2m__';
61
64
  /**
62
- * Default executor uses DummyExecutor for development and testing.
63
- * To implement real shell execution, create a RealExecutor class that:
64
- * - Spawns process with cmd.command in shell mode using child_process.spawn()
65
- * - Sets working directory from cmd.workdir
66
- * - Handles cmd.timeout for command timeout
67
- * - Captures stdout and stderr streams
68
- * - Calls onProgress with Running/Success/Failed status
69
- * - Returns CommandOutput with actual stdout, stderr, exitCode
70
- * - Handles errors (spawn failures, timeouts, non-zero exit codes)
65
+ * Parse stdout to extract workdir and clean output.
66
+ * Returns the cleaned output and the extracted workdir.
71
67
  */
72
- const executor = new DummyExecutor();
68
+ function parseWorkdir(rawOutput) {
69
+ const markerIndex = rawOutput.lastIndexOf(PWD_MARKER);
70
+ if (markerIndex === -1) {
71
+ return { output: rawOutput };
72
+ }
73
+ const output = rawOutput.slice(0, markerIndex).trimEnd();
74
+ const pwdPart = rawOutput.slice(markerIndex + PWD_MARKER.length).trim();
75
+ const lines = pwdPart.split('\n').filter((l) => l.trim());
76
+ const workdir = lines[0];
77
+ return { output, workdir };
78
+ }
79
+ /**
80
+ * Manages streaming output while filtering out the PWD marker.
81
+ * Buffers output to avoid emitting partial markers to the callback.
82
+ */
83
+ class OutputStreamer {
84
+ chunks = [];
85
+ emittedLength = 0;
86
+ callback;
87
+ constructor(callback) {
88
+ this.callback = callback;
89
+ }
90
+ /**
91
+ * Add new stdout data and emit safe content to callback.
92
+ * Buffers data to avoid emitting partial PWD markers.
93
+ */
94
+ pushStdout(data) {
95
+ this.chunks.push(data);
96
+ if (!this.callback)
97
+ return;
98
+ const accumulated = this.chunks.join('');
99
+ const markerIndex = accumulated.indexOf(PWD_MARKER);
100
+ if (markerIndex !== -1) {
101
+ // Marker found - emit everything before it (trimmed)
102
+ this.emitUpTo(accumulated.slice(0, markerIndex).trimEnd().length);
103
+ }
104
+ else {
105
+ // No marker yet - emit all but buffer for potential partial marker
106
+ const bufferSize = PWD_MARKER.length + 5;
107
+ const safeLength = Math.max(this.emittedLength, accumulated.length - bufferSize);
108
+ this.emitUpTo(safeLength);
109
+ }
110
+ }
111
+ /**
112
+ * Emit content up to the specified length if there's new content.
113
+ */
114
+ emitUpTo(length) {
115
+ if (length > this.emittedLength && this.callback) {
116
+ const accumulated = this.chunks.join('');
117
+ const newContent = accumulated.slice(this.emittedLength, length);
118
+ this.callback(newContent, 'stdout');
119
+ this.emittedLength = length;
120
+ }
121
+ }
122
+ /**
123
+ * Get the accumulated raw output.
124
+ */
125
+ getAccumulated() {
126
+ return this.chunks.join('');
127
+ }
128
+ }
129
+ /**
130
+ * Real executor that spawns shell processes and captures output.
131
+ */
132
+ export class RealExecutor {
133
+ outputCallback;
134
+ constructor(outputCallback) {
135
+ this.outputCallback = outputCallback;
136
+ }
137
+ /**
138
+ * Set or update the output callback
139
+ */
140
+ setOutputCallback(callback) {
141
+ this.outputCallback = callback;
142
+ }
143
+ execute(cmd, onProgress, _ = 0) {
144
+ return new Promise((resolve) => {
145
+ onProgress?.(ExecutionStatus.Running);
146
+ const stderr = [];
147
+ // Wrap command to capture final working directory
148
+ const wrappedCommand = `${cmd.command}; __exit=$?; echo ""; echo "${PWD_MARKER}"; pwd; exit $__exit`;
149
+ // Wrap spawn in try/catch to handle synchronous errors
150
+ let child;
151
+ try {
152
+ child = spawn(wrappedCommand, {
153
+ shell: true,
154
+ cwd: cmd.workdir || process.cwd(),
155
+ });
156
+ }
157
+ catch (error) {
158
+ const errorMessage = error instanceof Error ? error.message : 'Failed to spawn process';
159
+ const commandResult = {
160
+ description: cmd.description,
161
+ command: cmd.command,
162
+ output: '',
163
+ errors: errorMessage,
164
+ result: ExecutionResult.Error,
165
+ error: errorMessage,
166
+ };
167
+ onProgress?.(ExecutionStatus.Failed);
168
+ resolve(commandResult);
169
+ return;
170
+ }
171
+ // Handle timeout if specified
172
+ const SIGKILL_GRACE_PERIOD = 3000;
173
+ let timeoutId;
174
+ let killTimeoutId;
175
+ if (cmd.timeout && cmd.timeout > 0) {
176
+ timeoutId = setTimeout(() => {
177
+ child.kill('SIGTERM');
178
+ // Escalate to SIGKILL if process doesn't terminate
179
+ killTimeoutId = setTimeout(() => {
180
+ child.kill('SIGKILL');
181
+ }, SIGKILL_GRACE_PERIOD);
182
+ }, cmd.timeout);
183
+ }
184
+ // Use OutputStreamer for buffered stdout streaming
185
+ const stdoutStreamer = new OutputStreamer(this.outputCallback);
186
+ child.stdout.on('data', (data) => {
187
+ stdoutStreamer.pushStdout(data.toString());
188
+ });
189
+ child.stderr.on('data', (data) => {
190
+ const text = data.toString();
191
+ stderr.push(text);
192
+ this.outputCallback?.(text, 'stderr');
193
+ });
194
+ child.on('error', (error) => {
195
+ if (timeoutId)
196
+ clearTimeout(timeoutId);
197
+ if (killTimeoutId)
198
+ clearTimeout(killTimeoutId);
199
+ const commandResult = {
200
+ description: cmd.description,
201
+ command: cmd.command,
202
+ output: stdoutStreamer.getAccumulated(),
203
+ errors: error.message,
204
+ result: ExecutionResult.Error,
205
+ error: error.message,
206
+ };
207
+ onProgress?.(ExecutionStatus.Failed);
208
+ resolve(commandResult);
209
+ });
210
+ child.on('close', (code) => {
211
+ if (timeoutId)
212
+ clearTimeout(timeoutId);
213
+ if (killTimeoutId)
214
+ clearTimeout(killTimeoutId);
215
+ const success = code === 0;
216
+ const { output, workdir } = parseWorkdir(stdoutStreamer.getAccumulated());
217
+ const commandResult = {
218
+ description: cmd.description,
219
+ command: cmd.command,
220
+ output,
221
+ errors: stderr.join(''),
222
+ result: success ? ExecutionResult.Success : ExecutionResult.Error,
223
+ error: success ? undefined : `Exit code: ${code}`,
224
+ workdir,
225
+ };
226
+ onProgress?.(success ? ExecutionStatus.Success : ExecutionStatus.Failed);
227
+ resolve(commandResult);
228
+ });
229
+ });
230
+ }
231
+ }
232
+ // Create real executor instance
233
+ const realExecutor = new RealExecutor();
234
+ // Default executor for production use
235
+ const executor = realExecutor;
236
+ /**
237
+ * Set a callback to receive command output in real-time
238
+ */
239
+ export function setOutputCallback(callback) {
240
+ realExecutor.setOutputCallback(callback);
241
+ }
73
242
  /**
74
243
  * Execute a single shell command
75
244
  */
@@ -1,5 +1,6 @@
1
1
  import { homedir } from 'os';
2
2
  import { join } from 'path';
3
+ import { AppError, ErrorCode } from '../types/errors.js';
3
4
  import { defaultFileSystem } from './filesystem.js';
4
5
  import { displayWarning } from './logger.js';
5
6
  import { getUnknownSkillMessage } from './messages.js';
@@ -189,7 +190,7 @@ export function expandSkillReferences(execution, skillLookup, visited = new Set(
189
190
  }
190
191
  // Check for circular reference
191
192
  if (visited.has(skillName)) {
192
- throw new Error(`Circular skill reference detected: ${Array.from(visited).join(' → ')} → ${skillName}`);
193
+ throw new AppError(`Circular skill reference detected: ${Array.from(visited).join(' → ')} → ${skillName}`, ErrorCode.CircularReference);
193
194
  }
194
195
  // Second: Match against skill name
195
196
  const skill = skillLookup(skillName);
@@ -110,15 +110,17 @@ They enable cleaner, more reusable component logic.
110
110
 
111
111
  ## Common Mistakes to Avoid
112
112
 
113
- Starting with "Here's the answer:" or "Let me explain:"
114
- Exceeding 4 lines or 80 characters per line
115
- Including unnecessary details
116
- Using overly technical jargon without explanation
117
- Repeating the question in the answer
118
- Using citation tags like `<cite>` or any HTML/XML markup
119
-
120
- ✅ Direct, concise answers
121
- ✅ Proper line breaks at natural phrase boundaries
122
- Essential information only
123
- Clear, accessible language
124
- Plain text only - no markup tags
113
+ **DO NOT:**
114
+ - Start with "Here's the answer:" or "Let me explain:"
115
+ - Exceed 4 lines or 80 characters per line
116
+ - Include unnecessary details
117
+ - Use overly technical jargon without explanation
118
+ - Repeat the question in the answer
119
+ - Use citation tags like `<cite>` or any HTML/XML markup
120
+
121
+ **DO:**
122
+ - Give direct, concise answers
123
+ - Use proper line breaks at natural phrase boundaries
124
+ - Include essential information only
125
+ - Use clear, accessible language
126
+ - Use plain text only - no markup tags