@openagents-org/agent-launcher 0.2.203 → 0.2.204

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.
@@ -0,0 +1,224 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * One place for "this CLI run failed — why, and what does the channel get
5
+ * told". Pure: no process, network or adapter state, so every branch is
6
+ * unit-testable (see test/run-failure.test.js).
7
+ *
8
+ * Every CLI adapter hit the same dead end — a failed run reached the user as
9
+ * "No response generated. Please try again.", with the real reason (bad key,
10
+ * blocked network, exhausted quota) only in the daemon log. Each adapter that
11
+ * fixed it grew its own copy of the same regexes and the same
12
+ * "guidance + Details:" shape. This module is that copy, once.
13
+ *
14
+ * Two things stay per-adapter, and are passed in:
15
+ * - `cli`, the name to use in the fallback wording;
16
+ * - `guidance`, the sentence to lead with per kind, because what a user
17
+ * should DO about a bad key differs per CLI (env var, `x login`, the
18
+ * launcher). Kinds without a sentence fall back to generic wording.
19
+ *
20
+ * What the CLI actually said is always appended, redacted, as "Details: …" —
21
+ * that is the part that makes a report actionable when the guidance guessed
22
+ * wrong.
23
+ */
24
+
25
+ const { redactSecrets } = require('./utils');
26
+
27
+ /** How much of the CLI's own words to quote back. */
28
+ const DETAIL_CAP = 300;
29
+
30
+ // A config file named next to a word that says it could not be read as one.
31
+ // The file name alone is not a failure: CLIs print the path of the settings
32
+ // they loaded on every run, and "settings.json not found" is a missing file,
33
+ // not a broken one.
34
+ const CONFIG_FILE = '(?:settings|providers|config)\\.(?:json|ya?ml|toml)';
35
+ const UNREADABLE = '(?:invalid|malformed|corrupt|syntax error|unexpected token|(?:could not|cannot|failed to|unable to) parse)';
36
+
37
+ /**
38
+ * Failure kinds, in the order they are tested. Earlier wins, so the more
39
+ * specific causes come first: "authentication failed or timed out" is an auth
40
+ * failure, not a timeout.
41
+ *
42
+ * Each pattern wants the failure itself, not a word that is merely near one —
43
+ * this text is whatever a CLI printed, and "sign-in page rendered" or
44
+ * "path is forbidden by the sandbox" is a tool talking about its work. So
45
+ * "sign in" counts only as a request or a requirement, and "forbidden" only
46
+ * as the HTTP status or the error itself.
47
+ */
48
+ const PATTERNS = [
49
+ ['session', /Error resuming session|Invalid session identifier|No previous sessions found/i],
50
+ ['auth', /authentication (?:required|failed)|not authenticated|no valid credentials|please (?:sign|log) in|(?:sign|log)[ -]?in (?:is )?required|not (?:signed|logged) in|Please set an Auth method|API key not valid|API[_ ]?KEY[_ ]?INVALID|UNAUTHENTICATED|PERMISSION_DENIED|invalid_grant|re-?authenticate|IneligibleTier|account is not eligible|\bunauthorized\b|\b403\b[^\n]{0,24}\bforbidden\b|\bforbidden\b[^\n]{0,24}\b403\b|\berror["']?[:=]\s*["']?forbidden\b|(?:invalid|incorrect)[^\n]{0,20}(?:api.?key|token|credential)|api[_ -]?key (?:is )?(?:missing|required|not set|unset)|\b(?:status|HTTP):? 40[13]\b|GEMINI_API_KEY/i],
51
+ ['quota', /RESOURCE_EXHAUSTED|\bquota\b|exhausted your capacity|rate.?limit|too many requests|\b429\b|overloaded/i],
52
+ ['network', /fetch failed|ENOTFOUND|ETIMEDOUT|ECONNREFUSED|ECONNRESET|EAI_AGAIN|UND_ERR_CONNECT_TIMEOUT|socket hang up|getaddrinfo|network error|self[- ]signed certificate|unable to verify the first certificate/i],
53
+ ['model', /ModelNotFound|models?\b[^\n]{0,60}\bnot (?:found|supported)|unknown model|invalid model|unsupported model|no such model|model[^\n]{0,30}(?:unavailable|does not exist)|\bstatus:? 404\b/i],
54
+ ['provider', /modelProvider|model provider|unknown provider|no (?:inference )?provider configured|provider[^\n]{0,30}(?:not|un)(?:available|configured|supported|known)/i],
55
+ ['config', new RegExp(
56
+ `${CONFIG_FILE}[^\\n]{0,60}${UNREADABLE}|${UNREADABLE}[^\\n]{0,60}${CONFIG_FILE}`
57
+ + '|config(?:uration)? (?:error|is invalid|invalid|malformed)|invalid json|malformed (?:json|ya?ml|toml|config)',
58
+ 'i',
59
+ )],
60
+ ['timeout', /print-timeout|timed? ?out|deadline exceeded/i],
61
+ ];
62
+
63
+ /**
64
+ * Generic wording for a kind the adapter gave no sentence for. Deliberately
65
+ * vague about the fix — an adapter that knows better passes `guidance`.
66
+ */
67
+ function defaultGuidance(kind, cli) {
68
+ switch (kind) {
69
+ case 'session':
70
+ return `${cli} could not resume this channel's previous session.`;
71
+ case 'auth':
72
+ return `${cli} could not authenticate. Check this agent's API key or sign-in.`;
73
+ case 'quota':
74
+ return 'The provider is rate-limiting this agent, or its quota is exhausted. Wait and try again.';
75
+ case 'network':
76
+ return `${cli} could not reach its provider from this device. Check the device's network, or its proxy.`;
77
+ case 'model':
78
+ return `The provider rejected the requested model. Check the model configured for this agent.`;
79
+ case 'provider':
80
+ return `${cli} has no usable provider configured.`;
81
+ case 'config':
82
+ return `${cli}'s configuration looks invalid.`;
83
+ case 'timeout':
84
+ return `${cli} timed out before producing a response.`;
85
+ default:
86
+ return '';
87
+ }
88
+ }
89
+
90
+ /** The message text of a `{type, message}` error, a bare string, or nothing. */
91
+ function errorMessage(error) {
92
+ if (!error) return '';
93
+ if (typeof error === 'string') return error;
94
+ if (typeof error === 'object') return String(error.message || error.type || '');
95
+ return String(error);
96
+ }
97
+
98
+ const oneLine = (s) => s.replace(/\s+/g, ' ').trim();
99
+ const cap = (s, max = DETAIL_CAP) => (s.length > max ? `${s.slice(0, max - 1)}…` : s);
100
+
101
+ // stderr lines that say something about the failure, as opposed to the
102
+ // "Loaded cached credentials." / "YOLO mode is enabled." chatter around it.
103
+ const TELLING_RE = /error|fail|invalid|denied|not |please|unable|cannot|refused/i;
104
+
105
+ /**
106
+ * Did the run fail? The CLI's own verdict comes first: a success result
107
+ * settles it whatever the exit code and whatever error events came before it
108
+ * (an error the run recovered from is not a failed run — reporting it would
109
+ * post a notice under a reply that was delivered). Without one, an error
110
+ * result, an error-severity event, or a non-zero exit (a signal leaves code
111
+ * null) is a failure.
112
+ */
113
+ function isFailedRun({ code, resultStatus, errorMessages = [] } = {}) {
114
+ const status = String(resultStatus || '').toLowerCase();
115
+ if (status === 'success') return false;
116
+ if (status === 'error' || errorMessages.length > 0) return true;
117
+ return code !== 0;
118
+ }
119
+
120
+ /**
121
+ * The most useful part of what the CLI said, secrets stripped. A structured
122
+ * error wins over stderr, which is mostly startup chatter. Redaction runs over
123
+ * the whole text BEFORE it is cut, so a key split across the cut cannot
124
+ * survive as a fragment.
125
+ *
126
+ * `secrets` are the values the caller knows to be secret — the agent's own
127
+ * keys and its workspace token (BaseAdapter._knownSecrets). They are masked by
128
+ * value, which is the only protection for a key whose format no pattern knows.
129
+ */
130
+ function failureDetail({ stderr, error, errorMessages = [], secrets = [], max = DETAIL_CAP } = {}) {
131
+ const structured = [errorMessage(error), ...errorMessages].filter(Boolean).join(' | ');
132
+ if (structured) return cap(oneLine(redactSecrets(structured, secrets)), max);
133
+ const lines = redactSecrets(stderr || '', secrets).split('\n').map((l) => l.trim()).filter(Boolean);
134
+ if (!lines.length) return '';
135
+ const telling = lines.filter((l) => TELLING_RE.test(l));
136
+ return cap(oneLine((telling.length ? telling : lines).slice(-2).join(' ')), max);
137
+ }
138
+
139
+ /**
140
+ * Which kind of failure the text describes, or null. Matched against the RAW
141
+ * text, never the redacted one: redaction rewrites the very words ("api_key",
142
+ * "token") some patterns key on.
143
+ */
144
+ function classifyFailureText(text, { skip = [] } = {}) {
145
+ const s = String(text || '');
146
+ if (!s.trim()) return null;
147
+ for (const [kind, re] of PATTERNS) {
148
+ if (skip.includes(kind)) continue;
149
+ if (re.test(s)) return kind;
150
+ }
151
+ return null;
152
+ }
153
+
154
+ /**
155
+ * Turn a failed run into `{ kind, message, detail }`, where `message` is what
156
+ * the channel should read: guidance for a recognised cause, then the CLI's own
157
+ * words. An unrecognised failure quotes those words with the exit code, which
158
+ * still beats "No response generated".
159
+ *
160
+ * @param {object} info
161
+ * @param {number|null} info.code process exit code (null when signalled)
162
+ * @param {string} info.stderr everything the process wrote to stderr
163
+ * @param {object|string} info.error a structured error from the CLI's stream
164
+ * @param {string[]} info.errorMessages error-severity events from the stream
165
+ * @param {string} info.cli the CLI's name, for the fallback wording
166
+ * @param {object} info.guidance kind → the sentence to lead with
167
+ * @param {string[]} info.skip kinds this CLI can never produce
168
+ * @param {string[]} info.secrets values to mask wherever they appear
169
+ * @param {string} info.codeLabel how to name `code` when it is not an exit
170
+ * code — "HTTP 429" for an adapter that talks to an API rather than a CLI.
171
+ */
172
+ function classifyRunFailure({
173
+ code, stderr, error, errorMessages = [], cli = 'The CLI', guidance = {}, skip = [],
174
+ secrets = [], codeLabel = '',
175
+ } = {}) {
176
+ const errType = error && typeof error === 'object' ? String(error.type || '') : '';
177
+ const structured = [errType, errorMessage(error), ...errorMessages].filter(Boolean).join('\n');
178
+ const detail = failureDetail({ stderr, error, errorMessages, secrets });
179
+ const kind = classifyFailureText([structured, stderr].filter(Boolean).join('\n'), { skip });
180
+
181
+ if (kind) {
182
+ const lead = guidance[kind] || defaultGuidance(kind, cli);
183
+ return { kind, detail, message: detail ? `${lead}\n\nDetails: ${detail}` : lead };
184
+ }
185
+ return {
186
+ kind: 'unknown',
187
+ detail,
188
+ message: detail
189
+ ? `${cli} failed (${codeLabel || `exit ${code ?? '?'}`}): ${detail}`
190
+ : (codeLabel
191
+ ? `${cli} failed (${codeLabel}) without a response.`
192
+ : `${cli} exited with code ${code ?? '?'} without a response.`),
193
+ };
194
+ }
195
+
196
+ /**
197
+ * An Error whose message is already the sentence the channel should read.
198
+ * Adapters that report a failure by throwing (rather than posting inline) mark
199
+ * it this way so their catch can post it as-is instead of wrapping it in
200
+ * "Error processing message: …", which reads like an adapter bug.
201
+ */
202
+ function classifiedError(message) {
203
+ const err = new Error(message);
204
+ err.classified = true;
205
+ return err;
206
+ }
207
+
208
+ /** True for an error carrying a message meant for the channel verbatim. */
209
+ function isClassifiedError(e) {
210
+ return !!(e && e.classified);
211
+ }
212
+
213
+ module.exports = {
214
+ DETAIL_CAP,
215
+ classifiedError,
216
+ isClassifiedError,
217
+ PATTERNS,
218
+ isFailedRun,
219
+ errorMessage,
220
+ failureDetail,
221
+ classifyFailureText,
222
+ classifyRunFailure,
223
+ defaultGuidance,
224
+ };
@@ -123,29 +123,99 @@ function formatAttachmentsForPrompt(
123
123
  return lines.join('\n');
124
124
  }
125
125
 
126
+ /**
127
+ * Environment variable names whose value is a credential. Deliberately broad:
128
+ * masking a value that turns out to be harmless costs one word of an error
129
+ * notice, while missing a key posts it to every member of the workspace.
130
+ */
131
+ const SECRET_NAME_RE = /KEY|TOKEN|SECRET|PASSWORD|PASSWD|AUTH/i;
132
+ /** Shorter than this and a value is as likely a flag ("1", "true") as a secret. */
133
+ const MIN_SECRET_LENGTH = 8;
134
+
135
+ /**
136
+ * The exact values an agent must never quote back: everything in its
137
+ * environment whose name says it is a credential, plus whatever the caller
138
+ * already knows to be one (the workspace token). Longest first, so a secret
139
+ * that contains another is masked whole rather than leaving its tail behind.
140
+ *
141
+ * @param {object} env the environment the agent's CLI runs with
142
+ * @param {string[]} extra further values to mask
143
+ * @returns {string[]}
144
+ */
145
+ function secretValues(env, extra = []) {
146
+ const out = new Set();
147
+ const add = (value) => {
148
+ const v = typeof value === 'string' ? value.trim() : '';
149
+ if (v.length >= MIN_SECRET_LENGTH) out.add(v);
150
+ };
151
+ for (const [name, value] of Object.entries(env || {})) {
152
+ if (SECRET_NAME_RE.test(name)) add(value);
153
+ }
154
+ for (const value of extra || []) add(value);
155
+ return [...out].sort((x, y) => y.length - x.length);
156
+ }
157
+
158
+ /**
159
+ * Mask known secret values in `text` and touch nothing else. For text that is
160
+ * mostly prose or code — a model's partial answer — where the shape rules of
161
+ * redactSecrets would rewrite ordinary words ("token limit", `password: string`).
162
+ */
163
+ function maskSecretValues(text, secrets) {
164
+ let out = String(text == null ? '' : text);
165
+ for (const secret of secrets || []) {
166
+ if (typeof secret === 'string' && secret.length >= MIN_SECRET_LENGTH) {
167
+ out = out.split(secret).join('[REDACTED]');
168
+ }
169
+ }
170
+ return out;
171
+ }
172
+
126
173
  /**
127
174
  * Strip secrets out of anything on its way to a log line or a channel message.
128
175
  *
129
176
  * Adapter diagnostics quote raw CLI output, and a CLI that fails on auth tends
130
- * to echo the credential it was handed. The shapes here are the ones that
131
- * actually turn up in that output; the closing catch-all takes any long opaque
132
- * token the named patterns missed.
177
+ * to echo the credential it was handed. Two passes:
178
+ *
179
+ * 1. `secrets` — the values we already know are secret (see secretValues),
180
+ * masked wherever they appear. No pattern can know every provider's key
181
+ * format; this needs no format at all. It runs first because a pattern
182
+ * that recognises half of a key would otherwise leave the other half.
183
+ * 2. The shapes that actually turn up in CLI output, for a credential that
184
+ * is not ours to know (another tool's token, a key in a config file). The
185
+ * closing catch-all takes any long opaque token the named patterns missed.
133
186
  *
134
187
  * Lived as a private static on two adapters before claude needed it as well —
135
188
  * a third identical copy is one copy too many for a security-relevant rule.
189
+ *
190
+ * @param {string} s
191
+ * @param {string[]} [secrets] exact values to mask, e.g. from secretValues()
136
192
  */
137
- function redactSecrets(s) {
138
- let out = String(s == null ? '' : s);
193
+ function redactSecrets(s, secrets) {
194
+ let out = maskSecretValues(s, secrets);
139
195
  out = out
196
+ // scheme://user:password@host, and scheme://token@host.
197
+ .replace(/(\b[a-z][a-z0-9+.-]*:\/\/)[^/\s@?#]+@/gi, '$1[REDACTED]@')
140
198
  .replace(/\bsk-[A-Za-z0-9_-]{6,}/g, 'sk-[REDACTED]')
141
199
  .replace(/\b(?:github_pat|gh[pousr])_[A-Za-z0-9_]{10,}/g, '[REDACTED_TOKEN]')
142
200
  .replace(/\bxox[baprs]-[A-Za-z0-9-]{8,}/g, '[REDACTED_TOKEN]')
143
201
  .replace(/\bAKIA[0-9A-Z]{12,}/g, '[REDACTED_KEY]')
144
202
  .replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g, '[REDACTED_JWT]')
145
- .replace(/(authorization|api[_-]?key|x-api-key|token|bearer|secret|password|passwd)(["'\s:=]+)([^\s"',}]+)/gi,
203
+ // Google API keys are 39 chars, one short of the catch-all below.
204
+ .replace(/\bAIza[0-9A-Za-z_-]{30,}/g, '[REDACTED_KEY]')
205
+ .replace(/\bya29\.[0-9A-Za-z_-]{20,}/g, '[REDACTED_TOKEN]')
206
+ // key: value. An Authorization value is "<scheme> <credential>", so the
207
+ // scheme word is skipped — taking it for the value masked "Bearer" and
208
+ // left the token standing right behind it.
209
+ .replace(/(authorization|api[_-]?key|x-api-key|token|bearer|secret|password|passwd)(["'\s:=]+)(?:(?:bearer|basic|token)[ \t]+)?([^\s"',}]+)/gi,
146
210
  (m, k, sep) => `${k}${sep}[REDACTED]`)
211
+ // A Basic credential quoted without its header name. Base64 has no shape
212
+ // of its own, so this wants padding or some length before it believes it.
213
+ .replace(/\b(basic)[ \t]+(?:[A-Za-z0-9+/]{16,}={0,2}|[A-Za-z0-9+/]{4,}={1,2})/gi, '$1 [REDACTED]')
147
214
  .replace(/([?&](?:api[_-]?key|key|token|access_token)=)[^&\s"']+/gi, '$1[REDACTED]')
148
- .replace(/\b[A-Za-z0-9_-]{40,}\b/g, '[REDACTED]');
215
+ .replace(/\b[A-Za-z0-9_-]{40,}\b/g, '[REDACTED]')
216
+ // Keys too short for the catch-all with no prefix to know them by: bare
217
+ // hex (32+), and the "<32 hex>.<secret>" form Zhipu issues.
218
+ .replace(/\b[0-9a-f]{32,}(?:\.[A-Za-z0-9]{8,})?\b/gi, '[REDACTED]');
149
219
  return out;
150
220
  }
151
221
 
@@ -187,4 +257,6 @@ module.exports = {
187
257
  generateSessionTitle,
188
258
  formatAttachmentsForPrompt,
189
259
  redactSecrets,
260
+ maskSecretValues,
261
+ secretValues,
190
262
  };
@@ -583,8 +583,14 @@ function buildApiSkillsPrompt({ endpoint, workspaceId, token, agentName, channel
583
583
  `"hour":8,"minute":0,` +
584
584
  `"network":"${workspaceId}",` +
585
585
  `"source":"openagents:${agentName}"}'\`\n\n` +
586
- '**List active routines:**\n' +
586
+ '**List routines (active + paused):**\n' +
587
587
  `\`${curl} -s -H "${h}" "${baseUrl}/v1/routines?network=${workspaceId}"\`\n\n` +
588
+ '**Edit a routine** (only the fields you send change — this keeps the ' +
589
+ 'routine\'s id and history, so prefer it over cancel-and-recreate). ' +
590
+ '`status` is `active` or `paused`:\n' +
591
+ `\`${curl} -s -X PATCH -H "${h}" -H "Content-Type: application/json" ` +
592
+ `${baseUrl}/v1/routines/ROUTINE_ID -d '{"hour":9,"minute":30,` +
593
+ `"network":"${workspaceId}"}'\`\n\n` +
588
594
  '**Cancel a routine:**\n' +
589
595
  `\`${curl} -s -X DELETE -H "${h}" ${baseUrl}/v1/routines/ROUTINE_ID\`\n`
590
596
  );
@@ -720,6 +726,7 @@ function buildClaudeMcpToolBlock() {
720
726
  'Use workspace_put_todos to track your progress. ALWAYS create a to-do list when given multiple tasks or multi-step work.\n' +
721
727
  'Use workspace_create_timer to set a reminder that wakes you up later.\n' +
722
728
  'Use workspace_create_routine to set up recurring scheduled tasks (e.g. daily reviews).\n' +
729
+ 'Use workspace_update_routine to change an existing routine — its schedule, task or paused state — instead of cancelling and recreating it.\n' +
723
730
  'Use workspace_send_notification to send a notification to the workspace inbox when you complete a task or have important results.\n' +
724
731
  'Use workspace_request_approval BEFORE deploying, spending money, emailing customers, deleting data, or any irreversible action; it blocks until a person decides. If it returns PENDING, stop and end your turn — the decision arrives as a message in the thread.\n' +
725
732
  'Use workspace_write_knowledge to create or update shared knowledge base entries that persist across conversations.\n' +
package/src/config.js CHANGED
@@ -175,8 +175,14 @@ class Config {
175
175
  }
176
176
  }
177
177
 
178
+ /**
179
+ * Queue a line for the daemon, which reads and deletes the file every 200ms.
180
+ * Appended, not overwritten: two commands landing inside one poll (a Start
181
+ * clicked in the launcher and a heartbeat nudge from a workspace page) both
182
+ * have to arrive.
183
+ */
178
184
  writeCommand(cmd) {
179
- fs.writeFileSync(this.cmdFile, cmd + '\n', 'utf-8');
185
+ fs.appendFileSync(this.cmdFile, cmd + '\n', 'utf-8');
180
186
  }
181
187
 
182
188
  getLogs(agentName, lines = 200) {
package/src/daemon.js CHANGED
@@ -910,9 +910,8 @@ async _runNodeCommand(n, cmd) {
910
910
  if (rc2.code !== 0) throw new Error(rc2.stderr || rc2.stdout || 'connect failed');
911
911
  } else {
912
912
  // Restart in-process. `agn stop` + `agn start` both round-trip
913
- // through daemon.cmd, and writeCommand() OVERWRITES that file — the
914
- // start could clobber the unread stop (agent keeps the stale env) or
915
- // interleave with the poll so the agent stops and never restarts.
913
+ // through daemon.cmd, and the pair can interleave with the poll so
914
+ // the agent stops and never restarts.
916
915
  this._saveNodeAgentEnv(name, type, args);
917
916
  await this.restartAgent(name);
918
917
  }
@@ -1953,6 +1952,11 @@ async _runNodeCommand(n, cmd) {
1953
1952
  } else if (cmd === 'reload') {
1954
1953
  this._log('Command: reload');
1955
1954
  this._reload();
1955
+ } else if (cmd === 'heartbeat') {
1956
+ // A workspace page in the launcher just queued a command for this
1957
+ // device: heartbeat now so it is picked up, instead of on the next
1958
+ // 10s tick. Not logged — it carries nothing worth a line.
1959
+ this._nodeHeartbeat().catch(() => {});
1956
1960
  }
1957
1961
  }
1958
1962
  } catch {}
package/src/mcp-server.js CHANGED
@@ -412,9 +412,39 @@ function buildToolDefs(disabledModules) {
412
412
  },
413
413
  {
414
414
  name: 'workspace_list_routines',
415
- description: 'List active routines in the current channel.',
415
+ description: 'List routines in the current channel, active and paused.',
416
416
  inputSchema: { type: 'object', properties: {} },
417
417
  },
418
+ {
419
+ name: 'workspace_update_routine',
420
+ description: 'Edit an existing routine instead of cancelling and recreating it (which would lose its id and run history). Only the fields you pass change. Use status to pause a routine and resume it later.',
421
+ inputSchema: {
422
+ type: 'object',
423
+ properties: {
424
+ routine_id: { type: 'string', description: 'Routine ID to edit (from workspace_list_routines)' },
425
+ name: { type: 'string', description: 'New human-readable label' },
426
+ message: { type: 'string', description: 'New trigger message. Changing it regenerates the routine context unless you also pass context.' },
427
+ context: { type: 'string', description: 'New comprehensive context posted each time the routine fires. Pass this whenever you change what the routine is for.' },
428
+ hour: { type: 'integer', description: 'Daily mode: hour in UTC (0-23). Omit if using interval_minutes.' },
429
+ minute: { type: 'integer', description: 'Daily mode: minute (0-59). Omit if using interval_minutes.' },
430
+ days: {
431
+ type: 'array',
432
+ items: { type: 'integer' },
433
+ description: 'Daily mode: days of week to fire (0=Mon, 6=Sun). Omit to keep the current days.',
434
+ },
435
+ interval_minutes: {
436
+ type: 'integer',
437
+ description: 'Interval mode: fire every N minutes (1-1440). Mutually exclusive with hour/minute.',
438
+ },
439
+ status: {
440
+ type: 'string',
441
+ enum: ['active', 'paused'],
442
+ description: 'Pause a routine (stops firing, stays listed) or resume it. Cancelling is workspace_cancel_routine.',
443
+ },
444
+ },
445
+ required: ['routine_id'],
446
+ },
447
+ },
418
448
  {
419
449
  name: 'workspace_cancel_routine',
420
450
  description: 'Cancel a recurring routine by its ID.',
@@ -1088,7 +1118,7 @@ class McpServer {
1088
1118
  case 'workspace_list_routines': {
1089
1119
  const data = await this.ws.listRoutines(this.workspaceId, this.channelName, this.token);
1090
1120
  const routines = (data && data.routines) || [];
1091
- if (!routines.length) return text('No active routines.');
1121
+ if (!routines.length) return text('No routines.');
1092
1122
  const lines = routines.map((r) => {
1093
1123
  let when;
1094
1124
  if (r.schedule_interval_minutes != null) {
@@ -1097,11 +1127,38 @@ class McpServer {
1097
1127
  when = `at ${String(r.schedule_hour).padStart(2,'0')}:${String(r.schedule_minute).padStart(2,'0')} UTC` +
1098
1128
  (r.schedule_days ? ` [days: ${r.schedule_days.join(',')}]` : ' (daily)');
1099
1129
  }
1100
- return `- ${r.id}: "${r.name}" ${when} — next: ${r.next_fires_at} (by ${r.created_by})`;
1130
+ const state = r.status && r.status !== 'active' ? ` [${r.status}]` : '';
1131
+ return `- ${r.id}: "${r.name}"${state} ${when} — next: ${r.next_fires_at} (by ${r.created_by})`;
1101
1132
  });
1102
1133
  return text(lines.join('\n'));
1103
1134
  }
1104
1135
 
1136
+ case 'workspace_update_routine': {
1137
+ const updated = await this.ws.updateRoutine(
1138
+ this.workspaceId, this.token, args.routine_id,
1139
+ {
1140
+ name: args.name,
1141
+ message: args.message,
1142
+ context: args.context,
1143
+ hour: args.hour,
1144
+ minute: args.minute,
1145
+ days: args.days,
1146
+ interval_minutes: args.interval_minutes,
1147
+ status: args.status,
1148
+ },
1149
+ );
1150
+ let when;
1151
+ if (updated.schedule_interval_minutes != null) {
1152
+ when = `every ${updated.schedule_interval_minutes} min`;
1153
+ } else {
1154
+ const daysStr = updated.schedule_days ? `days [${updated.schedule_days.join(',')}]` : 'every day';
1155
+ when = `at ${String(updated.schedule_hour).padStart(2,'0')}:${String(updated.schedule_minute).padStart(2,'0')} UTC, ${daysStr}`;
1156
+ }
1157
+ return text(
1158
+ `Routine updated: "${updated.name}" ${when} — status ${updated.status}, next: ${updated.next_fires_at} (id: ${updated.id})`,
1159
+ );
1160
+ }
1161
+
1105
1162
  case 'workspace_cancel_routine': {
1106
1163
  await this.ws.cancelRoutine(this.workspaceId, this.token, args.routine_id);
1107
1164
  return text(`Routine cancelled: ${args.routine_id}`);
@@ -970,6 +970,30 @@ class WorkspaceClient {
970
970
  return data.data || data;
971
971
  }
972
972
 
973
+ /**
974
+ * Edit a routine in place. Only the fields passed are changed; the schedule
975
+ * keeps the same either/or rule as creation (`interval_minutes`, or
976
+ * `hour`/`minute`/`days`). `status` is 'active' | 'paused' — cancelling
977
+ * still goes through `cancelRoutine`.
978
+ */
979
+ async updateRoutine(workspaceId, token, routineId, { name, message, context, hour, minute, days, interval_minutes, source, status } = {}) {
980
+ const body = { network: workspaceId };
981
+ if (name != null) body.name = name;
982
+ if (message != null) body.message = message;
983
+ if (context != null) body.context = context;
984
+ if (source != null) body.source = source;
985
+ if (status != null) body.status = status;
986
+ if (interval_minutes != null) {
987
+ body.interval_minutes = interval_minutes;
988
+ } else {
989
+ if (hour != null) body.hour = hour;
990
+ if (minute != null) body.minute = minute;
991
+ if (days != null) body.days = days;
992
+ }
993
+ const data = await this._patch(`/v1/routines/${routineId}`, body, this._wsHeaders(token));
994
+ return data.data || data;
995
+ }
996
+
973
997
  async cancelRoutine(workspaceId, token, routineId) {
974
998
  const data = await this._delete(`/v1/routines/${routineId}`, this._wsHeaders(token));
975
999
  return data.data || data;
@@ -1407,12 +1431,20 @@ class WorkspaceClient {
1407
1431
  try {
1408
1432
  const parsed = JSON.parse(data);
1409
1433
  if (res.statusCode >= 400) {
1410
- reject(new Error(parsed.message || `HTTP ${res.statusCode}`));
1434
+ const err = new Error(parsed.message || `HTTP ${res.statusCode}`);
1435
+ // Callers act on it: removeAgentFromWorkspace takes a 404 as
1436
+ // "already gone". Without it that check never matched, and an
1437
+ // agent whose membership was already removed could not be
1438
+ // deleted at all ("Member not found").
1439
+ err.status = res.statusCode;
1440
+ reject(err);
1411
1441
  } else {
1412
1442
  resolve(parsed);
1413
1443
  }
1414
1444
  } catch {
1415
- reject(new Error(`Invalid response: ${data.slice(0, 200)}`));
1445
+ const err = new Error(`Invalid response: ${data.slice(0, 200)}`);
1446
+ if (res.statusCode >= 400) err.status = res.statusCode;
1447
+ reject(err);
1416
1448
  }
1417
1449
  });
1418
1450
  });