@matatbread/matbot-background-jobs-node 0.4.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Mat Woolf
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,16 @@
1
+ # @matatbread/matbot-background-jobs-node
2
+
3
+ This is a [matbot](https://github.com/MatAtBread/matbot) plugin.
4
+
5
+ [`@matatbread/matbot-background-jobs`](../background-jobs), with each job run in its own process rather than in
6
+ this one. Same tools (`background_job`, `background_job_action`), same store, same meaning — a job reports by
7
+ appending to a conversation — so an install switches between the two by changing which one it loads.
8
+
9
+ A job's process is a full matbot booted from this one's config. It shares this process's storage and none of
10
+ its turns, so it never writes a session itself: its appends go back over an IPC channel to the process that
11
+ started it, which applies them when no turn is running. What else the job changes (a file it writes) is
12
+ announced there too, so the web UI shows it.
13
+
14
+ Why choose it: a job that hangs, spins or leaks can be killed outright, and nothing it does shares the
15
+ server's heap. Why not: every run pays a full boot — every plugin, every index — which an interval job pays on
16
+ every tick. Node only.
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@matatbread/matbot-background-jobs-node",
3
+ "matbotRuntime": [
4
+ "node"
5
+ ],
6
+ "version": "0.4.18",
7
+ "engines": {
8
+ "node": ">=24.0.0"
9
+ },
10
+ "files": [
11
+ "src"
12
+ ],
13
+ "description": "Node background jobs: @matatbread/matbot-background-jobs with each job run in its own process — a hard boundary that can be killed, at the cost of a full boot per run.",
14
+ "keywords": [
15
+ "matbot",
16
+ "matbot-plugin",
17
+ "llm",
18
+ "ai",
19
+ "agent"
20
+ ],
21
+ "license": "Apache-2.0",
22
+ "type": "module",
23
+ "exports": {
24
+ ".": "./src/index.ts"
25
+ },
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/MatAtBread/matbot.git",
29
+ "directory": "plugins/background-jobs-node"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "dependencies": {
35
+ "@matatbread/matbot-background-jobs": "^0.4.18"
36
+ },
37
+ "peerDependencies": {
38
+ "@matatbread/matbot-plugin-api": "^0.4.18"
39
+ },
40
+ "devDependencies": {
41
+ "@types/node": "^22.0.0",
42
+ "typescript": "^6.0.3",
43
+ "@matatbread/matbot-plugin-api": "^0.4.18"
44
+ },
45
+ "scripts": {
46
+ "typecheck": "tsc --noEmit"
47
+ }
48
+ }
package/src/channel.ts ADDED
@@ -0,0 +1,193 @@
1
+ import type { AppendMessage, AppendResult, NotifyInput, Principal } from '@matatbread/matbot-plugin-api';
2
+ import { ItemChangeKind } from '@matatbread/matbot-plugin-api';
3
+ import type { JobInfo } from '@matatbread/matbot-background-jobs';
4
+ export type { JobInfo };
5
+
6
+ // The protocol between a job and the process that spawned it, over Node's IPC channel. A job shares
7
+ // its parent's storage medium but none of its parent's turns, so it must not write a session itself;
8
+ // it asks. The channel is per child, so who is asking needs no token: the parent knows which job it
9
+ // spawned on the other end.
10
+
11
+
12
+ /** Job → parent. A request carries `rid` and is answered; a `notify` is fire-and-forget. */
13
+ export type ChildMessage =
14
+ | { op: 'job'; rid: number }
15
+ | { op: 'append'; rid: number; sessionId?: string; messages: AppendMessage[] }
16
+ | { op: 'notify'; notification: unknown };
17
+
18
+ /** Parent → job: the answer to one request. */
19
+ export type ParentMessage =
20
+ | { rid: number; ok: true; value: unknown }
21
+ | { rid: number; ok: false; error: string };
22
+
23
+ /** One end of the channel as far as this protocol uses it: the `ChildProcess` on the parent's side,
24
+ * `process` on the job's. Narrowed so a test can drive both ends without spawning anything. */
25
+ export interface Endpoint {
26
+ send(message: unknown, callback: (error: Error | null) => void): unknown;
27
+ on(event: 'message', listener: (message: unknown) => void): unknown;
28
+ }
29
+
30
+ export interface JobHandlers {
31
+ info(): Promise<JobInfo>;
32
+ append(sessionId: string | undefined, messages: AppendMessage[]): Promise<AppendResult>;
33
+ notify(notification: unknown): void;
34
+ }
35
+
36
+ const errorText = (e: unknown): string => e instanceof Error ? e.message : String(e);
37
+
38
+ /** The parent's side: answer one job's requests for as long as its channel is open. */
39
+ export function serveJob(child: Endpoint, handlers: JobHandlers): void {
40
+ // A reply to a job that has already gone has nowhere to go, and that is not this side's failure.
41
+ const reply = (message: ParentMessage): void => { try { child.send(message, () => {}); } catch { /* gone */ } };
42
+ child.on('message', raw => {
43
+ // A job is a separate program: what arrives is checked here, at the boundary, not trusted.
44
+ if (typeof raw !== 'object' || raw === null) return;
45
+ const msg = raw as { op?: unknown; rid?: unknown; sessionId?: unknown; messages?: unknown; notification?: unknown };
46
+ if (msg.op === 'notify') { handlers.notify(msg.notification); return; }
47
+ if (typeof msg.rid !== 'number') return;
48
+ const rid = msg.rid;
49
+ const answer = (work: Promise<unknown>): void => {
50
+ work.then(value => reply({ rid, ok: true, value }), (e: unknown) => reply({ rid, ok: false, error: errorText(e) }));
51
+ };
52
+ switch (msg.op) {
53
+ case 'job':
54
+ answer(handlers.info());
55
+ return;
56
+ case 'append': {
57
+ const sessionId = typeof msg.sessionId === 'string' ? msg.sessionId : undefined;
58
+ answer(Promise.resolve().then(() => handlers.append(sessionId, jobText(msg.messages))));
59
+ return;
60
+ }
61
+ default:
62
+ reply({ rid, ok: false, error: `Unknown request "${String(msg.op)}".` });
63
+ }
64
+ });
65
+ }
66
+
67
+ // What a job may say: assistant text and nothing else. It speaks for itself — never as the user, and
68
+ // never with metadata of its own, which the parent supplies.
69
+ function jobText(raw: unknown): AppendMessage[] {
70
+ if (!Array.isArray(raw) || raw.length === 0) throw new Error('Nothing to append.');
71
+ return raw.map((m: unknown) => {
72
+ const msg = m as { role?: unknown; content?: unknown };
73
+ if (msg.role !== 'assistant') throw new Error('A background job may append only assistant messages.');
74
+ if (!Array.isArray(msg.content) || msg.content.length === 0) throw new Error('An appended message needs content.');
75
+ return {
76
+ role: 'assistant',
77
+ content: msg.content.map((c: unknown) => {
78
+ const block = c as { type?: unknown; text?: unknown };
79
+ if (block.type !== 'text' || typeof block.text !== 'string') throw new Error('An appended message may carry text only.');
80
+ return { type: 'text' as const, text: block.text, origin: 'robo' as const };
81
+ }),
82
+ };
83
+ });
84
+ }
85
+
86
+ export interface ParentLink {
87
+ request<T>(message: { op: 'job' } | { op: 'append'; sessionId?: string; messages: AppendMessage[] }): Promise<T>;
88
+ /** Fire-and-forget. Tracked, so {@link flush} can wait for it before the job exits. */
89
+ post(message: { op: 'notify'; notification: unknown }): void;
90
+ /** Settles once every {@link post} has been handed to the channel (or failed). */
91
+ flush(): Promise<void>;
92
+ /** The channel is gone: fail whatever is still waiting on an answer. */
93
+ close(reason: string): void;
94
+ }
95
+
96
+ /** A channel's handle (`process.channel`): whether it keeps the event loop alive. */
97
+ export interface Holdable { ref(): void; unref(): void }
98
+
99
+ /**
100
+ * The job's side.
101
+ *
102
+ * The channel is held exactly while something is outstanding — an answer awaited, a send not yet
103
+ * handed over — and released otherwise. Released for good, a job waiting on its parent's answer has
104
+ * nothing keeping it alive and exits mid-request (measured: "unsettled top-level await", exit 13); held
105
+ * for good, a job whose turn has ended never exits at all.
106
+ */
107
+ export function connectToParent(parent: Endpoint, handle?: Holdable): ParentLink {
108
+ let next = 0;
109
+ const waiting = new Map<number, { resolve: (v: unknown) => void; reject: (e: Error) => void }>();
110
+ const inFlight = new Set<Promise<void>>();
111
+ let closed: string | undefined;
112
+ let outstanding = 0;
113
+ const hold = (): void => { if (outstanding++ === 0) handle?.ref(); };
114
+ const release = (): void => { if (outstanding > 0 && --outstanding === 0) handle?.unref(); };
115
+ handle?.unref();
116
+
117
+ parent.on('message', raw => {
118
+ const msg = raw as Partial<ParentMessage>;
119
+ if (typeof msg.rid !== 'number') return;
120
+ const w = waiting.get(msg.rid);
121
+ if (!w) return;
122
+ waiting.delete(msg.rid);
123
+ if (msg.ok === true) w.resolve((msg as { value: unknown }).value);
124
+ else w.reject(new Error((msg as { error?: string }).error ?? 'The parent refused the request.'));
125
+ });
126
+
127
+ // `send` on a closed channel reports through its callback rather than throwing — and returns false,
128
+ // which is NOT a capability check: the callback is the only honest answer.
129
+ const send = (message: ChildMessage): Promise<void> => new Promise((resolve, reject) => {
130
+ if (closed !== undefined) { reject(new Error(closed)); return; }
131
+ try { parent.send(message, err => (err ? reject(err) : resolve())); }
132
+ catch (e) { reject(e instanceof Error ? e : new Error(String(e))); }
133
+ });
134
+
135
+ return {
136
+ request<T>(message: { op: 'job' } | { op: 'append'; sessionId?: string; messages: AppendMessage[] }): Promise<T> {
137
+ const rid = ++next;
138
+ hold();
139
+ const answered = new Promise<T>((resolve, reject) => {
140
+ waiting.set(rid, { resolve: v => resolve(v as T), reject });
141
+ send({ ...message, rid } as ChildMessage).catch((e: unknown) => {
142
+ waiting.delete(rid);
143
+ reject(e instanceof Error ? e : new Error(String(e)));
144
+ });
145
+ });
146
+ void answered.then(release, release);
147
+ return answered;
148
+ },
149
+ post(message) {
150
+ hold();
151
+ const sent = send(message).catch(() => { /* a lost announcement is a stale panel, not an error */ });
152
+ inFlight.add(sent);
153
+ void sent.finally(() => { inFlight.delete(sent); release(); });
154
+ },
155
+ async flush() {
156
+ await Promise.allSettled([...inFlight]);
157
+ },
158
+ close(reason) {
159
+ closed = reason;
160
+ for (const w of waiting.values()) w.reject(new Error(reason));
161
+ waiting.clear();
162
+ },
163
+ };
164
+ }
165
+
166
+ /**
167
+ * A job's announcement, as the parent may republish it — or `undefined` if it may not.
168
+ *
169
+ * Only `ItemChange` crosses: "the item at (namespace, id) changed", which holds for the parent too, since
170
+ * the job wrote the store they share. A registry change describes the JOB's own process — every job
171
+ * registers its tools at boot — and relayed it would rebuild the parent's type index and tool search on
172
+ * every spawn. Any other kind has no known meaning outside the job. One already carrying an `instance`
173
+ * was relayed once; passing it on again is the loop that field exists to break.
174
+ */
175
+ export function relayable(raw: unknown, instance: string): NotifyInput | undefined {
176
+ if (typeof raw !== 'object' || raw === null) return undefined;
177
+ const n = raw as Record<string, unknown>;
178
+ if (n['kind'] !== ItemChangeKind || n['instance'] !== undefined) return undefined;
179
+ const { plugin, source, namespace, id, operation, key, detail, principal } = n;
180
+ if (typeof plugin !== 'string' || typeof source !== 'string' || typeof namespace !== 'string' || typeof id !== 'string') return undefined;
181
+ if (operation !== 'saved' && operation !== 'deleted') return undefined;
182
+ return {
183
+ kind: ItemChangeKind, plugin, source, namespace, id, operation, instance,
184
+ ...(typeof key === 'string' ? { key } : {}),
185
+ ...(detail !== undefined ? { detail } : {}),
186
+ ...(isPrincipal(principal) ? { principal } : {}),
187
+ };
188
+ }
189
+
190
+ function isPrincipal(v: unknown): v is Principal {
191
+ return typeof v === 'object' && v !== null
192
+ && typeof (v as { id?: unknown }).id === 'string' && typeof (v as { type?: unknown }).type === 'string';
193
+ }
package/src/index.ts ADDED
@@ -0,0 +1,191 @@
1
+ import { spawn, type ChildProcess } from 'node:child_process';
2
+ import { execArgv, argv, execPath } from 'node:process';
3
+ import { resolve, dirname } from 'node:path';
4
+ import { existsSync } from 'node:fs';
5
+ import { pathToFileURL } from 'node:url';
6
+ import type { MatbotMachine, MatbotPluginSpec, AppendResult } from '@matatbread/matbot-plugin-api';
7
+ import { ItemChangeKind } from '@matatbread/matbot-plugin-api';
8
+ import {
9
+ createBackgroundJobsPlugin, appendFor, jobContext, jobInfo, REPLY_TAIL,
10
+ type JobInfo, type JobRunner, type RunOutcome, type RunSpec,
11
+ } from '@matatbread/matbot-background-jobs';
12
+ import { connectToParent, relayable, serveJob, type Endpoint, type ParentLink } from './channel.js';
13
+
14
+ // `matbot-background-jobs` with each job run in a child process of its own: a full matbot booted from
15
+ // this one's config, which shares its storage and none of its turns. The process is the boundary — a job
16
+ // that hangs or leaks can be killed outright, and nothing it does touches this process's heap — at the
17
+ // cost of a whole boot per run. The child never writes a session itself; it asks over an IPC channel,
18
+ // and what it changes elsewhere is announced back over the same channel.
19
+
20
+ // When true, jobs run in a new process group and survive the parent exiting.
21
+ const DETACH_JOBS = false;
22
+
23
+ // Relative path args (--import, --require, --loader) resolve against the CWD at launch time, which may
24
+ // differ from dirname(argv[1]). Walk up from the script directory until we find the file, then emit a
25
+ // file:// URL so the child resolves it regardless of its own CWD.
26
+ function absoluteExecArgv(scriptPath: string): string[] {
27
+ return execArgv.map((arg, i, arr) => {
28
+ const prev = arr[i - 1];
29
+ if (prev !== undefined && ['--import', '--require', '--loader'].includes(prev)) {
30
+ if (arg.startsWith('./') || arg.startsWith('../')) {
31
+ let dir = dirname(scriptPath);
32
+ while (true) {
33
+ const candidate = resolve(dir, arg);
34
+ if (existsSync(candidate)) return pathToFileURL(candidate).href;
35
+ const parent = dirname(dir);
36
+ if (parent === dir) break;
37
+ dir = parent;
38
+ }
39
+ }
40
+ }
41
+ return arg;
42
+ });
43
+ }
44
+
45
+ function buildJobConfig(configPath: string, prompt: string, provider?: string): string {
46
+ const escapedPath = configPath.replace(/'/g, "''");
47
+ const indented = prompt.split('\n').map(l => ' ' + l).join('\n');
48
+ const providerLine = provider !== undefined ? `default_provider: '${provider.replace(/'/g, "''")}'\n` : '';
49
+ return `extends: '${escapedPath}'\nephemeral: true\n${providerLine}prompt: |\n${indented}\n`;
50
+ }
51
+
52
+ // What a job changed, republished here: the job wrote the shared store, so a reader here re-reading
53
+ // finds it, but the announcement went to the job's own bus — which nobody here listens to.
54
+ function relay(machine: MatbotMachine, job: RunSpec, raw: unknown): void {
55
+ const n = relayable(raw, `job:${job.id}`);
56
+ if (n !== undefined) machine.Notifier.notify(n);
57
+ }
58
+
59
+ /**
60
+ * Feed a job process its config and wait for it to end. The result is the reason it never started, if
61
+ * that is how it ended.
62
+ *
63
+ * Both `error` listeners matter. A process that cannot be spawned (EAGAIN under load, a vanished
64
+ * executable) reports it only as `error` on the child, and with no listener that event throws in the
65
+ * parent, taking the server down with it. Its stdin then fails the write with EPIPE, which is likewise
66
+ * fatal unheard. And `exit` may never follow, so waiting for `exit` alone would hang the run for good.
67
+ * An `error` from a child that did start (a failed kill, a send to a closed channel) does not end it, so
68
+ * that wait goes on.
69
+ */
70
+ export function superviseChild(child: ChildProcess, input: string): Promise<Error | undefined> {
71
+ const ended = new Promise<Error | undefined>(resolve => {
72
+ child.once('exit', () => resolve(undefined));
73
+ child.on('error', e => { if (child.pid === undefined) resolve(e); });
74
+ });
75
+ child.stdin?.on('error', () => { /* reported as the child's own error or exit */ });
76
+ child.stdin?.end(input);
77
+ return ended;
78
+ }
79
+
80
+ function spawnRunner(machine: MatbotMachine): JobRunner | undefined {
81
+ const configPath = machine.configPath;
82
+ const script = argv[1];
83
+ if (configPath === undefined || script === undefined) {
84
+ console.warn('[background-jobs] no config path or entry script to spawn a job from, so no job can run here.');
85
+ return undefined;
86
+ }
87
+
88
+ return {
89
+ async run(job: RunSpec, signal: AbortSignal): Promise<RunOutcome | undefined> {
90
+ const child = spawn(
91
+ execPath,
92
+ [...absoluteExecArgv(script), script, '--config', '-'],
93
+ {
94
+ detached: DETACH_JOBS,
95
+ // stdin carries the job's config, the fourth fd the channel back to this process.
96
+ stdio: ['pipe', 'pipe', 'inherit', 'ipc'],
97
+ // The env channel carries process identity/mode; the piped config (stdin) carries the task.
98
+ // IS_SUB_AGENT stops the job arming a scheduler of its own; MATBOT_PRINCIPAL delegates the
99
+ // creator's identity so the job runs as them.
100
+ env: {
101
+ ...process.env,
102
+ IS_SUB_AGENT: '1',
103
+ ...(job.principal !== undefined ? { MATBOT_PRINCIPAL: JSON.stringify(job.principal) } : {}),
104
+ },
105
+ },
106
+ );
107
+ if (!child.stdin) return undefined;
108
+ const ended = superviseChild(child, buildJobConfig(configPath, job.prompt, job.provider));
109
+
110
+ let tail = '';
111
+ child.stdout?.setEncoding('utf8');
112
+ child.stdout?.on('data', (chunk: string) => { tail = (tail + chunk).slice(-REPLY_TAIL); });
113
+
114
+ let appended = 0;
115
+ serveJob(child as unknown as Endpoint, {
116
+ info: () => jobInfo(machine, job),
117
+ append: async (sessionId, messages) => {
118
+ const result = await appendFor(machine, job, sessionId, messages);
119
+ appended += result.messageIds.length;
120
+ return result;
121
+ },
122
+ notify: n => relay(machine, job, n),
123
+ });
124
+
125
+ // The IPC channel holds the event loop open on its own, so `child.unref()` alone stops working once
126
+ // it exists — a parent with nothing else to do would wait for every job. Measured: 5.1s held versus
127
+ // 72ms released. Unref'ing it does not stop delivery while this process is alive for its own reasons.
128
+ child.channel?.unref();
129
+ (child.stdout as { unref?: () => void } | null)?.unref?.();
130
+ child.unref();
131
+
132
+ const kill = (): void => { child.kill(); };
133
+ signal.addEventListener('abort', kill, { once: true });
134
+ const failed = await ended;
135
+ signal.removeEventListener('abort', kill);
136
+ // Not a rejection: a scheduled job's loop would end on one, and this failure may not recur.
137
+ if (failed !== undefined) {
138
+ console.error(`[background-jobs] job ${job.name ?? job.id} could not start its process: ${failed.message}`);
139
+ return undefined;
140
+ }
141
+ return { appended, reply: tail.trim() };
142
+ },
143
+ };
144
+ }
145
+
146
+ // ── The job's side ────────────────────────────────────────────────────────────
147
+
148
+ // The job's side of its channel, when this process IS a job.
149
+ let parentLink: ParentLink | undefined;
150
+
151
+ async function setupJob(services: MatbotMachine, signal: AbortSignal): Promise<void> {
152
+ // Spawned by something else — the plugin this replaces, or by hand — there is no channel, and so no
153
+ // way to report: the host's appender keeps refusing, which is the honest answer.
154
+ if (typeof process.send !== 'function' || !process.connected) return;
155
+ // Held only while a request or a send is outstanding (see connectToParent): held for good, it would
156
+ // keep this process alive after its turn has ended; released for good, it would let it exit mid-request.
157
+ const link = connectToParent(process as unknown as Endpoint, process.channel);
158
+ parentLink = link;
159
+ process.once('disconnect', () => link.close('The process that started this job has gone.'));
160
+
161
+ let job: JobInfo;
162
+ try { job = await link.request<JobInfo>({ op: 'job' }); }
163
+ catch { return; }
164
+
165
+ await services.register('SessionAppender', {
166
+ ...(job.session !== undefined ? { defaultSessionId: job.session } : {}),
167
+ append: (sessionId, messages) => link.request<AppendResult>({
168
+ op: 'append', ...(sessionId !== undefined ? { sessionId } : {}), messages: [...messages],
169
+ }),
170
+ });
171
+ services.systemContext.register(() => jobContext(job));
172
+ // What this job changes, announced where someone is listening. Locally produced only — a relayed one
173
+ // carries an `instance`, and relaying it back would be the loop the field exists to break.
174
+ services.Notifier.consume(
175
+ n => link.post({ op: 'notify', notification: n }),
176
+ signal,
177
+ n => n.kind === ItemChangeKind && n.instance === undefined,
178
+ );
179
+ }
180
+
181
+ export const plugin: MatbotPluginSpec = createBackgroundJobsPlugin({
182
+ description: 'Background jobs — now, at a time, or on an interval — that report into a conversation by appending to it. '
183
+ + 'Each job runs in its own process: it can be killed and shares no heap with the server, at the cost of a full boot per run.',
184
+ runner: spawnRunner,
185
+ inJob: setupJob,
186
+ // A job's last announcements are still in the channel when its turn ends; let them go before it exits.
187
+ async teardown() {
188
+ await parentLink?.flush();
189
+ parentLink = undefined;
190
+ },
191
+ });