agency-lang 0.0.7 → 0.0.9

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,4 +1,4 @@
1
- import { AgencyComment, AgencyProgram, Assignment, Literal, PromptLiteral, TypeAlias, TypeHint } from "../types.js";
1
+ import { AgencyComment, AgencyProgram, Assignment, Literal, PromptLiteral, TypeAlias, TypeHint, VariableType } from "../types.js";
2
2
  import { AccessExpression, DotFunctionCall, DotProperty, IndexAccess } from "../types/access.js";
3
3
  import { AgencyArray, AgencyObject } from "../types/dataStructures.js";
4
4
  import { FunctionCall, FunctionDefinition } from "../types/function.js";
@@ -20,6 +20,7 @@ export declare class AgencyGenerator extends BaseGenerator {
20
20
  protected generateImports(): string;
21
21
  protected preprocess(): string;
22
22
  protected postprocess(): string;
23
+ protected aliasedTypeToString(aliasedType: VariableType): string;
23
24
  protected processTypeAlias(node: TypeAlias): string;
24
25
  protected processTypeHint(node: TypeHint): string;
25
26
  protected processAssignment(node: Assignment): string;
@@ -6,8 +6,8 @@ export class AgencyGenerator extends BaseGenerator {
6
6
  constructor() {
7
7
  super();
8
8
  }
9
- indent() {
10
- return " ".repeat(this.indentLevel * this.indentSize);
9
+ indent(level = this.indentLevel) {
10
+ return " ".repeat(level * this.indentSize);
11
11
  }
12
12
  increaseIndent() {
13
13
  this.indentLevel++;
@@ -28,10 +28,26 @@ export class AgencyGenerator extends BaseGenerator {
28
28
  postprocess() {
29
29
  return "";
30
30
  }
31
+ aliasedTypeToString(aliasedType) {
32
+ if (aliasedType.type === "objectType") {
33
+ const props = aliasedType.properties
34
+ .map((prop) => {
35
+ let str = `${this.indent(this.indentLevel + 1)}`;
36
+ str += `${prop.key}: ${this.aliasedTypeToString(prop.value)}`;
37
+ if (prop.description) {
38
+ str += ` # ${prop.description}`;
39
+ }
40
+ return str;
41
+ })
42
+ .join(";\n");
43
+ return `{\n${props}\n}`;
44
+ }
45
+ return variableTypeToString(aliasedType, this.typeAliases);
46
+ }
31
47
  // Type system methods
32
48
  processTypeAlias(node) {
33
49
  this.typeAliases[node.aliasName] = node.aliasedType;
34
- const aliasedTypeStr = variableTypeToString(node.aliasedType, this.typeAliases);
50
+ const aliasedTypeStr = this.aliasedTypeToString(node.aliasedType);
35
51
  return this.indentStr(`type ${node.aliasName} = ${aliasedTypeStr}\n`);
36
52
  }
37
53
  processTypeHint(node) {
@@ -19,7 +19,9 @@ export class TypeScriptGenerator extends BaseGenerator {
19
19
  processTypeAlias(node) {
20
20
  this.typeAliases[node.aliasName] = node.aliasedType;
21
21
  const typeAliasStr = this.typeAliasToString(node);
22
- this.generatedTypeAliases.push(typeAliasStr);
22
+ if (!this.generatedTypeAliases.includes(typeAliasStr)) {
23
+ this.generatedTypeAliases.push(typeAliasStr);
24
+ }
23
25
  return "";
24
26
  }
25
27
  typeAliasToString(node) {
@@ -1,4 +1,4 @@
1
- export declare const template = "import OpenAI from \"openai\";\nimport { zodResponseFormat } from \"openai/helpers/zod\";\nimport { z } from \"zod\";\nimport * as readline from \"readline\";\nimport fs from \"fs\";\nimport { Graph, goToNode } from \"simplemachine\";\nimport { StatelogClient } from \"statelog-client\";\nimport { nanoid } from \"nanoid\";\n\nconst statelogHost = \"http://localhost:1065\";\nconst traceId = nanoid();\nconst statelogClient = new StatelogClient({host: statelogHost, tid: traceId});\nconst model = \"gpt-4.1-nano-2025-04-14\";\n\nconst openai = new OpenAI({\n apiKey: process.env.OPENAI_API_KEY,\n});\n\ntype State = {\n messages: string[];\n data: any;\n}\n\n// enable debug logging\nconst graphConfig = {\n debug: {\n log: true,\n logData: true,\n },\n statelogHost,\n traceId\n};\n\n// Define the names of the nodes in the graph\n// Useful for type safety\nconst nodes = {{{nodes:string}}} as const;\ntype Node = (typeof nodes)[number];\n\nconst graph = new Graph<State, Node>(nodes, graphConfig);";
1
+ export declare const template = "import OpenAI from \"openai\";\nimport { zodResponseFormat } from \"openai/helpers/zod\";\nimport { z } from \"zod\";\nimport * as readline from \"readline\";\nimport fs from \"fs\";\nimport { PieMachine, goToNode } from \"piemachine\";\nimport { StatelogClient } from \"statelog-client\";\nimport { nanoid } from \"nanoid\";\nimport { assistantMessage, getClient, userMessage } from \"smoltalk\";\n\nconst statelogHost = \"https://statelog.adit.io\";\nconst traceId = nanoid();\nconst statelogConfig = {\n host: statelogHost,\n traceId: traceId,\n apiKey: process.env.STATELOG_API_KEY || \"\",\n projectId: \"agency-lang\",\n debugMode: false,\n };\nconst statelogClient = new StatelogClient(statelogConfig);\nconst model = \"gpt-4o-mini\";\n\nconst client = getClient({\n openAiApiKey: process.env.OPENAI_API_KEY || \"\",\n googleApiKey: process.env.GEMINI_API_KEY || \"\",\n model,\n logLevel: \"warn\",\n});\n\ntype State = {\n messages: string[];\n data: any;\n}\n\n// enable debug logging\nconst graphConfig = {\n debug: {\n log: true,\n logData: true,\n },\n statelog: statelogConfig,\n};\n\n// Define the names of the nodes in the graph\n// Useful for type safety\nconst nodes = {{{nodes:string}}} as const;\ntype Node = (typeof nodes)[number];\n\nconst graph = new PieMachine<State, Node>(nodes, graphConfig);";
2
2
  export type TemplateType = {
3
3
  nodes: string;
4
4
  };
@@ -7,17 +7,28 @@ import { zodResponseFormat } from "openai/helpers/zod";
7
7
  import { z } from "zod";
8
8
  import * as readline from "readline";
9
9
  import fs from "fs";
10
- import { Graph, goToNode } from "simplemachine";
10
+ import { PieMachine, goToNode } from "piemachine";
11
11
  import { StatelogClient } from "statelog-client";
12
12
  import { nanoid } from "nanoid";
13
+ import { assistantMessage, getClient, userMessage } from "smoltalk";
13
14
 
14
- const statelogHost = "http://localhost:1065";
15
+ const statelogHost = "https://statelog.adit.io";
15
16
  const traceId = nanoid();
16
- const statelogClient = new StatelogClient({host: statelogHost, tid: traceId});
17
- const model = "gpt-4.1-nano-2025-04-14";
17
+ const statelogConfig = {
18
+ host: statelogHost,
19
+ traceId: traceId,
20
+ apiKey: process.env.STATELOG_API_KEY || "",
21
+ projectId: "agency-lang",
22
+ debugMode: false,
23
+ };
24
+ const statelogClient = new StatelogClient(statelogConfig);
25
+ const model = "gpt-4o-mini";
18
26
 
19
- const openai = new OpenAI({
20
- apiKey: process.env.OPENAI_API_KEY,
27
+ const client = getClient({
28
+ openAiApiKey: process.env.OPENAI_API_KEY || "",
29
+ googleApiKey: process.env.GEMINI_API_KEY || "",
30
+ model,
31
+ logLevel: "warn",
21
32
  });
22
33
 
23
34
  type State = {
@@ -31,8 +42,7 @@ const graphConfig = {
31
42
  log: true,
32
43
  logData: true,
33
44
  },
34
- statelogHost,
35
- traceId
45
+ statelog: statelogConfig,
36
46
  };
37
47
 
38
48
  // Define the names of the nodes in the graph
@@ -40,7 +50,7 @@ const graphConfig = {
40
50
  const nodes = {{{nodes:string}}} as const;
41
51
  type Node = (typeof nodes)[number];
42
52
 
43
- const graph = new Graph<State, Node>(nodes, graphConfig);`;
53
+ const graph = new PieMachine<State, Node>(nodes, graphConfig);`;
44
54
  const render = (args) => {
45
55
  return apply(template, args);
46
56
  };
@@ -1,4 +1,4 @@
1
- export declare const template = "import OpenAI from \"openai\";\nimport { zodResponseFormat } from \"openai/helpers/zod\";\nimport { z } from \"zod\";\nimport * as readline from \"readline\";\nimport fs from \"fs\";\nimport { StatelogClient } from \"statelog-client\";\nimport { nanoid } from \"nanoid\";\n\nconst statelogHost = \"http://localhost:1065\";\nconst traceId = nanoid();\nconst statelogClient = new StatelogClient({host: statelogHost, tid: traceId});\n\nconst model = \"gpt-5-nano-2025-08-07\";\n\nconst openai = new OpenAI({\n apiKey: process.env.OPENAI_API_KEY,\n});";
1
+ export declare const template = "import OpenAI from \"openai\";\nimport { zodResponseFormat } from \"openai/helpers/zod\";\nimport { z } from \"zod\";\nimport * as readline from \"readline\";\nimport fs from \"fs\";\nimport { StatelogClient } from \"statelog-client\";\nimport { nanoid } from \"nanoid\";\n\nconst statelogHost = \"http://localhost:1065\";\nconst traceId = nanoid();\nconst statelogClient = new StatelogClient({\n host: statelogHost,\n traceId: traceId,\n apiKey: process.env.STATELOG_API_KEY || \"\",\n projectId: \"agency-lang\",\n debugMode: true,\n });\n\nconst model = \"gpt-5-nano-2025-08-07\";\n\nconst openai = new OpenAI({\n apiKey: process.env.OPENAI_API_KEY,\n});";
2
2
  export type TemplateType = {};
3
3
  declare const render: (args: TemplateType) => string;
4
4
  export default render;
@@ -12,7 +12,13 @@ import { nanoid } from "nanoid";
12
12
 
13
13
  const statelogHost = "http://localhost:1065";
14
14
  const traceId = nanoid();
15
- const statelogClient = new StatelogClient({host: statelogHost, tid: traceId});
15
+ const statelogClient = new StatelogClient({
16
+ host: statelogHost,
17
+ traceId: traceId,
18
+ apiKey: process.env.STATELOG_API_KEY || "",
19
+ projectId: "agency-lang",
20
+ debugMode: true,
21
+ });
16
22
 
17
23
  const model = "gpt-5-nano-2025-08-07";
18
24
 
@@ -1,4 +1,4 @@
1
- export declare const template = "\nasync function _{{{variableName:string}}}({{{argsStr:string}}}): Promise<{{{typeString:string}}}> {\n const prompt = {{{promptCode:string}}};\n const startTime = performance.now();\n const messages:any[] = [{ role: \"user\", content: prompt }];\n const tools = {{{tools}}};\n\n let completion = await openai.chat.completions.create({\n model,\n messages,\n tools,\n response_format: zodResponseFormat(z.object({\n value: {{{zodSchema:string}}}\n }), \"{{{variableName:string}}}_response\"),\n });\n const endTime = performance.now();\n statelogClient.promptCompletion({\n messages,\n completion,\n model,\n timeTaken: endTime - startTime,\n });\n\n let responseMessage = completion.choices[0].message;\n // Handle function calls\n while (responseMessage.tool_calls && responseMessage.tool_calls.length > 0) {\n // Add assistant's response with tool calls to message history\n messages.push(responseMessage);\n let toolCallStartTime, toolCallEndTime;\n\n // Process each tool call\n for (const toolCall of responseMessage.tool_calls) {\n {{{functionCalls:string}}}\n }\n\n const nextStartTime = performance.now();\n // Get the next response from the model\n completion = await openai.chat.completions.create({\n model,\n messages: messages,\n tools: tools,\n });\n const nextEndTime = performance.now();\n\n statelogClient.promptCompletion({\n messages,\n completion,\n model,\n timeTaken: nextEndTime - nextStartTime,\n });\n\n responseMessage = completion.choices[0].message;\n }\n\n // Add final assistant response to history\n messages.push(responseMessage);\n\n try {\n const result = JSON.parse(completion.choices[0].message.content || \"\");\n return result.value;\n } catch (e) {\n return completion.choices[0].message.content;\n // console.error(\"Error parsing response for variable '{{{variableName:string}}}':\", e);\n // console.error(\"Full completion response:\", JSON.stringify(completion, null, 2));\n // throw e;\n }\n}\n";
1
+ export declare const template = "\nasync function _{{{variableName:string}}}({{{argsStr:string}}}): Promise<{{{typeString:string}}}> {\n const prompt = {{{promptCode:string}}};\n const startTime = performance.now();\n const messages: Message[] = [userMessage(prompt)];\n const tools = {{{tools}}};\n\n // Need to make sure this is always an object\n const responseFormat = z.object({\n response: {{{zodSchema:string}}}\n });\n\n let completion = await client.text({\n messages,\n tools,\n responseFormat,\n });\n\n const endTime = performance.now();\n statelogClient.promptCompletion({\n messages,\n completion,\n model,\n timeTaken: endTime - startTime,\n });\n\n if (!completion.success) {\n throw new Error(\n `Error getting response from ${model}: ${completion.error}`\n );\n }\n\n let responseMessage = completion.value;\n\n // Handle function calls\n while (responseMessage.toolCalls.length > 0) {\n // Add assistant's response with tool calls to message history\n messages.push(assistantMessage(responseMessage.output));\n let toolCallStartTime, toolCallEndTime;\n\n // Process each tool call\n for (const toolCall of responseMessage.toolCalls) {\n {{{functionCalls:string}}}\n }\n\n const nextStartTime = performance.now();\n let completion = await client.text({\n messages,\n tools,\n responseFormat,\n });\n\n const nextEndTime = performance.now();\n\n statelogClient.promptCompletion({\n messages,\n completion,\n model,\n timeTaken: nextEndTime - nextStartTime,\n });\n\n if (!completion.success) {\n throw new Error(\n `Error getting response from ${model}: ${completion.error}`\n );\n }\n responseMessage = completion.value;\n }\n\n // Add final assistant response to history\n messages.push(assistantMessage(responseMessage.output));\n\n try {\n const result = JSON.parse(responseMessage.output || \"\");\n return result.response;\n } catch (e) {\n return responseMessage.output;\n // console.error(\"Error parsing response for variable '{{{variableName:string}}}':\", e);\n // console.error(\"Full completion response:\", JSON.stringify(completion, null, 2));\n // throw e;\n }\n}\n";
2
2
  export type TemplateType = {
3
3
  variableName: string;
4
4
  argsStr: string;
@@ -6,17 +6,20 @@ export const template = `
6
6
  async function _{{{variableName:string}}}({{{argsStr:string}}}): Promise<{{{typeString:string}}}> {
7
7
  const prompt = {{{promptCode:string}}};
8
8
  const startTime = performance.now();
9
- const messages:any[] = [{ role: "user", content: prompt }];
9
+ const messages: Message[] = [userMessage(prompt)];
10
10
  const tools = {{{tools}}};
11
11
 
12
- let completion = await openai.chat.completions.create({
13
- model,
12
+ // Need to make sure this is always an object
13
+ const responseFormat = z.object({
14
+ response: {{{zodSchema:string}}}
15
+ });
16
+
17
+ let completion = await client.text({
14
18
  messages,
15
19
  tools,
16
- response_format: zodResponseFormat(z.object({
17
- value: {{{zodSchema:string}}}
18
- }), "{{{variableName:string}}}_response"),
20
+ responseFormat,
19
21
  });
22
+
20
23
  const endTime = performance.now();
21
24
  statelogClient.promptCompletion({
22
25
  messages,
@@ -25,25 +28,32 @@ async function _{{{variableName:string}}}({{{argsStr:string}}}): Promise<{{{type
25
28
  timeTaken: endTime - startTime,
26
29
  });
27
30
 
28
- let responseMessage = completion.choices[0].message;
31
+ if (!completion.success) {
32
+ throw new Error(
33
+ \`Error getting response from $\{model\}: $\{completion.error\}\`
34
+ );
35
+ }
36
+
37
+ let responseMessage = completion.value;
38
+
29
39
  // Handle function calls
30
- while (responseMessage.tool_calls && responseMessage.tool_calls.length > 0) {
40
+ while (responseMessage.toolCalls.length > 0) {
31
41
  // Add assistant's response with tool calls to message history
32
- messages.push(responseMessage);
42
+ messages.push(assistantMessage(responseMessage.output));
33
43
  let toolCallStartTime, toolCallEndTime;
34
44
 
35
45
  // Process each tool call
36
- for (const toolCall of responseMessage.tool_calls) {
46
+ for (const toolCall of responseMessage.toolCalls) {
37
47
  {{{functionCalls:string}}}
38
48
  }
39
49
 
40
50
  const nextStartTime = performance.now();
41
- // Get the next response from the model
42
- completion = await openai.chat.completions.create({
43
- model,
44
- messages: messages,
45
- tools: tools,
51
+ let completion = await client.text({
52
+ messages,
53
+ tools,
54
+ responseFormat,
46
55
  });
56
+
47
57
  const nextEndTime = performance.now();
48
58
 
49
59
  statelogClient.promptCompletion({
@@ -53,17 +63,22 @@ async function _{{{variableName:string}}}({{{argsStr:string}}}): Promise<{{{type
53
63
  timeTaken: nextEndTime - nextStartTime,
54
64
  });
55
65
 
56
- responseMessage = completion.choices[0].message;
66
+ if (!completion.success) {
67
+ throw new Error(
68
+ \`Error getting response from $\{model\}: $\{completion.error\}\`
69
+ );
70
+ }
71
+ responseMessage = completion.value;
57
72
  }
58
73
 
59
74
  // Add final assistant response to history
60
- messages.push(responseMessage);
75
+ messages.push(assistantMessage(responseMessage.output));
61
76
 
62
77
  try {
63
- const result = JSON.parse(completion.choices[0].message.content || "");
64
- return result.value;
78
+ const result = JSON.parse(responseMessage.output || "");
79
+ return result.response;
65
80
  } catch (e) {
66
- return completion.choices[0].message.content;
81
+ return responseMessage.output;
67
82
  // console.error("Error parsing response for variable '{{{variableName:string}}}':", e);
68
83
  // console.error("Full completion response:", JSON.stringify(completion, null, 2));
69
84
  // throw e;
@@ -155,6 +155,7 @@ async function main() {
155
155
  }
156
156
  format(fmtContents, verbose);
157
157
  break;
158
+ case "ast":
158
159
  case "parse":
159
160
  let contents;
160
161
  if (filteredArgs.length < 2) {
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,36 @@
1
+ #!/usr/bin/env node
2
+ import path, { dirname } from "path";
3
+ import fs from "fs";
4
+ import { generateTypeScript } from "../lib/backends/typescriptGenerator.js";
5
+ import { parseAgency } from "../lib/parser.js";
6
+ import { fileURLToPath } from "url";
7
+ const __filename = fileURLToPath(import.meta.url);
8
+ const __dirname = dirname(__filename);
9
+ const fixturesDir = path.join(__dirname, "../../tests/typescriptGenerator");
10
+ function regenerateFixtures(dir, relativePath = "") {
11
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
12
+ for (const entry of entries) {
13
+ const fullPath = path.join(dir, entry.name);
14
+ if (entry.isDirectory()) {
15
+ regenerateFixtures(fullPath, path.join(relativePath, entry.name));
16
+ }
17
+ else if (entry.isFile() && entry.name.endsWith(".agency")) {
18
+ const baseName = entry.name.replace(".agency", "");
19
+ const mtsPath = path.join(dir, `${baseName}.mts`);
20
+ const agencyContent = fs.readFileSync(fullPath, "utf-8");
21
+ const parseResult = parseAgency(agencyContent);
22
+ if (parseResult.success) {
23
+ const tsCode = generateTypeScript(parseResult.result);
24
+ fs.writeFileSync(mtsPath, tsCode, "utf-8");
25
+ const fixtureRelPath = path.join(relativePath, baseName) || baseName;
26
+ console.log(`✓ Updated ${fixtureRelPath}.mts`);
27
+ }
28
+ else {
29
+ console.error(`✗ Failed to parse ${fullPath}: ${parseResult.message}`);
30
+ }
31
+ }
32
+ }
33
+ }
34
+ console.log("Regenerating fixture files...\n");
35
+ regenerateFixtures(fixturesDir);
36
+ console.log("\nDone!");
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,36 @@
1
+ #!/usr/bin/env node
2
+ import path, { dirname } from "path";
3
+ import fs from "fs";
4
+ import { generateGraph } from "../lib/backends/graphGenerator.js";
5
+ import { parseAgency } from "../lib/parser.js";
6
+ import { fileURLToPath } from "url";
7
+ const __filename = fileURLToPath(import.meta.url);
8
+ const __dirname = dirname(__filename);
9
+ const fixturesDir = path.join(__dirname, "../../tests/graphGenerator");
10
+ function regenerateFixtures(dir, relativePath = "") {
11
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
12
+ for (const entry of entries) {
13
+ const fullPath = path.join(dir, entry.name);
14
+ if (entry.isDirectory()) {
15
+ regenerateFixtures(fullPath, path.join(relativePath, entry.name));
16
+ }
17
+ else if (entry.isFile() && entry.name.endsWith(".agency")) {
18
+ const baseName = entry.name.replace(".agency", "");
19
+ const mtsPath = path.join(dir, `${baseName}.mts`);
20
+ const agencyContent = fs.readFileSync(fullPath, "utf-8");
21
+ const parseResult = parseAgency(agencyContent);
22
+ if (parseResult.success) {
23
+ const graphCode = generateGraph(parseResult.result);
24
+ fs.writeFileSync(mtsPath, graphCode, "utf-8");
25
+ const fixtureRelPath = path.join(relativePath, baseName) || baseName;
26
+ console.log(`✓ Updated ${fixtureRelPath}.mts`);
27
+ }
28
+ else {
29
+ console.error(`✗ Failed to parse ${fullPath}: ${parseResult.message}`);
30
+ }
31
+ }
32
+ }
33
+ }
34
+ console.log("Regenerating graph generator fixture files...\n");
35
+ regenerateFixtures(fixturesDir);
36
+ console.log("\nDone!");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agency-lang",
3
- "version": "0.0.7",
3
+ "version": "0.0.9",
4
4
  "description": "The Agency language",
5
5
  "main": "lib/index.js",
6
6
  "scripts": {
@@ -10,7 +10,8 @@
10
10
  "start": "node dist/lib/index.js",
11
11
  "templates": "typestache ./lib/templates",
12
12
  "typecheck": "tsc --noEmit",
13
- "agency": "node ./dist/scripts/agency.js"
13
+ "agency": "node ./dist/scripts/agency.js",
14
+ "compile": "node ./dist/scripts/agency.js compile"
14
15
  },
15
16
  "bin": {
16
17
  "agency": "./dist/scripts/agency.js"
@@ -24,9 +25,9 @@
24
25
  ],
25
26
  "exports": {
26
27
  ".": {
28
+ "types": "./dist/lib/index.d.ts",
27
29
  "import": "./dist/lib/index.js",
28
- "require": "./dist/lib/index.js",
29
- "types": "./dist/lib/index.d.ts"
30
+ "require": "./dist/lib/index.js"
30
31
  }
31
32
  },
32
33
  "type": "module",
@@ -42,8 +43,9 @@
42
43
  "egonlog": "^0.0.2",
43
44
  "nanoid": "^5.1.6",
44
45
  "openai": "^6.15.0",
45
- "simplemachine": "github:egonSchiele/simplemachine",
46
- "statelog-client": "^0.0.28",
46
+ "piemachine": "^0.0.2",
47
+ "smoltalk": "^0.0.8",
48
+ "statelog-client": "^0.0.31",
47
49
  "tarsec": "^0.1.1",
48
50
  "typestache": "^0.4.4",
49
51
  "zod": "^4.2.1"