@matatbread/matbot-parallel-map-reduce 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +55 -2
  3. package/package.json +42 -3
  4. package/src/index.ts +226 -0
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 CHANGED
@@ -1,3 +1,56 @@
1
- # Temporary Holding Version
1
+ # @matatbread/matbot-parallel-map-reduce
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ This is a [matbot](https://github.com/MatAtBread/matbot) plugin.
4
+
5
+ `parallel_map_reduce` asks one question of each item of a set, each as its own sub-agent turn (`single_turn`),
6
+ run concurrently, and has the conversation combine the answers in a later turn (Node and browser).
7
+
8
+ ```json
9
+ { "mapPrompt": "Which Node version does the repository below target? Look at package.json, .nvmrc and CI config. Reply with the version and the file that says so.",
10
+ "items": ["/repos/api-server", "/repos/web"],
11
+ "reducePrompt": "List the repositories above still on Node 18 or older, and what to change in each." }
12
+ ```
13
+
14
+ Each turn is asked `mapPrompt`, then its item, and sees nothing else: whatever a turn should know about the
15
+ wider task belongs in `mapPrompt`. An item is text, or `{ "attach": "<attachment id>" }` for a file to look
16
+ at (an attachment of the conversation, or with `tools: false` a stored file by name). Every turn opens with
17
+ the same text, so a provider's prompt cache serves the shared part. For hundreds of items, build the list in
18
+ code rather than writing it out:
19
+
20
+ ```ts
21
+ const s = await tool.session_action({ action: 'list' });
22
+ return tool.parallel_map_reduce({
23
+ mapPrompt: 'Read the conversation named below and suggest 1–3 topic tags. Reply with the tags only.',
24
+ items: s.items.map(x => `Session ID: ${x.id}`),
25
+ reducePrompt: 'Group the conversations above by their tags.',
26
+ });
27
+ ```
28
+
29
+ It returns at once with `{ wave, started, session }`. The answers do not come back to the caller:
30
+
31
+ - As each turn finishes, its answer is appended to the conversation as `[w-ab3k 2/2 /repos/web] …`, named by
32
+ its item (shortened to 60 characters; the index tells two alike apart). A failed turn is appended too, so
33
+ a missing answer is never mistaken for one that was not asked.
34
+ - Once every turn has answered, `reducePrompt` is asked in the conversation (a robo-submit, `queue`),
35
+ prefixed with the tally — `[w-ab3k: 2 of 2 answered]`, or which items failed. It is answered with every
36
+ answer in front of it, so ask the map turns for short answers.
37
+
38
+ The conversation is the buffer: the reduce turn reads the answers as history, and retrieves nothing.
39
+
40
+ - **`tools`** defaults to true, because a map turn exists to do reading the caller should not: a turn told to
41
+ read a file it cannot open answers from nothing. `false` makes each turn one request with no tools.
42
+ - **`session`** names the conversation to report to. By default it is the one the call is made from, or for
43
+ a background job the conversation it was created with. A call with no conversation of its own (the HTTP
44
+ tool door) must name one.
45
+ - **`concurrency`**: how many of a wave's turns run at once (default 4); the rest wait. They share the
46
+ provider's rate limits, so more at once can mean more refused calls rather than a faster wave.
47
+ - **Stopping**: the turns run under the calling turn's signal, so stopping that turn stops the wave. What
48
+ finished stays in the conversation, a line says the wave stopped, and the reduce is not asked.
49
+
50
+ Use it when each item needs reading or work far larger than its answer. Not for items that constrain one
51
+ another (an itinerary, a budget, a single argument), and not for a few small items a model can answer
52
+ directly. Where an answer is mechanical (a field read from a templated document), a `tool_function` body
53
+ that extracts it in code is cheaper still.
54
+
55
+ What a sub-turn's tools record as markers (`session_data`, a session function) is not kept: the call that
56
+ could carry them into the session has returned before the turns finish.
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@matatbread/matbot-parallel-map-reduce",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "matbotRuntime": [
4
+ "node",
5
+ "browser"
6
+ ],
7
+ "version": "0.5.0",
8
+ "engines": {
9
+ "node": ">=24.0.0"
10
+ },
11
+ "files": [
12
+ "src"
13
+ ],
14
+ "description": "Put one question to each item of a set as concurrent sub-agent turns, append each answer to the conversation, then ask it to combine them.",
15
+ "keywords": [
16
+ "matbot",
17
+ "matbot-plugin",
18
+ "llm",
19
+ "ai",
20
+ "agent"
21
+ ],
22
+ "license": "Apache-2.0",
23
+ "type": "module",
24
+ "exports": {
25
+ ".": "./src/index.ts"
26
+ },
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/MatAtBread/matbot.git",
30
+ "directory": "plugins/parallel-map-reduce"
31
+ },
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "peerDependencies": {
36
+ "@matatbread/matbot-plugin-api": "^0.5.0"
37
+ },
38
+ "devDependencies": {
39
+ "typescript": "^6.0.3",
40
+ "@matatbread/matbot-plugin-api": "^0.5.0"
41
+ },
42
+ "scripts": {
43
+ "typecheck": "tsc --noEmit"
44
+ }
6
45
  }
