jive-agentic-workflow-comment-answering 0.0.0-stage → 0.2.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 (41) hide show
  1. package/README.md +101 -2
  2. package/dist/comment-answering.js +12 -0
  3. package/dist/comment-answering.js.map +1 -0
  4. package/dist/generated/commentAnswering.js +36 -0
  5. package/dist/generated/commentAnswering.js.map +1 -0
  6. package/dist/generated/workflows.js +6 -0
  7. package/dist/generated/workflows.js.map +1 -0
  8. package/dist/index.js +8 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/rules.js +77 -0
  11. package/dist/rules.js.map +1 -0
  12. package/dist/steps/answer.js +49 -0
  13. package/dist/steps/answer.js.map +1 -0
  14. package/dist/steps/check-reply.js +23 -0
  15. package/dist/steps/check-reply.js.map +1 -0
  16. package/dist/steps/decide.js +26 -0
  17. package/dist/steps/decide.js.map +1 -0
  18. package/dist/steps/mark-seen.js +15 -0
  19. package/dist/steps/mark-seen.js.map +1 -0
  20. package/dist/steps/post-reply.js +27 -0
  21. package/dist/steps/post-reply.js.map +1 -0
  22. package/dist/steps/shared.js +25 -0
  23. package/dist/steps/shared.js.map +1 -0
  24. package/dist/task.js +25 -0
  25. package/dist/task.js.map +1 -0
  26. package/dist/testing/harness.js +153 -0
  27. package/dist/testing/harness.js.map +1 -0
  28. package/package.json +33 -4
  29. package/src/comment-answering.ts +12 -0
  30. package/src/generated/commentAnswering.ts +36 -0
  31. package/src/generated/workflows.ts +7 -0
  32. package/src/index.ts +7 -0
  33. package/src/rules.ts +97 -0
  34. package/src/steps/answer.ts +50 -0
  35. package/src/steps/check-reply.ts +22 -0
  36. package/src/steps/decide.ts +26 -0
  37. package/src/steps/mark-seen.ts +15 -0
  38. package/src/steps/post-reply.ts +27 -0
  39. package/src/steps/shared.ts +32 -0
  40. package/src/task.ts +28 -0
  41. package/src/testing/harness.ts +166 -0
