loopengine 0.3.65 → 0.3.67

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.
@@ -1,5 +1,5 @@
1
1
  import type { ModelCall } from '#core/run-agent.js';
2
- import { type GoalFocus } from './goal-playbooks.js';
2
+ import { type Focus, type GoalFocus, type Lever } from './goal-playbooks.js';
3
3
  /** What LoopEngine knows about the person: the workspace, the website,
4
4
  * what they said. `kind` uses the playbook's vocabulary of needs (email,
5
5
  * messaging, web-search, orders-or-crm…). */
@@ -27,6 +27,9 @@ export interface GoalBrief {
27
27
  /** How the goal was read, e.g. "literal" or "a stretch goal for the business". */
28
28
  reading: string;
29
29
  focus: GoalFocus | 'other';
30
+ /** When no focus in the playbook fits: the one the planner named
31
+ * (generic words; saved in the workspace's own playbook). */
32
+ newFocus?: Focus;
30
33
  measure: string;
31
34
  /** Where the measure's number comes from (a system, or "none"), and
32
35
  * whether that's connected: when it isn't, the plan says how the
@@ -101,6 +104,10 @@ export interface GoalPlan {
101
104
  };
102
105
  /** The playbook version the plan was made with. */
103
106
  playbookVersion: number;
107
+ /** Levers the planner wrote because the playbook had none that fit
108
+ * (generic, like the playbook's own; saved in the workspace's own
109
+ * playbook, and the jobs made from them refer to them). */
110
+ newLevers?: Lever[];
104
111
  }