package/src/index.ts ADDED
@@ -0,0 +1,226 @@
1
+ import type { MatbotMachine, MatbotPluginSpec, SessionAppender, Tool, ToolContext, ToolContract } from '@matatbread/matbot-plugin-api';
2
+ import { invokeTool, PLUGIN_API_VERSION, toolResult } from '@matatbread/matbot-plugin-api';
3
+
4
+ export const TOOL_NAME = 'parallel_map_reduce';
5
+
6
+ /** How many of a wave's turns run at once unless the call says (`concurrency`); the rest wait for a free
7
+ * slot. They share a provider's rate limits, so a larger wave takes longer rather than failing. Per wave. */
8
+ export const MAX_CONCURRENT_TURNS = 4;
9
+
10
+ /** What one turn is asked about, after `mapPrompt`: text, or a file for it to look at. */
11
+ export type MapItem = string | { attach: string };
12
+
13
+ export interface ParallelMapReduce {
14
+ mapPrompt: string;
15
+ items: MapItem[];
16
+ reducePrompt: string;
17
+ tools?: boolean;
18
+ provider?: string;
19
+ session?: string;
20
+ concurrency?: number;
21
+ }
22
+
23
+ export interface WaveStarted {
24
+ wave: string;
25
+ started: number;
26
+ session: string;
27
+ }
28
+
29
+ declare module '@matatbread/matbot-plugin-api' {
30
+ interface ToolContracts {
31
+ parallel_map_reduce: ToolContract<WaveStarted, ParallelMapReduce>;
32
+ }
33
+ }
34
+
35
+ // Sent with every turn, so it says what decides the call. Probed on DeepSeek and Gemini beside the same
36
+ // guidance written as a pattern in tool_function's description: the tool was used where each item needed a
37
+ // model to read it, the pattern hardly at all, and neither for the trivial or coupled prompts. Gemini left
38
+ // `tools` out of every call whose turns had to read a file, which is why it defaults to true here.
39
+ export const DESCRIPTION =
40
+ 'Put the same question to each item of a set, each as its own sub-agent turn, run concurrently, then ' +
41
+ 'combine the answers in a later turn of this conversation. It returns at once: the answers do NOT come ' +
42
+ 'back to you. Each turn is asked `mapPrompt` followed by its item, and sees nothing else, so say in ' +
43
+ '`mapPrompt` what the answers are for. As each turn finishes, its answer is appended to this conversation ' +
44
+ '(a failure is appended too); once every turn has answered, `reducePrompt` is asked here as a new request, ' +
45
+ 'answered with all the answers in front of it and a count of how many arrived. Your turn can end ' +
46
+ 'meanwhile. Each turn can act with your tools unless `tools` is false. Every answer is read by the reduce, ' +
47
+ 'so ask for a short one. An item is text, or { "attach": "<attachment id>" } for a file to look at; for ' +
48
+ 'hundreds of items, build `items` in code rather than writing them out.\n' +
49
+ 'Use it when each item needs reading or work far larger than its answer — many conversations, documents ' +
50
+ 'or sites — so doing them here would flood this conversation or take too long. Not for items that ' +
51
+ 'constrain one another (an itinerary, a budget, a single argument): those need one mind. Not for a few ' +
52
+ 'small items you can answer directly.\n' +
53
+ '"Which of my repositories still use Node 18?":\n' +
54
+ ' { "mapPrompt": "Which Node version does the repository below target? Look at package.json, .nvmrc and CI config. Reply with the version and the file that says so.",\n' +
55
+ ' "items": ["/repos/api-server", "/repos/web", …],\n' +
56
+ ' "reducePrompt": "List the repositories above still on Node 18 or older, and what to change in each." }';
57
+
58
+ const FIELDS = new Set(['mapPrompt', 'items', 'reducePrompt', 'tools', 'provider', 'session', 'concurrency']);
59
+
60
+ // Validators are optional and a minimal install has none, so this is the boundary for that install.
61
+ function refusal(input: unknown): string | undefined {
62
+ if (input === null || typeof input !== 'object' || Array.isArray(input)) return 'parallel_map_reduce takes { "mapPrompt": "…", "items": ["…", …], "reducePrompt": "…" }.';
63
+ const a = input as Record<string, unknown>;
64
+ const stray = Object.keys(a).find(k => !FIELDS.has(k));
65
+ if (stray !== undefined) return `Unknown field "${stray}". It takes mapPrompt, items, reducePrompt, tools, provider, session and concurrency.`;
66
+ if (typeof a['mapPrompt'] !== 'string' || a['mapPrompt'].trim() === '') return '"mapPrompt" is what each turn is asked, followed by its item: a non-empty string.';
67
+ if (typeof a['reducePrompt'] !== 'string' || a['reducePrompt'].trim() === '') return '"reducePrompt" is the request to ask once every turn has answered: a non-empty string.';
68
+ for (const k of ['provider', 'session'] as const) {
69
+ if (a[k] !== undefined && typeof a[k] !== 'string') return `"${k}" is a string.`;
70
+ }
71
+ if (a['tools'] !== undefined && typeof a['tools'] !== 'boolean') return '"tools" is true or false.';
72
+ if (a['concurrency'] !== undefined && !(Number.isInteger(a['concurrency']) && (a['concurrency'] as number) >= 1)) {
73
+ return `"concurrency" is how many turns run at once: a whole number, 1 or more (default ${MAX_CONCURRENT_TURNS}).`;
74
+ }
75
+ if (!Array.isArray(a['items']) || a['items'].length === 0) return '"items" is a list of at least one item.';
76
+ for (const [i, item] of a['items'].entries()) {
77
+ if (typeof item === 'string') {
78
+ if (item.trim() === '') return `Item ${i + 1} is empty.`;
79
+ continue;
80
+ }
81
+ const ok = item !== null && typeof item === 'object' && !Array.isArray(item)
82
+ && Object.keys(item).length === 1 && typeof (item as { attach?: unknown }).attach === 'string' && (item as { attach: string }).attach !== '';
83
+ if (!ok) return `Item ${i + 1} is neither text nor { "attach": "<attachment id>" }.`;
84
+ }
85
+ return undefined;
86
+ }
87
+
88
+ const WAVE_ALPHABET = 'abcdefghijkmnpqrstuvwxyz23456789'; // no l/1/o/0: a wave id is read back by a model
89
+ function waveId(): string {
90
+ const bytes = crypto.getRandomValues(new Uint8Array(4));
91
+ return 'w-' + [...bytes].map(b => WAVE_ALPHABET[b % WAVE_ALPHABET.length]).join('');
92
+ }
93
+
94
+ const LABEL_CHARS = 60;
95
+ // An item names its own answer: in its row, and in the tally if it failed. Its index tells two alike apart.
96
+ function labelOf(item: MapItem): string {
97
+ const text = (typeof item === 'string' ? item : item.attach).replace(/\s+/g, ' ').trim();
98
+ return text.length > LABEL_CHARS ? text.slice(0, LABEL_CHARS - 1) + '…' : text;
99
+ }
100
+
101
+ const NAMED_FAILURES = 10;
102
+ function failures(labels: readonly string[]): string {
103
+ if (labels.length === 0) return '';
104
+ const more = labels.length - NAMED_FAILURES;
105
+ return `; failed: ${labels.slice(0, NAMED_FAILURES).join(', ')}${more > 0 ? ` and ${more} more` : ''}`;
106
+ }
107
+
108
+ const message = (e: unknown): string => (e instanceof Error ? e.message : String(e));
109
+ const said = (text: string) => [{ role: 'assistant' as const, content: [{ type: 'text' as const, text, origin: 'robo' as const }] }];
110
+
111
+ /**
112
+ * The wave, run after the call has returned. Completion is causal: the reduce is asked from the settling of
113
+ * the appends themselves, so it cannot start before them, and `queue` makes it wait for a turn still running
114
+ * there, whose end writes any append that turn deferred. Nothing here may reject: the call that started it
115
+ * has returned, so a rejection would have nobody to reach.
116
+ */
117
+ async function runWave(
118
+ machine: MatbotMachine,
119
+ ctx: ToolContext,
120
+ appender: SessionAppender,
121
+ target: string,
122
+ wave: string,
123
+ args: ParallelMapReduce,
124
+ ): Promise<void> {
125
+ const n = args.items.length;
126
+ const failed: string[] = [];
127
+ let answered = 0;
128
+ let next = 0;
129
+ const tools = args.tools ?? true;
130
+
131
+ const one = async (i: number): Promise<void> => {
132
+ const item = args.items[i]!;
133
+ const label = labelOf(item);
134
+ const head = `[${wave} ${i + 1}/${n} ${label}]`;
135
+ let text: string;
136
+ try {
137
+ // The prompt leads and the item follows it, so every turn of the wave opens with the same text.
138
+ const turn: { prompt: string; tools: boolean; attach?: string[]; provider?: string } = typeof item === 'string'
139
+ ? { prompt: `${args.mapPrompt}\n\n${item}`, tools }
140
+ : { prompt: args.mapPrompt, attach: [item.attach], tools };
141
+ if (args.provider !== undefined) turn.provider = args.provider;
142
+ const result = await toolResult(invokeTool(machine, 'single_turn', turn, ctx));
143
+ const answer = (result as { text?: unknown } | null)?.text;
144
+ text = `${head} ${typeof answer === 'string' ? answer : JSON.stringify(result)}`;
145
+ answered++;
146
+ } catch (e) {
147
+ failed.push(label);
148
+ text = `${head} failed: ${message(e)}`;
149
+ }
150
+ try { await appender.append(target, said(text)); }
151
+ catch (e) { console.error(`[parallel_map_reduce] ${wave}: could not append the answer for item ${i + 1} to ${target}: ${message(e)}`); }
152
+ };
153
+
154
+ const worker = async (): Promise<void> => {
155
+ for (let i = next++; i < n && !ctx.signal.aborted; i = next++) await one(i);
156
+ };
157
+ await Promise.all(Array.from({ length: Math.min(args.concurrency ?? MAX_CONCURRENT_TURNS, n) }, worker));
158
+
159
+ try {
160
+ // Stopped by the person: what finished is in the conversation, and nothing more is started on their behalf.
161
+ if (ctx.signal.aborted) {
162
+ await appender.append(target, said(`[${wave}: stopped, ${answered} of ${n} answered]`));
163
+ return;
164
+ }
165
+ await appender.append(target, [{
166
+ role: 'user', mode: 'queue', from: `parallel_map_reduce wave ${wave}`,
167
+ content: [{ type: 'text', text: `[${wave}: ${answered} of ${n} answered${failures(failed)}] ${args.reducePrompt}`, origin: 'robo' }],
168
+ }]);
169
+ } catch (e) {
170
+ console.error(`[parallel_map_reduce] ${wave}: could not ask for the reduce in ${target}: ${message(e)}`);
171
+ }
172
+ }
173
+
174
+ export function makeParallelMapReduceTool(machine: MatbotMachine): Tool<WaveStarted> {
175
+ return {
176
+ name: TOOL_NAME,
177
+ description: DESCRIPTION,
178
+ inputSchema: {
179
+ type: 'object',
180
+ required: ['mapPrompt', 'items', 'reducePrompt'],
181
+ properties: {
182
+ mapPrompt: { type: 'string', description: 'Asked of every item: each turn sees this, then its item, and nothing else.' },
183
+ items: {
184
+ type: 'array', minItems: 1, description: 'One sub-agent turn per item, run concurrently. An item also names its answer.',
185
+ items: { anyOf: [
186
+ { type: 'string' },
187
+ { type: 'object', required: ['attach'], properties: { attach: { type: 'string', description: 'An attachment id from this conversation, or (with tools false) a stored file name.' } } },
188
+ ] },
189
+ },
190
+ reducePrompt: { type: 'string', description: 'Asked in this conversation once every turn has answered, with their answers in front of it. Write it to stand alone.' },
191
+ tools: { type: 'boolean', description: 'Default true: each turn is a full agent turn that can act with your tools. false: one request with no tools, when mapPrompt and the item hold everything it needs.' },
192
+ provider: { type: 'string', description: 'A configured provider for the turns. Default: the current one.' },
193
+ session: { type: 'string', description: 'The conversation to append to and ask in. Default: this one.' },
194
+ concurrency: { type: 'integer', minimum: 1, description: `How many turns run at once; the rest wait. Default ${MAX_CONCURRENT_TURNS}. They share the provider's rate limits.` },
195
+ },
196
+ },
197
+ executor: {
198
+ async *execute(input: unknown, ctx: ToolContext) {
199
+ const why = refusal(input);
200
+ if (why !== undefined) { yield { type: 'error', message: why, failure: 'invalid' }; return; }
201
+ const args = input as ParallelMapReduce;
202
+ const appender = ctx.appender ?? machine.SessionAppender;
203
+ if (appender === undefined) { yield { type: 'error', message: 'Nothing here can append to a conversation, so a wave has nowhere to report.' }; return; }
204
+ // As `session_action append` decides it: a job's own session, or a door's (`#http`), is nobody's
205
+ // conversation, so a run with no conversation of its own must name one.
206
+ const throwaway = machine.isSubAgent() || ctx.appender !== undefined || ctx.session.id.startsWith('#');
207
+ const target = args.session ?? appender.defaultSessionId ?? (throwaway ? undefined : ctx.session.id);
208
+ if (target === undefined) { yield { type: 'error', message: 'This run reports to no conversation, so name the one to append to ("session").', failure: 'invalid' }; return; }
209
+ if (machine.tools.resolve('single_turn') === null) { yield { type: 'error', message: 'single_turn is not registered here, so there is nothing to run a turn with.' }; return; }
210
+
211
+ const wave = waveId();
212
+ void runWave(machine, ctx, appender, target, wave, args)
213
+ .catch(e => console.error(`[parallel_map_reduce] ${wave}: ${message(e)}`));
214
+ yield { type: 'result', value: { wave, started: args.items.length, session: target } };
215
+ },
216
+ },
217
+ };
218
+ }
219
+
220
+ export const plugin: MatbotPluginSpec = {
221
+ apiVersion: PLUGIN_API_VERSION,
222
+ manifest: { description: 'Ask one question of each item of a set as concurrent sub-agent turns, append each answer to the conversation, then ask it to combine them (`parallel_map_reduce`).' },
223
+ async setup(machine: MatbotMachine) {
224
+ machine.tools.register(makeParallelMapReduceTool(machine));
225
+ },
226
+ };