@@ -0,0 +1,153 @@
1
+ import { AgentRunner, FileStore, lineOutOfStep, WorkflowComments } from "@jive-sh/workflow-platform";
2
+ import { Effect, Layer, Option, Schema } from "effect";
3
+ import { commentAnswering } from "../generated/commentAnswering";
4
+ /**
5
+ * A source's comments in memory, behaving as the organization's server does: one reply per conversation and key, a
6
+ * reaction put on or taken off once, and an edit only of the agent's own reply. It records every write.
7
+ */
8
+ export class FakeComments {
9
+ place;
10
+ comments = [];
11
+ writes = [];
12
+ next = 1;
13
+ constructor(place = { workflow: "skillRefinement", version: { kind: "current" }, element: "step:judge", link: "https://jive.sh/comments", graph: { name: "skillRefinement" } }) {
14
+ this.place = place;
15
+ }
16
+ /** A person's comment, or an agent's post, in the conversation `conversation` (a new one when absent). */
17
+ add(input) {
18
+ const id = `c${this.next++}`;
19
+ this.comments.push({ id, author: input.author, text: input.text, createdAt: this.next, reactions: [], conversation: input.conversation ?? id });
20
+ return id;
21
+ }
22
+ personReacts(input) {
23
+ const comment = this.find(input.comment);
24
+ this.replace({ ...comment, reactions: [...comment.reactions, { emoji: input.emoji, by: { kind: "person", account: "alex" } }] });
25
+ }
26
+ find(id) {
27
+ const comment = this.comments.find((one) => one.id === id);
28
+ if (comment === undefined)
29
+ throw new Error(`no comment ${id}`);
30
+ return comment;
31
+ }
32
+ replace(comment) {
33
+ this.comments[this.comments.findIndex((one) => one.id === comment.id)] = comment;
34
+ }
35
+ *get(input) {
36
+ const comment = this.find(input.comment);
37
+ const strip = ({ conversation: _conversation, key: _key, ...rest }) => rest;
38
+ return {
39
+ place: this.place,
40
+ conversation: comment.conversation,
41
+ comment: strip(comment),
42
+ comments: this.comments.filter((one) => one.conversation === comment.conversation).map(strip),
43
+ };
44
+ }
45
+ *react(input) {
46
+ const comment = this.find(input.comment);
47
+ const has = comment.reactions.some((r) => r.emoji === input.emoji && r.by.kind === "agent" && r.by.agent === input.agent);
48
+ if (has === input.on)
49
+ return;
50
+ this.writes.push(`${input.on ? "react" : "unreact"} ${input.emoji} ${input.comment}`);
51
+ this.replace({
52
+ ...comment,
53
+ reactions: input.on
54
+ ? [...comment.reactions, { emoji: input.emoji, by: { kind: "agent", agent: input.agent } }]
55
+ : comment.reactions.filter((r) => !(r.emoji === input.emoji && r.by.kind === "agent" && r.by.agent === input.agent)),
56
+ });
57
+ }
58
+ *reply(input) {
59
+ const before = this.comments.find((one) => one.conversation === input.conversation && one.key === input.key);
60
+ if (before !== undefined)
61
+ return { comment: before.id, created: false };
62
+ const id = `c${this.next++}`;
63
+ this.comments.push({ id, author: { kind: "agent", agent: input.agent, workflow: "commentAnswering", run: "run" }, text: input.text, createdAt: this.next, reactions: [], conversation: input.conversation, key: input.key });
64
+ this.writes.push(`reply ${id}`);
65
+ return { comment: id, created: true };
66
+ }
67
+ *edit(input) {
68
+ const comment = this.find(input.comment);
69
+ if (comment.author.kind !== "agent")
70
+ return yield* Effect.fail(new WorkflowComments.WorkflowCommentsCallFailed({ call: "edit", cause: "not the agent's" }));
71
+ this.writes.push(`edit ${input.comment}`);
72
+ this.replace({ ...comment, text: input.text, editedAt: this.next++ });
73
+ }
74
+ }
75
+ /** An agent that answers each call with the next of `outputs`, recording what it was asked. */
76
+ export class ScriptedAgent {
77
+ outputs;
78
+ asked = [];
79
+ constructor(outputs) {
80
+ this.outputs = outputs;
81
+ }
82
+ *run(input) {
83
+ this.asked.push(input);
84
+ const output = this.outputs[Math.min(this.asked.length - 1, this.outputs.length - 1)] ?? "";
85
+ return {
86
+ output,
87
+ agent: "scripted",
88
+ transcript: { name: "transcript.json", ref: "t" },
89
+ stoppedAtTurnLimit: false,
90
+ spend: { fresh: 0, cacheWrite: 0, cacheRead: 0, output: 0, requests: 1, costUsd: 0 },
91
+ };
92
+ }
93
+ }
94
+ class MemoryFiles {
95
+ bytes = new Map();
96
+ next = 1;
97
+ *write(input) {
98
+ const ref = `f${this.next++}`;
99
+ this.bytes.set(ref, input.bytes);
100
+ return { name: input.name, ref };
101
+ }
102
+ *read(file) {
103
+ const found = this.bytes.get(file.ref);
104
+ if (found === undefined)
105
+ return yield* Effect.fail(new FileStore.FileStoreError({ file: file.name, cause: "missing" }));
106
+ return found;
107
+ }
108
+ }
109
+ /**
110
+ * One task through the compiled workflow in memory: each step's own code runs on the fakes, and the platform's own
111
+ * `lineOutOfStep` decides what comes next from the workflow's lines, their limits included. `runTwice` runs a step's code twice in a row, as a run whose report was
112
+ * lost is run again, to show it writes nothing twice.
113
+ */
114
+ export const runTask = async (input) => {
115
+ const files = new MemoryFiles();
116
+ const layer = Layer.mergeAll(Layer.succeed(WorkflowComments.WorkflowComments, input.comments), Layer.succeed(AgentRunner.AgentRunner, input.agent), Layer.succeed(FileStore.FileStore, files));
117
+ const decodeFields = Schema.decodeUnknownSync(commentAnswering.task.fields);
118
+ let fields = decodeFields(input.fields);
119
+ let taskFiles = [];
120
+ const notes = [];
121
+ const trace = [];
122
+ const lines = commentAnswering.graph.lines;
123
+ let at = lines.find((line) => "event" in line.from).to;
124
+ let travelled = [];
125
+ for (let turn = 0; turn < 50 && "step" in at; turn++) {
126
+ const name = at.step;
127
+ const step = commentAnswering.runnableSteps[name];
128
+ trace.push(name);
129
+ const run = () => Effect.runPromise(Effect.provide(Effect.gen(() => step.run({ taskId: "task-1", fields, files: taskFiles, notes, lastFingerprint: Option.none() })), layer));
130
+ if (input.runTwice === name)
131
+ await run();
132
+ const outcome = await run();
133
+ if (outcome.fields !== undefined)
134
+ fields = { ...fields, ...outcome.fields };
135
+ for (const file of outcome.files ?? []) {
136
+ const written = await Effect.runPromise(Effect.gen(() => files.write(file)));
137
+ taskFiles = [...taskFiles.filter((one) => one.name !== file.name), written];
138
+ }
139
+ if (outcome.note !== undefined)
140
+ notes.push({ workflow: "commentAnswering", step: name, note: outcome.note, at: turn });
141
+ const next = lineOutOfStep({ graph: commentAnswering.graph, step: name, endState: outcome.endState, travelled });
142
+ if (Option.isNone(next))
143
+ throw new Error(`no line out of ${name} for ${outcome.endState}`);
144
+ if (Option.isSome(next.value.limitReached))
145
+ notes.push({ workflow: "commentAnswering", step: name, note: `ended ${next.value.endState}: line ${next.value.limitReached.value.id} reached its limit`, at: turn });
146
+ travelled = [...next.value.travelled];
147
+ at = next.value.line.to;
148
+ }
149
+ if (!("end" in at))
150
+ throw new Error("the task never ended");
151
+ return { end: at.end, trace, fields, notes };
152
+ };
153
+ //# sourceMappingURL=harness.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"harness.js","sourceRoot":"","sources":["../../../../src/testing/harness.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,SAAS,EAAgC,aAAa,EAAiC,gBAAgB,EAAE,MAAM,4BAA4B,CAAA;AACjK,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAA;AAKhE;;;GAGG;AACH,MAAM,OAAO,YAAY;IAKF;IAJZ,QAAQ,GAA8E,EAAE,CAAC;IACzF,MAAM,GAAkB,EAAE,CAAA;IAC3B,IAAI,GAAG,CAAC,CAAA;IAEhB,YAAqB,QAAQ,EAAE,QAAQ,EAAE,iBAAiB,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,SAAS,EAAW,EAAE,OAAO,EAAE,YAAY,EAAE,IAAI,EAAE,0BAA0B,EAAE,KAAK,EAAE,EAAE,IAAI,EAAE,iBAAiB,EAAE,EAAE;QAA3K,UAAK,GAAL,KAAK,CAAsK;IAAG,CAAC;IAEpM,0GAA0G;IAC1G,GAAG,CAAC,KAAoG;QACtG,MAAM,EAAE,GAAG,IAAI,IAAI,CAAC,IAAI,EAAE,EAAE,CAAA;QAC5B,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,EAAE,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,SAAS,EAAE,IAAI,CAAC,IAAI,EAAE,SAAS,EAAE,EAAE,EAAE,YAAY,EAAE,KAAK,CAAC,YAAY,IAAI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SAAS,GAAG,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,CAAA;QACrC,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAA;IACzB,CAAC;IACD,IAAI,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,sBAAsB,CAAC,CAAA;IAC3D,OAAO,EAAE,GAAG,EAAE,EAAE,CAAC,GAAG,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,CAAA;AAC9C,CAAC,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
+ "exports": {
3
+ ".": {
4
+ "types": "./src/index.ts",
5
+ "import": "./dist/index.js"
6
+ },
7
+ "./README.md": "./README.md",
8
+ "./workflows": "./src/generated/workflows.ts"
9
+ },
2
10
  "name": "jive-agentic-workflow-comment-answering",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