105
112
  export interface GoalPipelineInput {
106
113
  goal: string;
@@ -109,9 +116,30 @@ export interface GoalPipelineInput {
109
116
  /** The focus the person chose, instead of the one the brief reads. */
110
117
  focus?: GoalFocus | 'other';
111
118
  }
112
- export declare const GOAL_BRIEF_PROMPT = "You read a goal someone gives LoopEngine, a platform of AI agents that work with information and software: they search, read, write, draft, track, and act in connected apps (email, chat, stores, CRMs, payments, code hosts). They can't do physical work or run large real-world projects on their own.\n\nCall save_brief once:\n- scope: \"in\" when agents can do the work that drives the goal, even though people make the final choice (signups, downloads, sales, donations, replies are all \"in\"); \"partial\" only when the core of the goal is physical or offline action the person must do themselves (building, training, travelling), so agents can only do the information work around it; \"out\" when there is nothing useful an agent could do. scopeReason: one sentence.\n- reading: how you read it. When the wording could be a metaphor (\"land on the moon\", \"climb Everest\" said of a business), prefer the reading the context supports and say which.\n- focus: the one stage of the goal to plan for. Growth of users means \"new-signups\" unless the goal speaks of using, keeping or activating people. Answering customers sooner is \"faster-support\". Use \"other\" only when none fits.\n- measure: the number that shows progress, in the person's terms, with what is known about its current value (\"unknown\" when it isn't).\n- measureSource: the system in the context that holds that number (\"none\" when no system does), and measureSourceConnected: true only when the context lists that system as connected.\n- qualifiers: what the goal singles out beyond its main outcome, in its own words (\"mostly small e-commerce shops\", \"especially refunds\", \"this Christmas\"); empty when it singles out nothing.\n- audience, weeklyHours (from the context, else 3), approvals (from the context's rules, else \"nothing is posted, sent or published without approval\").";
113
- export declare const GOAL_PLAN_PROMPT = "You plan workflows for a confirmed goal brief in LoopEngine. Each workflow is one recurring job for one AI agent; a person reviews what it drafts.\n\nRules:\n1. Levers first, capabilities second. Choose what moves this focus's measure (the playbook's levers, or your own new idea when the context calls for one), then map each to what the workspace has. Never start from what the connected tools could do.\n2. Every workflow serves the brief's focus directly and moves its measure. Workflows that only support it (reporting, onboarding for an acquisition goal, support) go in leftOut with a reason, not in workflows.\n3. One lever per workflow, named in a few generic words (no business, product, person, place or site names: \"list in app marketplaces\", not \"list Wick & Ember on Shopify\"); no two workflows on the same lever. Never propose a lever already saved under the goal (built, proposed or dismissed): those are listed in the request.\n4. Three to five workflows for an \"in\" goal, ordered by impact against effort, quickest useful one first; startsAfter when one depends on another. Their humanMinutesPerWeek together stay within three quarters of the brief's weeklyHours, so the plan survives a busy week.\n4b. Each one is a job: kind \"recurring\" when it runs again and again (a weekly scan, a reply to each signup), kind \"once\" for work on a finite list or done one time (submitting to a set of directories, a one-time audit, researching a list of communities). A once job is done by an agent once, in Chat; never make it a weekly job that runs out of things to do.\n4c. measure: the job's own number, in the person's terms, that shows it's working (\"replies per week\", \"signups tagged ref=directories\"); for a once job, what done looks like (\"done when: listed in 15 directories\"). A playbook lever says the kind and measure it usually has: start from those, and change them only when the context calls for it.\n5. Specific to this context: name the person's own communities, systems, products and channels in each request. A request anyone could use unchanged is wrong.\n6. needs: what each workflow uses, each with a kind from the playbook's vocabulary and connected true only when the context lists that kind as connected.\n7. Every request that posts, sends or publishes says nothing goes out without the person's approval.\n8. The measure must be readable. When measureSourceConnected is false, setup says how the number will be read: connecting that source (name it, e.g. \"connect Clerk's user.created webhook so signups and their ref are recorded\"), or, when it can't be connected, a light manual record the person updates weekly (kept with the Records ability). Always record a baseline: the number today. Tag what workflows produce (ref=<channel>) so each one's effect can be told apart.\n8b. Every qualifier in the brief is covered by at least one workflow that addresses it directly; list it in that workflow's covers.\n9. \"partial\" scope: at most three workflows, only ones that help the person pursue the goal, and say so in the message (\"helps you pursue\", never \"achieves\"). \"out\" scope: no workflows; the message says plainly why, and offers a smaller or related goal.\n10. agent: an existing agent's exact name when its work fits. When none fits, or there are no agents yet, suggest a new one: agent and newAgent.name the same short lowercase name with hyphens (e.g. \"community-agent\"), and newAgent.instructions two or three sentences on what it does and how it behaves. Group workflows that belong together in one agent rather than one agent each.\n\nCall save_plan once.";
114
- export declare const GOAL_CRITIQUE_PROMPT = "You check a goal plan against its rules before a person sees it. List every issue (be strict, quote the workflow):\n- a workflow that doesn't serve the brief's focus or move its measure;\n- two workflows on the same lever, or one repeating a lever already saved;\n- a request generic enough to fit any business;\n- a need marked connected that the context doesn't list as connected;\n- a request that posts, sends or publishes without saying it waits for approval;\n- review time over three quarters of the weekly budget;\n- a measure whose source isn't connected, with no setup step that connects it or a manual record, or no baseline;\n- a qualifier from the brief no workflow addresses;\n- a recurring job on a finite list that will run out (it should be kind \"once\");\n- a plan claiming to achieve a goal that is only partly in scope, or workflows for an out-of-scope goal.\nCall save_review once: passed true only when there are no issues.";
119
+ export declare const GOAL_BRIEF_PROMPT = "You read a goal someone gives LoopEngine, a platform of AI agents that work with information and software: they search, read, write, draft, track, and act in connected apps (email, chat, stores, CRMs, payments, code hosts). They can't do physical work or run large real-world projects on their own.\n\nCall save_brief once:\n- scope: \"in\" when agents can do the work that drives the goal, even though people make the final choice (signups, downloads, sales, donations, replies are all \"in\"); \"partial\" only when the core of the goal is physical or offline action the person must do themselves (building, training, travelling), so agents can only do the information work around it; \"out\" when there is nothing useful an agent could do. scopeReason: one sentence.\n- reading: how you read it. When the wording could be a metaphor (\"land on the moon\", \"climb Everest\" said of a business), prefer the reading the context supports and say which.\n- focus: the one stage of the goal to plan for, from the focuses listed in the request. Growth of users means \"new-signups\" unless the goal speaks of using, keeping or activating people. Answering customers sooner is \"faster-support\". When none fits, focus \"other\" and newFocus: name the stage in a few generic words (label, e.g. \"Hiring\", \"Closing sales deals\", \"Personal health habits\") with a one-sentence hint of what goals with this focus are about. No names of the business, its products, people or places.\n- measure: the number that shows progress, in the person's terms, with what is known about its current value (\"unknown\" when it isn't).\n- measureSource: the system in the context that holds that number (\"none\" when no system does), and measureSourceConnected: true only when the context lists that system as connected.\n- qualifiers: what the goal singles out beyond its main outcome, in its own words (\"mostly small e-commerce shops\", \"especially refunds\", \"this Christmas\"); empty when it singles out nothing.\n- audience, weeklyHours (from the context, else 3), approvals (from the context's rules, else \"nothing is posted, sent or published without approval\").";
120
+ export declare const GOAL_PLAN_PROMPT = "You plan workflows for a confirmed goal brief in LoopEngine. Each workflow is one recurring job for one AI agent; a person reviews what it drafts.\n\nRules:\n1. Levers first, capabilities second. Choose what moves this focus's measure (the playbook's levers, or your own when the context calls for one), then map each to what the workspace has. Never start from what the connected tools could do.\n1b. When the request lists no playbook levers for this focus (none yet, or every one already under this goal), write the levers you need first, in newLevers (two to five), then make each workflow from one of them (its leverId is the lever's key). When levers are listed but one this goal clearly needs is missing, you may add up to two. A new lever is like the playbook's: one distinct approach (one reason it works), in generic words that fit many businesses (no names of this business, its products, people, places or sites), with when it fits and doesn't, what it needs, review time, how its effect shows up, guardrails (approval before anything is sent, posted or published), and a generic template with {placeholders}. The workflow's request is where this business's specifics go.\n2. Every workflow serves the brief's focus directly and moves its measure. Workflows that only support it (reporting, onboarding for an acquisition goal, support) go in leftOut with a reason, not in workflows.\n3. One lever per workflow, named in a few generic words (no business, product, person, place or site names: \"list in app marketplaces\", not \"list Wick & Ember on Shopify\"); no two workflows on the same lever. Never propose a lever already saved under the goal (built, proposed or dismissed): those are listed in the request.\n4. Three to five workflows for an \"in\" goal, ordered by impact against effort, quickest useful one first; startsAfter when one depends on another. Their humanMinutesPerWeek together stay within three quarters of the brief's weeklyHours, so the plan survives a busy week.\n4b. Each one is a job: kind \"recurring\" when it runs again and again (a weekly scan, a reply to each signup), kind \"once\" for work on a finite list or done one time (submitting to a set of directories, a one-time audit, researching a list of communities). A once job is done by an agent once, in Chat; never make it a weekly job that runs out of things to do.\n4c. measure: the job's own number, in the person's terms, that shows it's working (\"replies per week\", \"signups tagged ref=directories\"); for a once job, what done looks like (\"done when: listed in 15 directories\"). A playbook lever says the kind and measure it usually has: start from those, and change them only when the context calls for it.\n5. Specific to this context: name the person's own communities, systems, products and channels in each request. A request anyone could use unchanged is wrong.\n6. needs: what each workflow uses, each with a kind from the playbook's vocabulary and connected true only when the context lists that kind as connected.\n7. Every request that posts, sends or publishes says nothing goes out without the person's approval.\n8. The measure must be readable. When measureSourceConnected is false, setup says how the number will be read: connecting that source (name it, e.g. \"connect Clerk's user.created webhook so signups and their ref are recorded\"), or, when it can't be connected, a light manual record the person updates weekly (kept with the Records ability). Always record a baseline: the number today. Tag what workflows produce (ref=<channel>) so each one's effect can be told apart.\n8b. Every qualifier in the brief is covered by at least one workflow that addresses it directly; list it in that workflow's covers.\n9. \"partial\" scope: at most three workflows, only ones that help the person pursue the goal, and say so in the message (\"helps you pursue\", never \"achieves\"). \"out\" scope: no workflows; the message says plainly why, and offers a smaller or related goal.\n10. agent: an existing agent's exact name when its work fits. When none fits, or there are no agents yet, suggest a new one: agent and newAgent.name the same short lowercase name with hyphens (e.g. \"community-agent\"), and newAgent.instructions two or three sentences on what it does and how it behaves. Group workflows that belong together in one agent rather than one agent each.\n\nCall save_plan once.";
121
+ export declare const GOAL_CRITIQUE_PROMPT = "You check a goal plan against its rules before a person sees it. List every issue (be strict, quote the workflow):\n- a workflow that doesn't serve the brief's focus or move its measure;\n- two workflows on the same lever, or one repeating a lever already saved;\n- a request generic enough to fit any business;\n- a need marked connected that the context doesn't list as connected;\n- a request that posts, sends or publishes without saying it waits for approval;\n- review time over three quarters of the weekly budget;\n- a measure whose source isn't connected, with no setup step that connects it or a manual record, or no baseline;\n- a qualifier from the brief no workflow addresses;\n- a recurring job on a finite list that will run out (it should be kind \"once\");\n- a lever in newLevers that names this business, its products, people, places or sites, mixes several approaches, or has no way to see its effect;\n- a workflow made from no lever when the request listed none for this focus (it should come from one of newLevers);\n- a plan claiming to achieve a goal that is only partly in scope, or workflows for an out-of-scope goal.\nCall save_review once: passed true only when there are no issues.";
122
+ /** A job a person added in their own words, shaped like a planned one. */
123
+ export declare const GOAL_ADD_JOB_PROMPT = "A person adds a job of their own to a goal in LoopEngine, in their own words. Shape it into one job like a planner's, and judge it honestly; it's their business, so advise, don't lecture.\n\nShape it:\n- title, kind (\"recurring\" when it repeats, \"once\" for finite work), measure (its own number, or for a once job what done looks like), why it moves the goal (mechanism), the agent (an existing agent's exact name when its work fits, else newAgent with a short name and two or three sentences of instructions), needs (connected only when the context lists it), humanMinutesPerWeek, and a request specific to this business that the agent can act on. Anything that posts, sends or publishes says nothing goes out without the person's approval.\n- lever: when it's one of the playbook levers listed, its id in leverId. When none fits, write one generic lever in newLever (one approach, no names of this business, its products, people, places or sites; when it fits and doesn't; what it needs; how its effect shows up; guardrails; a generic template) and put its key in leverId.\n\nJudge it, in verdict:\n- \"added\": it fits the goal and is safe.\n- \"changed\": a sound idea with risky details you changed (an approval added, volume limited, a platform's rules respected); say what you changed in note.\n- \"warned\": it's safe but unlikely to move the goal's measure, repeats a job already under the goal, or is unlikely to work; say why in note and give a better-aimed alternative.\n- \"refused\": it's deceptive, illegal or against a platform's rules (fake reviews or accounts, spam, buying followers, harvesting private data, impersonation, misleading claims) or could harm people. Don't shape it; say why in note, plainly and briefly, and give a legitimate alternative.\n\nCall save_job once.";
124
+ export interface ShapedJob {
125
+ verdict: 'added' | 'changed' | 'warned' | 'refused';
126
+ note: string;
127
+ alternative: string;
128
+ /** Missing when refused, or when the answer had no usable job. */
129
+ job?: PlannedGoalWorkflow;
130
+ /** The lever the planner wrote for it, when none fit. */
131
+ newLever?: Lever;
132
+ }
133
+ /** Shapes a job a person typed, under a goal already planned: its kind,
134
+ * measure, agent, request and lever (an existing one, or a new generic
135
+ * one), and judges it: added, changed, warned or refused. */
136
+ export declare function shapeJob(modelCall: ModelCall, input: {
137
+ goal: string;
138
+ brief: GoalBrief;
139
+ context: GoalContext;
140
+ saved?: SavedGoalWorkflow[];
141
+ idea: string;
142
+ }): Promise<ShapedJob>;
115
143
  export declare function contextText(context: GoalContext): string;
116
144
  /** A suggested agent's name as a folder name: lowercase, hyphens. */
117
145
  export declare function agentName(raw: string): string;
@@ -1,4 +1,4 @@
1
- import { GOAL_FOCUSES, activePlaybook, leversFor } from './goal-playbooks.js';
1
+ import { activePlaybook, leversFor } from './goal-playbooks.js';
2
2
  // The prompt lists at most this many of a focus's levers, so a growing
3
3
  // playbook never makes a long prompt. (Later: the best-ranked first.)
4
4
  const MAX_LEVERS_IN_PROMPT = 10;
@@ -8,7 +8,7 @@ export const GOAL_BRIEF_PROMPT = `You read a goal someone gives LoopEngine, a pl
8
8
  Call save_brief once:
9
9
  - scope: "in" when agents can do the work that drives the goal, even though people make the final choice (signups, downloads, sales, donations, replies are all "in"); "partial" only when the core of the goal is physical or offline action the person must do themselves (building, training, travelling), so agents can only do the information work around it; "out" when there is nothing useful an agent could do. scopeReason: one sentence.
10
10
  - reading: how you read it. When the wording could be a metaphor ("land on the moon", "climb Everest" said of a business), prefer the reading the context supports and say which.
11
- - focus: the one stage of the goal to plan for. Growth of users means "new-signups" unless the goal speaks of using, keeping or activating people. Answering customers sooner is "faster-support". Use "other" only when none fits.
11
+ - focus: the one stage of the goal to plan for, from the focuses listed in the request. Growth of users means "new-signups" unless the goal speaks of using, keeping or activating people. Answering customers sooner is "faster-support". When none fits, focus "other" and newFocus: name the stage in a few generic words (label, e.g. "Hiring", "Closing sales deals", "Personal health habits") with a one-sentence hint of what goals with this focus are about. No names of the business, its products, people or places.
12
12
  - measure: the number that shows progress, in the person's terms, with what is known about its current value ("unknown" when it isn't).
13
13
  - measureSource: the system in the context that holds that number ("none" when no system does), and measureSourceConnected: true only when the context lists that system as connected.
14
14
  - qualifiers: what the goal singles out beyond its main outcome, in its own words ("mostly small e-commerce shops", "especially refunds", "this Christmas"); empty when it singles out nothing.
@@ -16,7 +16,8 @@ Call save_brief once:
16
16
  export const GOAL_PLAN_PROMPT = `You plan workflows for a confirmed goal brief in LoopEngine. Each workflow is one recurring job for one AI agent; a person reviews what it drafts.
17
17
 
18
18
  Rules:
19
- 1. Levers first, capabilities second. Choose what moves this focus's measure (the playbook's levers, or your own new idea when the context calls for one), then map each to what the workspace has. Never start from what the connected tools could do.
19
+ 1. Levers first, capabilities second. Choose what moves this focus's measure (the playbook's levers, or your own when the context calls for one), then map each to what the workspace has. Never start from what the connected tools could do.
20
+ 1b. When the request lists no playbook levers for this focus (none yet, or every one already under this goal), write the levers you need first, in newLevers (two to five), then make each workflow from one of them (its leverId is the lever's key). When levers are listed but one this goal clearly needs is missing, you may add up to two. A new lever is like the playbook's: one distinct approach (one reason it works), in generic words that fit many businesses (no names of this business, its products, people, places or sites), with when it fits and doesn't, what it needs, review time, how its effect shows up, guardrails (approval before anything is sent, posted or published), and a generic template with {placeholders}. The workflow's request is where this business's specifics go.
20
21
  2. Every workflow serves the brief's focus directly and moves its measure. Workflows that only support it (reporting, onboarding for an acquisition goal, support) go in leftOut with a reason, not in workflows.
21
22
  3. One lever per workflow, named in a few generic words (no business, product, person, place or site names: "list in app marketplaces", not "list Wick & Ember on Shopify"); no two workflows on the same lever. Never propose a lever already saved under the goal (built, proposed or dismissed): those are listed in the request.
22
23
  4. Three to five workflows for an "in" goal, ordered by impact against effort, quickest useful one first; startsAfter when one depends on another. Their humanMinutesPerWeek together stay within three quarters of the brief's weeklyHours, so the plan survives a busy week.
@@ -41,11 +42,14 @@ export const GOAL_CRITIQUE_PROMPT = `You check a goal plan against its rules bef
41
42
  - a measure whose source isn't connected, with no setup step that connects it or a manual record, or no baseline;
42
43
  - a qualifier from the brief no workflow addresses;
43
44
  - a recurring job on a finite list that will run out (it should be kind "once");
45
+ - a lever in newLevers that names this business, its products, people, places or sites, mixes several approaches, or has no way to see its effect;
46
+ - a workflow made from no lever when the request listed none for this focus (it should come from one of newLevers);
44
47
  - a plan claiming to achieve a goal that is only partly in scope, or workflows for an out-of-scope goal.
45
48
  Call save_review once: passed true only when there are no issues.`;
46
49
  // ---------- tools ----------
47
- const focusEnum = [...GOAL_FOCUSES, 'other'];
48
- const BRIEF_TOOL = {
50
+ /** The focus ids the planner may pick: the playbook in use's, and "other". */
51
+ const focusEnum = () => [...activePlaybook().focuses.map((f) => f.id), 'other'];
52
+ const briefTool = () => ({
49
53
  name: 'save_brief',
50
54
  description: 'Save how the goal was read.',
51
55
  input_schema: {
@@ -54,7 +58,8 @@ const BRIEF_TOOL = {
54
58
  scope: { type: 'string', enum: ['in', 'partial', 'out'] },
55
59
  scopeReason: { type: 'string' },
56
60
  reading: { type: 'string' },
57
- focus: { type: 'string', enum: focusEnum },
61
+ focus: { type: 'string', enum: focusEnum() },
62
+ newFocus: { type: 'object', properties: { label: { type: 'string' }, hint: { type: 'string' } }, required: ['label', 'hint'], description: 'only when focus is "other": the stage, named in generic words' },
58
63
  measure: { type: 'string' },
59
64
  measureSource: { type: 'string' },
60
65
  measureSourceConnected: { type: 'boolean' },
@@ -65,8 +70,27 @@ const BRIEF_TOOL = {
65
70
  },
66
71
  required: ['scope', 'scopeReason', 'reading', 'focus', 'measure', 'measureSource', 'measureSourceConnected', 'qualifiers', 'audience', 'weeklyHours', 'approvals'],
67
72
  },
73
+ });
74
+ const NEW_LEVER_SCHEMA = {
75
+ type: 'object',
76
+ description: 'a lever the playbook lacks, in generic words (no names of the business, its products, people, places or sites)',
77
+ properties: {
78
+ key: { type: 'string', description: 'a short lowercase-hyphenated key; workflows made from it put this key in leverId' },
79
+ name: { type: 'string', description: 'the approach in a few words' },
80
+ kind: { type: 'string', enum: ['recurring', 'once'] },
81
+ mechanism: { type: 'string', description: 'why it tends to move the measure, one sentence' },
82
+ fitsWhen: { type: 'array', items: { type: 'string' } },
83
+ notWhen: { type: 'array', items: { type: 'string' } },
84
+ needs: { type: 'array', items: { type: 'string' }, description: 'kinds of app or ability it uses (email, messaging, web-search, records, …)' },
85
+ humanMinutesPerWeek: { type: 'number' },
86
+ firstResultDays: { type: 'number' },
87
+ measureLink: { type: 'string', description: 'how its effect shows up, generically' },
88
+ guardrails: { type: 'array', items: { type: 'string' } },
89
+ template: { type: 'string', description: 'the request it starts from, generic, with {placeholders}' },
90
+ },
91
+ required: ['key', 'name', 'kind', 'mechanism', 'fitsWhen', 'notWhen', 'needs', 'humanMinutesPerWeek', 'firstResultDays', 'measureLink', 'guardrails', 'template'],
68
92
  };
69
- const PLAN_TOOL = {
93
+ const planTool = () => ({
70
94
  name: 'save_plan',
71
95
  description: 'Save the plan.',
72
96
  input_schema: {
@@ -81,9 +105,9 @@ const PLAN_TOOL = {
81
105
  title: { type: 'string' },
82
106
  kind: { type: 'string', enum: ['recurring', 'once'] },
83
107
  measure: { type: 'string', description: "the job's own number, or for a once job what done looks like" },
84
- leverId: { type: 'string', description: "the playbook lever's id; empty for a new idea" },
108
+ leverId: { type: 'string', description: "the playbook lever's id, or the key of one of your newLevers" },
85
109
  lever: { type: 'string', description: 'the lever in a few generic words, with no names of the business, its products, people, places or sites' },
86
- focus: { type: 'string', enum: focusEnum },
110
+ focus: { type: 'string' },
87
111
  mechanism: { type: 'string', description: 'why it moves the measure, one sentence' },
88
112
  request: { type: 'string', description: 'the workflow request, specific to this context' },
89
113
  agent: { type: 'string' },
@@ -97,13 +121,70 @@ const PLAN_TOOL = {
97
121
  required: ['title', 'lever', 'focus', 'mechanism', 'request', 'agent', 'needs', 'humanMinutesPerWeek', 'measureLink'],
98
122
  },
99
123
  },
124
+ newLevers: { type: 'array', items: NEW_LEVER_SCHEMA, description: 'levers the playbook lacks; required when the request lists none for this focus' },
100
125
  leftOut: { type: 'array', items: { type: 'string' } },
101
126
  assumptions: { type: 'array', items: { type: 'string' } },
102
127
  message: { type: 'string' },
103
128
  },
104
129
  required: ['setup', 'workflows', 'leftOut', 'assumptions', 'message'],
105
130
  },
131
+ });
132
+ /** A job a person added in their own words, shaped like a planned one. */
133
+ export const GOAL_ADD_JOB_PROMPT = `A person adds a job of their own to a goal in LoopEngine, in their own words. Shape it into one job like a planner's, and judge it honestly; it's their business, so advise, don't lecture.
134
+
135
+ Shape it:
136
+ - title, kind ("recurring" when it repeats, "once" for finite work), measure (its own number, or for a once job what done looks like), why it moves the goal (mechanism), the agent (an existing agent's exact name when its work fits, else newAgent with a short name and two or three sentences of instructions), needs (connected only when the context lists it), humanMinutesPerWeek, and a request specific to this business that the agent can act on. Anything that posts, sends or publishes says nothing goes out without the person's approval.
137
+ - lever: when it's one of the playbook levers listed, its id in leverId. When none fits, write one generic lever in newLever (one approach, no names of this business, its products, people, places or sites; when it fits and doesn't; what it needs; how its effect shows up; guardrails; a generic template) and put its key in leverId.
138
+
139
+ Judge it, in verdict:
140
+ - "added": it fits the goal and is safe.
141
+ - "changed": a sound idea with risky details you changed (an approval added, volume limited, a platform's rules respected); say what you changed in note.
142
+ - "warned": it's safe but unlikely to move the goal's measure, repeats a job already under the goal, or is unlikely to work; say why in note and give a better-aimed alternative.
143
+ - "refused": it's deceptive, illegal or against a platform's rules (fake reviews or accounts, spam, buying followers, harvesting private data, impersonation, misleading claims) or could harm people. Don't shape it; say why in note, plainly and briefly, and give a legitimate alternative.
144
+
145
+ Call save_job once.`;
146
+ const addJobTool = () => {
147
+ const plan = planTool().input_schema;
148
+ return {
149
+ name: 'save_job',
150
+ description: 'Save the shaped job and your verdict.',
151
+ input_schema: {
152
+ type: 'object',
153
+ properties: {
154
+ verdict: { type: 'string', enum: ['added', 'changed', 'warned', 'refused'] },
155
+ note: { type: 'string', description: 'for changed, warned or refused: one or two sentences for the person' },
156
+ alternative: { type: 'string', description: 'for warned or refused: a better-aimed or legitimate job, in a sentence' },
157
+ job: plan.properties.workflows.items,
158
+ newLever: NEW_LEVER_SCHEMA,
159
+ },
160
+ required: ['verdict'],
161
+ },
162
+ };
106
163
  };
164
+ /** Shapes a job a person typed, under a goal already planned: its kind,
165
+ * measure, agent, request and lever (an existing one, or a new generic
166
+ * one), and judges it: added, changed, warned or refused. */
167
+ export async function shapeJob(modelCall, input) {
168
+ const focus = input.brief.focus;
169
+ const levers = focus === 'other' ? [] : leversFor(focus);
170
+ const user = [
171
+ contextText(input.context),
172
+ briefText(input.brief),
173
+ levers.length ? `Playbook levers for this focus:\n${levers.slice(0, MAX_LEVERS_IN_PROMPT * 2).map((l) => `- ${l.id}: ${l.name}. ${l.mechanism} Usually ${l.kind === 'once' ? 'a once job' : 'a recurring job'}; its measure: ${l.measureLink}.`).join('\n')}` : 'Playbook levers: none for this focus yet.',
174
+ savedText(input.saved),
175
+ `The goal:\n${input.goal}`,
176
+ `The job the person wants to add, in their words:\n${input.idea}`,
177
+ ].join('\n\n');
178
+ const raw = await callTool(modelCall, GOAL_ADD_JOB_PROMPT, user, addJobTool());
179
+ const verdict = raw.verdict === 'changed' || raw.verdict === 'warned' || raw.verdict === 'refused' ? raw.verdict : 'added';
180
+ const note = str(raw.note).slice(0, 600);
181
+ const alternative = str(raw.alternative).slice(0, 400);
182
+ if (verdict === 'refused')
183
+ return { verdict, note, alternative };
184
+ const shaped = parsePlan({ workflows: raw.job ? [raw.job] : [], newLevers: raw.newLever ? [raw.newLever] : [] }, focus);
185
+ const job = shaped.workflows[0];
186
+ return { verdict, note, alternative, ...(job ? { job } : {}), ...(job && shaped.newLevers?.[0] ? { newLever: shaped.newLevers[0] } : {}) };
187
+ }
107
188
  const REVIEW_TOOL = {
108
189
  name: 'save_review',
109
190
  description: 'Save the check.',
@@ -160,10 +241,18 @@ export function contextText(context) {
160
241
  context.weeklyHours ? `Time to review drafts: about ${context.weeklyHours} hours a week` : '',
161
242
  ].filter(Boolean).join('\n');
162
243
  }
163
- function leversText(focus) {
164
- if (focus === 'other')
165
- return 'Playbook levers: none for this focus; use your own ideas, each marked as a new idea.';
166
- return 'Playbook levers for this focus (id: name; why; fits when; not when; needs; minutes a week):\n' + leversFor(focus).slice(0, MAX_LEVERS_IN_PROMPT).map((l) => `- ${l.id}: ${l.name}. ${l.mechanism} Fits when: ${l.fitsWhen.join('; ')}. Not when: ${l.notWhen.join('; ')}. Needs: ${[...(l.needs.anyOf?.length ? [`one of ${l.needs.anyOf.join('/')}`] : []), ...(l.needs.plus ?? [])].join(' + ')}. About ${l.humanMinutesPerWeek} min/week. Usually ${l.kind === 'once' ? 'a once job' : 'a recurring job'}; its measure: ${l.measureLink}. Template: ${l.template}`).join('\n');
244
+ /** The focus's levers the plan may still use (none already under the
245
+ * goal). With none left, the planner writes new ones, as for a new focus,
246
+ * so Generate more keeps finding approaches. */
247
+ function leversText(focus, saved = []) {
248
+ const used = new Set(saved.flatMap((s) => (s.leverId ? [s.leverId] : [])));
249
+ const all = focus === 'other' ? [] : leversFor(focus);
250
+ const levers = all.filter((l) => !used.has(l.id));
251
+ if (!levers.length)
252
+ return all.length
253
+ ? 'Playbook levers: every one for this focus is already under this goal. Write new levers in newLevers (rule 1b: two to five, each a different approach from those already saved), and make each workflow from one of them.'
254
+ : 'Playbook levers: none for this focus yet. Write the levers this goal needs in newLevers (rule 1b), and make each workflow from one of them.';
255
+ return 'Playbook levers for this focus (id: name; why; fits when; not when; needs; minutes a week):\n' + levers.slice(0, MAX_LEVERS_IN_PROMPT).map((l) => `- ${l.id}: ${l.name}. ${l.mechanism} Fits when: ${l.fitsWhen.join('; ')}. Not when: ${l.notWhen.join('; ')}. Needs: ${[...(l.needs.anyOf?.length ? [`one of ${l.needs.anyOf.join('/')}`] : []), ...(l.needs.plus ?? [])].join(' + ')}. About ${l.humanMinutesPerWeek} min/week. Usually ${l.kind === 'once' ? 'a once job' : 'a recurring job'}; its measure: ${l.measureLink}. Template: ${l.template}`).join('\n');
167
256
  }
168
257
  function savedText(saved) {
169
258
  if (!saved?.length)
@@ -176,15 +265,74 @@ export function agentName(raw) {
176
265
  }
177
266
  const str = (v, fallback = '') => (typeof v === 'string' ? v.trim() : fallback);
178
267
  const strings = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string' && x.trim().length > 0).map((x) => x.trim()) : []);
179
- const focusOf = (v) => (typeof v === 'string' && focusEnum.includes(v) ? v : 'other');
268
+ const focusOf = (v) => (typeof v === 'string' && focusEnum().includes(v) ? v : 'other');
269
+ const slug = (v) => v.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40).replace(/-+$/, '');
270
+ /** Text that shouldn't leave the workspace in a lever: links, addresses,
271
+ * handles, long numbers. */
272
+ const UNSAFE_LEVER_TEXT = /https?:|www\.|@|\.(com|co|io|app|net|org|ai)\b|\d{4,}/i;
273
+ /** The focus the brief named, as a workspace's own focus ("x-..."). */
274
+ function newFocusFrom(raw) {
275
+ const f = raw && typeof raw === 'object' ? raw : {};
276
+ const label = str(f.label).slice(0, 60);
277
+ const hint = str(f.hint).slice(0, 300);
278
+ const id = `x-${slug(label)}`;
279
+ if (!label || !hint || id === 'x-' || UNSAFE_LEVER_TEXT.test(`${label} ${hint}`))
280
+ return undefined;
281
+ return { id, label, hint };
282
+ }
283
+ /** The levers a plan wrote, as a workspace's own levers under the focus
284
+ * (ids "<focus>.x-<key>"), keyed by the key its workflows use. One with
285
+ * unsafe text or a missing part is dropped. */
286
+ function newLeversFrom(raw, focus) {
287
+ const out = new Map();
288
+ if (!Array.isArray(raw) || focus === 'other')
289
+ return out;
290
+ for (const item of raw.slice(0, 5)) {
291
+ const x = item && typeof item === 'object' ? item : {};
292
+ const key = slug(str(x.key) || str(x.name));
293
+ const lever = {
294
+ id: `${focus}.x-${key}`,
295
+ focus,
296
+ name: str(x.name).slice(0, 80),
297
+ kind: x.kind === 'once' ? 'once' : 'recurring',
298
+ mechanism: str(x.mechanism).slice(0, 400),
299
+ fitsWhen: strings(x.fitsWhen).slice(0, 5),
300
+ notWhen: strings(x.notWhen).slice(0, 5),
301
+ needs: { ...(strings(x.needs).length ? { anyOf: strings(x.needs).map((n) => n.toLowerCase()).slice(0, 5) } : {}) },
302
+ humanMinutesPerWeek: typeof x.humanMinutesPerWeek === 'number' && x.humanMinutesPerWeek >= 0 ? Math.round(x.humanMinutesPerWeek) : 20,
303
+ firstResultDays: typeof x.firstResultDays === 'number' && x.firstResultDays >= 0 ? Math.round(x.firstResultDays) : 7,
304
+ measureLink: str(x.measureLink).slice(0, 200),
305
+ guardrails: strings(x.guardrails).slice(0, 5),
306
+ template: str(x.template).slice(0, 800),
307
+ };
308
+ const text = [lever.name, lever.mechanism, ...lever.fitsWhen, ...lever.notWhen, lever.measureLink, ...lever.guardrails, lever.template].join(' ');
309
+ if (!key || !lever.name || !lever.mechanism || !lever.measureLink || !lever.template || !lever.fitsWhen.length || UNSAFE_LEVER_TEXT.test(text))
310
+ continue;
311
+ if (!lever.guardrails.length)
312
+ lever.guardrails = ['Nothing is posted, sent or published without the person\u2019s approval.'];
313
+ out.set(key, lever);
314
+ }
315
+ return out;
316
+ }
180
317
  export async function readGoalBrief(modelCall, goal, context) {
181
- const raw = await callTool(modelCall, GOAL_BRIEF_PROMPT, `${contextText(context)}\n\nThe goal, as the person said it:\n${goal}`, BRIEF_TOOL);
318
+ const focuses = activePlaybook().focuses.map((f) => `- ${f.id}: ${f.label} (${f.hint})`).join('\n');
319
+ const raw = await callTool(modelCall, GOAL_BRIEF_PROMPT, `${contextText(context)}\n\nFocuses in the playbook:\n${focuses}\n\nThe goal, as the person said it:\n${goal}`, briefTool());
182
320
  const scope = raw.scope === 'partial' || raw.scope === 'out' ? raw.scope : 'in';
321
+ // A focus the planner named becomes the workspace's own, unless one by
322
+ // that name is already in use.
323
+ let focus = focusOf(raw.focus);
324
+ const named = focus === 'other' ? newFocusFrom(raw.newFocus) : undefined;
325
+ const existing = named && activePlaybook().focuses.find((f) => f.id === named.id || f.label.toLowerCase() === named.label.toLowerCase());
326
+ if (existing)
327
+ focus = existing.id;
328
+ else if (named)
329
+ focus = named.id;
183
330
  return {
184
331
  scope,
185
332
  scopeReason: str(raw.scopeReason),
186
333
  reading: str(raw.reading),
187
- focus: focusOf(raw.focus),
334
+ focus,
335
+ ...(named && !existing ? { newFocus: named } : {}),
188
336
  measure: str(raw.measure, 'unknown'),
189
337
  measureSource: str(raw.measureSource, 'none'),
190
338
  measureSourceConnected: raw.measureSourceConnected === true,
@@ -195,11 +343,12 @@ export async function readGoalBrief(modelCall, goal, context) {
195
343
  };
196
344
  }
197
345
  function briefText(brief) {
198
- return `Confirmed brief:\n- scope: ${brief.scope} (${brief.scopeReason})\n- reading: ${brief.reading}\n- focus: ${brief.focus}\n- measure: ${brief.measure}\n- measure source: ${brief.measureSource} (${brief.measureSourceConnected ? 'connected' : 'not connected'})\n- qualifiers: ${brief.qualifiers.join('; ') || 'none'}\n- audience: ${brief.audience}\n- weekly review time: ${brief.weeklyHours} hours\n- approvals: ${brief.approvals}`;
346
+ return `Confirmed brief:\n- scope: ${brief.scope} (${brief.scopeReason})\n- reading: ${brief.reading}\n- focus: ${brief.focus}${brief.newFocus ? ` (${brief.newFocus.label}: ${brief.newFocus.hint}; new, not in the playbook yet)` : ''}\n- measure: ${brief.measure}\n- measure source: ${brief.measureSource} (${brief.measureSourceConnected ? 'connected' : 'not connected'})\n- qualifiers: ${brief.qualifiers.join('; ') || 'none'}\n- audience: ${brief.audience}\n- weekly review time: ${brief.weeklyHours} hours\n- approvals: ${brief.approvals}`;
199
347
  }
200
- function parsePlan(raw) {
348
+ function parsePlan(raw, focus) {
201
349
  const { levers } = activePlaybook();
202
350
  const KNOWN_LEVER_IDS = new Set(levers.map((l) => l.id));
351
+ const written = newLeversFrom(raw.newLevers, focus);
203
352
  const workflows = (Array.isArray(raw.workflows) ? raw.workflows : []).flatMap((w) => {
204
353
  if (!w || typeof w !== 'object')
205
354
  return [];
@@ -208,8 +357,10 @@ function parsePlan(raw) {
208
357
  const request = str(x.request);
209
358
  if (!title || !request)
210
359
  return [];
211
- // Some models put the playbook id in lever and leave leverId empty.
212
- const leverId = str(x.leverId) || (KNOWN_LEVER_IDS.has(str(x.lever)) ? str(x.lever) : '');
360
+ // Some models put the playbook id in lever and leave leverId empty. A
361
+ // key of one of the plan's own levers means that lever.
362
+ const own = written.get(slug(str(x.leverId))) ?? written.get(slug(str(x.lever)));
363
+ const leverId = own?.id || str(x.leverId) && KNOWN_LEVER_IDS.has(str(x.leverId)) && str(x.leverId) || (KNOWN_LEVER_IDS.has(str(x.lever)) ? str(x.lever) : '');
213
364
  const na = x.newAgent && typeof x.newAgent === 'object' ? x.newAgent : undefined;
214
365
  const newAgentName = na ? agentName(str(na.name) || str(x.agent)) : '';
215
366
  const needs = (Array.isArray(x.needs) ? x.needs : []).flatMap((n) => {
@@ -238,18 +389,20 @@ function parsePlan(raw) {
238
389
  newIdea: !leverId,
239
390
  }];
240
391
  });
241
- return { setup: strings(raw.setup), workflows, leftOut: strings(raw.leftOut), assumptions: strings(raw.assumptions), message: str(raw.message) };
392
+ // The plan's own levers that a workflow is made from: the ones to keep.
393
+ const used = [...written.values()].filter((l) => workflows.some((w) => w.leverId === l.id));
394
+ return { setup: strings(raw.setup), workflows, leftOut: strings(raw.leftOut), assumptions: strings(raw.assumptions), message: str(raw.message), ...(used.length ? { newLevers: used } : {}) };
242
395
  }
243
396
  export async function draftGoalPlan(modelCall, input, brief, issues = []) {
244
397
  const user = [
245
398
  contextText(input.context),
246
399
  briefText(brief),
247
- leversText(brief.focus),
400
+ leversText(brief.focus, input.saved),
248
401
  savedText(input.saved),
249
402
  `The goal, as the person said it:\n${input.goal}`,
250
403
  issues.length ? `A check found these issues in your last plan; fix every one:\n${issues.map((i) => `- ${i}`).join('\n')}` : '',
251
404
  ].filter(Boolean).join('\n\n');
252
- return parsePlan(await callTool(modelCall, GOAL_PLAN_PROMPT, user, PLAN_TOOL));
405
+ return parsePlan(await callTool(modelCall, GOAL_PLAN_PROMPT, user, planTool()), brief.focus);
253
406
  }
254
407
  export async function critiqueGoalPlan(modelCall, input, brief, plan) {
255
408
  const user = [contextText(input.context), briefText(brief), savedText(input.saved), `The plan:\n${JSON.stringify(plan, null, 2)}`].join('\n\n');
@@ -1,5 +1,17 @@
1
- export type GoalFocus = 'new-signups' | 'activation' | 'retention' | 'faster-support' | 'revenue-recovery' | 'ops-hygiene';
2
- export declare const GOAL_FOCUSES: readonly GoalFocus[];
1
+ /** A focus id: a shared one (below), or a workspace's own ("x-..."). */
2
+ export type GoalFocus = string;
3
+ /** The shared playbook's focuses, as bundled. */
4
+ export declare const GOAL_FOCUSES: readonly string[];
5
+ export interface Focus {
6
+ /** lowercase-hyphenated; a workspace's own starts with "x-". */
7
+ id: string;
8
+ /** What people read: "Getting new signups or customers". */
9
+ label: string;
10
+ /** What the planner reads: what goals with this focus are about. */
11
+ hint: string;
12
+ }
13
+ /** Whether an id is a workspace's own focus or lever (never shared as is). */
14
+ export declare const isLocalId: (id: string) => boolean;
3
15
  export interface Lever {
4
16
  /** `<focus>.<name>`, stable. */
5
17
  id: string;
@@ -29,25 +41,47 @@ export interface Lever {
29
41
  /** The request it starts from, with {placeholders} filled from context. */
30
42
  template: string;
31
43
  }
32
- /** Checks the playbook's shape, naming the lever at fault. */
33
- export declare function parsePlaybook(raw: unknown): {
44
+ /** Checks the playbook's shape, naming the lever at fault. A lever's
45
+ * focus must be one the playbook lists, or one of `knownFocuses`. */
46
+ export declare function parsePlaybook(raw: unknown, knownFocuses?: readonly string[]): {
34
47
  version: number;
48
+ focuses: Focus[];
35
49
  levers: Lever[];
36
50
  };
37
51
  /** The playbook bundled with this package. */
38
52
  export declare const PLAYBOOK_VERSION: number;
39
53
  export declare const LEVERS: readonly Lever[];
54
+ export declare const FOCUSES: readonly Focus[];
40
55
  /** Where the fetched playbook is cached: the project folder. */
41
56
  export declare function setPlaybookProjectDir(dir: string | undefined): void;
42
57
  export declare function mergePlaybooks(bundled: readonly Lever[], fetched: {
43
58
  levers: Lever[];
44
59
  retired?: string[];
45
60
  } | undefined): Lever[];
46
- /** The levers in use, and the version they come from (the fetched one's
47
- * when there is one, else the bundled one's). */
61
+ /** The workspace's own focuses and levers (empty when there are none, or
62
+ * the file doesn't pass the checks). */
63
+ export declare function readLocalPlaybook(dir?: string | undefined): {
64
+ focuses: Focus[];
65
+ levers: Lever[];
66
+ };
67
+ /** Adds focuses and levers to the workspace's own playbook (by id: a new
68
+ * one is added, one with an id already there replaces it). Only local
69
+ * ids ("x-...") are kept. */
70
+ export declare function addToLocalPlaybook(dir: string, add: {
71
+ focuses?: Focus[];
72
+ levers?: Lever[];
73
+ }): {
74
+ focuses: Focus[];
75
+ levers: Lever[];
76
+ };
77
+ /** The playbook in use: the bundled one, the fetched one over it, and the
78
+ * workspace's own focuses and levers; the version is the shared one's. */
48
79
  export declare function activePlaybook(): {
49
80
  version: number;
81
+ focuses: readonly Focus[];
50
82
  levers: readonly Lever[];
51
83
  };
84
+ /** A focus's label for people: its playbook label, else its id. */
85
+ export declare function focusLabel(id: string): string;
52
86
  /** The levers in use for a focus. */
53
87
  export declare function leversFor(focus: GoalFocus): Lever[];