11
+ "version": "0.2.0",
12
+ "license": "MIT",
13
+ "type": "module",
14
+ "description": "The comment answering workflow: a comment left on a workflow diagram element becomes a task; the agent answers it or posts a plan, and the reply is posted once.",
15
+ "repository": {
16
+ "type": "git",
17
+ "url": "git+https://github.com/jive-sh/jive-agentic-workflow-comment-answering.git"
18
+ },
19
+ "publishConfig": {
20
+ "access": "public",
21
+ "provenance": true
22
+ },
23
+ "main": "./dist/index.js",
24
+ "module": "./dist/index.js",
25
+ "types": "./src/index.ts",
26
+ "files": [
27
+ "README.md",
28
+ "dist",
29
+ "src"
30
+ ],
31
+ "peerDependencies": {
32
+ "@jive-sh/workflow-platform": "^1.9.1",
33
+ "effect": "^4.1.7"
34
+ }
35
+ }
@@ -0,0 +1,12 @@
1
+ import { commentTask } from "./task"
2
+
3
+ /**
4
+ * The workflow's settings; its flow is workflows/comment-answering.bpmn. One agent and one code step run at once to
5
+ * start: each comment needs one agent run, and a second comment waits in Answer's queue rather than starting a run that
6
+ * can't progress.
7
+ */
8
+ export const commentAnswering = {
9
+ task: commentTask,
10
+ endStates: ["answered", "planned", "ignored", "approvalReceived", "unanswered", "failed"],
11
+ budgets: { agents: 1, cpu: 1 },
12
+ } as const
@@ -0,0 +1,36 @@
1
+ // Generated by jive-abstract-agentic-workflow from workflows/comment-answering.bpmn. Change the diagram or the step code, never this file.
2
+ import { Workflow } from "@jive-sh/workflow-platform";
3
+ import { decide, markSeen, answer, checkReply, postReply } from "../index";
4
+ import { commentAnswering as settings } from "../comment-answering";
5
+
6
+ export const commentAnswering = Workflow.make({
7
+ name: "commentAnswering",
8
+ ...settings,
9
+ events: {
10
+ "task": { kind: "task" },
11
+ },
12
+ steps: () => ({
13
+ decide,
14
+ markSeen,
15
+ answer,
16
+ checkReply,
17
+ postReply,
18
+ }),
19
+ lines: [
20
+ { from: { event: "task" }, to: { step: "decide" } },
21
+ { from: { step: "decide", endState: "forAgent" }, to: { step: "markSeen" } },
22
+ { from: { step: "decide", endState: "notForAgent" }, to: { end: "ignored" } },
23
+ { from: { step: "decide", endState: "approves" }, to: { end: "approvalReceived" } },
24
+ { from: { step: "decide", endState: "failed" }, to: { end: "failed" } },
25
+ { from: { step: "markSeen", endState: "seen" }, to: { step: "answer" } },
26
+ { from: { step: "markSeen", endState: "failed" }, to: { end: "failed" } },
27
+ { from: { step: "answer", endState: "drafted" }, to: { step: "checkReply" } },
28
+ { from: { step: "answer", endState: "failed" }, to: { end: "failed" } },
29
+ { from: { step: "checkReply", endState: "ok" }, to: { step: "postReply" } },
30
+ { from: { step: "checkReply", endState: "again" }, to: { step: "answer" }, limit: { times: 2, giveUp: "givenUp" } },
31
+ { from: { step: "checkReply", endState: "givenUp" }, to: { end: "unanswered" } },
32
+ { from: { step: "postReply", endState: "answered" }, to: { end: "answered" } },
33
+ { from: { step: "postReply", endState: "planned" }, to: { end: "planned" } },
34
+ { from: { step: "postReply", endState: "failed" }, to: { end: "failed" } },
35
+ ],
36
+ });
@@ -0,0 +1,7 @@
1
+ // Generated by jive-abstract-agentic-workflow from the diagrams in workflows/. Change them or the step code, never this file.
2
+ import { commentAnswering } from "./commentAnswering";
3
+
4
+ export { commentAnswering };
5
+
6
+ /** Every workflow of this package, each after the workflows of this package it runs as a step. */
7
+ export const workflows = [commentAnswering] as const;
package/src/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ export { commentTask } from "./task"
2
+ export { commentAnswering } from "./comment-answering"
3
+ export { decide } from "./steps/decide"
4
+ export { markSeen } from "./steps/mark-seen"
5
+ export { answer } from "./steps/answer"
6
+ export { checkReply } from "./steps/check-reply"
7
+ export { postReply } from "./steps/post-reply"
package/src/rules.ts ADDED
@@ -0,0 +1,97 @@
1
+ import type { WorkflowComments } from "@jive-sh/workflow-platform"
2
+
3
+ /**
4
+ * Alex's rules for talking to the agent, carried over from skill-sync's comment watch. Every agent post starts with
5
+ * `🤖:`, so a post that does is never for the agent, whoever wrote it. A plan starts `🤖: **Plan**`, and a person approves
6
+ * it with a reply of "yes" (or "@clanker yes") or a 👍. Pure.
7
+ */
8
+
9
+ /** The name a comment tags the agent with, without its @. */
10
+ export const AGENT = "clanker"
11
+ export const AGENT_PREFIX = "🤖:"
12
+ export const PLAN_HEADING = "**Plan**"
13
+ export const SEEN = "👀"
14
+ export const APPROVE = "👍"
15
+ /** The most a source's comment holds, the Jive app's 8000 characters, less room for the prefix and the plan heading. */
16
+ export const MOST_REPLY_CHARACTERS = 7_980
17
+
18
+ type Comment = WorkflowComments.WorkflowComment
19
+
20
+ /**
21
+ * Whether a post is an agent's: posted by an agent, starting with 🤖 (with or without the colon), or exactly "...",
22
+ * which another automation on Alex's account posts to say it saw a comment.
23
+ */
24
+ export const isAgentPost = (comment: Comment): boolean =>
25
+ comment.author.kind === "agent" || comment.text.trimStart().startsWith("🤖") || comment.text.trim() === "..."
26
+
27
+ /** Whether a post is an agent's plan. */
28
+ export const isPlan = (comment: Comment): boolean => comment.author.kind === "agent" && comment.text.startsWith(`${AGENT_PREFIX} ${PLAN_HEADING}`)
29
+
30
+ /** The text with quoted lines (`> `), fenced code blocks and inline code taken out, where a tag doesn't count. */
31
+ const outsideQuotesAndCode = (text: string): string =>
32
+ text
33
+ .replace(/```[\s\S]*?```/g, " ")
34
+ .replace(/`[^`\n]*`/g, " ")
35
+ .split("\n")
36
+ .filter((line) => !line.trimStart().startsWith(">"))
37
+ .join("\n")
38
+
39
+ const tagPattern = new RegExp(`(^|[^\\w@.])@${AGENT}(?![\\w-]|\\.\\w)`, "i")
40
+
41
+ /** Whether the text tags the agent: `@clanker` in any capitals, not inside a longer name, a quoted line or code. */
42
+ export const tagsAgent = (text: string): boolean => tagPattern.test(outsideQuotesAndCode(text))
43
+
44
+ /** Whether the words are an approval: "yes", alone or after the tag, in any capitals, with trailing punctuation. */
45
+ export const saysYes = (text: string): boolean =>
46
+ text
47
+ .replace(new RegExp(`@${AGENT}`, "ig"), "")
48
+ .trim()
49
+ .replace(/[.!]+$/, "")
50
+ .toLowerCase() === "yes"
51
+
52
+ /** What a comment asks of the workflow. */
53
+ export type Decision = { readonly kind: "forAgent" } | { readonly kind: "notForAgent"; readonly why: string } | { readonly kind: "approves"; readonly plan: string }
54
+
55
+ /**
56
+ * What a new comment or a person's reaction asks. A reaction asks something only when it is a person's 👍 on an agent's
57
+ * plan. A comment asks nothing when it is an agent's post. A person's "yes" replying in a conversation whose newest agent
58
+ * post is a plan approves that plan. Every other person's comment on a workflow's diagram is for the agent, tagged or
59
+ * not, as in a Google Doc. Pure.
60
+ */
61
+ export const decide = (input: { readonly event: "comment" | "reaction"; readonly comment: Comment; readonly comments: ReadonlyArray<Comment> }): Decision => {
62
+ const { comment } = input
63
+ if (input.event === "reaction") {
64
+ const approvedByPerson = comment.reactions.some((reaction) => reaction.emoji === APPROVE && reaction.by.kind === "person")
65
+ return isPlan(comment) && approvedByPerson ? { kind: "approves", plan: comment.id } : { kind: "notForAgent", why: "the reaction is no person's 👍 on a plan" }
66
+ }
67
+ if (isAgentPost(comment)) return { kind: "notForAgent", why: "it is an agent's post" }
68
+ const earlier = input.comments.slice(0, Math.max(0, input.comments.findIndex((one) => one.id === comment.id)))
69
+ const newestAgentPost = [...earlier].reverse().find(isAgentPost)
70
+ if (newestAgentPost !== undefined && isPlan(newestAgentPost) && saysYes(comment.text)) return { kind: "approves", plan: newestAgentPost.id }
71
+ return { kind: "forAgent" }
72
+ }
73
+
74
+ /** A draft as the agent writes it. */
75
+ export interface Draft {
76
+ readonly kind: "answer" | "plan"
77
+ readonly text: string
78
+ }
79
+
80
+ /** What is wrong with a draft, in words the agent can act on; empty when it may be posted. Pure. */
81
+ export const draftProblems = (draft: Draft): ReadonlyArray<string> => {
82
+ const problems: Array<string> = []
83
+ const text = draft.text.trim()
84
+ if (text.length === 0) problems.push("the text is empty")
85
+ if (text.length > MOST_REPLY_CHARACTERS) problems.push(`the text has ${text.length} characters, more than the ${MOST_REPLY_CHARACTERS} a reply holds`)
86
+ if (text.startsWith("🤖")) problems.push("the text starts with 🤖, which the workflow adds itself")
87
+ if (text.startsWith(PLAN_HEADING)) problems.push(`the text starts with ${PLAN_HEADING}, which the workflow adds to a plan itself`)
88
+ if (tagsAgent(text)) problems.push(`the text tags @${AGENT}, which would hand the reply back to the agent`)
89
+ return problems
90
+ }
91
+
92
+ /** The reply as it is posted: the agent prefix, and the plan heading on a plan. Pure. */
93
+ export const replyText = (draft: Draft): string =>
94
+ draft.kind === "plan" ? `${AGENT_PREFIX} ${PLAN_HEADING}\n\n${draft.text.trim()}` : `${AGENT_PREFIX} ${draft.text.trim()}`
95
+
96
+ /** The key a comment's reply is posted under, so posting it again posts nothing. Pure. */
97
+ export const replyKey = (comment: string): string => `reply:${comment}`
@@ -0,0 +1,50 @@
1
+ import { AgentRunner, WorkflowComments } from "@jive-sh/workflow-platform"
2
+ import { AGENT, AGENT_PREFIX, MOST_REPLY_CHARACTERS } from "../rules"
3
+ import { DRAFT_FILE, RETRIES, step } from "./shared"
4
+
5
+ /** What the agent is told to be, the same for every comment, so the provider reads it from its cache. */
6
+ export const ANSWER_INSTRUCTIONS = `You are ${AGENT}, the agent people talk to in comments on a Jive workflow's diagram. Each comment is on one element of the workflow's graph: a step, a decision, an event, a line or an end state, named by a key such as step:<id>.
7
+
8
+ Reply to the newest comment, reading the whole conversation and the graph you are given.
9
+ - When the comment asks a question, answer it: plainly, in complete sentences, with only what answers it. Name every step, field and end state by its id in the graph.
10
+ - When the comment asks for any change (to the workflow, its code, a document or anything else), make no change and claim none. Reply with a plan instead: the concrete changes, each naming what it touches, and what each changes for the person. A person approves it by replying "yes".
11
+ - Never claim anything the graph, the conversation or the comment does not show. Say what you don't know.
12
+
13
+ Answer with one JSON object and nothing else: {"kind": "answer" | "plan", "text": "<your reply>"}. The text is at most ${MOST_REPLY_CHARACTERS} characters of plain Markdown. Don't start it with ${AGENT_PREFIX} or with a heading: the workflow adds them. Never write @${AGENT}.`
14
+
15
+ /**
16
+ * ANSWER: the agent reads the comment, its conversation and the graph of the version it is on, and drafts an answer or a
17
+ * plan into `reply.json`. A draft Check reply sent back comes with why, from the task's notes.
18
+ */
19
+ export const answer = step.agent({
20
+ endStates: ["drafted", "failed"],
21
+ access: { services: [AgentRunner.AgentRunner, WorkflowComments.WorkflowComments] },
22
+ retries: RETRIES,
23
+ run: function* (task) {
24
+ const comments = yield* WorkflowComments.WorkflowComments
25
+ const read = yield* comments.get({ comment: task.fields.comment })
26
+ const sentBack = task.notes.filter((note) => note.step === "checkReply").map((note) => note.note)
27
+ const conversation = read.comments
28
+ .map((comment) => `[${comment.id}] ${comment.author.kind === "agent" ? `agent ${comment.author.agent}` : `person ${comment.author.account}`}: ${comment.text}`)
29
+ .join("\n\n")
30
+ const prompt = [
31
+ `The comment is on ${read.place.element} of the workflow ${read.place.workflow}, ${read.place.version.kind === "current" ? "its installed version" : `its proposal ${read.place.version.ref}`}. Its link: ${read.place.link}`,
32
+ `The conversation, oldest first:\n\n${conversation}`,
33
+ `Reply to the newest comment, [${read.comment.id}].`,
34
+ ...(sentBack.length > 0 ? [`Your earlier drafts were sent back:\n${sentBack.map((why) => `- ${why}`).join("\n")}`] : []),
35
+ ].join("\n\n")
36
+ const runner = yield* AgentRunner.AgentRunner
37
+ const result = yield* runner.run({
38
+ instructions: ANSWER_INSTRUCTIONS,
39
+ cached: `The graph of that version of ${read.place.workflow}:\n${JSON.stringify(read.place.graph)}`,
40
+ prompt,
41
+ files: [],
42
+ tools: { kind: "none" },
43
+ })
44
+ return {
45
+ endState: "drafted" as const,
46
+ files: [{ name: DRAFT_FILE, bytes: new TextEncoder().encode(result.output) }],
47
+ note: result.stoppedAtTurnLimit ? "the agent stopped at its turn limit before it answered" : `drafted by ${result.agent}`,
48
+ }
49
+ },
50
+ })
@@ -0,0 +1,22 @@
1
+ import { FileStore } from "@jive-sh/workflow-platform"
2
+ import { Effect, Result } from "effect"
3
+ import { draftProblems } from "../rules"
4
+ import { DRAFT_FILE, draftOf, readTaskFile, step } from "./shared"
5
+
6
+ /**
7
+ * CHECK REPLY: the verifier of Answer's draft, apart from the agent that wrote it. A draft that holds one answer or one
8
+ * plan, fits a reply and hands nothing back to the agent goes on to be posted. Any other goes back to Answer with why, on
9
+ * the line `again`, which the diagram caps at two travels: the third draft that fails ends `givenUp` instead, and the
10
+ * comment is left unanswered, with its 👀 still on it to say so.
11
+ */
12
+ export const checkReply = step.code({
13
+ endStates: ["ok", "again", "givenUp"],
14
+ access: { services: [FileStore.FileStore] },
15
+ run: function* (task) {
16
+ const words = yield* readTaskFile({ files: task.files, name: DRAFT_FILE })
17
+ const parsed = yield* Effect.result(draftOf(words))
18
+ const problems = Result.isSuccess(parsed) ? draftProblems(parsed.success) : [parsed.failure]
19
+ if (problems.length === 0 && Result.isSuccess(parsed)) return { endState: "ok" as const, fields: { replyKind: parsed.success.kind } }
20
+ return { endState: "again" as const, note: problems.join("; ") }
21
+ },
22
+ })
@@ -0,0 +1,26 @@
1
+ import { WorkflowComments } from "@jive-sh/workflow-platform"
2
+ import { decide as decideComment } from "../rules"
3
+ import { RETRIES, step } from "./shared"
4
+
5
+ /**
6
+ * DECIDE: reads the comment and its conversation from its source and says what it asks: an answer from the agent, nothing
7
+ * (an agent's own post, or a reaction that approves nothing), or approval of a plan.
8
+ */
9
+ export const decide = step.code({
10
+ endStates: ["forAgent", "notForAgent", "approves", "failed"],
11
+ access: { services: [WorkflowComments.WorkflowComments] },
12
+ retries: RETRIES,
13
+ run: function* (task) {
14
+ const comments = yield* WorkflowComments.WorkflowComments
15
+ const read = yield* comments.get({ comment: task.fields.comment })
16
+ const decision = decideComment({ event: task.fields.event, comment: read.comment, comments: read.comments })
17
+ switch (decision.kind) {
18
+ case "forAgent":
19
+ return { endState: "forAgent" as const }
20
+ case "notForAgent":
21
+ return { endState: "notForAgent" as const, note: `not for the agent: ${decision.why}` }
22
+ case "approves":
23
+ return { endState: "approves" as const, note: `approves the plan ${decision.plan}` }
24
+ }
25
+ },
26
+ })
@@ -0,0 +1,15 @@
1
+ import { WorkflowComments } from "@jive-sh/workflow-platform"
2
+ import { AGENT, SEEN } from "../rules"
3
+ import { RETRIES, step } from "./shared"
4
+
5
+ /** MARK SEEN: puts the agent's 👀 on the comment, which Post reply takes off once the reply is posted. */
6
+ export const markSeen = step.code({
7
+ endStates: ["seen", "failed"],
8
+ access: { services: [WorkflowComments.WorkflowComments] },
9
+ retries: RETRIES,
10
+ run: function* (task) {
11
+ const comments = yield* WorkflowComments.WorkflowComments
12
+ yield* comments.react({ comment: task.fields.comment, agent: AGENT, emoji: SEEN, on: true })
13
+ return { endState: "seen" as const }
14
+ },
15
+ })
@@ -0,0 +1,27 @@
1
+ import { FileStore, WorkflowComments } from "@jive-sh/workflow-platform"
2
+ import { Effect } from "effect"
3
+ import { AGENT, replyKey, replyText, SEEN } from "../rules"
4
+ import { DRAFT_FILE, draftOf, RETRIES, readTaskFile, step } from "./shared"
5
+
6
+ /**
7
+ * POST REPLY: posts the checked draft in the comment's conversation once, under the comment's reply key, so a run tried
8
+ * again posts nothing more; then takes the agent's 👀 off the comment. The only writer of the agent's reply.
9
+ */
10
+ export const postReply = step.code({
11
+ endStates: ["answered", "planned", "failed"],
12
+ access: { services: [WorkflowComments.WorkflowComments, FileStore.FileStore] },
13
+ retries: RETRIES,
14
+ run: function* (task) {
15
+ const comments = yield* WorkflowComments.WorkflowComments
16
+ const draft = yield* draftOf(yield* readTaskFile({ files: task.files, name: DRAFT_FILE }))
17
+ const read = yield* comments.get({ comment: task.fields.comment })
18
+ const posted = yield* comments.reply({ conversation: read.conversation, agent: AGENT, text: replyText(draft), key: replyKey(task.fields.comment) })
19
+ yield* comments.react({ comment: task.fields.comment, agent: AGENT, emoji: SEEN, on: false })
20
+ yield* Effect.logInfo(`posted ${posted.comment}${posted.created ? "" : ", which was already there"}`)
21
+ return {
22
+ endState: draft.kind === "plan" ? ("planned" as const) : ("answered" as const),
23
+ fields: { posted: posted.comment },
24
+ note: posted.created ? `posted ${posted.comment}` : `the reply ${posted.comment} was already posted`,
25
+ }
26
+ },
27
+ })
@@ -0,0 +1,32 @@
1
+ import { FileStore, Workflow } from "@jive-sh/workflow-platform"
2
+ import { Effect, Schema } from "effect"
3
+ import type { Draft } from "../rules"
4
+ import { commentTask } from "../task"
5
+
6
+ /** The steps' builder: it types each step's run by the services its `access` lists. */
7
+ export const step = Workflow.stepsOf(commentTask)
8
+
9
+ /**
10
+ * How a run that fails (the organization's server or the agent's provider unreachable) is tried again before it parks
11
+ * at `failed`: three times, a minute apart.
12
+ */
13
+ export const RETRIES = { limit: 3, delayMs: 60_000, giveUp: "failed" as const }
14
+
15
+ export const DRAFT_FILE = "reply.json"
16
+
17
+ const DraftJson = Schema.fromJsonString(Schema.Struct({ kind: Schema.Literals(["answer", "plan"]), text: Schema.String }))
18
+
19
+ /** The JSON object in a model's reply, which may be wrapped in words or a fence. Pure. */
20
+ export const jsonIn = (text: string): string => text.slice(text.indexOf("{"), text.lastIndexOf("}") + 1)
21
+
22
+ /** The draft in the agent's words, or why they hold none. */
23
+ export const draftOf = (words: string): Effect.Effect<Draft, string> =>
24
+ Effect.mapError(Schema.decodeUnknownEffect(DraftJson)(jsonIn(words)), () => 'the reply was not one JSON object {"kind": "answer" | "plan", "text": "..."}')
25
+
26
+ /** The text of a task file, read through the organization's file store. */
27
+ export const readTaskFile = function* (input: { readonly files: ReadonlyArray<{ readonly name: string; readonly ref: string }>; readonly name: string }) {
28
+ const file = input.files.find((one) => one.name === input.name)
29
+ if (file === undefined) return yield* Effect.fail(`the task has no ${input.name}`)
30
+ const store = yield* FileStore.FileStore
31
+ return new TextDecoder().decode(yield* store.read(file))
32
+ }
package/src/task.ts ADDED
@@ -0,0 +1,28 @@
1
+ import { TaskSchema } from "@jive-sh/workflow-platform"
2
+ import { Effect, Schema } from "effect"
3
+
4
+ /** A field every pass starts from empty: null, which a later step writes (an absent key can't be unset). */
5
+ const emptyUntilSet = <S extends Schema.Top>(schema: S) => Schema.NullOr(schema).pipe(Schema.withDecodingDefaultKey(Effect.succeed(null)))
6
+
7
+ /**
8
+ * One comment to answer. The task carries only references: where the comment is (`source`), which comment, and what
9
+ * happened to it (a new comment, or a reaction to one). Its words, its conversation and what it is on are read from the
10
+ * source by each step, so the source stays their one owner. The agent's draft is the file `reply.json`.
11
+ */
12
+ export const commentTask = TaskSchema.make({
13
+ fields: Schema.Struct({
14
+ /** Where the comment was left: today only on an element of a workflow's diagram in the Jive app. */
15
+ source: Schema.Literal("workflow-diagram"),
16
+ /** The comment's id in its source. */
17
+ comment: Schema.String,
18
+ /** What made the task: a new comment, or a person's reaction to one. */
19
+ event: Schema.Literals(["comment", "reaction"]),
20
+ /** What the checked draft is: an answer, or a plan that waits for approval. */
21
+ replyKind: emptyUntilSet(Schema.Literals(["answer", "plan"])),
22
+ /** The reply Post reply posted, by its id in the source. */
23
+ posted: emptyUntilSet(Schema.String),
24
+ }),
25
+ files: ["reply.json"],
26
+ })
27
+
28
+ export type CommentFields = typeof commentTask.fields.Type